Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

Release v1.0.1

sora76a5f6860a72
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index e72444c..a9815de 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -55,6 +55,33 @@ jobs:
- name: Install frontend dependencies
run: npm ci
+ - name: Extract release notes from CHANGELOG.md
+ id: release_notes
+ shell: bash
+ run: |
+ node -e '
+ const fs = require("fs");
+ const conf = JSON.parse(fs.readFileSync("src-tauri/tauri.conf.json", "utf8"));
+ const version = String(conf.version || "").replace(/^v/i, "");
+ const md = fs.existsSync("CHANGELOG.md") ? fs.readFileSync("CHANGELOG.md", "utf8") : "";
+ const lines = md.replace(/\r\n/g, "\n").split("\n");
+ const re = /^##\s+\[?v?([0-9]+\.[0-9]+\.[0-9]+(?:-[^\s\]]+)?)\]?(?:\s+.*)?$/i;
+ let capturing = false;
+ const out = [];
+ for (const line of lines) {
+ const m = re.exec(line.trim());
+ if (m) {
+ if (capturing) break;
+ if (m[1] === version) capturing = true;
+ continue;
+ }
+ if (capturing) out.push(line);
+ }
+ const body = out.join("\n").trim() || "See the assets below to download and install Ink Studio.";
+ const delimiter = "RELEASE_NOTES_EOF_" + Math.random().toString(36).slice(2);
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `body<<${delimiter}\n${body}\n${delimiter}\n`);
+ '
+
- name: Build and publish Tauri release
uses: tauri-apps/tauri-action@v0
env:
@@ -64,7 +91,7 @@ jobs:
with:
tagName: v__VERSION__
releaseName: 'Ink Studio v__VERSION__'
- releaseBody: 'See the assets below to download and install Ink Studio.'
+ releaseBody: ${{ steps.release_notes.outputs.body }}
releaseDraft: true
prerelease: false
includeUpdaterJson: true
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..7d58992
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,26 @@
+# Changelog
+
+## v1.0.1
+
+### New
+- Added Multi-layer Liquify
+- Added a geometric shapes tool
+- Added import/export brushes in the `.inkb` extension
+- Added straight ruler (with rotate + lock functions)
+- Added the drag and drop files function from File Explorer directly into the "Layers" section
+
+### Improvements
+- Adapted the entire 3D interface
+
+### Bug Fixes
+- Fixed a rendering bug that occurred when attempting to change a layer's name
+- Fixed 3D layer import crash
+- Fixed Sub Tool three-dot menu clipping
+- Fixed Eraser stylus tap tile shift / corruption
+- Fixed a rendering issue that occurred when attempting to use Transform tool
+- Fixed the issue with opening `.csp` files and splitting layers
+- Fixed an issue with artifacts when attempting to use Mesh Warp
+- Fixed most micro-freezes
+
+### Other
+- Removed the "Old Vintage" theme
diff --git a/package-lock.json b/package-lock.json
index 2e7b0b3..e7f0889 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "ink-studio",
- "version": "1.0.0",
+ "version": "1.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ink-studio",
- "version": "1.0.0",
+ "version": "1.0.1",
"license": "GPL-3.0",
"dependencies": {
"@tailwindcss/vite": "^4.3.3",
diff --git a/package.json b/package.json
index c82d777..e1401a9 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "ink-studio",
"private": true,
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Collaborative Drawing Studio",
"author": "Sora",
"license": "GPL-3.0",
diff --git a/site/app.js b/site/app.js
index 0a3acf8..3bbfb60 100644
--- a/site/app.js
+++ b/site/app.js
@@ -418,6 +418,81 @@
container.appendChild(list);
}
+ function appendInlineCodeText(parent, text) {
+ const parts = String(text || '').split(/(`[^`]+`)/g);
+ for (const part of parts) {
+ if (!part) continue;
+ if (part.length >= 2 && part.startsWith('`') && part.endsWith('`')) {
+ parent.appendChild(el('code', 'release-notes-code mono', part.slice(1, -1)));
+ } else {
+ parent.appendChild(document.createTextNode(part));
+ }
+ }
+ }
+
+ function renderReleaseNotesBody(body) {
+ const container = el('div', 'release-notes');
+ const lines = String(body || '').replace(/\r\n/g, '\n').split('\n');
+ const headingToneMap = {
+ new: 'new',
+ improvements: 'improvements',
+ 'bug fixes': 'fixes',
+ other: 'other',
+ };
+
+ let currentSection = null;
+ let currentList = null;
+
+ function ensureSection() {
+ if (!currentSection) {
+ currentSection = el('div', 'release-notes-section');
+ container.appendChild(currentSection);
+ }
+ return currentSection;
+ }
+
+ for (const rawLine of lines) {
+ const trimmed = rawLine.trim();
+ if (!trimmed) {
+ currentList = null;
+ continue;
+ }
+
+ const headingMatch = /^#{2,4}\s+(.+)$/.exec(trimmed);
+ if (headingMatch) {
+ const title = headingMatch[1].trim();
+ const tone = headingToneMap[title.toLowerCase()] || 'default';
+ currentSection = el('div', 'release-notes-section');
+ currentSection.appendChild(
+ el('div', `release-notes-heading release-notes-heading--${tone}`, title)
+ );
+ container.appendChild(currentSection);
+ currentList = null;
+ continue;
+ }
+
+ const bulletMatch = /^[-*]\s+(.+)$/.exec(trimmed);
+ if (bulletMatch) {
+ const sec = ensureSection();
+ if (!currentList) {
+ currentList = el('ul', 'release-notes-list');
+ sec.appendChild(currentList);
+ }
+ const li = el('li', '');
+ appendInlineCodeText(li, bulletMatch[1].trim());
+ currentList.appendChild(li);
+ continue;
+ }
+
+ currentList = null;
+ const p = el('p', 'release-notes-para');
+ appendInlineCodeText(p, trimmed);
+ ensureSection().appendChild(p);
+ }
+
+ return container;
+ }
+
function renderReleaseHistory() {
const host = document.getElementById('release-history');
if (!host) return;
@@ -456,8 +531,7 @@
card.appendChild(top);
if (rel.body) {
- const cleanBody = rel.body.length > 520 ? `${rel.body.slice(0, 520)}...` : rel.body;
- card.appendChild(el('p', 'release-notes', cleanBody));
+ card.appendChild(renderReleaseNotesBody(rel.body));
}
if (rel.assets.length > 0) {
diff --git a/site/styles.css b/site/styles.css
index 5630487..50b2dde 100644
--- a/site/styles.css
+++ b/site/styles.css
@@ -1241,11 +1241,71 @@ h3 {
.release-notes {
margin: 0;
+ padding: 10px 12px;
+ border-radius: 6px;
+ background: var(--bg-canvas);
+ border: 1px solid var(--border);
font-size: 12.5px;
- color: var(--text-muted);
- white-space: pre-line;
- max-height: 150px;
+ color: #c8c8c8;
+ max-height: 260px;
overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.release-notes-section {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.release-notes-heading {
+ font-size: 10.5px;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--text-primary);
+}
+
+.release-notes-heading--new {
+ color: var(--emerald);
+}
+
+.release-notes-heading--improvements {
+ color: #38bdf8;
+}
+
+.release-notes-heading--fixes {
+ color: #fbbf24;
+}
+
+.release-notes-heading--other {
+ color: #a0a0a0;
+}
+
+.release-notes-list {
+ margin: 0;
+ padding-left: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ line-height: 1.5;
+}
+
+.release-notes-para {
+ margin: 0;
+ line-height: 1.55;
+ color: var(--text-muted);
+}
+
+.release-notes-code {
+ font-size: 11px;
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: var(--bg-panel);
+ border: 1px solid var(--border-strong);
+ color: var(--text-primary);
}
.release-assets-inline {
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index e8602b0..967c463 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1954,7 +1954,7 @@ dependencies = [
[[package]]
name = "ink-studio"
-version = "1.0.0"
+version = "1.0.1"
dependencies = [
"axum",
"futures-util",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index e43be0b..a1a0f14 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "ink-studio"
-version = "1.0.0"
+version = "1.0.1"
description = "Collaborative Drawing Studio"
authors = ["Sora"]
license = "GPL-3.0"
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 26596a4..4790a59 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -92,7 +92,7 @@ fn sanitize_id(raw: &str) -> String {
const ALLOWED_DOCUMENT_EXTS: &[&str] = &[
"sora", "ink", "inkb", "psd", "psb", "clip", "csp", "sut", "png", "jpg", "jpeg", "webp", "bmp",
- "gif", "svg", "glb", "gltf", "obj",
+ "gif", "svg", "avif", "ico", "glb", "gltf", "obj",
];
const DELETE_ALLOWED_EXTS: &[&str] = &[
@@ -378,6 +378,19 @@ async fn read_file_from_disk(app: tauri::AppHandle, path: String) -> Result<Vec<
tokio::fs::read(&canonical).await.map_err(|e| e.to_string())
}
+#[tauri::command]
+async fn read_file_binary(
+ app: tauri::AppHandle,
+ path: String,
+) -> Result<tauri::ipc::Response, String> {
+ let allowed_dirs = get_allowed_base_dirs(&app);
+ let (canonical, _) = validate_read_path(&path, &allowed_dirs).await?;
+ let bytes = tokio::fs::read(&canonical)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(tauri::ipc::Response::new(bytes))
+}
+
#[tauri::command]
async fn recovery_init_session(
app: tauri::AppHandle,
@@ -555,7 +568,7 @@ pub fn run() {
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
if let Some(main_window) = app.get_webview_window("main") {
- let _ = main_window.set_fullscreen(true);
+ let _ = main_window.maximize();
}
}
Ok(())
@@ -580,6 +593,7 @@ pub fn run() {
clear_undo_tile_cache,
delete_file_from_disk,
read_file_from_disk,
+ read_file_binary,
recovery_init_session,
recovery_append_wal_entry,
recovery_checkpoint,
diff --git a/src-tauri/src/recovery.rs b/src-tauri/src/recovery.rs
index cd16fa9..d897538 100644
--- a/src-tauri/src/recovery.rs
+++ b/src-tauri/src/recovery.rs
@@ -222,19 +222,38 @@ pub async fn append_wal_entry(
if payload.len() > MAX_WAL_FRAME_PAYLOAD_BYTES {
return Err("WAL payload exceeds 64 MB safety ceiling".to_string());
}
+
+ // Build WAL frame and compute CRC32 outside WAL_IO_LOCK (and off Tokio worker threads for large payloads)
+ let frame = if payload.len() >= 262_144 {
+ let owned = payload.to_vec();
+ tokio::task::spawn_blocking(move || {
+ let mut frame = Vec::with_capacity(13 + owned.len());
+ frame.extend_from_slice(WAL_MAGIC);
+ frame.push(entry_type);
+ frame.extend_from_slice(&(owned.len() as u32).to_le_bytes());
+ let crc = compute_crc32(&owned);
+ frame.extend_from_slice(&crc.to_le_bytes());
+ frame.extend_from_slice(&owned);
+ frame
+ })
+ .await
+ .map_err(|e| format!("WAL framing worker failed: {}", e))?
+ } else {
+ let mut frame = Vec::with_capacity(13 + payload.len());
+ frame.extend_from_slice(WAL_MAGIC);
+ frame.push(entry_type);
+ frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
+ let crc = compute_crc32(payload);
+ frame.extend_from_slice(&crc.to_le_bytes());
+ frame.extend_from_slice(payload);
+ frame
+ };
+
let _wal_guard = WAL_IO_LOCK.lock().await;
let safe_id = sanitize_session_id(session_id);
let session_dir = get_recovery_root(app).join(&safe_id);
let wal_path = session_dir.join("journal.wal");
- let mut frame = Vec::with_capacity(13 + payload.len());
- frame.extend_from_slice(WAL_MAGIC);
- frame.push(entry_type);
- frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
- let crc = compute_crc32(payload);
- frame.extend_from_slice(&crc.to_le_bytes());
- frame.extend_from_slice(payload);
-
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
diff --git a/src-tauri/src/scratch_disk.rs b/src-tauri/src/scratch_disk.rs
index f841d10..54493ac 100644
--- a/src-tauri/src/scratch_disk.rs
+++ b/src-tauri/src/scratch_disk.rs
@@ -182,6 +182,13 @@ pub async fn init_scratch_disk(session_id: &str) -> Result<PathBuf, String> {
Ok(dir)
}
+struct CompressedTileWrite {
+ tile_x: i32,
+ tile_y: i32,
+ uncompressed_len: u32,
+ compressed: Vec<u8>,
+}
+
pub async fn write_tiles(
session_id: &str,
tiles: Vec<TileWritePayload>,
@@ -190,6 +197,33 @@ pub async fn write_tiles(
return Ok(0);
}
+ // Validate & LZ4-compress tiles off Tokio async worker threads and BEFORE acquiring SCRATCH_IO_LOCK
+ let compressed_by_layer = tokio::task::spawn_blocking(move || -> Result<(usize, HashMap<String, Vec<CompressedTileWrite>>), String> {
+ let mut grouped: HashMap<String, Vec<CompressedTileWrite>> = HashMap::new();
+ let count = tiles.len();
+ for tile in tiles {
+ if tile.data.len() > MAX_UNCOMPRESSED_TILE_BYTES {
+ return Err("Tile uncompressed payload exceeds 4 MB safety ceiling".to_string());
+ }
+ let uncompressed_len = tile.data.len() as u32;
+ let compressed = lz4_flex::compress_prepend_size(&tile.data);
+ grouped
+ .entry(tile.layer_id)
+ .or_default()
+ .push(CompressedTileWrite {
+ tile_x: tile.tile_x,
+ tile_y: tile.tile_y,
+ uncompressed_len,
+ compressed,
+ });
+ }
+ Ok((count, grouped))
+ })
+ .await
+ .map_err(|e| format!("Scratch disk LZ4 compression worker failed: {}", e))??;
+
+ let (count_written, tiles_by_layer) = compressed_by_layer;
+
let _io_guard = SCRATCH_IO_LOCK.lock().await;
let scratch_dir = get_scratch_root(session_id);
@@ -199,17 +233,6 @@ pub async fn write_tiles(
.map_err(|e| format!("Failed to create scratch dir: {}", e))?;
}
- // Group tiles by layer
- let mut tiles_by_layer: HashMap<String, Vec<TileWritePayload>> = HashMap::new();
- for tile in tiles {
- tiles_by_layer
- .entry(tile.layer_id.clone())
- .or_default()
- .push(tile);
- }
-
- let count_written = tiles_by_layer.values().map(|v| v.len()).sum();
-
for (layer_id, layer_tiles) in tiles_by_layer {
let safe_name = sanitize_layer_id(&layer_id);
let bucket_path = scratch_dir.join(format!("bucket_{}.bin", safe_name));
@@ -245,12 +268,7 @@ pub async fn write_tiles(
let mut new_entries: Vec<TileIndexEntry> = Vec::with_capacity(layer_tiles.len());
for tile in layer_tiles {
- if tile.data.len() > MAX_UNCOMPRESSED_TILE_BYTES {
- return Err("Tile uncompressed payload exceeds 4 MB safety ceiling".to_string());
- }
- let uncompressed_len = tile.data.len() as u32;
- let compressed = lz4_flex::compress_prepend_size(&tile.data);
- let compressed_len = compressed.len() as u32;
+ let compressed_len = tile.compressed.len() as u32;
let write_offset = if let Some(prev) = existing_layer_entries.get(&(tile.tile_x, tile.tile_y)) {
if compressed_len <= prev.compressed_len {
@@ -279,7 +297,7 @@ pub async fn write_tiles(
};
bucket_file
- .write_all(&compressed)
+ .write_all(&tile.compressed)
.await
.map_err(|e| format!("Failed to write to bucket file: {}", e))?;
@@ -288,7 +306,7 @@ pub async fn write_tiles(
tile_y: tile.tile_y,
offset: write_offset,
compressed_len,
- uncompressed_len,
+ uncompressed_len: tile.uncompressed_len,
});
}
@@ -454,6 +472,10 @@ pub async fn read_tile(
.await
.map_err(|e| format!("Failed to read compressed tile bytes: {}", e))?;
+ // Release file/IO mutex before CPU decompression
+ drop(bucket_file);
+ drop(_io_guard);
+
if compressed_buf.len() < 4 {
return Err("Corrupt LZ4 tile header".to_string());
}
@@ -462,9 +484,18 @@ pub async fn read_tile(
return Err("LZ4 declared uncompressed size exceeds 4 MB safety ceiling".to_string());
}
- // 3. Decompress using LZ4
- let decompressed = lz4_flex::decompress_size_prepended(&compressed_buf)
- .map_err(|e| format!("LZ4 decompression failed: {}", e))?;
+ // 3. Decompress using LZ4 (offload large tiles to blocking pool)
+ let decompressed = if declared_uncompressed >= 131_072 {
+ tokio::task::spawn_blocking(move || {
+ lz4_flex::decompress_size_prepended(&compressed_buf)
+ .map_err(|e| format!("LZ4 decompression failed: {}", e))
+ })
+ .await
+ .map_err(|e| format!("LZ4 decompression worker failed: {}", e))??
+ } else {
+ lz4_flex::decompress_size_prepended(&compressed_buf)
+ .map_err(|e| format!("LZ4 decompression failed: {}", e))?
+ };
Ok(decompressed)
}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 3acaa08..7429202 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Ink Studio",
- "version": "1.0.0",
+ "version": "1.0.1",
"identifier": "com.inkstudio.app",
"build": {
"beforeDevCommand": "npm run dev",
@@ -18,7 +18,7 @@
"height": 840,
"minWidth": 900,
"minHeight": 600,
- "fullscreen": true,
+ "maximized": true,
"decorations": false,
"additionalBrowserArgs": "--disable-features=StylusHandwritingWin,StylusHandwriting,msAbydos,msAbydosHandwritingAttr,msAbydosGestureSupport"
}
diff --git a/src/App.tsx b/src/App.tsx
index 562ff26..5ba8360 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -25,6 +25,7 @@ import { useLayerManager } from './hooks/useLayerManager';
import { useCollabSync } from './hooks/useCollabSync';
import { useTonalAndFilterActions } from './hooks/useTonalAndFilterActions';
import { useAppMenuSections } from './hooks/useAppMenuSections';
+import { useExternalFileDrop } from './hooks/useExternalFileDrop';
import {
autoActionStoreActions,
documentStoreActions,
@@ -54,6 +55,7 @@ export function App() {
const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);
const animationTimeline = useDocumentStore((s) => s.animationTimeline);
const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);
+ const appView = useUiStore((s) => s.appView);
// Delayed silent startup check for desktop Tauri updates (never blocks startup or crash recovery)
useEffect(() => {
@@ -1019,6 +1021,17 @@ export function App() {
]
);
+ const handleMarkActiveDocumentDirty = useCallback(() => {
+ documentStoreActions.markDocumentDirty(activeDocumentId, true);
+ }, [activeDocumentId]);
+
+ const externalFileDrop = useExternalFileDrop({
+ enabled: hasOpenDocument && appView === 'workspace',
+ importImageFileAsLayer: layerMgr.importImageFileAsLayer,
+ onMarkDirty: handleMarkActiveDocumentDirty,
+ showToast,
+ });
+
return (
<AppShell
fileInputRef={docLifecycle.fileInputRef}
@@ -1105,6 +1118,7 @@ export function App() {
onEditVectorLayer={shapeFillTools.openLayerForEditing}
onRasterizeLayer={handleRasterizeLayer}
onPlayAutoAction={handlePlayAutoAction}
+ externalFileDropTarget={externalFileDrop.activeDropTarget}
>
<DocumentLifecycleManager
layers={layerMgr.layers}
diff --git a/src/components/AboutModal.tsx b/src/components/AboutModal.tsx
index 0610bfd..c3feed2 100644
--- a/src/components/AboutModal.tsx
+++ b/src/components/AboutModal.tsx
@@ -19,6 +19,8 @@ import {
GITHUB_REPO_URL,
openExternalUrl,
} from '../utils/externalLinks';
+import { getChangelogForVersion } from '../utils/changelog';
+import { ChangelogBox } from './ChangelogBox';
import { DiscordIcon } from './DiscordIcon';
export interface AboutModalProps {
@@ -70,6 +72,7 @@ export const AboutModal: React.FC<AboutModalProps> = ({
}
const version = runtimeAppVersion || APP_VERSION;
+ const changelogEntry = getChangelogForVersion(version) ?? getChangelogForVersion();
const envLabel = isDesktopTauri ? 'Desktop' : 'Web';
const buildInfo = `Ink Studio v${version} (${envLabel})`;
@@ -102,7 +105,7 @@ export const AboutModal: React.FC<AboutModalProps> = ({
>
<div
onClick={(e) => e.stopPropagation()}
- className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-md flex flex-col overflow-hidden text-xs text-[#e5e5e5] border border-[#2c2c2c]"
+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-lg max-h-[85vh] flex flex-col overflow-hidden text-xs text-[#e5e5e5] border border-[#2c2c2c]"
>
{/* Header */}
<div className="h-10 px-4 flex items-center justify-between bg-[#161616] border-b border-[#2c2c2c] shrink-0">
@@ -124,7 +127,7 @@ export const AboutModal: React.FC<AboutModalProps> = ({
</div>
{/* Body */}
- <div className="p-5 space-y-4">
+ <div className="p-5 space-y-4 overflow-y-auto min-h-0">
{/* App identity */}
<div className="flex items-center gap-3.5">
<div className="w-12 h-12 rounded-lg bg-[#161616] border border-[#2c2c2c] flex items-center justify-center shrink-0">
@@ -209,6 +212,18 @@ export const AboutModal: React.FC<AboutModalProps> = ({
</div>
</div>
+ {/* What's New / Changelog */}
+ {changelogEntry && (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium text-[#e5e5e5]">
+ What&apos;s New in v{changelogEntry.version}
+ </span>
+ </div>
+ <ChangelogBox entry={changelogEntry} maxHeightClass="max-h-40" />
+ </div>
+ )}
+
{/* Links & actions */}
<div className="flex flex-wrap items-center gap-2">
<button
diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx
index 3ef77df..6010c6f 100644
--- a/src/components/AppShell.tsx
+++ b/src/components/AppShell.tsx
@@ -22,6 +22,7 @@ import {
import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';
import { TextPlacementSession, FrameDragPreview } from '../hooks/drawing/useShapeAndFillTools';
import { AutoAction } from '../utils/autoActionEngine';
+import { ExternalFileDropTarget } from '../utils/fileDropImport';
import {
documentStoreActions,
selectHasOpenDocument,
@@ -116,6 +117,7 @@ interface CanvasAreaContainerProps {
onAddAnimationCel: (frameIndex: number) => void;
onDeleteAnimationCel: (frameIndex: number) => void;
onSelectCelLayer: (layerId: string) => void;
+ isExternalFileDropActive?: boolean;
}
/**
@@ -284,6 +286,7 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((prop
onDeleteAnimationCel={props.onDeleteAnimationCel}
onSelectCelLayer={props.onSelectCelLayer}
softProofSettings={softProofSettings}
+ isExternalFileDropActive={props.isExternalFileDropActive}
/>
);
});
@@ -421,6 +424,7 @@ export interface AppShellProps {
onEditVectorLayer?: (layer: LayerItem) => void;
onRasterizeLayer?: (layerId: string) => void;
onPlayAutoAction?: (action: AutoAction) => void;
+ externalFileDropTarget?: ExternalFileDropTarget | null;
children?: React.ReactNode;
}
@@ -510,6 +514,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
onEditVectorLayer,
onRasterizeLayer,
onPlayAutoAction,
+ externalFileDropTarget = null,
children,
}) => {
const dimensions = useDocumentStore((s) => s.dimensions);
@@ -782,6 +787,14 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
onOpenLayerStylesModal: handleOpenLayerStylesModal,
onEditVectorLayer,
onRasterizeLayer,
+ externalFileDropIndicator:
+ externalFileDropTarget?.zone === 'layers'
+ ? {
+ active: true,
+ targetLayerId: externalFileDropTarget.targetLayerId,
+ position: externalFileDropTarget.position,
+ }
+ : null,
}),
[
hasOpenDocument,
@@ -841,6 +854,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
handleOpenLayerStylesModal,
onEditVectorLayer,
onRasterizeLayer,
+ externalFileDropTarget,
]
);
@@ -867,7 +881,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
<input
ref={fileInputRef}
type="file"
- accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.psd,.psb,.clip,.csp,.sora,.ink,.inkb,.sut"
+ accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.psd,.psb,.clip,.csp,.lip,.sora,.ink,.inkb,.sut"
onChange={handleFileInputChange}
className="hidden"
/>
@@ -964,7 +978,10 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
)}
<div className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden relative">
- <CanvasAreaContainer {...canvasProps} />
+ <CanvasAreaContainer
+ {...canvasProps}
+ isExternalFileDropActive={externalFileDropTarget?.zone === 'canvas'}
+ />
</div>
{showStatusBar && (
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index e689934..8c9cd1c 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -145,6 +145,7 @@ interface CanvasAreaProps {
activeLayerId?: string;
colorMode?: CanvasColorMode;
tileGrid?: SparseTileGrid;
+ isExternalFileDropActive?: boolean;
}
export function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
@@ -316,6 +317,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
activeLayerId,
colorMode = 'color',
tileGrid = globalTileGrid,
+ isExternalFileDropActive = false,
}) => {
const tileGridRef = useRef<SparseTileGrid>(tileGrid);
tileGridRef.current = tileGrid;
@@ -1268,6 +1270,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}
};
+ const handleCanvasPointerCancel = (e: React.PointerEvent<HTMLElement>) => {
+ handleCanvasPointerUp(e);
+ };
+
const handleContextMenu = (e: React.MouseEvent<HTMLElement>) => {
const modSettings = useUiStore.getState().appSettings.modifierKeys;
if (modSettings.rightClick !== 'none' || modSettings.stylusButton1 !== 'none') {
@@ -1342,6 +1348,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
return (
<main
ref={viewportRef}
+ data-drop-zone="canvas"
onPointerDown={handleViewportPointerDown}
onContextMenu={handleContextMenu}
className="flex-1 bg-[#161616] overflow-hidden relative select-none canvas-viewport"
@@ -1673,6 +1680,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onPointerDown={handleCanvasPointerDown}
onPointerMove={handleCanvasPointerMove}
onPointerUp={handleCanvasPointerUp}
+ onPointerCancel={handleCanvasPointerCancel}
+ onLostPointerCapture={handleCanvasPointerCancel}
onPointerEnter={onPointerEnter}
onPointerLeave={onPointerLeave}
onContextMenu={handleContextMenu}
@@ -2058,6 +2067,17 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onSelectCelLayer={onSelectCelLayer}
/>
)}
+
+ {isExternalFileDropActive && (
+ <div
+ data-testid="canvas-file-drop-overlay"
+ className="pointer-events-none absolute inset-2 z-50 rounded-md border-2 border-dashed border-[var(--accent)] bg-[var(--accent)]/8 flex items-center justify-center"
+ >
+ <div className="px-3.5 py-2 rounded-md bg-[#161616]/95 border border-[var(--accent)]/60 text-xs font-medium text-[#f5f5f5] shadow-xl">
+ Drop image to import as layer
+ </div>
+ </div>
+ )}
</main>
);
});
diff --git a/src/components/ChangelogBox.tsx b/src/components/ChangelogBox.tsx
new file mode 100644
index 0000000..2b453ce
--- /dev/null
+++ b/src/components/ChangelogBox.tsx
@@ -0,0 +1,74 @@
+import React from 'react';
+import { ChangelogEntry } from '../utils/changelog';
+
+export interface ChangelogBoxProps {
+ entry: ChangelogEntry;
+ maxHeightClass?: string;
+}
+
+const SECTION_BADGE_CLASSES: Record<string, string> = {
+ new: 'text-emerald-400',
+ improvements: 'text-sky-400',
+ 'bug fixes': 'text-amber-400',
+ other: 'text-[#a0a0a0]',
+};
+
+const INLINE_CODE_RE = /(`[^`]+`)/g;
+
+/**
+ * Safely render inline backtick code spans (e.g. `.inkb`, `.csp`) as styled <code> tags
+ * without using dangerouslySetInnerHTML.
+ */
+function renderInlineCode(text: string): React.ReactNode {
+ const parts = text.split(INLINE_CODE_RE);
+ if (parts.length === 1) {
+ return text;
+ }
+
+ return parts.map((part, idx) => {
+ if (part.length >= 2 && part.startsWith('`') && part.endsWith('`')) {
+ return (
+ <code
+ key={idx}
+ className="font-mono text-[10px] px-1 py-0.5 rounded bg-[#242424] border border-[#323232] text-[#e5e5e5]"
+ >
+ {part.slice(1, -1)}
+ </code>
+ );
+ }
+ return <React.Fragment key={idx}>{part}</React.Fragment>;
+ });
+}
+
+/**
+ * Scrollable changelog card rendering categorized release notes from CHANGELOG.md.
+ */
+export const ChangelogBox: React.FC<ChangelogBoxProps> = ({
+ entry,
+ maxHeightClass = 'max-h-44',
+}) => {
+ return (
+ <div
+ className={`bg-[#161616] rounded border border-[#2c2c2c] p-3 ${maxHeightClass} overflow-y-auto space-y-3 select-text`}
+ >
+ {entry.sections.map((section, sectionIdx) => {
+ const titleColor =
+ SECTION_BADGE_CLASSES[section.title.toLowerCase()] ?? 'text-[#d4d4d4]';
+ return (
+ <div key={`${section.title || 'items'}-${sectionIdx}`} className="space-y-1">
+ {section.title && (
+ <div className={`text-[10px] font-semibold uppercase tracking-wider ${titleColor}`}>
+ {section.title}
+ </div>
+ )}
+ <ul className="space-y-1 pl-3.5 list-disc text-[11px] text-[#c8c8c8] leading-relaxed">
+ {section.items.map((item, idx) => (
+ <li key={`${section.title}-${idx}`}>{renderInlineCode(item)}</li>
+ ))}
+ </ul>
+ </div>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index 6d03e0b..2d13723 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -339,13 +339,14 @@ export function useDocumentLifecycle({
resetZoomAndCenter(doc.dimensions);
resetHistory(newDocId);
+ const topEditableLayer = doc.layers.find((l) => l.type === 'raster');
const newDoc: DocumentTab = {
id: newDocId,
name: doc.name,
dimensions: doc.dimensions,
colorMode: doc.colorMode,
layers: doc.layers,
- activeLayerId: doc.layers[0]?.id || 'layer-1',
+ activeLayerId: topEditableLayer?.id || doc.layers[0]?.id || 'layer-1',
perspectiveRuler: doc.perspectiveRuler ?? null,
};
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index 954a7a5..c7bdb2b 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -174,6 +174,11 @@ export interface RightSidebarProps {
onOpenFile?: () => void;
hideColorPanel?: boolean;
dockedMode?: 'full' | 'layers' | 'history';
+ externalFileDropIndicator?: {
+ active: boolean;
+ targetLayerId?: string;
+ position?: 'above' | 'below' | 'inside';
+ } | null;
}
const ClipToLayerIcon: React.FC<{ className?: string }> = ({ className = 'w-3 h-3' }) => (
@@ -261,6 +266,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onOpenFile,
hideColorPanel = false,
dockedMode = 'full',
+ externalFileDropIndicator = null,
}) => {
const [bottomTab, setBottomTab] = useState<'layers' | 'history'>(
dockedMode === 'history' ? 'history' : 'layers'
@@ -532,7 +538,10 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
)}
{/* 2. Spacious Layers / History Panel */}
- <section className={`flex-1 ${isDockedSingle ? 'min-h-0' : 'min-h-[70%]'} flex flex-col bg-[#202020] overflow-hidden`}>
+ <section
+ data-drop-zone={effectiveTab === 'layers' && hasOpenDocument ? 'layers' : undefined}
+ className={`relative flex-1 ${isDockedSingle ? 'min-h-0' : 'min-h-[70%]'} flex flex-col bg-[#202020] overflow-hidden`}
+ >
{/* Header Bar: Layers / History Switch + Quick Layer Actions */}
<div className="h-7 px-1.5 flex items-center justify-between shrink-0">
{isDockedSingle ? (
@@ -816,9 +825,18 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const isFrameFolder = layer.type === 'frame-folder';
const isInsideFolder = Boolean(layer.parentId);
const isTarget = dropIndicator?.id === layer.id;
- const isDropInside = isTarget && dropIndicator.position === 'inside';
- const isDropAbove = isTarget && dropIndicator.position === 'above';
- const isDropBelow = isTarget && dropIndicator.position === 'below';
+ const isExternalTarget =
+ Boolean(externalFileDropIndicator?.active) &&
+ externalFileDropIndicator?.targetLayerId === layer.id;
+ const isDropInside =
+ (isTarget && dropIndicator.position === 'inside') ||
+ (isExternalTarget && externalFileDropIndicator?.position === 'inside');
+ const isDropAbove =
+ (isTarget && dropIndicator.position === 'above') ||
+ (isExternalTarget && externalFileDropIndicator?.position === 'above');
+ const isDropBelow =
+ (isTarget && dropIndicator.position === 'below') ||
+ (isExternalTarget && externalFileDropIndicator?.position === 'below');
const isBeingDragged =
draggedLayerId === layer.id ||
(draggedLayerId !== null &&
@@ -835,6 +853,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
<div
key={layer.id}
data-layer-id={layer.id}
+ data-layer-folder={isFolder ? 'true' : 'false'}
onPointerDown={(e) => handleLayerPointerDown(e, layer.id)}
onClick={(e) => {
if (justDraggedRef.current) return;
@@ -1439,6 +1458,17 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
)}
</div>
)}
+
+ {effectiveTab === 'layers' && hasOpenDocument && externalFileDropIndicator?.active && (
+ <div
+ data-testid="layers-file-drop-overlay"
+ className="pointer-events-none absolute inset-0 z-40 rounded-xs border-2 border-dashed border-[var(--accent)] bg-[var(--accent)]/8 flex items-end justify-center p-2"
+ >
+ <span className="px-2 py-0.5 rounded bg-[#161616]/95 border border-[var(--accent)]/60 text-[10px] font-medium text-[#f5f5f5] shadow-md">
+ Drop image to import layer
+ </span>
+ </div>
+ )}
</section>
{/* Right-Click Context Menu */}
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 5586c15..af8055a 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -20,6 +20,8 @@ import {
import { isTauriEnvironment } from '../hooks/useMultiplayer';
import { updaterService } from '../services/updaterService';
import { useUpdaterStore } from '../stores/useUpdaterStore';
+import { getChangelogForVersion } from '../utils/changelog';
+import { ChangelogBox } from './ChangelogBox';
import {
AppSettings,
DEFAULT_APP_SETTINGS,
@@ -948,6 +950,23 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
Collaborative Drawing Studio supporting layered PSD/CSP workflows, GPU tile compositing, stylus pressure dynamics, vector inking, and real-time multiplayer drawing.
</p>
+ {(() => {
+ const activeVer = runtimeAppVersion || APP_VERSION;
+ const changelogEntry =
+ getChangelogForVersion(activeVer) ?? getChangelogForVersion();
+ if (!changelogEntry) return null;
+ return (
+ <section className="space-y-2 pt-2 border-t border-[#2c2c2c]">
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">
+ What&apos;s New in v{changelogEntry.version}
+ </h3>
+ </div>
+ <ChangelogBox entry={changelogEntry} maxHeightClass="max-h-48" />
+ </section>
+ );
+ })()}
+
{isDesktopTauri && (
<section className="space-y-2.5 pt-2 border-t border-[#2c2c2c]">
<div>
diff --git a/src/components/StraightRulerOverlay.tsx b/src/components/StraightRulerOverlay.tsx
index 0ae8854..2eb7aeb 100644
--- a/src/components/StraightRulerOverlay.tsx
+++ b/src/components/StraightRulerOverlay.tsx
@@ -1,4 +1,4 @@
-import React, { useRef, useEffect, useState, useCallback } from 'react';
+import React, { useRef, useEffect, useLayoutEffect, useState, useCallback } from 'react';
import { Lock, Unlock, Magnet, Crosshair, X, Move, RotateCw } from 'lucide-react';
import { StraightRuler } from '../types/perspective';
import { CanvasDimensions } from '../types/editor';
@@ -47,6 +47,8 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
const [dragMode, setDragMode] = useState<'move' | 'rotate-left' | 'rotate-right' | null>(null);
const dragMetaRef = useRef<{
+ pointerId: number | null;
+ capturedEl: HTMLElement | null;
startDocX: number;
startDocY: number;
initialRulerX: number;
@@ -54,6 +56,8 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
initialAngle: number;
startPointerAngle: number;
}>({
+ pointerId: null,
+ capturedEl: null,
startDocX: 0,
startDocY: 0,
initialRulerX: 0,
@@ -253,7 +257,7 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
ctx.restore();
}, [getLiveCamera, viewportRef]);
- useEffect(() => {
+ useLayoutEffect(() => {
render();
}, [render, ruler, dimensions, pan, zoom, rotation, flipX, flipY]);
@@ -279,13 +283,17 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
const startHandleDrag = (
mode: 'move' | 'rotate-left' | 'rotate-right',
- e: React.PointerEvent
+ e: React.PointerEvent<HTMLDivElement>
) => {
- if (ruler.locked) return;
+ if (ruler.locked || e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
const vp = viewportRef.current;
if (!vp) return;
+ const targetEl = e.currentTarget;
+ try {
+ targetEl.setPointerCapture(e.pointerId);
+ } catch {}
const vRect = vp.getBoundingClientRect();
const cam = getLiveCamera();
const docPt = screenToCanvas(
@@ -302,6 +310,8 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
const startPointerAngle =
(Math.atan2(docPt.y - ruler.y, docPt.x - ruler.x) * 180) / Math.PI;
dragMetaRef.current = {
+ pointerId: e.pointerId,
+ capturedEl: targetEl,
startDocX: docPt.x,
startDocY: docPt.y,
initialRulerX: ruler.x,
@@ -315,6 +325,8 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
useEffect(() => {
if (!dragMode) return;
const handleMove = (e: PointerEvent) => {
+ const m = dragMetaRef.current;
+ if (m.pointerId !== null && e.pointerId !== m.pointerId) return;
const vp = viewportRef.current;
if (!vp) return;
const p = propsRef.current;
@@ -332,7 +344,6 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
cam.flipX,
cam.flipY
);
- const m = dragMetaRef.current;
if (dragMode === 'move') {
p.onUpdateRuler({
@@ -341,8 +352,10 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
y: m.initialRulerY + (docPt.y - m.startDocY),
});
} else {
- const curPointerAngle =
- (Math.atan2(docPt.y - p.ruler.y, docPt.x - p.ruler.x) * 180) / Math.PI;
+ const dx = docPt.x - p.ruler.x;
+ const dy = docPt.y - p.ruler.y;
+ if (Math.hypot(dx, dy) < 1e-3) return;
+ const curPointerAngle = (Math.atan2(dy, dx) * 180) / Math.PI;
const delta = curPointerAngle - m.startPointerAngle;
const rawNext = m.initialAngle + delta;
const nextAngle = e.shiftKey
@@ -355,7 +368,24 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
}
};
- const handleUp = () => {
+ const releaseCapture = () => {
+ const m = dragMetaRef.current;
+ if (m.capturedEl && m.pointerId !== null) {
+ try {
+ if (m.capturedEl.hasPointerCapture(m.pointerId)) {
+ m.capturedEl.releasePointerCapture(m.pointerId);
+ }
+ } catch {}
+ }
+ m.capturedEl = null;
+ m.pointerId = null;
+ };
+
+ const handleUp = (e: PointerEvent) => {
+ if (dragMetaRef.current.pointerId !== null && e.pointerId !== dragMetaRef.current.pointerId) {
+ return;
+ }
+ releaseCapture();
setDragMode(null);
};
@@ -366,6 +396,7 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
window.removeEventListener('pointermove', handleMove);
window.removeEventListener('pointerup', handleUp);
window.removeEventListener('pointercancel', handleUp);
+ releaseCapture();
};
}, [dragMode, getLiveCamera, viewportRef]);
@@ -420,9 +451,11 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
data-testid="straight-ruler-move-handle"
onPointerDown={(e) => startHandleDrag('move', e)}
title="Drag to move ruler"
- className="absolute top-0 left-0 w-7 h-7 rounded-full bg-[#1a1a1a]/90 border-2 border-sky-400 text-sky-300 shadow-lg flex items-center justify-center cursor-move pointer-events-auto hover:scale-110 transition-transform"
+ className="absolute top-0 left-0 pointer-events-auto cursor-move group"
>
- <Move className="w-3.5 h-3.5" />
+ <div className="w-7 h-7 rounded-full bg-[#1a1a1a]/90 border-2 border-sky-400 text-sky-300 shadow-lg flex items-center justify-center transition-transform duration-100 group-hover:scale-110 group-active:scale-95">
+ <Move className="w-3.5 h-3.5" />
+ </div>
</div>
<div
@@ -430,9 +463,11 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
data-testid="straight-ruler-rotate-left"
onPointerDown={(e) => startHandleDrag('rotate-left', e)}
title="Drag to rotate ruler (hold Shift for 15° snap)"
- className="absolute top-0 left-0 w-6 h-6 rounded-full bg-[#1a1a1a]/90 border-2 border-sky-400 text-sky-300 shadow-lg flex items-center justify-center cursor-grab active:cursor-grabbing pointer-events-auto hover:scale-110 transition-transform"
+ className="absolute top-0 left-0 pointer-events-auto cursor-grab active:cursor-grabbing group"
>
- <RotateCw className="w-3 h-3" />
+ <div className="w-6 h-6 rounded-full bg-[#1a1a1a]/90 border-2 border-sky-400 text-sky-300 shadow-lg flex items-center justify-center transition-transform duration-100 group-hover:scale-110 group-active:scale-95">
+ <RotateCw className="w-3 h-3" />
+ </div>
</div>
<div
@@ -440,9 +475,11 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
data-testid="straight-ruler-rotate-right"
onPointerDown={(e) => startHandleDrag('rotate-right', e)}
title="Drag to rotate ruler (hold Shift for 15° snap)"
- className="absolute top-0 left-0 w-6 h-6 rounded-full bg-[#1a1a1a]/90 border-2 border-sky-400 text-sky-300 shadow-lg flex items-center justify-center cursor-grab active:cursor-grabbing pointer-events-auto hover:scale-110 transition-transform"
+ className="absolute top-0 left-0 pointer-events-auto cursor-grab active:cursor-grabbing group"
>
- <RotateCw className="w-3 h-3" />
+ <div className="w-6 h-6 rounded-full bg-[#1a1a1a]/90 border-2 border-sky-400 text-sky-300 shadow-lg flex items-center justify-center transition-transform duration-100 group-hover:scale-110 group-active:scale-95">
+ <RotateCw className="w-3 h-3" />
+ </div>
</div>
</>
)}
diff --git a/src/components/UpdateModal.tsx b/src/components/UpdateModal.tsx
index 67866ec..2fad5eb 100644
--- a/src/components/UpdateModal.tsx
+++ b/src/components/UpdateModal.tsx
@@ -13,6 +13,11 @@ import { isTauriEnvironment } from '../hooks/useMultiplayer';
import { updaterService } from '../services/updaterService';
import { useDocumentStore } from '../stores/useDocumentStore';
import { useUpdaterStore } from '../stores/useUpdaterStore';
+import {
+ hasStructuredChangelogMarkdown,
+ parseChangelogSections,
+} from '../utils/changelog';
+import { ChangelogBox } from './ChangelogBox';
export interface UpdateModalProps {
hasActiveCollabSession: boolean;
@@ -226,14 +231,34 @@ export const UpdateModal: React.FC<UpdateModalProps> = ({
)}
</div>
- {/* Scrollable plain-text release notes */}
+ {/* Scrollable release notes (structured Markdown or plain-text fallback) */}
<div className="space-y-1.5">
<div className="text-[11px] font-medium text-[#e5e5e5]">Release Notes</div>
- <div className="bg-[#161616] rounded p-3 max-h-44 overflow-y-auto border border-[#2c2c2c] select-text">
- <pre className="whitespace-pre-wrap break-words font-sans text-[11px] leading-relaxed text-[#e5e5e5]/90">
- {releaseNotes?.trim() || 'Bug fixes and performance improvements.'}
- </pre>
- </div>
+ {(() => {
+ const rawNotes = releaseNotes?.trim() || '';
+ if (rawNotes && hasStructuredChangelogMarkdown(rawNotes)) {
+ const sections = parseChangelogSections(rawNotes);
+ if (sections.length > 0) {
+ return (
+ <ChangelogBox
+ entry={{
+ version: availableVersion || '',
+ sections,
+ rawBody: rawNotes,
+ }}
+ maxHeightClass="max-h-48"
+ />
+ );
+ }
+ }
+ return (
+ <div className="bg-[#161616] rounded p-3 max-h-44 overflow-y-auto border border-[#2c2c2c] select-text">
+ <pre className="whitespace-pre-wrap break-words font-sans text-[11px] leading-relaxed text-[#e5e5e5]/90">
+ {rawNotes || 'Bug fixes and performance improvements.'}
+ </pre>
+ </div>
+ );
+ })()}
</div>
{/* Download progress bar */}
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index 77b3232..3fe0a29 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -50,6 +50,7 @@ import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../types/per
import { PerspectiveSnapSession } from '../../utils/perspectiveSnapping';
import { StraightRulerSnapSession } from '../../utils/straightRulerMath';
import { useToolStore, useUiStore } from '../../stores';
+import { recoveryService } from '../../services/recoveryService';
import { evaluateGlobalPressureCurve, isLinearPressureCurve } from '../../utils/pressureCurve';
import {
DraftCanvasElement,
@@ -338,6 +339,7 @@ export function useBrushStrokeSession({
if (drawRafIdRef.current !== null) {
cancelAnimationFrame(drawRafIdRef.current);
}
+ recoveryService.setDrawingActive(false);
};
}, [viewportRef, disabled, activeSessionId]);
@@ -400,7 +402,15 @@ export function useBrushStrokeSession({
}
strokePipelineRef.current.abortStroke();
frameGpuDabsRef.current.length = 0;
+ if (activePointerIdRef.current !== null && interactionRef.current) {
+ try {
+ interactionRef.current.releasePointerCapture(activePointerIdRef.current);
+ } catch {
+ // Ignore release errors when capture already ended
+ }
+ }
isDrawingRef.current = false;
+ recoveryService.setDrawingActive(false);
activePointerIdRef.current = null;
allStrokePointsRef.current = [];
stabilizedPointRef.current = null;
@@ -1430,13 +1440,16 @@ export function useBrushStrokeSession({
if (isDrawingRef.current) {
abortActiveStroke();
}
- flushPendingHistoryTasks();
const dims = dimensionsRef.current;
const currentLayerIdCheck = activeLayerIdRef.current;
if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
const canvas = getCachedLayerCanvas();
+ const activeLayerPre = (layersRef.current || []).find((l) => l.id === currentLayerIdCheck);
+ if (isMaskModeRef.current || canvas !== null || Boolean(activeLayerPre?.toneEnabled)) {
+ flushPendingHistoryTasks();
+ }
if (isMaskModeRef.current && !canvas) return;
if (viewportRef.current) {
@@ -1566,6 +1579,7 @@ export function useBrushStrokeSession({
}
activePointerIdRef.current = e.pointerId;
isDrawingRef.current = true;
+ recoveryService.setDrawingActive(true);
const firstEvent = e.nativeEvent;
const rawStartPoint = getCanvasPoint(firstEvent);
@@ -3222,6 +3236,7 @@ export function useBrushStrokeSession({
strokePipelineRef.current.abortStroke();
frameGpuDabsRef.current.length = 0;
isDrawingRef.current = false;
+ recoveryService.setDrawingActive(false);
activePointerIdRef.current = null;
allStrokePointsRef.current = [];
stabilizedPointRef.current = null;
diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.ts
index d169ceb..d2a974f 100644
--- a/src/hooks/drawing/useDrawingHistory.ts
+++ b/src/hooks/drawing/useDrawingHistory.ts
@@ -361,7 +361,7 @@ export function useDrawingHistory({
if (win?.requestIdleCallback) {
idleCallbackIdRef.current = win.requestIdleCallback(runTasks, { timeout: 1200 });
} else {
- idleCallbackIdRef.current = setTimeout(runTasks, 64);
+ idleCallbackIdRef.current = setTimeout(runTasks, 32);
}
};
const runTasks = () => {
@@ -370,13 +370,27 @@ export function useDrawingHistory({
scheduleRun();
return;
}
- const tasks = pendingHistoryTasksRef.current.splice(0);
- for (const t of tasks) {
+ const sliceBudgetMs = 6;
+ const start = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ while (pendingHistoryTasksRef.current.length > 0) {
+ if (isDrawingRef.current) {
+ break;
+ }
+ const nextTask = pendingHistoryTasksRef.current.shift();
+ if (!nextTask) break;
try {
- t();
+ nextTask();
} catch (err) {
console.warn('[History] Error running idle history task:', err);
}
+ const elapsed =
+ (typeof performance !== 'undefined' ? performance.now() : Date.now()) - start;
+ if (elapsed >= sliceBudgetMs && pendingHistoryTasksRef.current.length > 0) {
+ break;
+ }
+ }
+ if (pendingHistoryTasksRef.current.length > 0) {
+ scheduleRun();
}
};
scheduleRun();
diff --git a/src/hooks/useExternalFileDrop.ts b/src/hooks/useExternalFileDrop.ts
new file mode 100644
index 0000000..f42836f
--- /dev/null
+++ b/src/hooks/useExternalFileDrop.ts
@@ -0,0 +1,330 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import {
+ ExternalFileDropTarget,
+ LayerInsertTarget,
+ MAX_DROPPED_IMAGE_FILES,
+ filterDroppedImageFiles,
+ filterDroppedImagePaths,
+ isExternalFileDrag,
+ isSameDropTarget,
+ isSupportedImageExtension,
+ readTauriDroppedImageFile,
+ resolveDropZoneAtPoint,
+ resolveDropZoneFromElement,
+} from '../utils/fileDropImport';
+
+interface TauriWindow extends Window {
+ __TAURI_INTERNALS__?: unknown;
+}
+
+export interface UseExternalFileDropOptions {
+ enabled: boolean;
+ importImageFileAsLayer: (
+ file: File,
+ insertTarget?: LayerInsertTarget
+ ) => Promise<{ id: string; name: string }>;
+ onMarkDirty: () => void;
+ showToast: (message: string) => void;
+}
+
+export interface UseExternalFileDropResult {
+ activeDropTarget: ExternalFileDropTarget | null;
+ importDroppedFiles: (files: Iterable<File>, target?: LayerInsertTarget) => Promise<number>;
+}
+
+export function useExternalFileDrop({
+ enabled,
+ importImageFileAsLayer,
+ onMarkDirty,
+ showToast,
+}: UseExternalFileDropOptions): UseExternalFileDropResult {
+ const [activeDropTarget, setActiveDropTarget] = useState<ExternalFileDropTarget | null>(null);
+ const activeDropTargetRef = useRef<ExternalFileDropTarget | null>(null);
+ const tauriDragHasImagesRef = useRef<boolean>(true);
+
+ const updateDropTarget = useCallback((next: ExternalFileDropTarget | null) => {
+ if (isSameDropTarget(activeDropTargetRef.current, next)) return;
+ activeDropTargetRef.current = next;
+ setActiveDropTarget(next);
+ }, []);
+
+ const importDroppedFiles = useCallback(
+ async (rawFiles: Iterable<File>, target?: LayerInsertTarget): Promise<number> => {
+ const { accepted, rejectedCount, oversizedCount, truncatedCount } =
+ filterDroppedImageFiles(rawFiles);
+
+ if (accepted.length === 0) {
+ if (oversizedCount > 0) {
+ showToast('Image exceeds 100 MB limit.');
+ } else if (rejectedCount > 0) {
+ showToast('Unsupported file type. Drop PNG, JPG, WebP, GIF, BMP, or SVG images.');
+ }
+ return 0;
+ }
+
+ const importedNames: string[] = [];
+ let failedCount = 0;
+
+ // Import in reverse order so the first dropped file lands at the top and stays active.
+ let currentTarget: LayerInsertTarget | undefined = target;
+ for (let i = accepted.length - 1; i >= 0; i--) {
+ const file = accepted[i];
+ try {
+ const created = await importImageFileAsLayer(file, currentTarget);
+ importedNames.unshift(created.name);
+ currentTarget = { targetLayerId: created.id, position: 'above' };
+ } catch (err) {
+ failedCount++;
+ console.warn('Dropped image import failed:', err);
+ }
+ }
+
+ if (importedNames.length > 0) {
+ onMarkDirty();
+ }
+
+ const skippedTotal = rejectedCount + oversizedCount + failedCount;
+ if (importedNames.length === 1 && skippedTotal === 0 && truncatedCount === 0) {
+ showToast(`Imported "${importedNames[0]}" as layer`);
+ } else if (importedNames.length > 0) {
+ const notes: string[] = [];
+ if (skippedTotal > 0) notes.push(`${skippedTotal} skipped`);
+ if (truncatedCount > 0) notes.push(`max ${MAX_DROPPED_IMAGE_FILES} per drop`);
+ const suffix = notes.length > 0 ? ` (${notes.join(', ')})` : '';
+ showToast(
+ `Imported ${importedNames.length} image${importedNames.length === 1 ? '' : 's'} as layer${
+ importedNames.length === 1 ? '' : 's'
+ }${suffix}`
+ );
+ } else {
+ showToast('Failed to import dropped image.');
+ }
+
+ return importedNames.length;
+ },
+ [importImageFileAsLayer, onMarkDirty, showToast]
+ );
+
+ const importDroppedPaths = useCallback(
+ async (paths: readonly string[], target?: LayerInsertTarget): Promise<number> => {
+ const { accepted, rejectedCount, truncatedCount } = filterDroppedImagePaths(paths);
+ if (accepted.length === 0) {
+ if (rejectedCount > 0) {
+ showToast('Unsupported file type. Drop PNG, JPG, WebP, GIF, BMP, or SVG images.');
+ }
+ return 0;
+ }
+
+ const settled = await Promise.allSettled(
+ accepted.map((p) => readTauriDroppedImageFile(p))
+ );
+
+ const files: File[] = [];
+ let readFailedCount = 0;
+ for (const result of settled) {
+ if (result.status === 'fulfilled') {
+ files.push(result.value);
+ } else {
+ readFailedCount++;
+ console.warn('Failed to read dropped file from disk:', result.reason);
+ }
+ }
+
+ if (files.length === 0) {
+ showToast('Failed to read dropped image file.');
+ return 0;
+ }
+
+ const importedNames: string[] = [];
+ let decodeFailedCount = 0;
+ let currentTarget: LayerInsertTarget | undefined = target;
+ for (let i = files.length - 1; i >= 0; i--) {
+ try {
+ const created = await importImageFileAsLayer(files[i], currentTarget);
+ importedNames.unshift(created.name);
+ currentTarget = { targetLayerId: created.id, position: 'above' };
+ } catch (err) {
+ decodeFailedCount++;
+ console.warn('Failed to decode dropped image:', err);
+ }
+ }
+
+ if (importedNames.length > 0) {
+ onMarkDirty();
+ }
+
+ const skippedTotal = rejectedCount + readFailedCount + decodeFailedCount;
+ if (importedNames.length === 1 && skippedTotal === 0 && truncatedCount === 0) {
+ showToast(`Imported "${importedNames[0]}" as layer`);
+ } else if (importedNames.length > 0) {
+ const notes: string[] = [];
+ if (skippedTotal > 0) notes.push(`${skippedTotal} skipped`);
+ if (truncatedCount > 0) notes.push(`max ${MAX_DROPPED_IMAGE_FILES} per drop`);
+ const suffix = notes.length > 0 ? ` (${notes.join(', ')})` : '';
+ showToast(
+ `Imported ${importedNames.length} image${importedNames.length === 1 ? '' : 's'} as layer${
+ importedNames.length === 1 ? '' : 's'
+ }${suffix}`
+ );
+ } else {
+ showToast('Failed to import dropped image.');
+ }
+
+ return importedNames.length;
+ },
+ [importImageFileAsLayer, onMarkDirty, showToast]
+ );
+
+ // Clear highlight whenever feature disables (e.g., switching to Home view or closing doc)
+ useEffect(() => {
+ if (!enabled) {
+ updateDropTarget(null);
+ }
+ }, [enabled, updateDropTarget]);
+
+ // 1. HTML5 Drag-and-Drop listener (Browser / Web / Dev / Tests)
+ useEffect(() => {
+ if (!enabled || typeof window === 'undefined') return;
+
+ const resolveFromDragEvent = (e: DragEvent): ExternalFileDropTarget | null => {
+ const targetEl = e.target instanceof Element ? e.target : null;
+ return (
+ resolveDropZoneAtPoint(e.clientX, e.clientY) ??
+ resolveDropZoneFromElement(targetEl, e.clientY)
+ );
+ };
+
+ 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"]')) {
+ updateDropTarget(null);
+ return;
+ }
+
+ e.preventDefault();
+ const resolved = resolveFromDragEvent(e);
+ if (e.dataTransfer) {
+ e.dataTransfer.dropEffect = resolved ? 'copy' : 'none';
+ }
+ updateDropTarget(resolved);
+ };
+
+ const handleDragLeave = (e: DragEvent) => {
+ if (!activeDropTargetRef.current) return;
+ if (
+ e.relatedTarget === null ||
+ e.clientX <= 0 ||
+ e.clientY <= 0 ||
+ e.clientX >= window.innerWidth ||
+ e.clientY >= window.innerHeight
+ ) {
+ updateDropTarget(null);
+ }
+ };
+
+ 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"]')) {
+ updateDropTarget(null);
+ return;
+ }
+
+ e.preventDefault();
+ const resolved = resolveFromDragEvent(e) ?? activeDropTargetRef.current;
+ updateDropTarget(null);
+
+ if (!resolved) return;
+ const files = e.dataTransfer?.files;
+ if (!files || files.length === 0) return;
+
+ void importDroppedFiles(Array.from(files), {
+ targetLayerId: resolved.targetLayerId,
+ position: resolved.position,
+ });
+ };
+
+ window.addEventListener('dragover', handleDragOver);
+ window.addEventListener('dragleave', handleDragLeave);
+ window.addEventListener('drop', handleDrop);
+ return () => {
+ window.removeEventListener('dragover', handleDragOver);
+ window.removeEventListener('dragleave', handleDragLeave);
+ window.removeEventListener('drop', handleDrop);
+ };
+ }, [enabled, importDroppedFiles, updateDropTarget]);
+
+ // 2. Native Tauri v2 OS Drag-and-Drop listener (Desktop WebView2 / WKWebView / WebKitGTK)
+ useEffect(() => {
+ if (!enabled || typeof window === 'undefined') return;
+ if (!(window as TauriWindow).__TAURI_INTERNALS__) return;
+
+ let cancelled = false;
+ let unlisten: (() => void) | null = null;
+
+ const toLogicalPoint = (pos: { x: number; y: number }) => {
+ const dpr = window.devicePixelRatio || 1;
+ return { x: pos.x / dpr, y: pos.y / dpr };
+ };
+
+ 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') {
+ tauriDragHasImagesRef.current =
+ payload.paths.length === 0 || payload.paths.some(isSupportedImageExtension);
+ if (!tauriDragHasImagesRef.current) {
+ updateDropTarget(null);
+ return;
+ }
+ const pt = toLogicalPoint(payload.position);
+ updateDropTarget(resolveDropZoneAtPoint(pt.x, pt.y));
+ } else if (payload.type === 'over') {
+ if (!tauriDragHasImagesRef.current) {
+ updateDropTarget(null);
+ return;
+ }
+ const pt = toLogicalPoint(payload.position);
+ updateDropTarget(resolveDropZoneAtPoint(pt.x, pt.y));
+ } else if (payload.type === 'leave') {
+ tauriDragHasImagesRef.current = true;
+ updateDropTarget(null);
+ } else if (payload.type === 'drop') {
+ tauriDragHasImagesRef.current = true;
+ const pt = toLogicalPoint(payload.position);
+ const resolved =
+ resolveDropZoneAtPoint(pt.x, pt.y) ?? activeDropTargetRef.current;
+ updateDropTarget(null);
+ if (!resolved || payload.paths.length === 0) return;
+ void importDroppedPaths(payload.paths, {
+ targetLayerId: resolved.targetLayerId,
+ position: resolved.position,
+ });
+ }
+ });
+ if (cancelled) {
+ stop();
+ } else {
+ unlisten = stop;
+ }
+ } catch (err) {
+ console.warn('Failed to attach Tauri drag-drop listener:', err);
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ unlisten?.();
+ };
+ }, [enabled, importDroppedPaths, updateDropTarget]);
+
+ return {
+ activeDropTarget,
+ importDroppedFiles,
+ };
+}
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index 367eee2..baabaf4 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -27,6 +27,7 @@ import { documentStore } from '../utils/documentStore';
import { recoveryService } from '../services/recoveryService';
import { divideFramesInFolder, Point2D } from '../utils/frameEngine';
import { syncVectorObjectLayerToGrid } from '../utils/vectorLayerRenderer';
+import { LayerInsertTarget, sanitizeImportedLayerName } from '../utils/fileDropImport';
interface UseLayerManagerProps {
dimensions: CanvasDimensions;
@@ -2337,7 +2338,8 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
blendMode: BlendMode = 'normal',
opacity: number = 1,
customId?: string,
- layerOverrides?: Partial<LayerItem>
+ layerOverrides?: Partial<LayerItem>,
+ insertTarget?: LayerInsertTarget
) => {
const newId = customId || `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
const grid = activeTileGridRef.current;
@@ -2349,9 +2351,58 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);
setLayers((prev) => {
- const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
- const activeItem = prev[activeIdx];
- const defaultParentId = activeItem?.type === 'folder' ? activeItem.id : (activeItem?.parentId || null);
+ const getSubtreeEndIndex = (list: LayerItem[], folderIndex: number): number => {
+ const folderId = list[folderIndex].id;
+ const subtreeIds = new Set<string>([folderId]);
+ let endIdx = folderIndex + 1;
+ while (endIdx < list.length) {
+ const item = list[endIdx];
+ if (item.parentId && subtreeIds.has(item.parentId)) {
+ subtreeIds.add(item.id);
+ endIdx++;
+ } else {
+ break;
+ }
+ }
+ return endIdx;
+ };
+
+ let insertIdx = 0;
+ let resolvedParentId: string | null = null;
+ let expandFolderId: string | null = null;
+
+ const targetIdx = insertTarget?.targetLayerId
+ ? prev.findIndex((l) => l.id === insertTarget.targetLayerId)
+ : -1;
+
+ if (targetIdx >= 0) {
+ const targetItem = prev[targetIdx];
+ const pos = insertTarget?.position || (isFolderLikeLayer(targetItem) ? 'inside' : 'above');
+ if (pos === 'inside' && isFolderLikeLayer(targetItem)) {
+ resolvedParentId = targetItem.id;
+ insertIdx = targetIdx + 1;
+ if (targetItem.collapsed) expandFolderId = targetItem.id;
+ } else if (pos === 'below') {
+ resolvedParentId = targetItem.parentId;
+ insertIdx = isFolderLikeLayer(targetItem)
+ ? getSubtreeEndIndex(prev, targetIdx)
+ : targetIdx + 1;
+ } else {
+ resolvedParentId = targetItem.parentId;
+ insertIdx = targetIdx;
+ }
+ } else {
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);
+ const activeItem = activeIdx >= 0 ? prev[activeIdx] : undefined;
+ if (activeItem && isFolderLikeLayer(activeItem)) {
+ resolvedParentId = activeItem.id;
+ insertIdx = activeIdx + 1;
+ if (activeItem.collapsed) expandFolderId = activeItem.id;
+ } else {
+ resolvedParentId = activeItem?.parentId || null;
+ insertIdx = activeIdx >= 0 ? activeIdx : 0;
+ }
+ }
const newLayer: LayerItem = {
id: newId,
@@ -2362,21 +2413,23 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
blendMode,
locked: false,
collapsed: false,
- parentId: layerOverrides?.parentId !== undefined ? layerOverrides.parentId : defaultParentId,
+ parentId: layerOverrides?.parentId !== undefined ? layerOverrides.parentId : resolvedParentId,
thumbnailUrl: thumb,
...layerOverrides,
};
- const insertIdx = activeIdx >= 0 ? activeIdx : 0;
- const nextLayers = [...prev];
+ const nextLayers = expandFolderId
+ ? prev.map((l) => (l.id === expandFolderId ? { ...l, collapsed: false } : l))
+ : [...prev];
nextLayers.splice(insertIdx, 0, newLayer);
+ layersRef.current = nextLayers;
return nextLayers;
});
setActiveLayerId(newId);
return newId;
},
- [activeLayerId, setActiveLayerId]
+ [setActiveLayerId]
);
// Fill selection with non-destructive Clip Studio Paint screentone layer
@@ -2637,40 +2690,84 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
return { success: false };
}, [_dimensions, pasteLayerFromCanvas]);
- // Paste a photo from file
- const pasteLayerFromFile = useCallback(
- async (file: File): Promise<string> => {
- return new Promise<string>((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = (e) => {
- const img = new Image();
- img.onload = () => {
- const offscreen = document.createElement('canvas');
- offscreen.width = _dimensions.width;
- offscreen.height = _dimensions.height;
- const ctx = offscreen.getContext('2d');
- if (ctx) {
- const scale = Math.min(1, Math.min(_dimensions.width / img.naturalWidth, _dimensions.height / img.naturalHeight));
- const dw = Math.round(img.naturalWidth * scale);
- const dh = Math.round(img.naturalHeight * scale);
- const dx = Math.round((_dimensions.width - dw) / 2);
- const dy = Math.round((_dimensions.height - dh) / 2);
- ctx.drawImage(img, dx, dy, dw, dh);
- }
+ // Import an image file directly as a centered/fitted raster layer
+ const importImageFileAsLayer = useCallback(
+ async (file: File, insertTarget?: LayerInsertTarget): Promise<{ id: string; name: string }> => {
+ const decodeImage = (): Promise<HTMLImageElement> =>
+ new Promise((resolve, reject) => {
+ const canUseObjectUrl = typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function';
+ if (canUseObjectUrl) {
+ const url = URL.createObjectURL(file);
+ const img = new Image();
+ img.onload = () => {
+ URL.revokeObjectURL(url);
+ resolve(img);
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error(`Failed to decode image "${file.name}".`));
+ };
+ img.src = url;
+ return;
+ }
- const layerName = file.name.replace(/\.[^/.]+$/, '') || 'Pasted Image';
- pasteLayerFromCanvas(offscreen, layerName);
- releaseTemporaryCanvas(offscreen);
- resolve(layerName);
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error(`Failed to decode image "${file.name}".`));
+ img.src = e.target?.result as string;
};
- img.onerror = () => reject(new Error('Failed to decode image file.'));
- img.src = e.target?.result as string;
- };
- reader.onerror = () => reject(new Error('Failed to read file.'));
- reader.readAsDataURL(file);
- });
+ reader.onerror = () => reject(new Error(`Failed to read file "${file.name}".`));
+ reader.readAsDataURL(file);
+ });
+
+ const img = await decodeImage();
+ const natW = img.naturalWidth || img.width;
+ const natH = img.naturalHeight || img.height;
+ if (natW <= 0 || natH <= 0) {
+ throw new Error(`Image "${file.name}" has invalid dimensions.`);
+ }
+
+ const dims = dimensionsRef.current;
+ const offscreen = document.createElement('canvas');
+ offscreen.width = dims.width;
+ offscreen.height = dims.height;
+ const ctx = offscreen.getContext('2d');
+ if (ctx) {
+ const scale = Math.min(1, dims.width / natW, dims.height / natH);
+ const dw = Math.max(1, Math.round(natW * scale));
+ const dh = Math.max(1, Math.round(natH * scale));
+ const dx = Math.round((dims.width - dw) / 2);
+ const dy = Math.round((dims.height - dh) / 2);
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = 'high';
+ ctx.drawImage(img, dx, dy, dw, dh);
+ }
+
+ const layerName = sanitizeImportedLayerName(file.name);
+ const id = pasteLayerFromCanvas(
+ offscreen,
+ layerName,
+ 'normal',
+ 1,
+ undefined,
+ undefined,
+ insertTarget
+ );
+ releaseTemporaryCanvas(offscreen);
+ return { id, name: layerName };
+ },
+ [pasteLayerFromCanvas]
+ );
+
+ // Paste a photo from file
+ const pasteLayerFromFile = useCallback(
+ async (file: File, insertTarget?: LayerInsertTarget): Promise<string> => {
+ const { name } = await importImageFileAsLayer(file, insertTarget);
+ return name;
},
- [_dimensions, pasteLayerFromCanvas]
+ [importImageFileAsLayer]
);
// Resize canvas dimensions (content scaling or anchor expansion/crop)
@@ -3158,6 +3255,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
pasteLayer,
pasteLayerFromCanvas,
fillScreentoneSelection,
+ importImageFileAsLayer,
pasteLayerFromFile,
resizeCanvas,
toggleVisibility,
diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.ts
index d8106b6..390330c 100644
--- a/src/services/recoveryService.ts
+++ b/src/services/recoveryService.ts
@@ -5,7 +5,7 @@
* Provides atomic checkpoints, binary framing headers, CRC32 checksums, and rapid crash recovery.
*/
-import { deflateSync, inflateSync } from 'fflate';
+import { inflateSync } from 'fflate';
import {
TileDelta,
VectorStroke,
@@ -15,11 +15,12 @@ import {
import {
globalTileGrid,
SparseTileGrid,
- serializeTileDeltas,
+ serializeTileDeltasAsync,
deserializeTileDeltas,
- serializeSparseTileGrid,
+ serializeSparseTileGridAsync,
deserializeSparseTileGrid,
} from '../utils/tileEngine';
+import { deflateAsync } from '../utils/asyncCompression';
import { documentStore } from '../utils/documentStore';
export const WAL_MAGIC_BYTES = new Uint8Array([0x49, 0x4e, 0x4b, 0x57]); // 'INKW'
@@ -365,15 +366,27 @@ export function isTauriEnvironment(): boolean {
class RecoveryService {
private currentSessionId: string | null = null;
- private strokesSinceCheckpoint: number = 0;
- private idleCheckpointTimer: any = null;
+ private dirtySinceCheckpoint: boolean = false;
+ private isDrawingActive: boolean = false;
+ private checkpointGeneration: number = 0;
+ private idleCheckpointTimer: ReturnType<typeof setTimeout> | null = null;
private layerMutationDebounceTimer: ReturnType<typeof setTimeout> | null = null;
private isCheckpointing: boolean = false;
+ private walQueue: Promise<void> = Promise.resolve();
+ private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;
- private stripLayerTransientFields(layers?: LayerItem[]): LayerItem[] {
+ private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
+ if (!this.invokePromise) {
+ this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
+ }
+ return this.invokePromise;
+ }
+
+ private stripLayerTransientFields(layers?: LayerItem[], stripVectorStrokes: boolean = false): LayerItem[] {
if (!layers) return [];
- return layers.map(({ maskCanvas: _mc, maskThumbnailUrl: _mt, ...rest }) => ({
+ return layers.map(({ maskCanvas: _mc, maskThumbnailUrl: _mt, vectorStrokes, ...rest }) => ({
...rest,
+ ...(stripVectorStrokes ? {} : vectorStrokes !== undefined ? { vectorStrokes } : {}),
thumbnailUrl: '',
}));
}
@@ -385,6 +398,22 @@ class RecoveryService {
return this.currentSessionId;
}
+ /**
+ * Notifies the recovery service when the user starts or stops an active stroke
+ * so background checkpoints never contend with interactive drawing.
+ */
+ public setDrawingActive(active: boolean): void {
+ this.isDrawingActive = active;
+ if (active) {
+ if (this.idleCheckpointTimer) {
+ clearTimeout(this.idleCheckpointTimer);
+ this.idleCheckpointTimer = null;
+ }
+ } else if (this.dirtySinceCheckpoint && this.currentSessionId && isTauriEnvironment()) {
+ this.resetIdleCheckpointTimer(this.currentSessionId);
+ }
+ }
+
/**
* Initializes or binds an active recovery session for a document tab.
*/
@@ -404,7 +433,8 @@ class RecoveryService {
return;
}
- this.strokesSinceCheckpoint = 0;
+ this.checkpointGeneration++;
+ this.dirtySinceCheckpoint = false;
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
@@ -422,7 +452,7 @@ class RecoveryService {
}
: {};
const manifestJson = JSON.stringify(safeManifest);
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
await invoke('recovery_init_session', {
sessionId,
manifestJson,
@@ -432,28 +462,38 @@ class RecoveryService {
}
}
- private dispatchWalEntry(
+ private async dispatchWalEntryAsync(
sessionId: string,
entryType: number,
compressed: Uint8Array,
label: string
- ): void {
+ ): Promise<void> {
if (!isTauriEnvironment()) return;
- const payload = toExactUint8Array(compressed);
- import('@tauri-apps/api/core').then(({ invoke }) => {
- void invoke('recovery_append_wal_entry', payload, {
+ try {
+ const invoke = await this.getInvoke();
+ const payload = toExactUint8Array(compressed);
+ await invoke('recovery_append_wal_entry', payload, {
headers: {
'x-session-id': encodeURIComponent(sessionId),
'x-entry-type': String(entryType),
},
- }).catch((err) => {
- console.warn(`[RecoveryService] Non-blocking WAL ${label} append error:`, err);
});
- });
+ } catch (err) {
+ console.warn(`[RecoveryService] Non-blocking WAL ${label} append error:`, err);
+ }
+ }
+
+ private enqueueWalTask(task: () => Promise<void>): void {
+ this.walQueue = this.walQueue
+ .then(task)
+ .catch((err) => {
+ console.warn('[RecoveryService] Background WAL task failed:', err);
+ });
}
/**
- * Asynchronously appends a completed stroke's tile deltas or vector deltas to journal.wal without blocking UI.
+ * Asynchronously appends a completed stroke's tile deltas or vector deltas to journal.wal
+ * using off-main-thread Worker compression so UI and stylus inking never stall.
*/
public logStrokeDelta(
sessionId: string,
@@ -462,41 +502,53 @@ class RecoveryService {
layerId?: string
): void {
const activeId = sessionId || this.currentSessionId;
- if (!activeId) return;
+ if (!activeId || !isTauriEnvironment()) return;
+
+ const gen = this.checkpointGeneration;
- // 1. Dispatch tile deltas
+ // 1. Dispatch tile deltas off the main thread
if (tileDeltas && tileDeltas.length > 0) {
- try {
- const serialized = serializeTileDeltas(tileDeltas);
- const compressed = deflateSync(serialized, { level: 1 }); // Ultra-fast compression (<0.3ms)
- this.dispatchWalEntry(activeId, WAL_ENTRY_STROKE_TILE_DELTA, compressed, 'tile');
- } catch (err) {
- console.warn('[RecoveryService] Error serializing stroke tile delta:', err);
- }
+ const deltasSnapshot = tileDeltas;
+ this.enqueueWalTask(async () => {
+ if (this.checkpointGeneration !== gen) return;
+ try {
+ const serialized = await serializeTileDeltasAsync(deltasSnapshot);
+ const compressed = await deflateAsync(serialized, { level: 1, transfer: true });
+ if (this.checkpointGeneration !== gen) return;
+ await this.dispatchWalEntryAsync(activeId, WAL_ENTRY_STROKE_TILE_DELTA, compressed, 'tile');
+ } catch (err) {
+ console.warn('[RecoveryService] Error serializing stroke tile delta:', err);
+ }
+ });
}
- // 2. Dispatch vector stroke deltas
+ // 2. Dispatch vector stroke deltas off the main thread
if (vectorDelta && vectorDelta.after && vectorDelta.after.length > 0) {
- try {
- const payloadData = {
- layerId,
- strokes: vectorDelta.after,
- };
- const jsonBytes = _recoveryEncoder.encode(JSON.stringify(payloadData));
- const compressed = deflateSync(jsonBytes, { level: 1 });
- this.dispatchWalEntry(activeId, WAL_ENTRY_VECTOR_STROKE, compressed, 'vector');
- } catch (err) {
- console.warn('[RecoveryService] Error serializing vector stroke delta:', err);
- }
+ const afterStrokes = vectorDelta.after;
+ this.enqueueWalTask(async () => {
+ if (this.checkpointGeneration !== gen) return;
+ try {
+ const payloadData = {
+ layerId,
+ strokes: afterStrokes,
+ };
+ const jsonBytes = _recoveryEncoder.encode(JSON.stringify(payloadData));
+ const compressed = await deflateAsync(jsonBytes, { level: 1, transfer: true });
+ if (this.checkpointGeneration !== gen) return;
+ await this.dispatchWalEntryAsync(activeId, WAL_ENTRY_VECTOR_STROKE, compressed, 'vector');
+ } catch (err) {
+ console.warn('[RecoveryService] Error serializing vector stroke delta:', err);
+ }
+ });
}
- // Increment checkpoint stroke counter and defer full grid snapshot to idle timer so active drawing never freezes
- this.strokesSinceCheckpoint++;
+ this.dirtySinceCheckpoint = true;
this.resetIdleCheckpointTimer(activeId);
}
/**
- * Logs layer structure changes (add, delete, reorder, visibility, opacity, blendMode).
+ * Logs layer structure changes (add, delete, reorder, visibility, opacity, blendMode)
+ * with debouncing and off-main-thread compression.
*/
public logLayerMutation(
sessionId: string,
@@ -505,22 +557,29 @@ class RecoveryService {
activeLayerId?: string
): void {
const activeId = sessionId || this.currentSessionId;
- if (!activeId) return;
+ if (!activeId || !isTauriEnvironment()) return;
+
+ const gen = this.checkpointGeneration;
+ const strippedLayers = this.stripLayerTransientFields(layers, true);
const flushMutation = () => {
- try {
- const payloadData = {
- mutationType,
- layers: this.stripLayerTransientFields(layers),
- activeLayerId,
- timestamp: Date.now(),
- };
- const jsonBytes = _recoveryEncoder.encode(JSON.stringify(payloadData));
- const compressed = deflateSync(jsonBytes, { level: 1 });
- this.dispatchWalEntry(activeId, WAL_ENTRY_LAYER_MUTATION, compressed, 'layer mutation');
- } catch (err) {
- console.warn('[RecoveryService] Error logging layer mutation:', err);
- }
+ this.enqueueWalTask(async () => {
+ if (this.checkpointGeneration !== gen) return;
+ try {
+ const payloadData = {
+ mutationType,
+ layers: strippedLayers,
+ activeLayerId,
+ timestamp: Date.now(),
+ };
+ const jsonBytes = _recoveryEncoder.encode(JSON.stringify(payloadData));
+ const compressed = await deflateAsync(jsonBytes, { level: 1, transfer: true });
+ if (this.checkpointGeneration !== gen) return;
+ await this.dispatchWalEntryAsync(activeId, WAL_ENTRY_LAYER_MUTATION, compressed, 'layer mutation');
+ } catch (err) {
+ console.warn('[RecoveryService] Error logging layer mutation:', err);
+ }
+ });
};
const isContinuous =
@@ -529,28 +588,28 @@ class RecoveryService {
mutationType === 'tone' ||
mutationType === 'layer-color';
- if (isContinuous) {
- if (this.layerMutationDebounceTimer) {
- clearTimeout(this.layerMutationDebounceTimer);
- }
- this.layerMutationDebounceTimer = setTimeout(() => {
+ if (this.layerMutationDebounceTimer) {
+ clearTimeout(this.layerMutationDebounceTimer);
+ }
+ this.layerMutationDebounceTimer = setTimeout(
+ () => {
this.layerMutationDebounceTimer = null;
flushMutation();
- }, 250);
- } else {
- if (this.layerMutationDebounceTimer) {
- clearTimeout(this.layerMutationDebounceTimer);
- this.layerMutationDebounceTimer = null;
- }
- flushMutation();
- }
+ },
+ isContinuous ? 300 : 120
+ );
+ this.dirtySinceCheckpoint = true;
this.resetIdleCheckpointTimer(activeId);
}
private resetIdleCheckpointTimer(sessionId: string): void {
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
+ this.idleCheckpointTimer = null;
+ }
+ if (this.isDrawingActive || !isTauriEnvironment()) {
+ return;
}
this.idleCheckpointTimer = setTimeout(() => {
this.idleCheckpointTimer = null;
@@ -559,16 +618,19 @@ class RecoveryService {
}
/**
- * Executes a full background checkpoint:
- * 1. Compresses full active SparseTileGrid into baseline snapshot.
- * 2. Atomically overwrites base_snapshot.bin.
- * 3. Truncates journal.wal to zero bytes.
- * 4. Updates manifest.json & thumbnail.png.
+ * Executes a non-blocking background checkpoint:
+ * 1. Time-sliced SparseTileGrid serialization (yields every ~4ms, aborts if drawing resumes).
+ * 2. Off-main-thread Web Worker level-1 deflate compression (zero UI thread stall).
+ * 3. Atomically overwrites base_snapshot.bin and truncates journal.wal in Rust.
*/
public async triggerCheckpoint(sessionId: string): Promise<void> {
- if (this.isCheckpointing) return;
+ if (this.isCheckpointing || !isTauriEnvironment()) return;
const activeId = sessionId || this.currentSessionId;
- if (!activeId) return;
+ if (!activeId || !this.dirtySinceCheckpoint) return;
+
+ if (this.isDrawingActive) {
+ return;
+ }
this.isCheckpointing = true;
if (this.idleCheckpointTimer) {
@@ -576,11 +638,39 @@ class RecoveryService {
this.idleCheckpointTimer = null;
}
+ const gen = this.checkpointGeneration;
+ const shouldAbort = () =>
+ this.isDrawingActive ||
+ this.checkpointGeneration !== gen ||
+ this.currentSessionId !== activeId;
+
+ let abortedByActivity = false;
+
try {
- // 1. Snapshot SparseTileGrid for this specific document session
+ // Wait for any in-flight WAL appends before capturing baseline + truncating WAL
+ await this.walQueue;
+ if (shouldAbort()) {
+ abortedByActivity = this.isDrawingActive;
+ return;
+ }
+
+ // 1. Time-sliced SparseTileGrid snapshot for this document session
const targetGrid = documentStore.getSession(activeId)?.tileGrid ?? globalTileGrid;
- const rawSnapshot = serializeSparseTileGrid(targetGrid);
- const compressedSnapshot = deflateSync(rawSnapshot, { level: 4 });
+ const rawSnapshot = await serializeSparseTileGridAsync(targetGrid, {
+ shouldAbort,
+ chunkBudgetMs: 4,
+ });
+ if (!rawSnapshot || shouldAbort()) {
+ abortedByActivity = this.isDrawingActive;
+ return;
+ }
+
+ // Off-main-thread Worker compression (level 1 is ~2.5x faster than level 4 with identical ratio on sparse tiles)
+ const compressedSnapshot = await deflateAsync(rawSnapshot, { level: 1, transfer: true });
+ if (shouldAbort()) {
+ abortedByActivity = this.isDrawingActive;
+ return;
+ }
// 2. Manifest JSON (strip DOM canvas elements before serializing)
const rawManifest = this.manifestProvider?.() || null;
@@ -601,25 +691,31 @@ class RecoveryService {
} catch (_) {}
}
- if (isTauriEnvironment()) {
- const { invoke } = await import('@tauri-apps/api/core');
- const checkpointBody = packRecoveryCheckpointPayload(
- manifestJson,
- compressedSnapshot,
- thumbnailPng
- );
- await invoke('recovery_checkpoint', checkpointBody, {
- headers: {
- 'x-session-id': encodeURIComponent(activeId),
- },
- });
+ if (shouldAbort()) {
+ abortedByActivity = this.isDrawingActive;
+ return;
}
- this.strokesSinceCheckpoint = 0;
+ const invoke = await this.getInvoke();
+ const checkpointBody = packRecoveryCheckpointPayload(
+ manifestJson,
+ compressedSnapshot,
+ thumbnailPng
+ );
+ await invoke('recovery_checkpoint', checkpointBody, {
+ headers: {
+ 'x-session-id': encodeURIComponent(activeId),
+ },
+ });
+
+ this.dirtySinceCheckpoint = false;
} catch (err) {
console.warn('[RecoveryService] Checkpoint failed:', err);
} finally {
this.isCheckpointing = false;
+ if (abortedByActivity && !this.isDrawingActive && this.dirtySinceCheckpoint && this.currentSessionId === activeId) {
+ this.resetIdleCheckpointTimer(activeId);
+ }
}
}
@@ -630,15 +726,20 @@ class RecoveryService {
const activeId = sessionId || this.currentSessionId;
if (!activeId) return;
+ this.checkpointGeneration++;
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
this.idleCheckpointTimer = null;
}
- this.strokesSinceCheckpoint = 0;
+ if (this.layerMutationDebounceTimer) {
+ clearTimeout(this.layerMutationDebounceTimer);
+ this.layerMutationDebounceTimer = null;
+ }
+ this.dirtySinceCheckpoint = false;
if (isTauriEnvironment()) {
try {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
await invoke('recovery_close_session', { sessionId: activeId });
} catch (err) {
console.warn('[RecoveryService] Failed to clean up saved recovery session:', err);
diff --git a/src/utils/__tests__/changelog.test.ts b/src/utils/__tests__/changelog.test.ts
new file mode 100644
index 0000000..7d17e32
--- /dev/null
+++ b/src/utils/__tests__/changelog.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect } from 'vitest';
+import {
+ getChangelogEntries,
+ getChangelogForVersion,
+ hasStructuredChangelogMarkdown,
+ parseChangelog,
+ parseChangelogSections,
+} from '../changelog';
+
+describe('changelog parser', () => {
+ it('parses bundled CHANGELOG.md including v1.0.1 sections', () => {
+ const entries = getChangelogEntries();
+ expect(entries.length).toBeGreaterThan(0);
+
+ const v101 = getChangelogForVersion('1.0.1');
+ expect(v101).toBeDefined();
+ expect(v101?.version).toBe('1.0.1');
+
+ const sectionTitles = v101?.sections.map((s) => s.title);
+ expect(sectionTitles).toEqual(['New', 'Improvements', 'Bug Fixes', 'Other']);
+ expect(v101?.sections[0].items).toContain('Added Multi-layer Liquify');
+ expect(v101?.sections[3].items).toContain('Removed the "Old Vintage" theme');
+ });
+
+ it('handles v-prefixed lookup and plain-line items without bullets', () => {
+ const sample = `
+# Changelog
+
+## [v1.2.3] - 2026-12-01
+### New
+Added something cool
+- Added bullet item
+`;
+ const parsed = parseChangelog(sample);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0].version).toBe('1.2.3');
+ expect(parsed[0].sections[0].items).toEqual([
+ 'Added something cool',
+ 'Added bullet item',
+ ]);
+ });
+
+ it('parses standalone release notes bodies for the updater modal', () => {
+ const notes = `### New
+- Added brush import (\`.inkb\`)
+
+### Bug Fixes
+- Fixed micro-freezes`;
+
+ expect(hasStructuredChangelogMarkdown(notes)).toBe(true);
+ expect(hasStructuredChangelogMarkdown('Bug fixes and performance improvements.')).toBe(false);
+
+ const sections = parseChangelogSections(notes);
+ expect(sections).toEqual([
+ { title: 'New', items: ['Added brush import (`.inkb`)'] },
+ { title: 'Bug Fixes', items: ['Fixed micro-freezes'] },
+ ]);
+ });
+});
diff --git a/src/utils/__tests__/cspParser.test.ts b/src/utils/__tests__/cspParser.test.ts
new file mode 100644
index 0000000..0e671ff
--- /dev/null
+++ b/src/utils/__tests__/cspParser.test.ts
@@ -0,0 +1,595 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import initSqlJs from 'sql.js';
+import { zlibSync } from 'fflate';
+import {
+ mapCspBlendMode,
+ parseCspChunks,
+ extractExtaChunks,
+ parseOffscreenAttribute,
+ parseBlockDataPayload,
+ parseCspFile,
+} from '../cspParser';
+import { TILE_PIXELS, TILE_SIZE } from '../tileEngine';
+
+function concatBytes(parts: Uint8Array[]): Uint8Array {
+ let total = 0;
+ for (const p of parts) total += p.byteLength;
+ const out = new Uint8Array(total);
+ let off = 0;
+ for (const p of parts) {
+ out.set(p, off);
+ off += p.byteLength;
+ }
+ return out;
+}
+
+function u32BE(val: number): Uint8Array {
+ const b = new Uint8Array(4);
+ new DataView(b.buffer).setUint32(0, val >>> 0, false);
+ return b;
+}
+
+function u32LE(val: number): Uint8Array {
+ const b = new Uint8Array(4);
+ new DataView(b.buffer).setUint32(0, val >>> 0, true);
+ return b;
+}
+
+function u64BE(val: number): Uint8Array {
+ const b = new Uint8Array(8);
+ const view = new DataView(b.buffer);
+ view.setUint32(0, Math.floor(val / 0x100000000), false);
+ view.setUint32(4, val >>> 0, false);
+ return b;
+}
+
+function asciiBytes(s: string): Uint8Array {
+ const out = new Uint8Array(s.length);
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i) & 0xff;
+ return out;
+}
+
+function utf16BeTagged(s: string): Uint8Array {
+ const out = new Uint8Array(4 + s.length * 2);
+ new DataView(out.buffer).setUint32(0, s.length, false);
+ for (let i = 0; i < s.length; i++) {
+ out[4 + i * 2] = 0;
+ out[4 + i * 2 + 1] = s.charCodeAt(i) & 0xff;
+ }
+ return out;
+}
+
+function buildOffscreenAttribute(
+ bitmapW: number,
+ bitmapH: number,
+ defaultFill: number = 0,
+ ch1: number = 1,
+ ch2: number = 4
+): Uint8Array {
+ const gw = Math.ceil(bitmapW / TILE_SIZE);
+ const gh = Math.ceil(bitmapH / TILE_SIZE);
+ return concatBytes([
+ u32BE(88),
+ utf16BeTagged('Parameter'),
+ u32BE(bitmapW),
+ u32BE(bitmapH),
+ u32BE(gw),
+ u32BE(gh),
+ u32BE(defaultFill),
+ u32BE(0),
+ u32BE(ch1),
+ u32BE(ch2),
+ u32BE(0),
+ u32BE(0),
+ u32BE(0),
+ u32BE(0),
+ u32BE(0),
+ u32BE(8),
+ ]);
+}
+
+function buildBlockData(blocks: Array<Uint8Array | Uint8Array[] | null>): Uint8Array {
+ const parts: Uint8Array[] = [];
+ for (let idx = 0; idx < blocks.length; idx++) {
+ const entry = blocks[idx];
+ const beginTag = utf16BeTagged('BlockDataBeginChunk');
+ const endTag = utf16BeTagged('BlockDataEndChunk');
+ if (entry === null) {
+ const inner = concatBytes([
+ beginTag,
+ u32BE(idx),
+ u32BE(0),
+ u32BE(256),
+ u32BE(256),
+ u32BE(0), // empty block
+ endTag,
+ ]);
+ parts.push(u32BE(inner.byteLength), inner);
+ } else {
+ const planes = Array.isArray(entry) ? entry : [entry];
+ const subChunks = planes.map((plane) => {
+ const compressed = zlibSync(plane);
+ const outerLen = 4 + compressed.byteLength;
+ return concatBytes([u32BE(outerLen), u32LE(compressed.byteLength), compressed]);
+ });
+ const inner = concatBytes([
+ beginTag,
+ u32BE(idx),
+ u32BE(0),
+ u32BE(256),
+ u32BE(256),
+ u32BE(1), // hasData
+ ...subChunks,
+ endTag,
+ ]);
+ parts.push(u32BE(inner.byteLength), inner);
+ }
+ }
+ return concatBytes(parts);
+}
+
+function buildChunk(name: string, payload: Uint8Array): Uint8Array {
+ return concatBytes([asciiBytes('CHNK'), asciiBytes(name), u64BE(payload.byteLength), payload]);
+}
+
+function buildExtaChunk(externalId: string, payload: Uint8Array, includePayloadLen = true): Uint8Array {
+ const idBytes = asciiBytes(externalId);
+ const body = includePayloadLen
+ ? concatBytes([u64BE(idBytes.byteLength), idBytes, u64BE(payload.byteLength), payload])
+ : concatBytes([u64BE(idBytes.byteLength), idBytes, payload]);
+ return buildChunk('Exta', body);
+}
+
+function buildClipFile(chunks: Uint8Array[]): ArrayBuffer {
+ const body = concatBytes([...chunks, buildChunk('Foot', new Uint8Array(0))]);
+ const totalSize = 24 + body.byteLength;
+ const header = concatBytes([asciiBytes('CSFCHUNK'), u64BE(totalSize), u64BE(24)]);
+ const full = concatBytes([header, body]);
+ const out = new ArrayBuffer(full.byteLength);
+ new Uint8Array(out).set(full);
+ return out;
+}
+
+function makeColorTile(r: number, g: number, b: number, a: number): Uint8Array {
+ const raw = new Uint8Array(TILE_PIXELS * 5);
+ raw.fill(a, 0, TILE_PIXELS);
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ const off = TILE_PIXELS + p * 4;
+ raw[off] = b;
+ raw[off + 1] = g;
+ raw[off + 2] = r;
+ raw[off + 3] = 0;
+ }
+ return raw;
+}
+
+function createPixelCanvas(width: number, height: number) {
+ let w = width;
+ let h = height;
+ let pixels = new Uint8ClampedArray(w * h * 4);
+ const ctx = {
+ createImageData(iw: number, ih: number) {
+ return { data: new Uint8ClampedArray(iw * ih * 4), width: iw, height: ih };
+ },
+ putImageData(img: { data: Uint8ClampedArray; width: number; height: number }, dx: number, dy: number) {
+ for (let y = 0; y < img.height; y++) {
+ const ty = dy + y;
+ if (ty < 0 || ty >= h) continue;
+ for (let x = 0; x < img.width; x++) {
+ const tx = dx + x;
+ if (tx < 0 || tx >= w) continue;
+ const si = (y * img.width + x) * 4;
+ const di = (ty * w + tx) * 4;
+ pixels[di] = img.data[si];
+ pixels[di + 1] = img.data[si + 1];
+ pixels[di + 2] = img.data[si + 2];
+ pixels[di + 3] = img.data[si + 3];
+ }
+ }
+ },
+ getImageData(sx: number, sy: number, sw: number, sh: number) {
+ const out = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const py = sy + y;
+ if (py < 0 || py >= h) continue;
+ for (let x = 0; x < sw; x++) {
+ const px = sx + x;
+ if (px < 0 || px >= w) continue;
+ const si = (py * w + px) * 4;
+ const di = (y * sw + x) * 4;
+ out[di] = pixels[si];
+ out[di + 1] = pixels[si + 1];
+ out[di + 2] = pixels[si + 2];
+ out[di + 3] = pixels[si + 3];
+ }
+ }
+ return { data: out, width: sw, height: sh };
+ },
+ clearRect() {
+ pixels.fill(0);
+ },
+ drawImage() {},
+ fillRect() {},
+ };
+ return {
+ get width() {
+ return w;
+ },
+ set width(v: number) {
+ w = v;
+ pixels = new Uint8ClampedArray(Math.max(0, w) * Math.max(0, h) * 4);
+ },
+ get height() {
+ return h;
+ },
+ set height(v: number) {
+ h = v;
+ pixels = new Uint8ClampedArray(Math.max(0, w) * Math.max(0, h) * 4);
+ },
+ getContext: (t: string) => (t === '2d' ? ctx : null),
+ toDataURL: () => 'data:image/png;base64,MOCK',
+ } as unknown as HTMLCanvasElement;
+}
+
+describe('Clip Studio Paint (.clip) Parser', () => {
+ const prevDocument = (globalThis as Record<string, unknown>).document;
+
+ afterEach(() => {
+ if (prevDocument === undefined) {
+ delete (globalThis as Record<string, unknown>).document;
+ } else {
+ (globalThis as Record<string, unknown>).document = prevDocument;
+ }
+ });
+
+ it('maps CSP LayerComposite codes accurately to Ink Studio BlendMode', () => {
+ expect(mapCspBlendMode(0)).toBe('normal');
+ expect(mapCspBlendMode(1)).toBe('darken');
+ expect(mapCspBlendMode(2)).toBe('multiply');
+ expect(mapCspBlendMode(3)).toBe('color-burn');
+ expect(mapCspBlendMode(4)).toBe('linear-burn');
+ expect(mapCspBlendMode(7)).toBe('lighten');
+ expect(mapCspBlendMode(8)).toBe('screen');
+ expect(mapCspBlendMode(9)).toBe('color-dodge');
+ expect(mapCspBlendMode(10)).toBe('color-dodge-glow');
+ expect(mapCspBlendMode(12)).toBe('add-glow');
+ expect(mapCspBlendMode(14)).toBe('overlay');
+ expect(mapCspBlendMode(15)).toBe('soft-light');
+ expect(mapCspBlendMode(16)).toBe('hard-light');
+ expect(mapCspBlendMode(21)).toBe('difference');
+ expect(mapCspBlendMode(22)).toBe('exclusion');
+ expect(mapCspBlendMode(30)).toBe('pass-through');
+ expect(mapCspBlendMode(36)).toBe('divide');
+ });
+
+ it('parses CSFCHUNK, CHNKExta (with and without payloadLen), and Offscreen.Attribute', () => {
+ const attrBlob = buildOffscreenAttribute(512, 300, 1, 1, 4);
+ const parsed = parseOffscreenAttribute(attrBlob, 100, 100);
+ expect(parsed.bitmapWidth).toBe(512);
+ expect(parsed.bitmapHeight).toBe(300);
+ expect(parsed.blockGridWidth).toBe(2);
+ expect(parsed.blockGridHeight).toBe(2);
+ expect(parsed.defaultFill).toBe(1);
+ expect(parsed.firstPackingChannels).toBe(1);
+ expect(parsed.secondPackingChannels).toBe(4);
+
+ const tile = makeColorTile(10, 20, 30, 255);
+ const blockData = buildBlockData([null, tile]);
+ const buf = buildClipFile([
+ buildExtaChunk('extrnlid_withlen', blockData, true),
+ buildExtaChunk('extrnlid_nolen', blockData, false),
+ ]);
+ const chunks = parseCspChunks(new Uint8Array(buf));
+ const exta = extractExtaChunks(chunks);
+
+ expect(exta.has('extrnlid_withlen')).toBe(true);
+ expect(exta.has('extrnlid_nolen')).toBe(true);
+
+ // Sparse tile index 1 must NOT collapse onto index 0!
+ const decoded = parseBlockDataPayload(exta.get('extrnlid_withlen')!, 2);
+ expect(decoded.has(0)).toBe(false);
+ expect(decoded.has(1)).toBe(true);
+ expect(decoded.get(1)!.byteLength).toBe(TILE_PIXELS * 5);
+ });
+
+ it('decodes full editable layer hierarchy, folders, sparse tiles, offsets, masks, grayscale, mono, and paper', async () => {
+ (globalThis as Record<string, unknown>).document = {
+ createElement: () => createPixelCanvas(512, 256),
+ };
+
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+
+ db.run(`
+ CREATE TABLE Canvas (MainId INTEGER, CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasResolution REAL, CanvasRootFolder INTEGER);
+ CREATE TABLE Layer (
+ MainId INTEGER, LayerName TEXT, LayerType INTEGER, LayerFolder INTEGER,
+ LayerComposite INTEGER, LayerOpacity INTEGER, LayerVisibility INTEGER,
+ LayerLock INTEGER, LayerClip INTEGER, LayerSelect INTEGER,
+ LayerOffsetX REAL, LayerOffsetY REAL, LayerMaskOffsetX REAL, LayerMaskOffsetY REAL,
+ LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER,
+ LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER
+ );
+ CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
+ CREATE TABLE MipmapInfo (MainId INTEGER, ThisScale REAL, Offscreen INTEGER, NextIndex INTEGER);
+ CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
+ `);
+
+ // Canvas: 512x256 @ 600 DPI, root folder = 1
+ db.run('INSERT INTO Canvas VALUES (1, 512, 256, 600, 1)');
+
+ // Root folder (MainId=1): children bottom-to-top: Paper(2) -> Lineart(3) -> PaintFolder(4)
+ db.run('INSERT INTO Layer VALUES (1, "", 256, 1, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0)');
+ // Paper (MainId=2, bottom-most, no tiles -> solid white)
+ db.run('INSERT INTO Layer VALUES (2, "Paper", 1, 0, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0)');
+ // Lineart (MainId=3, 1-bit monochrome, visible, opacity 256, alpha locked)
+ db.run('INSERT INTO Layer VALUES (3, "Lineart", 1, 0, 2, 256, 1, 16, 0, 0, 0, 0, 0, 0, 4, 0, 10, 0)');
+ // PaintFolder (MainId=4, collapsed=true (17=1|16), pass-through=30, children bottom-to-top: Base(5) -> Shadow(6))
+ db.run('INSERT INTO Layer VALUES (4, "Paint", 256, 17, 30, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0)');
+ // Base (MainId=5, color layer with sparse tile at col=1 + layer mask enabled & linked!)
+ db.run('INSERT INTO Layer VALUES (5, "Base Color", 1, 0, 0, 256, 3, 0, 0, 256, 0, 0, 0, 0, 6, 0, 20, 21)');
+ // Shadow (MainId=6, clipped to Base, Multiply, 50% opacity = 128, grayscale 2-plane)
+ db.run('INSERT INTO Layer VALUES (6, "Shadow", 1, 0, 2, 128, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 30, 0)');
+
+ // Mipmap -> MipmapInfo -> Offscreen wiring (also include a 0.5x mipmap to verify 1.0x is chosen!)
+ db.run('INSERT INTO Mipmap VALUES (10, 100), (20, 200), (21, 210), (30, 300)');
+ db.run('INSERT INTO MipmapInfo VALUES (100, 1.0, 1000, 101), (101, 0.5, 1001, 0)');
+ db.run('INSERT INTO MipmapInfo VALUES (200, 1.0, 2000, 0)');
+ db.run('INSERT INTO MipmapInfo VALUES (210, 1.0, 2100, 0)');
+ db.run('INSERT INTO MipmapInfo VALUES (300, 1.0, 3000, 0)');
+
+ const attr512 = buildOffscreenAttribute(512, 256, 0, 1, 4);
+ const attrMask = buildOffscreenAttribute(512, 256, 0, 0, 1);
+
+ db.run('INSERT INTO Offscreen VALUES (1000, 3, "extrnlid_lineart", ?)', [attr512]);
+ db.run('INSERT INTO Offscreen VALUES (1001, 3, "extrnlid_lineart_half", ?)', [buildOffscreenAttribute(256, 128, 0, 1, 1)]);
+ db.run('INSERT INTO Offscreen VALUES (2000, 5, "extrnlid_base", ?)', [attr512]);
+ db.run('INSERT INTO Offscreen VALUES (2100, 5, "extrnlid_mask", ?)', [attrMask]);
+ db.run('INSERT INTO Offscreen VALUES (3000, 6, "extrnlid_shadow", ?)', [attr512]);
+
+ const sqliteBytes = db.export();
+ db.close();
+
+ // Lineart: 1-bit monochrome tile at block 0, pixel (0,0) = black ink (MSB bit 7 of byte 0)
+ const monoTile = new Uint8Array(8192);
+ monoTile[0] = 0x80; // pixel (0, 0) drawn
+ const lineartPayload = buildBlockData([monoTile, null]);
+
+ // Base Color: sparse — block 0 is EMPTY (null), block 1 (x=256..511) is solid crimson (220, 40, 60, 255) split into 2 planes!
+ const alphaPlane = new Uint8Array(TILE_PIXELS).fill(255);
+ const bgrxPlane = new Uint8Array(TILE_PIXELS * 4);
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ bgrxPlane[p * 4] = 60; // B
+ bgrxPlane[p * 4 + 1] = 40; // G
+ bgrxPlane[p * 4 + 2] = 220; // R
+ }
+ const basePayload = buildBlockData([null, [alphaPlane, bgrxPlane]]);
+
+ // Mask for Base Color: block 0 empty (defaultFill=0 -> masked), block 1 = 200
+ const maskTile = new Uint8Array(TILE_PIXELS).fill(200);
+ const maskPayload = buildBlockData([null, maskTile]);
+
+ // Shadow: grayscale 2-plane (alpha=180, gray=90) on block 0
+ const grayTile = new Uint8Array(TILE_PIXELS * 2);
+ grayTile.fill(180, 0, TILE_PIXELS);
+ grayTile.fill(90, TILE_PIXELS, TILE_PIXELS * 2);
+ const shadowPayload = buildBlockData([grayTile, null]);
+
+ const clipBuf = buildClipFile([
+ buildChunk('SQLi', sqliteBytes),
+ buildExtaChunk('extrnlid_lineart', lineartPayload),
+ buildExtaChunk('extrnlid_base', basePayload),
+ buildExtaChunk('extrnlid_mask', maskPayload),
+ buildExtaChunk('extrnlid_shadow', shadowPayload),
+ ]);
+
+ const doc = await parseCspFile(clipBuf, 'manga_page.clip');
+
+ expect(doc.name).toBe('manga_page');
+ expect(doc.dimensions).toEqual({ width: 512, height: 256, dpi: 600 });
+ expect(doc.tileGrid).toBeDefined();
+
+ // Expected top-to-bottom order: Paint (folder) -> Shadow -> Base Color -> Lineart -> Paper
+ expect(doc.layers.map((l) => l.name)).toEqual([
+ 'Paint',
+ 'Shadow',
+ 'Base Color',
+ 'Lineart',
+ 'Paper',
+ ]);
+
+ const [paintFolder, shadowLayer, baseLayer, lineartLayer, paperLayer] = doc.layers;
+
+ expect(paintFolder.type).toBe('folder');
+ expect(paintFolder.collapsed).toBe(true);
+ expect(paintFolder.blendMode).toBe('pass-through');
+ expect(paintFolder.parentId).toBeNull();
+
+ expect(shadowLayer.parentId).toBe(paintFolder.id);
+ expect(shadowLayer.clipped).toBe(true);
+ expect(shadowLayer.blendMode).toBe('multiply');
+ expect(shadowLayer.opacity).toBeCloseTo(0.5, 2);
+
+ expect(baseLayer.parentId).toBe(paintFolder.id);
+ expect(baseLayer.maskEnabled).toBe(true);
+ expect(baseLayer.maskLinked).toBe(true);
+ expect(baseLayer.maskCanvas).toBeDefined();
+ // Verify mask pixel: (10,10) = 0 (defaultFill), (260,10) = 200
+ const mCtx = baseLayer.maskCanvas!.getContext('2d')!;
+ expect(mCtx.getImageData(10, 10, 1, 1).data[0]).toBe(0);
+ expect(mCtx.getImageData(260, 10, 1, 1).data[0]).toBe(200);
+
+ expect(lineartLayer.alphaLocked).toBe(true);
+ expect(lineartLayer.locked).toBe(false);
+ expect(lineartLayer.blendMode).toBe('multiply');
+
+ // Verify decoded pixels in SparseTileGrid!
+ const grid = doc.tileGrid!;
+
+ // Base Color: x=10 (tile 0) must be unallocated (empty); x=260 (tile 1) must be RGBA(220, 40, 60, 255)
+ const baseTile0 = grid.getTile(baseLayer.id, 0, 0, 0);
+ expect(baseTile0).toBeNull();
+ const baseTile1 = grid.getTile(baseLayer.id, 1, 0, 0);
+ expect(baseTile1?.data).toBeDefined();
+ expect(Array.from(baseTile1!.data!.subarray(0, 4))).toEqual([220, 40, 60, 255]);
+
+ // Lineart 1-bit monochrome: pixel (0,0) = black (0,0,0,255), pixel (1,0) = transparent
+ const lineTile0 = grid.getTile(lineartLayer.id, 0, 0, 0);
+ expect(Array.from(lineTile0!.data!.subarray(0, 4))).toEqual([0, 0, 0, 255]);
+ expect(Array.from(lineTile0!.data!.subarray(4, 8))).toEqual([0, 0, 0, 0]);
+
+ // Shadow grayscale: pixel (0,0) = (90, 90, 90, 180)
+ const shadowTile0 = grid.getTile(shadowLayer.id, 0, 0, 0);
+ expect(Array.from(shadowTile0!.data!.subarray(0, 4))).toEqual([90, 90, 90, 180]);
+
+ // Paper: solid white across tiles
+ expect(grid.hasLayerTiles(paperLayer.id)).toBe(true);
+ });
+
+ it('respects LayerOffsetX/Y, bitmap boundary clipping, 2-plane monochrome, and disabled masks', async () => {
+ (globalThis as Record<string, unknown>).document = {
+ createElement: () => createPixelCanvas(300, 300),
+ };
+
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+ db.run(`
+ CREATE TABLE Canvas (MainId INTEGER, CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasRootFolder INTEGER);
+ CREATE TABLE Layer (
+ MainId INTEGER, LayerName TEXT, LayerType INTEGER, LayerFolder INTEGER,
+ LayerComposite INTEGER, LayerOpacity INTEGER, LayerVisibility INTEGER,
+ LayerLock INTEGER, LayerClip INTEGER, LayerSelect INTEGER,
+ LayerOffsetX REAL, LayerOffsetY REAL,
+ LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER,
+ LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER
+ );
+ CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
+ CREATE TABLE MipmapInfo (MainId INTEGER, ThisScale REAL, Offscreen INTEGER, NextIndex INTEGER);
+ CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
+ `);
+
+ db.run('INSERT INTO Canvas VALUES (1, 300, 300, 1)');
+ db.run('INSERT INTO Layer VALUES (1, "", 256, 1, 0, 256, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0)');
+ // Layer 2: shifted by (+10, +20), LayerVisibility=1 (visible, mask DISABLED), LayerSelect=0 (mask unlinked)
+ db.run('INSERT INTO Layer VALUES (2, "Mono2Plane", 1, 0, 0, 256, 1, 1, 0, 0, 10, 20, 0, 0, 10, 11)');
+ db.run('INSERT INTO Mipmap VALUES (10, 100), (11, 110)');
+ db.run('INSERT INTO MipmapInfo VALUES (100, 1.0, 1000, 0), (110, 1.0, 1100, 0)');
+ db.run('INSERT INTO Offscreen VALUES (1000, 2, "extrnlid_mono2", ?)', [buildOffscreenAttribute(100, 100, 0, 1, 1)]);
+ db.run('INSERT INTO Offscreen VALUES (1100, 2, "extrnlid_mask2", ?)', [buildOffscreenAttribute(300, 300, 1, 0, 1)]);
+
+ const sqliteBytes = db.export();
+ db.close();
+
+ // 2-plane 1-bit mono: pixel (0,0) = opaque white (alpha=1, color=1); pixel (1,0) = opaque black (alpha=1, color=0)
+ const mono2 = new Uint8Array(16384);
+ mono2[0] = 0xc0; // alpha bits for x=0,1
+ mono2[8192] = 0x80; // white bit for x=0 only
+
+ const clipBuf = buildClipFile([
+ buildChunk('SQLi', sqliteBytes),
+ buildExtaChunk('extrnlid_mono2', buildBlockData([mono2])),
+ buildExtaChunk('extrnlid_mask2', buildBlockData([null, null, null, null])),
+ ]);
+
+ const doc = await parseCspFile(clipBuf, 'offset_mono.clip');
+ expect(doc.layers.length).toBe(1);
+ const layer = doc.layers[0];
+ expect(layer.locked).toBe(true);
+ expect(layer.maskEnabled).toBe(false);
+ expect(layer.maskLinked).toBe(false);
+
+ // Offset (+10, +20): (10,20) must be white (255,255,255,255) and (11,20) must be black (0,0,0,255)
+ const tile = doc.tileGrid!.getTile(layer.id, 0, 0, 0)!;
+ const idxWhite = (20 * TILE_SIZE + 10) * 4;
+ const idxBlack = (20 * TILE_SIZE + 11) * 4;
+ expect(Array.from(tile.data!.subarray(idxWhite, idxWhite + 4))).toEqual([255, 255, 255, 255]);
+ expect(Array.from(tile.data!.subarray(idxBlack, idxBlack + 4))).toEqual([0, 0, 0, 255]);
+ });
+
+ it('accumulates parent folder LayerOffset, child LayerOffset, LayerRenderOffscrOffset, and LayerMaskOffscrOffset', async () => {
+ (globalThis as Record<string, unknown>).document = {
+ createElement: () => createPixelCanvas(512, 512),
+ };
+
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+ db.run(`
+ CREATE TABLE Canvas (MainId INTEGER, CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasRootFolder INTEGER);
+ CREATE TABLE Layer (
+ MainId INTEGER, LayerName TEXT, LayerType INTEGER, LayerFolder INTEGER,
+ LayerComposite INTEGER, LayerOpacity INTEGER, LayerVisibility INTEGER,
+ LayerLock INTEGER, LayerClip INTEGER, LayerSelect INTEGER,
+ LayerOffsetX REAL, LayerOffsetY REAL,
+ LayerRenderOffscrOffsetX REAL, LayerRenderOffscrOffsetY REAL,
+ LayerMaskOffsetX REAL, LayerMaskOffsetY REAL,
+ LayerMaskOffscrOffsetX REAL, LayerMaskOffscrOffsetY REAL,
+ LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER,
+ LayerRenderMipmap INTEGER, LayerLayerMaskMipmap INTEGER
+ );
+ CREATE TABLE Mipmap (MainId INTEGER, BaseMipmapInfo INTEGER);
+ CREATE TABLE MipmapInfo (MainId INTEGER, ThisScale REAL, Offscreen INTEGER, NextIndex INTEGER);
+ CREATE TABLE Offscreen (MainId INTEGER, LayerId INTEGER, BlockData TEXT, Attribute BLOB);
+ `);
+
+ db.run('INSERT INTO Canvas VALUES (1, 512, 512, 1)');
+ db.run('INSERT INTO Layer VALUES (1, "", 256, 1, 0, 256, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0)');
+ // Folder moved by (+40, +50)
+ db.run('INSERT INTO Layer VALUES (2, "MovedFolder", 256, 1, 30, 256, 1, 0, 0, 0, 40, 50, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0)');
+ // Child layer: LayerOffset(+10, +300), LayerRenderOffscrOffset(-30, -320) => effective render offset = (+20, +30)
+ // Mask: LayerMaskOffset(+5, +10), LayerMaskOffscrOffset(-15, -300) => effective mask offset = (40+10+5-15, 50+300+10-300) = (+40, +60)
+ db.run('INSERT INTO Layer VALUES (3, "Painted", 1, 0, 0, 256, 3, 0, 0, 256, 10, 300, -30, -320, 5, 10, -15, -300, 0, 0, 10, 11)');
+
+ db.run('INSERT INTO Mipmap VALUES (10, 100), (11, 110)');
+ db.run('INSERT INTO MipmapInfo VALUES (100, 1.0, 1000, 0), (110, 1.0, 1100, 0)');
+ db.run('INSERT INTO Offscreen VALUES (1000, 3, "extrnlid_off_paint", ?)', [buildOffscreenAttribute(256, 256, 0, 1, 4)]);
+ db.run('INSERT INTO Offscreen VALUES (1100, 3, "extrnlid_off_mask", ?)', [buildOffscreenAttribute(256, 256, 0, 0, 1)]);
+
+ const sqliteBytes = db.export();
+ db.close();
+
+ const paintTile = makeColorTile(10, 200, 30, 255);
+ const maskTile = new Uint8Array(TILE_PIXELS).fill(180);
+
+ const clipBuf = buildClipFile([
+ buildChunk('SQLi', sqliteBytes),
+ buildExtaChunk('extrnlid_off_paint', buildBlockData([paintTile])),
+ buildExtaChunk('extrnlid_off_mask', buildBlockData([maskTile])),
+ ]);
+
+ const doc = await parseCspFile(clipBuf, 'offsets.clip');
+ const painted = doc.layers.find((l) => l.name === 'Painted')!;
+
+ // Tile starts at (+20, +30): pixel (19, 30) must be transparent, pixel (20, 30) must be RGBA(10, 200, 30, 255)
+ const tile = doc.tileGrid!.getTile(painted.id, 0, 0, 0)!;
+ const beforeIdx = (30 * TILE_SIZE + 19) * 4;
+ const startIdx = (30 * TILE_SIZE + 20) * 4;
+ expect(Array.from(tile.data!.subarray(beforeIdx, beforeIdx + 4))).toEqual([0, 0, 0, 0]);
+ expect(Array.from(tile.data!.subarray(startIdx, startIdx + 4))).toEqual([10, 200, 30, 255]);
+
+ // Mask starts at (+40, +60): pixel (39, 60) = 0, pixel (40, 60) = 180
+ const mCtx = painted.maskCanvas!.getContext('2d')!;
+ expect(mCtx.getImageData(39, 60, 1, 1).data[0]).toBe(0);
+ expect(mCtx.getImageData(40, 60, 1, 1).data[0]).toBe(180);
+ });
+
+ it('guards against cyclic LayerNextIndex pointers and minimal/missing columns without hanging', async () => {
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+ db.run(`
+ CREATE TABLE Canvas (CanvasWidth INTEGER, CanvasHeight INTEGER, CanvasRootFolder INTEGER);
+ CREATE TABLE Layer (MainId INTEGER, LayerName TEXT, LayerNextIndex INTEGER, LayerFirstChildIndex INTEGER);
+ `);
+ db.run('INSERT INTO Canvas VALUES (256, 256, 1)');
+ db.run('INSERT INTO Layer VALUES (1, "", 0, 2)');
+ db.run('INSERT INTO Layer VALUES (2, "CycleA", 3, 0)');
+ db.run('INSERT INTO Layer VALUES (3, "CycleB", 2, 0)'); // cycle back to 2!
+ const sqliteBytes = db.export();
+ db.close();
+
+ const clipBuf = buildClipFile([buildChunk('SQLi', sqliteBytes)]);
+ const doc = await parseCspFile(clipBuf, 'cyclic.clip');
+
+ expect(doc.layers.map((l) => l.name)).toEqual(['CycleB', 'CycleA']);
+ expect(doc.layers.every((l) => l.type === 'raster')).toBe(true);
+ });
+});
diff --git a/src/utils/__tests__/fileDropImport.test.ts b/src/utils/__tests__/fileDropImport.test.ts
new file mode 100644
index 0000000..6a048eb
--- /dev/null
+++ b/src/utils/__tests__/fileDropImport.test.ts
@@ -0,0 +1,237 @@
+import { describe, it, expect } from 'vitest';
+import {
+ MAX_DROPPED_IMAGE_BYTES,
+ MAX_DROPPED_IMAGE_FILES,
+ extractFilenameFromPath,
+ filterDroppedImageFiles,
+ filterDroppedImagePaths,
+ getMimeTypeForFilename,
+ isExternalFileDrag,
+ isSameDropTarget,
+ isSupportedImageExtension,
+ isSupportedImageFile,
+ resolveDropZoneFromElement,
+ sanitizeImportedLayerName,
+} from '../fileDropImport';
+
+interface MockElement {
+ dataset: Record<string, string>;
+ rect: { top: number; height: number };
+ parent: MockElement | null;
+ closest: (selector: string) => MockElement | null;
+ getBoundingClientRect: () => DOMRect;
+}
+
+function makeEl(
+ dataset: Record<string, string>,
+ rect: { top: number; height: number } = { top: 0, height: 100 },
+ parent: MockElement | null = null
+): MockElement {
+ const el: MockElement = {
+ dataset,
+ rect,
+ parent,
+ closest(selector: string): MockElement | null {
+ let curr: MockElement | null = el;
+ while (curr) {
+ if (selector === '[data-drop-zone]' && curr.dataset.dropZone !== undefined) return curr;
+ if (selector === '[data-layer-id]' && curr.dataset.layerId !== undefined) return curr;
+ if (
+ selector === '[data-testid="sub-view-panel"]' &&
+ curr.dataset.testid === 'sub-view-panel'
+ ) {
+ return curr;
+ }
+ curr = curr.parent;
+ }
+ return null;
+ },
+ getBoundingClientRect() {
+ return {
+ top: el.rect.top,
+ bottom: el.rect.top + el.rect.height,
+ left: 0,
+ right: 200,
+ width: 200,
+ height: el.rect.height,
+ x: 0,
+ y: el.rect.top,
+ toJSON: () => ({}),
+ } as DOMRect;
+ },
+ };
+ return el;
+}
+
+function makeFakeFile(name: string, size: number, type = ''): File {
+ const file = new File([new Uint8Array(Math.min(size, 16))], name, { type });
+ if (size > 16) {
+ Object.defineProperty(file, 'size', { value: size });
+ }
+ return file;
+}
+
+describe('fileDropImport utilities', () => {
+ it('validates supported image extensions and rejects executables/docs/traversal', () => {
+ for (const name of [
+ 'photo.png',
+ 'PHOTO.JPG',
+ 'sketch.jpeg',
+ 'asset.webp',
+ 'icon.ico',
+ 'modern.avif',
+ 'vector.svg',
+ 'frame.gif',
+ 'raw.bmp',
+ 'C:\\Users\\Artist\\Desktop\\panel.PNG',
+ '/tmp/art/reference.jpg',
+ ]) {
+ expect(isSupportedImageExtension(name)).toBe(true);
+ }
+
+ for (const bad of [
+ 'malware.exe',
+ 'notes.txt',
+ 'archive.zip',
+ 'project.sora',
+ 'file.png.exe',
+ '.png',
+ 'noext',
+ '',
+ ]) {
+ expect(isSupportedImageExtension(bad)).toBe(false);
+ }
+ });
+
+ it('extracts filenames across Windows and POSIX paths and sanitizes layer names', () => {
+ expect(extractFilenameFromPath('C:\\Users\\Sora\\Art\\Hero_01.png')).toBe('Hero_01.png');
+ expect(extractFilenameFromPath('/home/sora/art/lineart.webp')).toBe('lineart.webp');
+ expect(sanitizeImportedLayerName('C:\\foo\\bar\\ my\u0000\u0007sketch .jpg')).toBe('mysketch');
+ expect(sanitizeImportedLayerName(' .png')).toBe('Imported Image');
+ expect(sanitizeImportedLayerName(`${'a'.repeat(120)}.png`).length).toBe(80);
+ expect(getMimeTypeForFilename('test.JPG')).toBe('image/jpeg');
+ expect(getMimeTypeForFilename('test.svg')).toBe('image/svg+xml');
+ });
+
+ it('filters files by type, empty size, 100MB cap, and max batch count', () => {
+ const valid = makeFakeFile('a.png', 1024, 'image/png');
+ const mimeOnly = makeFakeFile('clipboard-blob', 512, 'image/webp');
+ const empty = makeFakeFile('empty.png', 0, 'image/png');
+ const oversized = makeFakeFile('huge.png', MAX_DROPPED_IMAGE_BYTES + 1, 'image/png');
+ const unsupported = makeFakeFile('readme.txt', 100, 'text/plain');
+
+ expect(isSupportedImageFile(mimeOnly)).toBe(true);
+ const res = filterDroppedImageFiles([valid, mimeOnly, empty, oversized, unsupported]);
+ expect(res.accepted.map((f) => f.name)).toEqual(['a.png', 'clipboard-blob']);
+ expect(res.rejectedCount).toBe(2);
+ expect(res.oversizedCount).toBe(1);
+ expect(res.truncatedCount).toBe(0);
+
+ const flood = Array.from({ length: MAX_DROPPED_IMAGE_FILES + 5 }, (_, i) =>
+ makeFakeFile(`img_${i}.png`, 64, 'image/png')
+ );
+ const floodRes = filterDroppedImageFiles(flood);
+ expect(floodRes.accepted.length).toBe(MAX_DROPPED_IMAGE_FILES);
+ expect(floodRes.truncatedCount).toBe(5);
+ });
+
+ it('filters Tauri paths rejecting null bytes, unsupported extensions, and excess batch items', () => {
+ const res = filterDroppedImagePaths([
+ 'C:\\img\\1.png',
+ 'C:\\img\\bad\0.png',
+ 'C:\\img\\doc.pdf',
+ 'C:\\img\\2.webp',
+ ]);
+ expect(res.accepted).toEqual(['C:\\img\\1.png', 'C:\\img\\2.webp']);
+ expect(res.rejectedCount).toBe(2);
+ expect(res.truncatedCount).toBe(0);
+ });
+
+ it('distinguishes external OS file drags from internal dock panel drags', () => {
+ expect(
+ isExternalFileDrag({
+ types: ['Files'],
+ files: [],
+ } as unknown as DataTransfer)
+ ).toBe(true);
+
+ expect(
+ isExternalFileDrag({
+ types: ['application/x-inkstudio-dock-panel', 'Files'],
+ files: [],
+ } as unknown as DataTransfer)
+ ).toBe(false);
+
+ expect(
+ isExternalFileDrag({
+ types: ['text/plain'],
+ files: [],
+ } as unknown as DataTransfer)
+ ).toBe(false);
+ });
+
+ it('resolves canvas, layers container, layer row above/below, folder inside, and ignores SubView', () => {
+ const canvasEl = makeEl({ dropZone: 'canvas' });
+ expect(resolveDropZoneFromElement(canvasEl as unknown as Element, 50)).toEqual({
+ zone: 'canvas',
+ });
+
+ const layersSection = makeEl({ dropZone: 'layers' });
+ expect(resolveDropZoneFromElement(layersSection as unknown as Element, 50)).toEqual({
+ zone: 'layers',
+ });
+
+ const rasterRow = makeEl(
+ { layerId: 'layer-1', layerFolder: 'false' },
+ { top: 100, height: 40 },
+ layersSection
+ );
+ expect(resolveDropZoneFromElement(rasterRow as unknown as Element, 110)).toEqual({
+ zone: 'layers',
+ targetLayerId: 'layer-1',
+ position: 'above',
+ });
+ expect(resolveDropZoneFromElement(rasterRow as unknown as Element, 130)).toEqual({
+ zone: 'layers',
+ targetLayerId: 'layer-1',
+ position: 'below',
+ });
+
+ const folderRow = makeEl(
+ { layerId: 'folder-1', layerFolder: 'true' },
+ { top: 200, height: 40 },
+ layersSection
+ );
+ expect(resolveDropZoneFromElement(folderRow as unknown as Element, 205)).toEqual({
+ zone: 'layers',
+ targetLayerId: 'folder-1',
+ position: 'above',
+ });
+ expect(resolveDropZoneFromElement(folderRow as unknown as Element, 220)).toEqual({
+ zone: 'layers',
+ targetLayerId: 'folder-1',
+ position: 'inside',
+ });
+ expect(resolveDropZoneFromElement(folderRow as unknown as Element, 235)).toEqual({
+ zone: 'layers',
+ targetLayerId: 'folder-1',
+ position: 'below',
+ });
+
+ const subViewEl = makeEl({ testid: 'sub-view-panel' }, { top: 0, height: 100 }, canvasEl);
+ expect(resolveDropZoneFromElement(subViewEl as unknown as Element, 20)).toBeNull();
+
+ expect(
+ isSameDropTarget(
+ { zone: 'layers', targetLayerId: 'folder-1', position: 'inside' },
+ { zone: 'layers', targetLayerId: 'folder-1', position: 'inside' }
+ )
+ ).toBe(true);
+ expect(
+ isSameDropTarget(
+ { zone: 'layers', targetLayerId: 'folder-1', position: 'inside' },
+ { zone: 'layers', targetLayerId: 'folder-1', position: 'above' }
+ )
+ ).toBe(false);
+ });
+});
diff --git a/src/utils/__tests__/freezeOptimization.test.ts b/src/utils/__tests__/freezeOptimization.test.ts
new file mode 100644
index 0000000..8daa392
--- /dev/null
+++ b/src/utils/__tests__/freezeOptimization.test.ts
@@ -0,0 +1,165 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ SparseTileGrid,
+ TileMemoryManager,
+ InMemoryScratchDiskDriver,
+ serializeSparseTileGrid,
+ serializeSparseTileGridAsync,
+ deserializeSparseTileGrid,
+ serializeTileDeltas,
+ serializeTileDeltasAsync,
+ deserializeTileDeltas,
+ BYTES_32BIT,
+} from '../tileEngine';
+import { deflateAsync, inflateAsync, zlibAsync, unzlibAsync } from '../asyncCompression';
+import { UndoCacheManager } from '../undoCache';
+import type { HistoryItem, TileDelta } from '../../types/editor';
+
+function uint8Equal(a: Uint8Array, b: Uint8Array): boolean {
+ if (a.byteLength !== b.byteLength) return false;
+ for (let i = 0; i < a.byteLength; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+}
+
+describe('Main-thread freeze prevention & async background pipelines', () => {
+ it('async deflate/inflate and zlib/unzlib round-trip cleanly and enforce maxOutputBytes', async () => {
+ const src = new Uint8Array(64 * 1024);
+ for (let i = 0; i < src.length; i++) src[i] = (i * 31) & 0xff;
+
+ const deflated = await deflateAsync(src, { level: 1, transfer: false });
+ const inflated = await inflateAsync(deflated);
+ expect(uint8Equal(inflated, src)).toBe(true);
+
+ const zlibbed = await zlibAsync(src, { level: 1, transfer: false });
+ const unzlibbed = await unzlibAsync(zlibbed);
+ expect(uint8Equal(unzlibbed, src)).toBe(true);
+
+ await expect(
+ unzlibAsync(zlibbed, { maxOutputBytes: 1024 })
+ ).rejects.toThrow(/safety ceiling/i);
+ });
+
+ it('serializeSparseTileGridAsync produces byte-identical output to sync version and supports cooperative abort', async () => {
+ const grid = new SparseTileGrid();
+ for (let i = 0; i < 40; i++) {
+ const t = grid.getOrCreateTile(i % 2 === 0 ? 'layer-a' : 'layer-b', i, 0, 'color-32bit');
+ t.data![0] = (i + 1) & 0xff;
+ t.data![3] = 255;
+ }
+
+ const syncBytes = serializeSparseTileGrid(grid);
+ const asyncBytes = await serializeSparseTileGridAsync(grid, { chunkBudgetMs: 0 });
+ expect(asyncBytes).not.toBeNull();
+ expect(uint8Equal(asyncBytes!, syncBytes)).toBe(true);
+
+ const restored = new SparseTileGrid();
+ deserializeSparseTileGrid(restored, asyncBytes!);
+ expect(restored.getTile('layer-a', 0, 0)?.data?.[0]).toBe(1);
+ expect(restored.getTile('layer-b', 39, 0)?.data?.[0]).toBe(40);
+
+ // Cooperative abort mid-serialization when user resumes drawing
+ let checks = 0;
+ const aborted = await serializeSparseTileGridAsync(grid, {
+ chunkBudgetMs: 0,
+ shouldAbort: () => ++checks >= 3,
+ });
+ expect(aborted).toBeNull();
+ });
+
+ it('serializeTileDeltasAsync produces byte-identical output for large delta arrays', async () => {
+ const deltas: TileDelta[] = [];
+ for (let i = 0; i < 24; i++) {
+ const before = new Uint8Array(BYTES_32BIT);
+ const after = new Uint8Array(BYTES_32BIT);
+ before[0] = i;
+ after[0] = 255 - i;
+ deltas.push({
+ key: `layer-1:${i}:0`,
+ format: 'color-32bit',
+ beforeData: before,
+ afterData: after,
+ });
+ }
+
+ const syncBytes = serializeTileDeltas(deltas);
+ const asyncBytes = await serializeTileDeltasAsync(deltas, 0);
+ expect(uint8Equal(asyncBytes, syncBytes)).toBe(true);
+
+ const decoded = deserializeTileDeltas(asyncBytes);
+ expect(decoded).toHaveLength(24);
+ expect(decoded[23].afterData?.[0]).toBe(255 - 23);
+ });
+
+ it('TileMemoryManager chunks large evictions into <= 32 tiles per batch and handles driver failure without spinning', async () => {
+ const grid = new SparseTileGrid();
+ const driver = new InMemoryScratchDiskDriver();
+ const writeSpy = vi.spyOn(driver, 'writeTiles');
+
+ const mm = new TileMemoryManager(grid, {
+ budgetMb: 100,
+ driver,
+ sessionId: 'chunk-evict-test',
+ });
+ grid.setMemoryManager(mm);
+
+ const tiles = [];
+ for (let i = 0; i < 70; i++) {
+ const t = grid.getOrCreateTile('layer-1', i, 0, 'monochrome-1bit');
+ t.data![0] = i & 0xff;
+ tiles.push(t);
+ }
+
+ await mm.evictTiles(tiles);
+
+ // 70 tiles with batch size 32 => 3 batches (32 + 32 + 6)
+ expect(writeSpy).toHaveBeenCalledTimes(3);
+ expect(writeSpy.mock.calls[0][1].length).toBe(32);
+ expect(writeSpy.mock.calls[1][1].length).toBe(32);
+ expect(writeSpy.mock.calls[2][1].length).toBe(6);
+ expect(tiles.every((t) => t.data === null && t.isPagedToDisk)).toBe(true);
+
+ // Driver failure during checkBudgetAndEvict must terminate cleanly instead of spinning
+ const failingDriver = new InMemoryScratchDiskDriver();
+ vi.spyOn(failingDriver, 'writeTiles').mockRejectedValue(new Error('Disk full'));
+ const failGrid = new SparseTileGrid();
+ const failMm = new TileMemoryManager(failGrid, {
+ budgetMb: 1,
+ driver: failingDriver,
+ sessionId: 'fail-evict-test',
+ });
+ failGrid.setMemoryManager(failMm);
+ for (let i = 0; i < 6; i++) {
+ failGrid.getOrCreateTile('layer-1', i, 0, 'color-32bit');
+ }
+ await expect(failMm.checkBudgetAndEvict()).resolves.toBeUndefined();
+ });
+
+ it('UndoCacheManager coalesces concurrent offloads and avoids wiping deltas requested mid-offload', async () => {
+ const cache = new UndoCacheManager('race-test');
+ const data = new Uint8Array(BYTES_32BIT);
+ data[0] = 77;
+ const item: HistoryItem = {
+ id: 'step-race',
+ type: 'brush',
+ label: 'Stroke',
+ timestamp: Date.now(),
+ timeFormatted: '12:00:00',
+ thumbnailUrl: '',
+ layerId: 'layer-1',
+ tileDeltas: [{ key: 'layer-1:0:0', format: 'color-32bit', beforeData: null, afterData: data }],
+ };
+
+ // Start concurrent offload and immediate resolveDeltas
+ const offloadP1 = cache.offloadToDisk(item);
+ const offloadP2 = cache.offloadToDisk(item);
+ const resolved = await cache.resolveDeltas(item);
+ await Promise.all([offloadP1, offloadP2]);
+
+ expect(resolved).not.toBeNull();
+ expect(resolved![0].afterData?.[0]).toBe(77);
+ // Deltas must remain intact in RAM because resolveDeltas requested them during offload
+ expect(item.tileDeltas).toBeDefined();
+ });
+});
diff --git a/src/utils/__tests__/selectionAndTransform.test.ts b/src/utils/__tests__/selectionAndTransform.test.ts
index 3498401..f5d4d89 100644
--- a/src/utils/__tests__/selectionAndTransform.test.ts
+++ b/src/utils/__tests__/selectionAndTransform.test.ts
@@ -15,6 +15,8 @@ import {
createDefaultPerspectiveQuad,
createDefaultMeshPoints,
evaluateMeshSurface,
+ expandTriangleOutward,
+ renderMeshWarp,
} from '../transformEngine';
describe('Selection Boundary Modifiers and Wand', () => {
@@ -170,6 +172,71 @@ describe('Perspective and Mesh Transformation Engine', () => {
expect(mid.x).toBeCloseTo(50, 1);
expect(mid.y).toBeCloseTo(50, 1);
});
+
+ it('expands adjacent quad triangles strictly outward across their shared diagonal', () => {
+ const expand = 0.75;
+ // Unit quad (0,0)-(100,0)-(100,80)-(0,80) split along (100,0)-(0,80)
+ const t1 = expandTriangleOutward(0, 0, 100, 0, 0, 80, expand);
+ const t2 = expandTriangleOutward(100, 0, 100, 80, 0, 80, expand);
+ expect(t1).not.toBeNull();
+ expect(t2).not.toBeNull();
+
+ // Shared diagonal line: (100, 0) -> (0, 80); unit normal pointing toward t2 (+x, +y)
+ const len = Math.hypot(100, 80);
+ const nx = 80 / len;
+ const ny = 100 / len;
+ const signedDistToDiag = (x: number, y: number) => (x - 100) * nx + y * ny;
+
+ // t1 diagonal endpoints (indices 2,3 and 4,5) must shift outward into t2 (+expand)
+ expect(signedDistToDiag(t1![2], t1![3])).toBeCloseTo(expand, 5);
+ expect(signedDistToDiag(t1![4], t1![5])).toBeCloseTo(expand, 5);
+
+ // t2 diagonal endpoints (indices 0,1 and 4,5) must shift outward into t1 (-expand)
+ expect(signedDistToDiag(t2![0], t2![1])).toBeCloseTo(-expand, 5);
+ expect(signedDistToDiag(t2![4], t2![5])).toBeCloseTo(-expand, 5);
+ });
+
+ it('expands reversed-winding (flipped) triangles outward and rejects degenerate triangles', () => {
+ const expand = 0.75;
+ // Reversed winding of (0,0)-(100,0)-(0,100) -> (0,0)-(0,100)-(100,0)
+ const flipped = expandTriangleOutward(0, 0, 0, 100, 100, 0, expand);
+ expect(flipped).not.toBeNull();
+ const invSqrt2 = Math.SQRT1_2;
+ const dist = (x: number, y: number) => (x + y - 100) * invSqrt2;
+ expect(dist(flipped![2], flipped![3])).toBeCloseTo(expand, 5);
+ expect(dist(flipped![4], flipped![5])).toBeCloseTo(expand, 5);
+
+ // Collinear / zero-area triangle returns null
+ expect(expandTriangleOutward(0, 0, 50, 50, 100, 100, expand)).toBeNull();
+ });
+
+ it('falls back to Canvas2D triangle rendering cleanly when WebGL is unavailable', () => {
+ const clipCalls: number[][] = [];
+ const mockCtx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn((x: number, y: number) => clipCalls.push([x, y])),
+ lineTo: vi.fn((x: number, y: number) => clipCalls.push([x, y])),
+ closePath: vi.fn(),
+ clip: vi.fn(),
+ transform: vi.fn(),
+ drawImage: vi.fn(),
+ } as unknown as CanvasRenderingContext2D;
+
+ const src = { width: 100, height: 100 } as HTMLCanvasElement;
+ const quad = createDefaultPerspectiveQuad(0, 0, 100, 100, 0);
+ const mesh = createDefaultMeshPoints(quad, 3, 3);
+ renderMeshWarp(mockCtx, src, mesh, 2);
+
+ // (3-1)*2 = 4 cells per axis -> 16 cells -> 32 triangles -> 96 vertices
+ expect(mockCtx.drawImage).toHaveBeenCalledTimes(32);
+ expect(clipCalls.length).toBe(96);
+ for (const [x, y] of clipCalls) {
+ expect(Number.isFinite(x)).toBe(true);
+ expect(Number.isFinite(y)).toBe(true);
+ }
+ });
});
interface MockPixelCanvas {
diff --git a/src/utils/asyncCompression.ts b/src/utils/asyncCompression.ts
new file mode 100644
index 0000000..8d01ef4
--- /dev/null
+++ b/src/utils/asyncCompression.ts
@@ -0,0 +1,239 @@
+/**
+ * Off-Main-Thread Pooled Compression Worker Client
+ *
+ * Moves heavy fflate deflate/zlib/inflate/unzlib operations (WAL checkpoints,
+ * stroke deltas, undo cache offload) onto a reusable Web Worker with zero-copy
+ * ArrayBuffer transfer so the UI thread never stalls on large canvases.
+ */
+
+import { deflateSync, inflateSync, zlibSync, unzlibSync } from 'fflate';
+import type {
+ CompressionOp,
+ CompressionRequest,
+ CompressionResponse,
+} from '../workers/compression.worker';
+
+export type CompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
+
+export interface AsyncCompressionOptions {
+ level?: CompressionLevel;
+ /** When true and input owns an exact ArrayBuffer, transfers ownership to avoid copying. */
+ transfer?: boolean;
+ /** Optional safety ceiling for decompression output size. */
+ maxOutputBytes?: number;
+}
+
+interface PendingJob {
+ resolve: (data: Uint8Array) => void;
+ reject: (err: Error) => void;
+}
+
+let sharedWorker: Worker | null = null;
+let workerDisabled = false;
+let nextJobId = 1;
+const pendingJobs = new Map<number, PendingJob>();
+
+let yieldChannel: MessageChannel | null = null;
+const yieldQueue: Array<() => void> = [];
+
+/**
+ * Yields control back to the event loop as a low-latency macrotask so pending
+ * pointer/tap/paint events execute promptly without Windows 15.6ms setTimeout stalls.
+ */
+export function yieldToMain(): Promise<void> {
+ if (typeof window !== 'undefined' && typeof MessageChannel !== 'undefined') {
+ if (!yieldChannel) {
+ yieldChannel = new MessageChannel();
+ yieldChannel.port1.onmessage = () => {
+ const next = yieldQueue.shift();
+ if (next) next();
+ };
+ }
+ return new Promise((resolve) => {
+ yieldQueue.push(resolve);
+ yieldChannel!.port2.postMessage(null);
+ });
+ }
+ const g = globalThis as unknown as { setImmediate?: (cb: () => void) => void };
+ if (typeof g.setImmediate === 'function') {
+ return new Promise((resolve) => {
+ g.setImmediate!(resolve);
+ });
+ }
+ return new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+}
+
+function rejectAllPending(reason: Error): void {
+ const entries = Array.from(pendingJobs.values());
+ pendingJobs.clear();
+ for (const job of entries) {
+ job.reject(reason);
+ }
+}
+
+function canUseCompressionWorker(): boolean {
+ if (workerDisabled) return false;
+ if (typeof Worker === 'undefined' || typeof window === 'undefined') return false;
+ return true;
+}
+
+function getOrCreateWorker(): Worker | null {
+ if (!canUseCompressionWorker()) return null;
+ if (sharedWorker) return sharedWorker;
+
+ try {
+ const worker = new Worker(
+ new URL('../workers/compression.worker.ts', import.meta.url),
+ { type: 'module' }
+ );
+
+ worker.onmessage = (event: MessageEvent<CompressionResponse>) => {
+ const msg = event.data;
+ const pending = pendingJobs.get(msg.id);
+ if (!pending) return;
+ pendingJobs.delete(msg.id);
+ if (msg.ok && msg.data) {
+ pending.resolve(msg.data);
+ } else {
+ pending.reject(new Error(msg.error || 'Compression worker failed'));
+ }
+ };
+
+ worker.onerror = (event: ErrorEvent) => {
+ const err = new Error(event.message || 'Compression worker crashed');
+ if (sharedWorker === worker) {
+ sharedWorker = null;
+ }
+ worker.terminate();
+ workerDisabled = true;
+ rejectAllPending(err);
+ };
+
+ sharedWorker = worker;
+ return worker;
+ } catch {
+ workerDisabled = true;
+ return null;
+ }
+}
+
+function runFallbackSync(
+ op: CompressionOp,
+ data: Uint8Array,
+ options?: AsyncCompressionOptions
+): Uint8Array {
+ let result: Uint8Array;
+ if (op === 'deflate') {
+ result = deflateSync(data, { level: options?.level ?? 1 });
+ } else if (op === 'zlib') {
+ result = zlibSync(data, { level: options?.level ?? 1 });
+ } else if (op === 'inflate') {
+ result = inflateSync(data);
+ } else {
+ result = unzlibSync(data);
+ }
+ if (options?.maxOutputBytes !== undefined && result.byteLength > options.maxOutputBytes) {
+ throw new Error(`Decompressed payload exceeds safety ceiling (${options.maxOutputBytes} bytes)`);
+ }
+ return result;
+}
+
+function dispatchToWorker(
+ op: CompressionOp,
+ data: Uint8Array,
+ options?: AsyncCompressionOptions
+): Promise<Uint8Array> {
+ const worker = getOrCreateWorker();
+ if (!worker) {
+ return Promise.resolve().then(() => runFallbackSync(op, data, options));
+ }
+
+ return new Promise<Uint8Array>((resolve, reject) => {
+ const id = nextJobId++;
+ pendingJobs.set(id, { resolve, reject });
+
+ const isExactArrayBuffer =
+ data.buffer instanceof ArrayBuffer &&
+ data.byteOffset === 0 &&
+ data.byteLength === data.buffer.byteLength;
+
+ let payload: Uint8Array;
+ let transferables: Transferable[] | undefined;
+
+ if (options?.transfer) {
+ payload = isExactArrayBuffer ? data : data.slice();
+ transferables = [payload.buffer as ArrayBuffer];
+ } else {
+ // Clone only if we cannot transfer caller's buffer without neutering it
+ payload = data.slice();
+ transferables = [payload.buffer as ArrayBuffer];
+ }
+
+ const request: CompressionRequest = {
+ id,
+ op,
+ data: payload,
+ level: options?.level,
+ maxOutputBytes: options?.maxOutputBytes,
+ };
+
+ try {
+ worker.postMessage(request, transferables);
+ } catch {
+ pendingJobs.delete(id);
+ if (sharedWorker === worker) {
+ sharedWorker = null;
+ }
+ try {
+ worker.terminate();
+ } catch {
+ // Ignore terminate errors
+ }
+ workerDisabled = true;
+ try {
+ resolve(runFallbackSync(op, data, options));
+ } catch (fallbackErr) {
+ reject(fallbackErr instanceof Error ? fallbackErr : new Error(String(fallbackErr)));
+ }
+ }
+ });
+}
+
+export function deflateAsync(
+ data: Uint8Array,
+ options?: AsyncCompressionOptions
+): Promise<Uint8Array> {
+ return dispatchToWorker('deflate', data, options);
+}
+
+export function inflateAsync(
+ data: Uint8Array,
+ options?: AsyncCompressionOptions
+): Promise<Uint8Array> {
+ return dispatchToWorker('inflate', data, options);
+}
+
+export function zlibAsync(
+ data: Uint8Array,
+ options?: AsyncCompressionOptions
+): Promise<Uint8Array> {
+ return dispatchToWorker('zlib', data, options);
+}
+
+export function unzlibAsync(
+ data: Uint8Array,
+ options?: AsyncCompressionOptions
+): Promise<Uint8Array> {
+ return dispatchToWorker('unzlib', data, options);
+}
+
+export function disposeCompressionWorker(): void {
+ if (sharedWorker) {
+ sharedWorker.terminate();
+ sharedWorker = null;
+ }
+ rejectAllPending(new Error('Compression worker disposed'));
+ workerDisabled = false;
+}
diff --git a/src/utils/changelog.ts b/src/utils/changelog.ts
new file mode 100644
index 0000000..70c870f
--- /dev/null
+++ b/src/utils/changelog.ts
@@ -0,0 +1,171 @@
+import changelogRaw from '../../CHANGELOG.md?raw';
+
+export interface ChangelogSection {
+ title: string;
+ items: string[];
+}
+
+export interface ChangelogEntry {
+ version: string;
+ sections: ChangelogSection[];
+ rawBody: string;
+}
+
+const VERSION_HEADING_RE = /^##\s+\[?v?([0-9]+\.[0-9]+\.[0-9]+(?:-[^\s\]]+)?)\]?(?:\s+.*)?$/i;
+const SECTION_HEADING_RE = /^###\s+(.+)$/;
+const BULLET_PREFIX_RE = /^[-*]\s+/;
+
+function normalizeVersion(version: string): string {
+ return version.trim().replace(/^v/i, '');
+}
+
+/**
+ * Parse a single release body (without a `## vX.Y.Z` heading) into categorized sections.
+ * Useful for rendering updater `latest.json` notes with the same layout as CHANGELOG.md.
+ */
+export function parseChangelogSections(markdownBody: string): ChangelogSection[] {
+ const sections: ChangelogSection[] = [];
+ const lines = markdownBody.replace(/\r\n/g, '\n').split('\n');
+ let currentSection: ChangelogSection | null = null;
+
+ const flushSection = () => {
+ if (currentSection && currentSection.items.length > 0) {
+ sections.push(currentSection);
+ }
+ currentSection = null;
+ };
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ // Ignore top-level version heading if a caller accidentally passes one
+ if (VERSION_HEADING_RE.test(trimmed)) {
+ continue;
+ }
+
+ const sectionMatch = SECTION_HEADING_RE.exec(trimmed);
+ if (sectionMatch) {
+ flushSection();
+ currentSection = {
+ title: sectionMatch[1].trim(),
+ items: [],
+ };
+ continue;
+ }
+
+ if (!currentSection) {
+ currentSection = { title: '', items: [] };
+ }
+
+ currentSection.items.push(trimmed.replace(BULLET_PREFIX_RE, '').trim());
+ }
+
+ flushSection();
+ return sections;
+}
+
+/**
+ * Check whether a release body contains structured Markdown sections (`### Heading`)
+ * or bullet list items (`- ...` / `* ...`).
+ */
+export function hasStructuredChangelogMarkdown(markdownBody: string): boolean {
+ const lines = markdownBody.replace(/\r\n/g, '\n').split('\n');
+ return lines.some((line) => {
+ const trimmed = line.trim();
+ return SECTION_HEADING_RE.test(trimmed) || BULLET_PREFIX_RE.test(trimmed);
+ });
+}
+
+/**
+ * Parse a Markdown changelog document grouped by `## vX.Y.Z` version headings
+ * and `### Category` subheadings.
+ */
+export function parseChangelog(markdown: string): ChangelogEntry[] {
+ const entries: ChangelogEntry[] = [];
+ const lines = markdown.replace(/\r\n/g, '\n').split('\n');
+
+ let currentEntry: ChangelogEntry | null = null;
+ let currentSection: ChangelogSection | null = null;
+ let rawLines: string[] = [];
+
+ const flushSection = () => {
+ if (currentEntry && currentSection && currentSection.items.length > 0) {
+ currentEntry.sections.push(currentSection);
+ }
+ currentSection = null;
+ };
+
+ const flushEntry = () => {
+ flushSection();
+ if (currentEntry) {
+ currentEntry.rawBody = rawLines.join('\n').trim();
+ entries.push(currentEntry);
+ }
+ currentEntry = null;
+ rawLines = [];
+ };
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ const versionMatch = VERSION_HEADING_RE.exec(trimmed);
+ if (versionMatch) {
+ flushEntry();
+ currentEntry = {
+ version: versionMatch[1],
+ sections: [],
+ rawBody: '',
+ };
+ continue;
+ }
+
+ if (!currentEntry) {
+ continue;
+ }
+
+ rawLines.push(line);
+
+ const sectionMatch = SECTION_HEADING_RE.exec(trimmed);
+ if (sectionMatch) {
+ flushSection();
+ currentSection = {
+ title: sectionMatch[1].trim(),
+ items: [],
+ };
+ continue;
+ }
+
+ if (!trimmed) {
+ continue;
+ }
+
+ if (!currentSection) {
+ currentSection = { title: 'Changes', items: [] };
+ }
+
+ currentSection.items.push(trimmed.replace(BULLET_PREFIX_RE, '').trim());
+ }
+
+ flushEntry();
+ return entries;
+}
+
+let cachedEntries: ChangelogEntry[] | null = null;
+
+/** Return all parsed changelog entries from the root CHANGELOG.md file. */
+export function getChangelogEntries(): ChangelogEntry[] {
+ if (!cachedEntries) {
+ cachedEntries = parseChangelog(changelogRaw);
+ }
+ return cachedEntries;
+}
+
+/** Find changelog entry matching the given semver string, or the latest entry if omitted. */
+export function getChangelogForVersion(version?: string): ChangelogEntry | undefined {
+ const entries = getChangelogEntries();
+ if (!version) {
+ return entries[0];
+ }
+ const target = normalizeVersion(version);
+ return entries.find((entry) => normalizeVersion(entry.version) === target);
+}
diff --git a/src/utils/cspParser.ts b/src/utils/cspParser.ts
index ca74293..0b2f5d6 100644
--- a/src/utils/cspParser.ts
+++ b/src/utils/cspParser.ts
@@ -1,249 +1,1015 @@
-import initSqlJs, { Database } from 'sql.js';
-import { unzlibSync, inflateSync } from 'fflate';
-import { BlendMode, LayerItem, LoadedDocument } from '../types/editor';
+import initSqlJs, { Database, SqlValue } from 'sql.js';
+import { Unzlib, inflateSync } from 'fflate';
+import {
+ BlendMode,
+ CanvasColorMode,
+ LayerItem,
+ LoadedDocument,
+} from '../types/editor';
import { createCanvasThumbnail } from './canvasUtils';
+import { SparseTileGrid, TILE_SIZE, TILE_PIXELS } from './tileEngine';
-let sqlJsPromise: Promise<any> | null = null;
+const MAX_CANVAS_DIM = 32768;
+const MAX_BLOCKS_PER_LAYER = 16384; // 128x128 tiles = 32768x32768 px
+const MAX_COMPRESSED_TILE_BYTES = 2 * 1024 * 1024;
+const MAX_DECOMPRESSED_TILE_BYTES = 2 * 1024 * 1024;
+const MAX_FOLDER_DEPTH = 64;
+const MAX_LAYERS = 4096;
+
+const SQLITE_SIG = new Uint8Array([
+ 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66,
+ 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
+]);
+
+function encodeUtf16BeTagged(ascii: string): Uint8Array {
+ const out = new Uint8Array(4 + ascii.length * 2);
+ const view = new DataView(out.buffer);
+ view.setUint32(0, ascii.length, false);
+ for (let i = 0; i < ascii.length; i++) {
+ out[4 + i * 2] = 0;
+ out[4 + i * 2 + 1] = ascii.charCodeAt(i) & 0xff;
+ }
+ return out;
+}
+
+const TAG_BLOCK_BEGIN = encodeUtf16BeTagged('BlockDataBeginChunk');
+const TAG_BLOCK_END = encodeUtf16BeTagged('BlockDataEndChunk');
+const TAG_PARAMETER = encodeUtf16BeTagged('Parameter');
+const TAG_INIT_COLOR = encodeUtf16BeTagged('InitColor');
+
+let sqlJsPromise: Promise<Awaited<ReturnType<typeof initSqlJs>>> | null = null;
async function getSql() {
if (!sqlJsPromise) {
- sqlJsPromise = initSqlJs({
- locateFile: () => '/sql-wasm.wasm',
+ const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
+ sqlJsPromise = initSqlJs(
+ isBrowser ? { locateFile: () => '/sql-wasm.wasm' } : undefined
+ ).catch((err) => {
+ sqlJsPromise = null;
+ throw err;
});
}
return await sqlJsPromise;
}
/**
- * Maps Clip Studio Paint composite mode integer to Sora Paint BlendMode.
+ * Maps Clip Studio Paint LayerComposite integer to Ink Studio BlendMode.
+ * Reference: CSP internal composite mode enum (0..36).
*/
-function mapCspBlendMode(val: number): BlendMode {
+export function mapCspBlendMode(val: number): BlendMode {
switch (val) {
+ case 0:
+ return 'normal';
case 1:
- return 'multiply';
+ return 'darken';
case 2:
- return 'screen';
+ return 'multiply';
case 3:
- return 'overlay';
+ return 'color-burn';
case 4:
- return 'lighten';
+ return 'linear-burn';
case 5:
- return 'darken';
+ return 'difference'; // Subtract
case 6:
- return 'color-dodge';
+ return 'darken'; // Darker Color
case 7:
- return 'color-burn';
+ return 'lighten';
case 8:
- return 'hard-light';
+ return 'screen';
case 9:
- return 'soft-light';
+ return 'color-dodge';
case 10:
- return 'difference';
+ return 'color-dodge-glow'; // Glow Dodge
case 11:
+ return 'add-glow'; // Add (Linear Dodge)
+ case 12:
+ return 'add-glow'; // Add (Glow)
+ case 13:
+ return 'lighten'; // Lighter Color
+ case 14:
+ return 'overlay';
+ case 15:
+ return 'soft-light';
+ case 16:
+ case 17: // Vivid Light
+ case 18: // Linear Light
+ case 19: // Pin Light
+ case 20: // Hard Mix
+ return 'hard-light';
+ case 21:
+ return 'difference';
+ case 22:
return 'exclusion';
- case 0:
+ case 30:
+ return 'pass-through'; // Through (folder)
+ case 36:
+ return 'divide';
default:
return 'normal';
}
}
-interface CspChunk {
+function readU64BE(view: DataView, offset: number): number {
+ if (offset < 0 || offset + 8 > view.byteLength) return -1;
+ const hi = view.getUint32(offset, false);
+ const lo = view.getUint32(offset + 4, false);
+ if (hi > 0x1fffff) return -1; // exceeds MAX_SAFE_INTEGER
+ return hi * 0x100000000 + lo;
+}
+
+function readAscii(bytes: Uint8Array, start: number, len: number): string {
+ let out = '';
+ const end = Math.min(bytes.length, start + len);
+ for (let i = start; i < end; i++) {
+ out += String.fromCharCode(bytes[i]);
+ }
+ return out;
+}
+
+function indexOfBytes(haystack: Uint8Array, needle: Uint8Array, fromIndex: number = 0): number {
+ const nLen = needle.length;
+ const limit = haystack.length - nLen;
+ if (nLen === 0 || fromIndex > limit) return -1;
+ const first = needle[0];
+ let idx = fromIndex;
+ while (idx <= limit) {
+ idx = haystack.indexOf(first, idx);
+ if (idx === -1 || idx > limit) return -1;
+ let match = true;
+ for (let j = 1; j < nLen; j++) {
+ if (haystack[idx + j] !== needle[j]) {
+ match = false;
+ break;
+ }
+ }
+ if (match) return idx;
+ idx++;
+ }
+ return -1;
+}
+
+function isZlibHeader(b0: number, b1: number): boolean {
+ if (b0 !== 0x78) return false;
+ return b1 === 0x01 || b1 === 0x5e || b1 === 0x9c || b1 === 0xda;
+}
+
+/**
+ * Bounded zlib decompression immune to zip bombs.
+ */
+function safeUnzlib(src: Uint8Array, maxOutBytes: number = MAX_DECOMPRESSED_TILE_BYTES): Uint8Array | null {
+ if (src.byteLength < 6 || src.byteLength > MAX_COMPRESSED_TILE_BYTES) return null;
+ try {
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ let exceeded = false;
+ const stream = new Unzlib((chunk) => {
+ total += chunk.byteLength;
+ if (total > maxOutBytes) {
+ exceeded = true;
+ throw new Error('Decompressed tile exceeds safety cap');
+ }
+ chunks.push(chunk);
+ });
+ stream.push(src, true);
+ if (exceeded || total === 0) return null;
+ if (chunks.length === 1) return chunks[0];
+ const merged = new Uint8Array(total);
+ let pos = 0;
+ for (const c of chunks) {
+ merged.set(c, pos);
+ pos += c.byteLength;
+ }
+ return merged;
+ } catch {
+ // Fallback for raw deflate streams lacking valid adler32 trailer
+ if (src.byteLength > 2 && isZlibHeader(src[0], src[1])) {
+ try {
+ const raw = inflateSync(src.subarray(2));
+ if (raw.byteLength > 0 && raw.byteLength <= maxOutBytes) return raw;
+ } catch {
+ // invalid stream
+ }
+ }
+ return null;
+ }
+}
+
+export interface CspChunk {
name: string;
data: Uint8Array;
}
/**
- * Iterates top-level chunks of a Clip Studio Paint binary file.
+ * Parses top-level CSFCHUNK binary container without copying payloads.
*/
-function parseCspChunks(buffer: Uint8Array): CspChunk[] {
+export function parseCspChunks(buffer: Uint8Array): CspChunk[] {
const chunks: CspChunk[] = [];
- const fileHeaderSize = 24;
-
- if (buffer.length < fileHeaderSize) return chunks;
+ if (buffer.length < 24) return chunks;
+ if (readAscii(buffer, 0, 8) !== 'CSFCHUNK') return chunks;
- // Verify CSFCHUNK magic header
- const magic = new TextDecoder('ascii').decode(buffer.slice(0, 8));
- if (magic !== 'CSFCHUNK') {
- // If not standard CSFCHUNK, search for embedded SQLite directly
- return chunks;
- }
-
- let offset = fileHeaderSize;
const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ let offset = 24;
while (offset + 16 <= buffer.length) {
- const chunkTag = new TextDecoder('ascii').decode(buffer.slice(offset, offset + 4));
- if (chunkTag !== 'CHNK') {
- break;
- }
-
- const chunkName = new TextDecoder('ascii').decode(buffer.slice(offset + 4, offset + 8));
- const chunkSize = view.getUint32(offset + 12, false); // big-endian
+ if (readAscii(buffer, offset, 4) !== 'CHNK') break;
+ const chunkName = readAscii(buffer, offset + 4, 4);
+ const chunkSize = readU64BE(view, offset + 8);
+ if (chunkSize < 0) break;
const dataStart = offset + 16;
const dataEnd = dataStart + chunkSize;
-
if (dataEnd > buffer.length) break;
chunks.push({
name: chunkName,
- data: buffer.slice(dataStart, dataEnd),
+ data: buffer.subarray(dataStart, dataEnd),
});
offset = dataEnd;
+ if (chunkName === 'Foot') break;
}
return chunks;
}
-/**
- * Finds the SQLite database byte array from chunks or raw buffer.
- */
function findSqliteData(chunks: CspChunk[], rawBuffer: Uint8Array): Uint8Array | null {
- // First check CHNKSQLi chunk
const sqliChunk = chunks.find((c) => c.name === 'SQLi');
if (sqliChunk) {
- // Check if it starts directly with "SQLite format 3\0"
- const sig = 'SQLite format 3\0';
- const textHead = new TextDecoder('ascii').decode(sqliChunk.data.slice(0, 16));
- if (textHead === sig) {
- return sqliChunk.data;
- }
- // Search within chunk
- const idx = indexOfSequence(sqliChunk.data, [
- 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
- ]);
- if (idx >= 0) {
- return sqliChunk.data.slice(idx);
- }
+ const idx = indexOfBytes(sqliChunk.data, SQLITE_SIG, 0);
+ if (idx >= 0) return sqliChunk.data.subarray(idx);
}
+ const idx = indexOfBytes(rawBuffer, SQLITE_SIG, 0);
+ return idx >= 0 ? rawBuffer.subarray(idx) : null;
+}
+
+/**
+ * Extracts CHNKExta external payloads keyed by external ID (e.g. "extrnlid...").
+ */
+export function extractExtaChunks(chunks: CspChunk[]): Map<string, Uint8Array> {
+ const extaMap = new Map<string, Uint8Array>();
+
+ for (const c of chunks) {
+ if (c.name !== 'Exta' || c.data.length < 16) continue;
+ const view = new DataView(c.data.buffer, c.data.byteOffset, c.data.byteLength);
+ const idLen = readU64BE(view, 0);
+ if (idLen <= 0 || idLen > 256 || 8 + idLen > c.data.length) continue;
+
+ const externalId = readAscii(c.data, 8, idLen).replace(/\0+$/, '');
+ const afterId = 8 + idLen;
- // Fallback: search anywhere in buffer for SQLite header
- const idx = indexOfSequence(rawBuffer, [
- 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
- ]);
- if (idx >= 0) {
- return rawBuffer.slice(idx);
+ let payloadStart = afterId;
+ if (afterId + 8 <= c.data.length) {
+ const maybePayloadLen = readU64BE(view, afterId);
+ const remainingAfterLen = c.data.length - (afterId + 8);
+ if (maybePayloadLen === remainingAfterLen) {
+ payloadStart = afterId + 8;
+ } else {
+ // Also check if BlockDataBeginChunk starts right after an 8-byte header
+ const firstTagAt8 = indexOfBytes(c.data, TAG_BLOCK_BEGIN, afterId + 8);
+ const firstTagAt0 = indexOfBytes(c.data, TAG_BLOCK_BEGIN, afterId);
+ if (firstTagAt8 >= 0 && firstTagAt0 === firstTagAt8) {
+ payloadStart = afterId + 8;
+ }
+ }
+ }
+
+ extaMap.set(externalId, c.data.subarray(payloadStart));
}
- return null;
+ return extaMap;
}
-function indexOfSequence(haystack: Uint8Array, needle: number[]): number {
- const nLen = needle.length;
- const hLen = haystack.length;
- if (nLen > hLen) return -1;
+interface ParsedOffscreenAttribute {
+ bitmapWidth: number;
+ bitmapHeight: number;
+ blockGridWidth: number;
+ blockGridHeight: number;
+ defaultFill: number; // 0 = transparent/black, 1 = white/filled
+ firstPackingChannels: number;
+ secondPackingChannels: number;
+ bitDepthFlag: number;
+ initColor: [number, number, number, number] | null; // RGBA 0..255
+}
- for (let i = 0; i <= hLen - nLen; i++) {
- let match = true;
- for (let j = 0; j < nLen; j++) {
- if (haystack[i + j] !== needle[j]) {
- match = false;
+/**
+ * Parses Offscreen.Attribute binary blob ("Parameter" + optional "InitColor").
+ */
+export function parseOffscreenAttribute(
+ blob: Uint8Array | null,
+ fallbackW: number,
+ fallbackH: number
+): ParsedOffscreenAttribute {
+ const def: ParsedOffscreenAttribute = {
+ bitmapWidth: fallbackW,
+ bitmapHeight: fallbackH,
+ blockGridWidth: Math.max(1, Math.ceil(fallbackW / TILE_SIZE)),
+ blockGridHeight: Math.max(1, Math.ceil(fallbackH / TILE_SIZE)),
+ defaultFill: 0,
+ firstPackingChannels: 1,
+ secondPackingChannels: 4,
+ bitDepthFlag: 8,
+ initColor: null,
+ };
+
+ if (!blob || blob.byteLength < 32) return def;
+ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
+
+ const paramIdx = indexOfBytes(blob, TAG_PARAMETER, 0);
+ if (paramIdx >= 0) {
+ const afterParam = paramIdx + TAG_PARAMETER.length;
+ // Locate (bitmapWidth, bitmapHeight, blockGridWidth, blockGridHeight) using exact tile-grid invariant
+ let base = -1;
+ for (const shift of [0, 4, 8, 12]) {
+ const p = afterParam + shift;
+ if (p + 16 > blob.byteLength) break;
+ const bw = view.getUint32(p, false);
+ const bh = view.getUint32(p + 4, false);
+ const gw = view.getUint32(p + 8, false);
+ const gh = view.getUint32(p + 12, false);
+ if (
+ bw > 0 &&
+ bh > 0 &&
+ bw <= MAX_CANVAS_DIM &&
+ bh <= MAX_CANVAS_DIM &&
+ gw === Math.ceil(bw / TILE_SIZE) &&
+ gh === Math.ceil(bh / TILE_SIZE)
+ ) {
+ base = p;
break;
}
}
- if (match) return i;
+
+ if (base >= 0) {
+ def.bitmapWidth = view.getUint32(base, false);
+ def.bitmapHeight = view.getUint32(base + 4, false);
+ 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);
+ }
+ // Packing parameters follow defaultFill (up to 11 u32 values)
+ if (base + 32 <= blob.byteLength) {
+ const ch1 = view.getUint32(base + 24, false);
+ const ch2 = view.getUint32(base + 28, false);
+ if (ch1 <= 4 && ch2 <= 4) {
+ def.firstPackingChannels = ch1;
+ def.secondPackingChannels = ch2;
+ }
+ }
+ if (base + 56 <= blob.byteLength) {
+ def.bitDepthFlag = view.getUint32(base + 52, false);
+ }
+ }
}
- return -1;
+
+ 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 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];
+ }
+ }
+ }
+ }
+
+ return def;
+}
+
+function isValidTileByteLength(len: number): boolean {
+ return (
+ len === TILE_PIXELS * 5 ||
+ len === TILE_PIXELS * 4 ||
+ len === TILE_PIXELS * 2 ||
+ len === TILE_PIXELS ||
+ len === 16384 ||
+ len === 8192
+ );
+}
+
+function mergePlanes(planes: Uint8Array[]): Uint8Array | null {
+ if (planes.length === 0) return null;
+ if (planes.length === 1) return planes[0];
+ let total = 0;
+ for (const p of planes) total += p.byteLength;
+ if (total > MAX_DECOMPRESSED_TILE_BYTES) return null;
+ const merged = new Uint8Array(total);
+ let off = 0;
+ for (const p of planes) {
+ merged.set(p, off);
+ off += p.byteLength;
+ }
+ return merged;
}
/**
- * Extracts external chunks by ID from CHNKExta chunks.
+ * Extracts compressed sub-block payload(s) inside a single BlockDataBeginChunk..BlockDataEndChunk span.
*/
-function extractExtaChunks(chunks: CspChunk[]): Map<string, Uint8Array> {
- const extaMap = new Map<string, Uint8Array>();
+function decompressBlockSpan(span: Uint8Array): Uint8Array | null {
+ if (span.byteLength < 6) return null;
+ const view = new DataView(span.buffer, span.byteOffset, span.byteLength);
- for (const c of chunks) {
- if (c.name !== 'Exta' || c.data.length < 24) continue;
- const view = new DataView(c.data.buffer, c.data.byteOffset, c.data.byteLength);
- // name_length at offset 0 (u64 big-endian)
- const nameLen = view.getUint32(4, false); // low 32 bits of 64-bit int
- if (nameLen <= 0 || nameLen > 100 || 8 + nameLen + 8 > c.data.length) continue;
+ // Path 1: Standard CSP framed sub-blocks: [u32BE outerLen][u32LE innerLen][zlib...] (1 or 2 planes)
+ const planes: Uint8Array[] = [];
+ let pos = 0;
+
+ while (pos + 8 <= span.byteLength) {
+ const outerLen = view.getUint32(pos, false);
+ if (outerLen < 6 || pos + 4 + outerLen > span.byteLength) {
+ break;
+ }
+
+ let zStart = pos + 8;
+ const zEnd = pos + 4 + outerLen;
- const chunkId = new TextDecoder('ascii').decode(c.data.slice(8, 8 + nameLen));
- const payload = c.data.slice(8 + nameLen + 8);
- extaMap.set(chunkId, payload);
+ // Verify zlib header at +8 (after u32LE innerLen) or at +4 (no innerLen)
+ if (zStart + 2 <= zEnd && isZlibHeader(span[zStart], span[zStart + 1])) {
+ // standard CSP [u32BE outerLen][u32LE innerLen][zlib]
+ } else if (pos + 6 <= zEnd && isZlibHeader(span[pos + 4], span[pos + 5])) {
+ zStart = pos + 4;
+ } else {
+ break;
+ }
+
+ const decoded = safeUnzlib(span.subarray(zStart, zEnd));
+ if (!decoded) break;
+ planes.push(decoded);
+ pos = zEnd;
}
- return extaMap;
+ if (planes.length > 0) {
+ const merged = mergePlanes(planes);
+ if (merged && (pos === span.byteLength || isValidTileByteLength(merged.byteLength))) {
+ return merged;
+ }
+ }
+
+ // Path 2: Direct zlib stream at start or offset +4/+8
+ for (const offset of [0, 4, 8]) {
+ if (offset + 6 <= span.byteLength && isZlibHeader(span[offset], span[offset + 1])) {
+ const decoded = safeUnzlib(span.subarray(offset));
+ if (decoded) return decoded;
+ }
+ }
+
+ return null;
}
/**
- * Decodes 256x256 subblocks from an Exta bitmap chunk into an offscreen canvas.
+ * Parses a CSP BlockData external payload into a sparse map of gridIndex -> decompressed tile bytes.
*/
-function renderCspBitmapToCanvas(
- blockData: Uint8Array,
- canvasWidth: number,
- canvasHeight: number,
- offsetX: number = 0,
- offsetY: number = 0
-): HTMLCanvasElement | null {
- try {
- const canvas = document.createElement('canvas');
- canvas.width = canvasWidth;
- canvas.height = canvasHeight;
- const ctx = canvas.getContext('2d');
- if (!ctx) return null;
-
- // Scan for zlib header 0x78 (0x78 0x9c or 0x78 0x01 or 0x78 0xda)
- // and try inflating 256x256 pixel blocks
- const BLOCK_SIZE = 256;
- let blockIndex = 0;
-
- for (let i = 0; i < blockData.length - 8; i++) {
- if (blockData[i] === 0x78 && (blockData[i + 1] === 0x9c || blockData[i + 1] === 0x01 || blockData[i + 1] === 0xda)) {
- try {
- const sub = blockData.subarray(i);
- let decompressed: Uint8Array;
- try {
- decompressed = unzlibSync(sub);
- } catch {
- decompressed = inflateSync(sub.subarray(2));
- }
+export function parseBlockDataPayload(
+ payload: Uint8Array,
+ expectedBlocks: number
+): Map<number, Uint8Array> {
+ const tiles = new Map<number, Uint8Array>();
+ const maxBlocks = Math.min(Math.max(expectedBlocks, 1), MAX_BLOCKS_PER_LAYER);
+ const parsedEntries: Array<{ rawIndex: number; data: Uint8Array | null }> = [];
+
+ let cursor = 0;
+ let seqIdx = 0;
+ let foundTagged = false;
+
+ while (cursor < payload.length && seqIdx < maxBlocks * 2) {
+ const beginPos = indexOfBytes(payload, TAG_BLOCK_BEGIN, cursor);
+ if (beginPos < 0) break;
+ foundTagged = true;
+
+ const afterBegin = beginPos + TAG_BLOCK_BEGIN.length;
+ const endPos = indexOfBytes(payload, TAG_BLOCK_END, afterBegin);
+ const nextBegin = indexOfBytes(payload, TAG_BLOCK_BEGIN, afterBegin);
+
+ // Guard against empty blocks lacking an explicit BlockDataEndChunk
+ if (nextBegin >= 0 && (endPos < 0 || nextBegin < endPos)) {
+ parsedEntries.push({ rawIndex: seqIdx, data: null });
+ seqIdx++;
+ cursor = nextBegin;
+ continue;
+ }
+ if (endPos < 0) break;
+
+ const inner = payload.subarray(afterBegin, endPos);
+ const rawIndex =
+ inner.byteLength >= 4
+ ? new DataView(inner.buffer, inner.byteOffset, inner.byteLength).getUint32(0, false)
+ : seqIdx;
+
+ let decompressed: Uint8Array | null = null;
+ if (inner.byteLength > 20) {
+ const view = new DataView(inner.buffer, inner.byteOffset, inner.byteLength);
+ const hasDataAt16 = view.getUint32(16, false);
- // Expected: 256*256 bytes alpha + 256*256*4 bytes BGRX = 327680 bytes
- if (decompressed.length >= BLOCK_SIZE * BLOCK_SIZE * 5) {
- const k = BLOCK_SIZE * BLOCK_SIZE;
- const imgData = ctx.createImageData(BLOCK_SIZE, BLOCK_SIZE);
- const d = imgData.data;
-
- for (let p = 0; p < k; p++) {
- const alpha = decompressed[p];
- const b = decompressed[k + p * 4];
- const g = decompressed[k + p * 4 + 1];
- const r = decompressed[k + p * 4 + 2];
-
- const targetIdx = p * 4;
- d[targetIdx] = r;
- d[targetIdx + 1] = g;
- d[targetIdx + 2] = b;
- d[targetIdx + 3] = alpha;
- }
-
- const bx = (blockIndex % Math.ceil(canvasWidth / BLOCK_SIZE)) * BLOCK_SIZE + offsetX;
- const by = Math.floor(blockIndex / Math.ceil(canvasWidth / BLOCK_SIZE)) * BLOCK_SIZE + offsetY;
- ctx.putImageData(imgData, bx, by);
- blockIndex++;
- i += 100; // Skip ahead
+ if (hasDataAt16 !== 0) {
+ decompressed = decompressBlockSpan(inner.subarray(20));
+ }
+
+ // Probe alternate CSP version header offsets if standard +20 offset did not match
+ if (!decompressed && inner.byteLength > 28) {
+ for (const hdrLen of [16, 24, 12, 8]) {
+ if (inner.byteLength <= hdrLen + 6) continue;
+ const candidate = decompressBlockSpan(inner.subarray(hdrLen));
+ if (candidate && isValidTileByteLength(candidate.byteLength)) {
+ decompressed = candidate;
+ break;
}
- } catch {
- // Not a valid zlib block at this offset, continue scanning
}
}
}
- return blockIndex > 0 ? canvas : null;
- } catch (err) {
- console.warn('renderCspBitmapToCanvas failed:', err);
- return null;
+ parsedEntries.push({ rawIndex, data: decompressed });
+ seqIdx++;
+ cursor = endPos + TAG_BLOCK_END.length;
+ }
+
+ if (foundTagged) {
+ // Standard CSP emits every grid cell sequentially (empty or populated): use exact seqIdx.
+ // Only trust rawIndex when empty cells were omitted and rawIndex is strictly increasing within bounds.
+ let useRawIndex = parsedEntries.length < expectedBlocks && parsedEntries.length > 0;
+ if (useRawIndex) {
+ let prev = -1;
+ for (const e of parsedEntries) {
+ if (e.rawIndex <= prev || e.rawIndex >= maxBlocks) {
+ useRawIndex = false;
+ break;
+ }
+ prev = e.rawIndex;
+ }
+ }
+ for (let i = 0; i < parsedEntries.length; i++) {
+ const e = parsedEntries[i];
+ if (e.data) {
+ tiles.set(useRawIndex ? e.rawIndex : i, e.data);
+ }
+ }
+ return tiles;
+ }
+
+ // Fallback for non-tagged raw zlib block streams
+ let blockIdx = 0;
+ for (let i = 0; i < payload.length - 8 && blockIdx < maxBlocks; i++) {
+ if (isZlibHeader(payload[i], payload[i + 1])) {
+ const decoded = safeUnzlib(payload.subarray(i));
+ if (decoded && isValidTileByteLength(decoded.byteLength)) {
+ tiles.set(blockIdx, decoded);
+ blockIdx++;
+ i += 32;
+ }
+ }
+ }
+
+ return tiles;
+}
+
+/**
+ * Unpacks a single 256x256 decompressed CSP tile into RGBA (Uint8ClampedArray of length 262144).
+ * Returns true if any non-transparent pixel was written.
+ */
+export function decodeCspTileToRgba(
+ raw: Uint8Array,
+ outRgba: Uint8ClampedArray,
+ attr: ParsedOffscreenAttribute
+): boolean {
+ const len = raw.byteLength;
+ let hasPixels = false;
+
+ // 1. Standard CSP 32-bit Color: 1-byte Alpha plane (65536) + 4-byte BGRX plane (262144) = 327680
+ if (len >= TILE_PIXELS * 5) {
+ const colorOff = TILE_PIXELS;
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ const a = raw[p];
+ const di = p << 2;
+ if (a === 0) {
+ outRgba[di] = 0;
+ outRgba[di + 1] = 0;
+ outRgba[di + 2] = 0;
+ outRgba[di + 3] = 0;
+ } else {
+ const ci = colorOff + di;
+ outRgba[di] = raw[ci + 2]; // R
+ outRgba[di + 1] = raw[ci + 1]; // G
+ outRgba[di + 2] = raw[ci]; // B
+ outRgba[di + 3] = a;
+ hasPixels = true;
+ }
+ }
+ return hasPixels;
+ }
+
+ // 2. Single-plane 4-byte BGRA / BGRX (262144)
+ if (len >= TILE_PIXELS * 4) {
+ let anyAlpha = false;
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ if (raw[(p << 2) + 3] !== 0) {
+ anyAlpha = true;
+ break;
+ }
+ }
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ const i = p << 2;
+ const b = raw[i];
+ const g = raw[i + 1];
+ const r = raw[i + 2];
+ const a = anyAlpha ? raw[i + 3] : (r | g | b) !== 0 ? 255 : 0;
+ outRgba[i] = r;
+ outRgba[i + 1] = g;
+ outRgba[i + 2] = b;
+ outRgba[i + 3] = a;
+ if (a !== 0) hasPixels = true;
+ }
+ return hasPixels;
+ }
+
+ // 3. CSP Grayscale 2-plane: Alpha (65536) + Gray luminance (65536) = 131072
+ if (len >= TILE_PIXELS * 2) {
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ const a = raw[p];
+ const di = p << 2;
+ if (a === 0) {
+ outRgba[di] = 0;
+ outRgba[di + 1] = 0;
+ outRgba[di + 2] = 0;
+ outRgba[di + 3] = 0;
+ } else {
+ const g = raw[TILE_PIXELS + p];
+ outRgba[di] = g;
+ outRgba[di + 1] = g;
+ outRgba[di + 2] = g;
+ outRgba[di + 3] = a;
+ hasPixels = true;
+ }
+ }
+ return hasPixels;
+ }
+
+ // 4. Single-channel 8-bit (65536): Alpha-only ink layer (black or white depending on defaultFill)
+ if (len >= TILE_PIXELS) {
+ const ink = attr.defaultFill === 1 ? 255 : 0;
+ for (let p = 0; p < TILE_PIXELS; p++) {
+ const a = raw[p];
+ const di = p << 2;
+ if (a === 0) {
+ outRgba[di] = 0;
+ outRgba[di + 1] = 0;
+ outRgba[di + 2] = 0;
+ outRgba[di + 3] = 0;
+ } else {
+ outRgba[di] = ink;
+ outRgba[di + 1] = ink;
+ outRgba[di + 2] = ink;
+ outRgba[di + 3] = a;
+ hasPixels = true;
+ }
+ }
+ return hasPixels;
+ }
+
+ // 5. Monochrome 2-plane 1-bit: Alpha bits (8192) + White/Black color bits (8192) = 16384
+ if (len >= 16384) {
+ for (let byteIdx = 0; byteIdx < 8192; byteIdx++) {
+ const aByte = raw[byteIdx];
+ const cByte = raw[8192 + byteIdx];
+ const baseP = byteIdx << 3;
+ if (aByte === 0) {
+ outRgba.fill(0, baseP << 2, (baseP + 8) << 2);
+ continue;
+ }
+ for (let bit = 0; bit < 8; bit++) {
+ const mask = 1 << (7 - bit);
+ const di = (baseP + bit) << 2;
+ if ((aByte & mask) !== 0) {
+ const c = (cByte & mask) !== 0 ? 255 : 0;
+ outRgba[di] = c;
+ outRgba[di + 1] = c;
+ outRgba[di + 2] = c;
+ outRgba[di + 3] = 255;
+ hasPixels = true;
+ } else {
+ outRgba[di] = 0;
+ outRgba[di + 1] = 0;
+ outRgba[di + 2] = 0;
+ outRgba[di + 3] = 0;
+ }
+ }
+ }
+ return hasPixels;
+ }
+
+ // 6. Monochrome 1-plane 1-bit (8192): Black (or white) ink bits
+ if (len >= 8192) {
+ const ink = attr.defaultFill === 1 ? 255 : 0;
+ for (let byteIdx = 0; byteIdx < 8192; byteIdx++) {
+ const aByte = raw[byteIdx];
+ const baseP = byteIdx << 3;
+ if (aByte === 0) {
+ outRgba.fill(0, baseP << 2, (baseP + 8) << 2);
+ continue;
+ }
+ for (let bit = 0; bit < 8; bit++) {
+ const di = (baseP + bit) << 2;
+ if ((aByte & (1 << (7 - bit))) !== 0) {
+ outRgba[di] = ink;
+ outRgba[di + 1] = ink;
+ outRgba[di + 2] = ink;
+ outRgba[di + 3] = 255;
+ hasPixels = true;
+ } else {
+ outRgba[di] = 0;
+ outRgba[di + 1] = 0;
+ outRgba[di + 2] = 0;
+ outRgba[di + 3] = 0;
+ }
+ }
+ }
+ return hasPixels;
+ }
+
+ return false;
+}
+
+/**
+ * Unpacks a single 256x256 mask tile into 65536 grayscale bytes (0 = hidden, 255 = revealed).
+ */
+function decodeCspTileToMaskValues(raw: Uint8Array, outMask: Uint8Array): boolean {
+ if (raw.byteLength >= TILE_PIXELS) {
+ outMask.set(raw.subarray(0, TILE_PIXELS));
+ return true;
+ }
+ if (raw.byteLength >= 8192) {
+ for (let byteIdx = 0; byteIdx < 8192; byteIdx++) {
+ const b = raw[byteIdx];
+ const baseP = byteIdx << 3;
+ for (let bit = 0; bit < 8; bit++) {
+ outMask[baseP + bit] = (b & (1 << (7 - bit))) !== 0 ? 255 : 0;
+ }
+ }
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Writes a clipped tile rectangle into SparseTileGrid without allocating a full-document canvas.
+ */
+function writeClippedTileToGrid(
+ tileGrid: SparseTileGrid,
+ layerId: string,
+ tileRgba: Uint8ClampedArray,
+ tileDocX: number,
+ tileDocY: number,
+ maxBitmapW: number,
+ maxBitmapH: number,
+ offsetX: number,
+ offsetY: number,
+ docWidth: number,
+ docHeight: number
+): void {
+ const validRight = Math.min(docWidth, offsetX + maxBitmapW);
+ const validBottom = Math.min(docHeight, offsetY + maxBitmapH);
+
+ const srcX0 = Math.max(0, -tileDocX);
+ const srcY0 = Math.max(0, -tileDocY);
+ const srcX1 = Math.min(TILE_SIZE, validRight - tileDocX);
+ const srcY1 = Math.min(TILE_SIZE, validBottom - tileDocY);
+ if (srcX0 >= srcX1 || srcY0 >= srcY1) return;
+
+ if (srcX0 === 0 && srcY0 === 0 && srcX1 === TILE_SIZE && srcY1 === TILE_SIZE) {
+ tileGrid.writeImageData(
+ layerId,
+ { data: tileRgba, width: TILE_SIZE, height: TILE_SIZE },
+ tileDocX,
+ tileDocY,
+ 'color-32bit',
+ true
+ );
+ return;
+ }
+
+ const cw = srcX1 - srcX0;
+ const ch = srcY1 - srcY0;
+ const cropped = new Uint8ClampedArray(cw * ch * 4);
+ const rowBytes = cw * 4;
+ for (let row = 0; row < ch; row++) {
+ const srcOff = ((srcY0 + row) * TILE_SIZE + srcX0) * 4;
+ cropped.set(tileRgba.subarray(srcOff, srcOff + rowBytes), row * rowBytes);
}
+ tileGrid.writeImageData(
+ layerId,
+ { data: cropped, width: cw, height: ch },
+ tileDocX + srcX0,
+ tileDocY + srcY0,
+ 'color-32bit',
+ true
+ );
}
/**
- * Loads a PNG/JPEG blob/Uint8Array into an HTMLCanvasElement.
+ * Decodes a CSP mask offscreen into an Ink Studio maskCanvas (grayscale RGB, alpha=255).
*/
-function imageBytesToCanvas(bytes: Uint8Array, width?: number, height?: number): Promise<HTMLCanvasElement> {
- return new Promise((resolve, reject) => {
+function buildMaskCanvasFromOffscreen(
+ offscreen: OffscreenRecord,
+ extaChunks: Map<string, Uint8Array>,
+ maskOffsetX: number,
+ maskOffsetY: number,
+ docWidth: number,
+ docHeight: number,
+ maskScratch: Uint8Array
+): HTMLCanvasElement | undefined {
+ if (typeof document === 'undefined') return undefined;
+
+ const attr = parseOffscreenAttribute(offscreen.attribute, docWidth, docHeight);
+ const defaultVal = attr.defaultFill !== 0 ? 255 : 0;
+
+ const maskCanvas = document.createElement('canvas');
+ maskCanvas.width = docWidth;
+ maskCanvas.height = docHeight;
+ const mCtx = maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (!mCtx) return undefined;
+
+ const outImg = mCtx.createImageData(docWidth, docHeight);
+ const out = outImg.data;
+ for (let i = 0; i < out.length; i += 4) {
+ out[i] = defaultVal;
+ out[i + 1] = defaultVal;
+ out[i + 2] = defaultVal;
+ out[i + 3] = 255;
+ }
+
+ const payload = offscreen.blockDataId ? extaChunks.get(offscreen.blockDataId) : undefined;
+ if (payload) {
+ const totalBlocks = attr.blockGridWidth * attr.blockGridHeight;
+ const tiles = parseBlockDataPayload(payload, totalBlocks);
+ for (const [blockIdx, raw] of tiles.entries()) {
+ if (!decodeCspTileToMaskValues(raw, maskScratch)) continue;
+ const col = blockIdx % attr.blockGridWidth;
+ const row = Math.floor(blockIdx / attr.blockGridWidth);
+ const tileDocX = col * TILE_SIZE + maskOffsetX;
+ const tileDocY = row * TILE_SIZE + maskOffsetY;
+
+ const x0 = Math.max(0, -tileDocX);
+ const y0 = Math.max(0, -tileDocY);
+ const x1 = Math.min(TILE_SIZE, docWidth - tileDocX, attr.bitmapWidth - col * TILE_SIZE);
+ const y1 = Math.min(TILE_SIZE, docHeight - tileDocY, attr.bitmapHeight - row * TILE_SIZE);
+ if (x0 >= x1 || y0 >= y1) continue;
+
+ for (let sy = y0; sy < y1; sy++) {
+ const dy = tileDocY + sy;
+ const srcRow = sy * TILE_SIZE;
+ const dstRow = dy * docWidth;
+ for (let sx = x0; sx < x1; sx++) {
+ const v = maskScratch[srcRow + sx];
+ const di = (dstRow + tileDocX + sx) << 2;
+ out[di] = v;
+ out[di + 1] = v;
+ out[di + 2] = v;
+ out[di + 3] = 255;
+ }
+ }
+ }
+ }
+
+ mCtx.putImageData(outImg, 0, 0);
+ return maskCanvas;
+}
+
+type SqlRow = Record<string, SqlValue>;
+
+function getTableNames(db: Database): Set<string> {
+ const names = new Set<string>();
+ try {
+ const res = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
+ if (res.length > 0) {
+ for (const row of res[0].values) {
+ if (typeof row[0] === 'string') names.add(row[0]);
+ }
+ }
+ } catch {
+ // ignore
+ }
+ return names;
+}
+
+function queryTable(db: Database, tables: Set<string>, tableName: string): SqlRow[] {
+ if (!tables.has(tableName)) return [];
+ try {
+ const res = db.exec(`SELECT * FROM "${tableName.replace(/"/g, '""')}"`);
+ if (res.length === 0) return [];
+ const { columns, values } = res[0];
+ const out: SqlRow[] = new Array(values.length);
+ for (let i = 0; i < values.length; i++) {
+ const obj: SqlRow = {};
+ const row = values[i];
+ for (let c = 0; c < columns.length; c++) {
+ obj[columns[c]] = row[c];
+ }
+ out[i] = obj;
+ }
+ return out;
+ } catch {
+ return [];
+ }
+}
+
+function getNum(row: SqlRow, keys: string[], fallback: number): number {
+ for (const k of keys) {
+ const v = row[k];
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
+ }
+ return fallback;
+}
+
+function getOptNum(row: SqlRow, keys: string[]): number | null {
+ for (const k of keys) {
+ const v = row[k];
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
+ }
+ return null;
+}
+
+const utf8Decoder = new TextDecoder('utf-8', { fatal: false });
+
+function getStr(row: SqlRow, keys: string[], fallback: string): string {
+ for (const k of keys) {
+ const v = row[k];
+ if (typeof v === 'string' && v.length > 0) return v.replace(/\0+$/, '');
+ if (v instanceof Uint8Array && v.byteLength > 0) {
+ const decoded = utf8Decoder.decode(v).replace(/\0+$/, '');
+ if (decoded.length > 0) return decoded;
+ }
+ }
+ return fallback;
+}
+
+function getBytes(row: SqlRow, keys: string[]): Uint8Array | null {
+ for (const k of keys) {
+ const v = row[k];
+ if (v instanceof Uint8Array && v.byteLength > 0) return v;
+ }
+ return null;
+}
+
+function rgbToHex(r: number, g: number, b: number): string {
+ const clamp = (n: number) => Math.max(0, Math.min(255, Math.round(n)));
+ return (
+ '#' +
+ ((1 << 24) | (clamp(r) << 16) | (clamp(g) << 8) | clamp(b))
+ .toString(16)
+ .slice(1)
+ );
+}
+
+function normalizeColorChannel(v: number): number {
+ if (v <= 255) return Math.max(0, Math.round(v));
+ if (v <= 65535) return (v >> 8) & 0xff;
+ return (v >>> 24) & 0xff;
+}
+
+function bytesToPngDataUrl(bytes: Uint8Array): string | undefined {
+ if (bytes.byteLength < 8) return undefined;
+ // Detect PNG or JPEG magic
+ const isPng =
+ bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47;
+ const isJpeg = bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
+ if (!isPng && !isJpeg) return undefined;
+ const mime = isPng ? 'image/png' : 'image/jpeg';
+ if (typeof btoa === 'function') {
+ let bin = '';
+ const step = 0x8000;
+ for (let i = 0; i < bytes.byteLength; i += step) {
+ bin += String.fromCharCode(...bytes.subarray(i, Math.min(bytes.byteLength, i + step)));
+ }
+ return `data:${mime};base64,${btoa(bin)}`;
+ }
+ return undefined;
+}
+
+function decodeImageBytesToTileGrid(
+ bytes: Uint8Array,
+ tileGrid: SparseTileGrid,
+ layerId: string,
+ width: number,
+ height: number
+): Promise<boolean> {
+ if (typeof document === 'undefined' || typeof Image === 'undefined' || typeof URL === 'undefined') {
+ return Promise.resolve(false);
+ }
+ return new Promise((resolve) => {
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
const blob = new Blob([copy]);
@@ -252,31 +1018,98 @@ function imageBytesToCanvas(bytes: Uint8Array, width?: number, height?: number):
img.onload = () => {
URL.revokeObjectURL(url);
- const w = width || img.naturalWidth || 1440;
- const h = height || img.naturalHeight || 900;
const canvas = document.createElement('canvas');
- canvas.width = w;
- canvas.height = h;
- const ctx = canvas.getContext('2d');
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (ctx) {
- ctx.drawImage(img, 0, 0, w, h);
+ ctx.drawImage(img, 0, 0, width, height);
+ tileGrid.ingestCanvas(layerId, canvas, 'color-32bit');
}
- resolve(canvas);
+ canvas.width = 0;
+ canvas.height = 0;
+ resolve(Boolean(ctx));
};
- img.onerror = (e) => {
+ img.onerror = () => {
URL.revokeObjectURL(url);
- reject(e);
+ resolve(false);
};
img.src = url;
});
}
+interface OffscreenRecord {
+ mainId: number;
+ layerId: number;
+ blockDataId: string;
+ attribute: Uint8Array | null;
+}
+
+interface MipmapInfoRecord {
+ mainId: number;
+ offscreenId: number;
+ thisScale: number;
+ nextIndex: number;
+}
+
+/**
+ * Extracts Paper / Solid Color fill hex if the layer row or associated fill tables specify one.
+ */
+function extractSolidFillColor(
+ layerRow: SqlRow,
+ attr: ParsedOffscreenAttribute | null,
+ fillByLayerId: Map<number, string>,
+ isBottomMost: boolean
+): string | null {
+ const mainId = getNum(layerRow, ['MainId'], -1);
+ if (fillByLayerId.has(mainId)) {
+ return fillByLayerId.get(mainId)!;
+ }
+
+ // Check explicit fill color columns on Layer (present in some CSP versions)
+ const r = getOptNum(layerRow, ['LayerFillRed', 'FillColorRed', 'PaperRed']);
+ const g = getOptNum(layerRow, ['LayerFillGreen', 'FillColorGreen', 'PaperGreen']);
+ const b = getOptNum(layerRow, ['LayerFillBlue', 'FillColorBlue', 'PaperBlue']);
+ if (r !== null && g !== null && b !== null) {
+ return rgbToHex(normalizeColorChannel(r), normalizeColorChannel(g), normalizeColorChannel(b));
+ }
+
+ // Check packed ARGB/RGB color integer on Paper/Fill layers
+ const packedColor = getOptNum(layerRow, ['LayerFillColor', 'SolidColor', 'PaperColor']);
+ if (packedColor !== null && packedColor !== 0) {
+ return rgbToHex((packedColor >>> 16) & 0xff, (packedColor >>> 8) & 0xff, packedColor & 0xff);
+ }
+
+ // Check Offscreen Attribute InitColor (opaque)
+ if (attr?.initColor && attr.initColor[3] > 0) {
+ return rgbToHex(attr.initColor[0], attr.initColor[1], attr.initColor[2]);
+ }
+
+ // CSP Paper layer heuristic: bottom-most layer named Paper / 用紙 or defaultFill=1 with no tiles
+ const name = getStr(layerRow, ['LayerName'], '').trim().toLowerCase();
+ const isPaperName = name === 'paper' || name === '用紙' || name === 'papier' || name === 'papel';
+ const layerType = getNum(layerRow, ['LayerType'], -1);
+ // CSP Paper layer frequently has LayerType = 1 with no offscreen, or specific fill type, or defaultFill = 1
+ if (isPaperName || (isBottomMost && attr?.defaultFill === 1) || layerType === 1280) {
+ return '#ffffff';
+ }
+
+ return null;
+}
+
/**
- * Main parser for Clip Studio Paint (.clip / .csp) files.
+ * Main parser for Clip Studio Paint (.clip / .csp / .lip) files.
+ * Decodes full layer hierarchy, folders, raster/vector/text cached bitmaps,
+ * layer masks, blend modes, opacity, clipping, locks, and paper fills
+ * directly into a SparseTileGrid-backed LoadedDocument.
*/
-export async function parseCspFile(buffer: ArrayBuffer, fileName: string): Promise<LoadedDocument> {
+export async function parseCspFile(
+ buffer: ArrayBuffer,
+ fileName: string,
+ targetGrid?: SparseTileGrid
+): Promise<LoadedDocument> {
const bytes = new Uint8Array(buffer);
const chunks = parseCspChunks(bytes);
const sqliteData = findSqliteData(chunks, bytes);
@@ -286,192 +1119,509 @@ export async function parseCspFile(buffer: ArrayBuffer, fileName: string): Promi
}
const SQL = await getSql();
- const db: Database = new SQL.Database(sqliteData);
+ // sql.js requires a standalone Uint8Array copy when given a subarray view
+ const dbBytes =
+ sqliteData.byteOffset === 0 && sqliteData.byteLength === sqliteData.buffer.byteLength
+ ? sqliteData
+ : sqliteData.slice();
+ const db: Database = new SQL.Database(dbBytes);
- // 1. Get Canvas Dimensions
- let width = 1440;
- let height = 900;
try {
- const res = db.exec('SELECT CanvasWidth, CanvasHeight FROM Canvas LIMIT 1');
- if (res.length > 0 && res[0].values.length > 0) {
- width = Number(res[0].values[0][0]) || 1440;
- height = Number(res[0].values[0][1]) || 900;
+ const tables = getTableNames(db);
+
+ // 1. Canvas metadata
+ let width = 1440;
+ let height = 900;
+ let dpi = 300;
+ let rootFolderId: number | null = null;
+ const colorMode: CanvasColorMode = 'color';
+
+ const canvasRows = queryTable(db, tables, 'Canvas');
+ if (canvasRows.length > 0) {
+ const c = canvasRows[0];
+ const w = getNum(c, ['CanvasWidth'], 1440);
+ const h = getNum(c, ['CanvasHeight'], 900);
+ width = Math.max(1, Math.min(MAX_CANVAS_DIM, Math.round(w)));
+ height = Math.max(1, Math.min(MAX_CANVAS_DIM, Math.round(h)));
+ const res = getNum(c, ['CanvasResolution', 'CanvasDpi'], 300);
+ dpi = Math.max(1, Math.min(2400, Math.round(res)));
+ rootFolderId = getOptNum(c, ['CanvasRootFolder']);
}
- } catch (e) {
- console.warn('Could not read Canvas table in CSP file:', e);
- }
- // 2. Extract composite preview image if present
- let previewCanvas: HTMLCanvasElement | null = null;
- try {
- const previewRes = db.exec('SELECT ImageData FROM CanvasPreview LIMIT 1');
- if (previewRes.length > 0 && previewRes[0].values.length > 0) {
- const previewBytes = previewRes[0].values[0][0] as Uint8Array;
- if (previewBytes && previewBytes.length > 0) {
- previewCanvas = await imageBytesToCanvas(previewBytes, width, height);
+ // 2. Preview image bytes (for recent-doc thumbnail & last-resort fallback)
+ let previewBytes: Uint8Array | null = null;
+ const previewRows = queryTable(db, tables, 'CanvasPreview');
+ if (previewRows.length > 0) {
+ previewBytes = getBytes(previewRows[0], ['ImageData']);
+ }
+ const previewDataUrl = previewBytes ? bytesToPngDataUrl(previewBytes) : undefined;
+
+ // 3. External CHNKExta map
+ const extaChunks = extractExtaChunks(chunks);
+
+ // 4. Build Mipmap -> MipmapInfo -> Offscreen lookup tables
+ const mipmapBaseInfoById = new Map<number, number>();
+ for (const row of queryTable(db, tables, 'Mipmap')) {
+ const id = getNum(row, ['MainId'], -1);
+ const baseInfo = getNum(row, ['BaseMipmapInfo'], 0);
+ if (id >= 0 && baseInfo > 0) {
+ mipmapBaseInfoById.set(id, baseInfo);
}
}
- } catch (e) {
- console.warn('Could not read CanvasPreview in CSP file:', e);
- }
- // 3. Extract External Data Chunks
- const extaChunks = extractExtaChunks(chunks);
+ const mipmapInfoById = new Map<number, MipmapInfoRecord>();
+ const mipmapInfoTable = tables.has('MipmapInfo')
+ ? 'MipmapInfo'
+ : tables.has('MipmapStoring')
+ ? 'MipmapStoring'
+ : '';
+ if (mipmapInfoTable) {
+ for (const row of queryTable(db, tables, mipmapInfoTable)) {
+ const mainId = getNum(row, ['MainId'], -1);
+ const offscreenId = getNum(row, ['Offscreen'], 0);
+ const thisScale = getNum(row, ['ThisScale'], 1);
+ const nextIndex = getNum(row, ['NextIndex'], 0);
+ if (mainId >= 0) {
+ mipmapInfoById.set(mainId, { mainId, offscreenId, thisScale, nextIndex });
+ }
+ }
+ }
- // 4. Query Layers
- const layers: LayerItem[] = [];
- const layerCanvases = new Map<string, HTMLCanvasElement>();
+ const offscreenById = new Map<number, OffscreenRecord>();
+ const offscreensByLayerId = new Map<number, OffscreenRecord[]>();
+ for (const row of queryTable(db, tables, 'Offscreen')) {
+ const mainId = getNum(row, ['MainId'], -1);
+ const layerId = getNum(row, ['LayerId'], -1);
+ const blockDataId = getStr(row, ['BlockData'], '');
+ const attribute = getBytes(row, ['Attribute']);
+ if (mainId < 0) continue;
+ const rec: OffscreenRecord = { mainId, layerId, blockDataId, attribute };
+ offscreenById.set(mainId, rec);
+ if (layerId >= 0) {
+ let list = offscreensByLayerId.get(layerId);
+ if (!list) {
+ list = [];
+ offscreensByLayerId.set(layerId, list);
+ }
+ list.push(rec);
+ }
+ }
- try {
- // Check if Layer table exists
- const layerRes = db.exec(
- 'SELECT MainId, LayerName, LayerType, LayerComposite, LayerOpacity, LayerVisibility, LayerLock, LayerOffsetX, LayerOffsetY FROM Layer'
- );
+ // Optional solid-color / paper fill tables (CSP stores Paper/Fill color in Fill / SolidColor / Paper when present)
+ const fillByLayerId = new Map<number, string>();
+ for (const fillTable of ['SolidColor', 'FillLayer', 'Paper', 'Fill']) {
+ for (const row of queryTable(db, tables, fillTable)) {
+ const lid = getNum(row, ['LayerId', 'MainId'], -1);
+ if (lid < 0) continue;
+ const r = getOptNum(row, ['Red', 'ColorRed', 'FillRed', 'R']);
+ const g = getOptNum(row, ['Green', 'ColorGreen', 'FillGreen', 'G']);
+ const b = getOptNum(row, ['Blue', 'ColorBlue', 'FillBlue', 'B']);
+ if (r !== null && g !== null && b !== null) {
+ fillByLayerId.set(
+ lid,
+ rgbToHex(normalizeColorChannel(r), normalizeColorChannel(g), normalizeColorChannel(b))
+ );
+ }
+ }
+ }
- if (layerRes.length > 0 && layerRes[0].values.length > 0) {
- // Also query Offscreen table if available for raster chunks
- const offscreenMap = new Map<number, string>();
- try {
- const offRes = db.exec('SELECT LayerId, BlockData FROM Offscreen');
- if (offRes.length > 0) {
- for (const row of offRes[0].values) {
- const layerId = Number(row[0]);
- const blockDataId = String(row[1]);
- offscreenMap.set(layerId, blockDataId);
- }
+ const resolveMipmapToOffscreen = (mipmapId: number): OffscreenRecord | null => {
+ if (mipmapId <= 0) return null;
+ let infoId = mipmapBaseInfoById.get(mipmapId);
+ if (!infoId) return null;
+
+ let best: OffscreenRecord | null = null;
+ const seen = new Set<number>();
+ while (infoId && infoId > 0 && !seen.has(infoId)) {
+ seen.add(infoId);
+ const info = mipmapInfoById.get(infoId);
+ if (!info) break;
+ const off = offscreenById.get(info.offscreenId) ?? null;
+ if (off) {
+ if (Math.abs(info.thisScale - 1) < 0.001) return off;
+ if (!best) best = off;
}
- } catch {
- // Offscreen table optional
- }
-
- for (const row of layerRes[0].values) {
- const mainId = Number(row[0]);
- const name = String(row[1] || `Layer ${mainId}`);
- const layerType = Number(row[2]); // 0 = folder, 1/2 = raster
- const compositeVal = Number(row[3] || 0);
- const opacityVal = Number(row[4] ?? 255);
- const visibilityVal = Number(row[5] ?? 1);
- const lockVal = Number(row[6] ?? 0);
- const offsetX = Number(row[7] ?? 0);
- const offsetY = Number(row[8] ?? 0);
-
- const isFolder = layerType === 0;
- const id = `csp-${isFolder ? 'folder' : 'layer'}-${mainId}-${Date.now()}`;
- const blendMode = mapCspBlendMode(compositeVal);
- const opacity = Math.max(0, Math.min(1, opacityVal / 255));
- const visible = visibilityVal !== 0;
- const locked = lockVal !== 0;
-
- if (isFolder) {
- layers.push({
- id,
- name,
- type: 'folder',
- visible,
- opacity,
- blendMode,
- locked,
- collapsed: false,
- parentId: null,
- });
- } else {
- // Attempt to decode raster subblocks
- let canvas: HTMLCanvasElement | null = null;
- const blockId = offscreenMap.get(mainId);
- if (blockId && extaChunks.has(blockId)) {
- const rawBlock = extaChunks.get(blockId)!;
- canvas = renderCspBitmapToCanvas(rawBlock, width, height, offsetX, offsetY);
+ infoId = info.nextIndex;
+ }
+ return best;
+ };
+
+ // 5. Query Layer table and reconstruct full tree
+ const layerRows = queryTable(db, tables, 'Layer');
+ const layerRowById = new Map<number, SqlRow>();
+ const referencedAsMaskOffscreen = new Set<number>();
+
+ for (const row of layerRows) {
+ const mainId = getNum(row, ['MainId'], -1);
+ if (mainId < 0) continue;
+ layerRowById.set(mainId, row);
+ const maskMipmapId = getNum(row, ['LayerLayerMaskMipmap', 'LayerMaskMipmap'], 0);
+ const maskOff = resolveMipmapToOffscreen(maskMipmapId);
+ if (maskOff) referencedAsMaskOffscreen.add(maskOff.mainId);
+ }
+
+ // Collect ordered siblings (bottom-to-top in CSP) from a parent folder
+ const collectChildrenBottomToTop = (
+ firstChildId: number,
+ visitedNodes: Set<number>
+ ): SqlRow[] => {
+ const list: SqlRow[] = [];
+ let curId = firstChildId;
+ while (curId > 0 && !visitedNodes.has(curId) && list.length < MAX_LAYERS) {
+ const row = layerRowById.get(curId);
+ if (!row) break;
+ visitedNodes.add(curId);
+ list.push(row);
+ curId = getNum(row, ['LayerNextIndex'], 0);
+ }
+ return list;
+ };
+
+ const tileGrid = targetGrid ?? new SparseTileGrid();
+ const layers: LayerItem[] = [];
+ const tileRgbaScratch = new Uint8ClampedArray(TILE_PIXELS * 4);
+ const maskTileScratch = new Uint8Array(TILE_PIXELS);
+ const runStamp = Date.now();
+ let seq = 0;
+ let decodedAnyPixels = false;
+
+ const resolveLayerRenderOffscreen = (row: SqlRow, mainId: number): OffscreenRecord | null => {
+ const renderMipmapId = getNum(row, ['LayerRenderMipmap'], 0);
+ const fromMipmap = resolveMipmapToOffscreen(renderMipmapId);
+ if (fromMipmap) return fromMipmap;
+
+ const directOffId = getNum(row, ['LayerRenderOffscreen'], 0);
+ if (directOffId > 0 && offscreenById.has(directOffId)) {
+ return offscreenById.get(directOffId)!;
+ }
+
+ // Fallback: pick largest non-mask offscreen associated with this LayerId
+ const candidates = offscreensByLayerId.get(mainId);
+ if (!candidates || candidates.length === 0) return null;
+ let best: OffscreenRecord | null = null;
+ let bestArea = -1;
+ for (const c of candidates) {
+ if (referencedAsMaskOffscreen.has(c.mainId)) continue;
+ if (!c.blockDataId || !extaChunks.has(c.blockDataId)) continue;
+ const a = parseOffscreenAttribute(c.attribute, width, height);
+ const area = a.bitmapWidth * a.bitmapHeight;
+ if (area > bestArea) {
+ bestArea = area;
+ best = c;
+ }
+ }
+ return best;
+ };
+
+ const emitLayerNode = (
+ row: SqlRow,
+ parentId: string | null,
+ visitedNodes: Set<number>,
+ depth: number,
+ isBottomMostRoot: boolean,
+ parentOffsetX: number,
+ parentOffsetY: number
+ ): void => {
+ if (depth > MAX_FOLDER_DEPTH || layers.length >= MAX_LAYERS) return;
+
+ const mainId = getNum(row, ['MainId'], seq + 1);
+ const name = getStr(row, ['LayerName'], `Layer ${mainId}`);
+ const layerFolder = getOptNum(row, ['LayerFolder']);
+ const firstChildId = getNum(row, ['LayerFirstChildIndex'], 0);
+ const layerType = getNum(row, ['LayerType'], 1);
+ const compositeVal = getNum(row, ['LayerComposite'], 0);
+ const rawOpacity = getNum(row, ['LayerOpacity'], 256);
+ const visibilityVal = getNum(row, ['LayerVisibility'], 1);
+ const lockVal = getNum(row, ['LayerLock'], 0);
+ const clipVal = getNum(row, ['LayerClip'], 0);
+ const layerSelect = getOptNum(row, ['LayerSelect']);
+
+ // CSP accumulates folder LayerOffsetX/Y onto all descendants, and adds
+ // per-offscreen origin offsets (LayerRenderOffscrOffsetX/Y, LayerMaskOffscrOffsetX/Y).
+ const baseOffsetX = parentOffsetX + getNum(row, ['LayerOffsetX', 'LayerMoveOffsetX'], 0);
+ const baseOffsetY = parentOffsetY + getNum(row, ['LayerOffsetY', 'LayerMoveOffsetY'], 0);
+ const offsetX = Math.round(
+ baseOffsetX + getNum(row, ['LayerRenderOffscrOffsetX', 'LayerRenderOffsetX'], 0)
+ );
+ const offsetY = Math.round(
+ baseOffsetY + getNum(row, ['LayerRenderOffscrOffsetY', 'LayerRenderOffsetY'], 0)
+ );
+ const maskOffsetX = Math.round(
+ baseOffsetX +
+ getNum(row, ['LayerMaskOffsetX'], 0) +
+ getNum(row, ['LayerMaskOffscrOffsetX'], 0)
+ );
+ const maskOffsetY = Math.round(
+ baseOffsetY +
+ getNum(row, ['LayerMaskOffsetY'], 0) +
+ getNum(row, ['LayerMaskOffscrOffsetY'], 0)
+ );
+
+ const hasRenderOffscreen = Boolean(resolveLayerRenderOffscreen(row, mainId));
+ const isFolder =
+ (layerFolder !== null && layerFolder !== 0) ||
+ firstChildId > 0 ||
+ (layerFolder === null && layerType === 0 && !hasRenderOffscreen);
+
+ seq += 1;
+ const id = `csp-${isFolder ? 'folder' : 'layer'}-${mainId}-${runStamp}-${seq}`;
+ const blendMode = mapCspBlendMode(compositeVal);
+ // CSP stores opacity in [0..256] (256 = 100%)
+ const opacity = Math.max(0, Math.min(1, rawOpacity / 256));
+ const visible = (visibilityVal & 1) !== 0;
+ const locked = (lockVal & 1) !== 0;
+ const alphaLocked =
+ (lockVal & 16) !== 0 || getNum(row, ['LayerLockTransparentPixel', 'LayerAlphaLock'], 0) !== 0;
+ const clipped = clipVal !== 0;
+
+ // Optional layer mask
+ const maskMipmapId = getNum(row, ['LayerLayerMaskMipmap', 'LayerMaskMipmap'], 0);
+ const maskOffscreen = resolveMipmapToOffscreen(maskMipmapId);
+ let maskFields: Pick<
+ LayerItem,
+ 'maskCanvas' | 'maskEnabled' | 'maskLinked' | 'maskVersion' | 'maskThumbnailUrl'
+ > = {};
+ if (maskOffscreen) {
+ const maskCanvas = buildMaskCanvasFromOffscreen(
+ maskOffscreen,
+ extaChunks,
+ maskOffsetX,
+ maskOffsetY,
+ width,
+ height,
+ maskTileScratch
+ );
+ // CSP exact bitflags: LayerVisibility & 2 = mask enabled; LayerSelect & 256 = mask linked
+ const maskEnabled =
+ row['LayerVisibility'] !== undefined ? (visibilityVal & 2) !== 0 : true;
+ const maskLinked = layerSelect !== null ? (layerSelect & 256) !== 0 : true;
+ maskFields = {
+ maskCanvas,
+ maskEnabled,
+ maskLinked,
+ maskVersion: 1,
+ maskThumbnailUrl: maskCanvas ? createCanvasThumbnail(maskCanvas, false) : undefined,
+ };
+ }
+
+ if (isFolder) {
+ const collapsed = layerFolder !== null ? (layerFolder & 16) !== 0 : false;
+ layers.push({
+ id,
+ name,
+ type: 'folder',
+ visible,
+ opacity,
+ blendMode,
+ locked,
+ alphaLocked,
+ clipped,
+ collapsed,
+ parentId,
+ ...maskFields,
+ });
+
+ if (firstChildId > 0) {
+ const childrenBottomToTop = collectChildrenBottomToTop(firstChildId, visitedNodes);
+ // Reverse bottom-to-top into Ink Studio's top-to-bottom stack order
+ for (let i = childrenBottomToTop.length - 1; i >= 0; i--) {
+ emitLayerNode(
+ childrenBottomToTop[i],
+ id,
+ visitedNodes,
+ depth + 1,
+ false,
+ baseOffsetX,
+ baseOffsetY
+ );
}
+ }
+ return;
+ }
+
+ // Editable raster layer (including cached raster render of vector/text/balloon/tone/3D layers)
+ tileGrid.setLayerFormat(id, 'color-32bit');
+ tileGrid.markLayerIngested(id);
+
+ const offscreen = resolveLayerRenderOffscreen(row, mainId);
+ const attr = offscreen ? parseOffscreenAttribute(offscreen.attribute, width, height) : null;
+ let layerHasPixels = false;
- if (!canvas) {
- canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
+ if (offscreen && offscreen.blockDataId && extaChunks.has(offscreen.blockDataId)) {
+ const payload = extaChunks.get(offscreen.blockDataId)!;
+ const resolvedAttr = attr!;
+ const expectedBlocks = resolvedAttr.blockGridWidth * resolvedAttr.blockGridHeight;
+ const decodedTiles = parseBlockDataPayload(payload, expectedBlocks);
+
+ for (const [blockIdx, rawTile] of decodedTiles.entries()) {
+ if (decodeCspTileToRgba(rawTile, tileRgbaScratch, resolvedAttr)) {
+ const col = blockIdx % resolvedAttr.blockGridWidth;
+ const rowIdx = Math.floor(blockIdx / resolvedAttr.blockGridWidth);
+ const tileDocX = col * TILE_SIZE + offsetX;
+ const tileDocY = rowIdx * TILE_SIZE + offsetY;
+ writeClippedTileToGrid(
+ tileGrid,
+ id,
+ tileRgbaScratch,
+ tileDocX,
+ tileDocY,
+ resolvedAttr.bitmapWidth,
+ resolvedAttr.bitmapHeight,
+ offsetX,
+ offsetY,
+ width,
+ height
+ );
+ layerHasPixels = true;
+ decodedAnyPixels = true;
}
+ }
+ }
+
+ // Handle Paper / Solid Color Fill layers (no raster tiles, solid fill color)
+ if (!layerHasPixels) {
+ const fillHex = extractSolidFillColor(row, attr, fillByLayerId, isBottomMostRoot);
+ if (fillHex) {
+ tileGrid.fillLayerSolidColor(id, width, height, fillHex, 'color-32bit');
+ layerHasPixels = true;
+ decodedAnyPixels = true;
+ }
+ }
+
+ const thumb = createCanvasThumbnail(
+ { grid: tileGrid, layerId: id, dimensions: { width, height } },
+ true
+ );
+
+ layers.push({
+ id,
+ name,
+ type: 'raster',
+ visible,
+ opacity,
+ blendMode,
+ locked,
+ alphaLocked,
+ clipped,
+ parentId,
+ thumbnailUrl: thumb,
+ ...maskFields,
+ });
+ };
+
+ // Determine root container and traverse hierarchy
+ const visited = new Set<number>();
+ let rootRow: SqlRow | undefined;
- layerCanvases.set(id, canvas);
- const thumb = createCanvasThumbnail(canvas, true);
-
- layers.push({
- id,
- name,
- type: 'raster',
- visible,
- opacity,
- blendMode,
- locked,
- parentId: null,
- thumbnailUrl: thumb,
- });
+ if (rootFolderId !== null && layerRowById.has(rootFolderId)) {
+ rootRow = layerRowById.get(rootFolderId);
+ } else {
+ // Heuristic: find an unreferenced root folder that has children
+ const referenced = new Set<number>();
+ for (const row of layerRows) {
+ const nextId = getNum(row, ['LayerNextIndex'], 0);
+ const childId = getNum(row, ['LayerFirstChildIndex'], 0);
+ if (nextId > 0) referenced.add(nextId);
+ if (childId > 0) referenced.add(childId);
+ }
+ for (const row of layerRows) {
+ const id = getNum(row, ['MainId'], -1);
+ const childId = getNum(row, ['LayerFirstChildIndex'], 0);
+ if (id >= 0 && childId > 0 && !referenced.has(id)) {
+ rootRow = row;
+ break;
}
}
}
- } catch (err) {
- console.warn('Error reading layers table from CSP:', err);
- }
- // If no raster layers could be decoded or layers array is empty, fallback to composite preview
- const hasRasterPixels = Array.from(layerCanvases.values()).some((c) => {
- const ctx = c.getContext('2d');
- if (!ctx) return false;
- const sample = ctx.getImageData(0, 0, Math.min(100, c.width), Math.min(100, c.height));
- return sample.data.some((byte) => byte !== 0);
- });
+ if (rootRow) {
+ const rootMainId = getNum(rootRow, ['MainId'], -1);
+ if (rootMainId >= 0) visited.add(rootMainId);
+ const rootOffsetX = getNum(rootRow, ['LayerOffsetX', 'LayerMoveOffsetX'], 0);
+ const rootOffsetY = getNum(rootRow, ['LayerOffsetY', 'LayerMoveOffsetY'], 0);
+ const firstChild = getNum(rootRow, ['LayerFirstChildIndex'], 0);
+ if (firstChild > 0) {
+ const topLevelBottomToTop = collectChildrenBottomToTop(firstChild, visited);
+ for (let i = topLevelBottomToTop.length - 1; i >= 0; i--) {
+ emitLayerNode(
+ topLevelBottomToTop[i],
+ null,
+ visited,
+ 0,
+ i === 0,
+ rootOffsetX,
+ rootOffsetY
+ );
+ }
+ }
+ }
- if (!hasRasterPixels && previewCanvas) {
- const bgId = `csp-preview-base-${Date.now()}`;
- layerCanvases.set(bgId, previewCanvas);
- const thumb = createCanvasThumbnail(previewCanvas, false);
-
- // Replace or prepend the preview canvas layer
- layers.unshift({
- id: bgId,
- name: 'CSP Composite Artwork',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- parentId: null,
- thumbnailUrl: thumb,
- });
- }
+ // Fallback: if linked-list traversal yielded nothing (minimal/legacy schema), emit flat Layer rows
+ if (layers.length === 0 && layerRows.length > 0) {
+ for (let i = layerRows.length - 1; i >= 0; i--) {
+ const row = layerRows[i];
+ const mid = getNum(row, ['MainId'], -1);
+ if (rootFolderId !== null && mid === rootFolderId) continue;
+ emitLayerNode(row, null, visited, 0, i === 0, 0, 0);
+ }
+ }
- // Ensure at least one valid layer exists
- if (layers.length === 0) {
- const fallbackId = `layer-${Date.now()}`;
- const canvas = previewCanvas || document.createElement('canvas');
- if (!previewCanvas) {
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d');
- if (ctx) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, width, height);
- }
- }
- layerCanvases.set(fallbackId, canvas);
-
- layers.push({
- id: fallbackId,
- name: 'Layer 1',
- type: 'raster',
- visible: true,
- opacity: 1,
- blendMode: 'normal',
- locked: false,
- parentId: null,
- thumbnailUrl: createCanvasThumbnail(canvas, false),
- });
- }
+ // Last-resort fallback: ONLY if zero raster pixels were decoded from any layer AND preview exists
+ if (!decodedAnyPixels && previewBytes && previewBytes.byteLength > 0) {
+ const bgId = `csp-preview-base-${runStamp}`;
+ const loaded = await decodeImageBytesToTileGrid(previewBytes, tileGrid, bgId, width, height);
+ if (loaded) {
+ const thumb = createCanvasThumbnail(
+ { grid: tileGrid, layerId: bgId, dimensions: { width, height } },
+ false
+ );
+ layers.push({
+ id: bgId,
+ name: 'CSP Composite Preview',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ parentId: null,
+ thumbnailUrl: thumb,
+ });
+ }
+ }
- db.close();
+ // Guarantee at least one editable layer
+ if (layers.length === 0) {
+ const fallbackId = `layer-${runStamp}`;
+ tileGrid.fillLayerSolidWhite(fallbackId, width, height, 'color-32bit');
+ layers.push({
+ id: fallbackId,
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ parentId: null,
+ thumbnailUrl: createCanvasThumbnail(
+ { grid: tileGrid, layerId: fallbackId, dimensions: { width, height } },
+ false
+ ),
+ });
+ }
- return {
- name: fileName.replace(/\.[^/.]+$/, ''),
- dimensions: { width, height },
- colorMode: 'color',
- layers,
- layerCanvases,
- };
+ return {
+ name: fileName.replace(/\.[^/.]+$/, ''),
+ dimensions: { width, height, dpi },
+ colorMode,
+ layers,
+ tileGrid,
+ previewDataUrl,
+ };
+ } finally {
+ db.close();
+ }
}
diff --git a/src/utils/documentStore.ts b/src/utils/documentStore.ts
index 29a7252..e6314fe 100644
--- a/src/utils/documentStore.ts
+++ b/src/utils/documentStore.ts
@@ -142,7 +142,6 @@ export class DocumentStore {
private driver: IScratchDiskDriver;
private offloadInactiveUndoOnSwitch: boolean;
private tileBudgetPromise: Promise<void> | null = null;
- private needsAnotherTileBudgetPass: boolean = false;
constructor(options?: DocumentStoreOptions) {
const budgetMb = options?.totalTileBudgetMb ?? 1024;
@@ -316,7 +315,6 @@ export class DocumentStore {
*/
public async enforceSharedTileBudget(): Promise<void> {
if (this.tileBudgetPromise) {
- this.needsAnotherTileBudgetPass = true;
return this.tileBudgetPromise;
}
@@ -327,7 +325,6 @@ export class DocumentStore {
this.tileBudgetPromise = (async () => {
try {
while (this.getTotalActiveTileBytes() > this.totalTileBudgetBytes) {
- this.needsAnotherTileBudgetPass = false;
const targetBytes = this.totalTileBudgetBytes * 0.9;
let bytesToFree = this.getTotalActiveTileBytes() - targetBytes;
let freedTotal = 0;
@@ -357,13 +354,12 @@ export class DocumentStore {
}
}
- if (freedTotal <= 0 && !this.needsAnotherTileBudgetPass) {
+ if (freedTotal <= 0) {
break;
}
}
} finally {
this.tileBudgetPromise = null;
- this.needsAnotherTileBudgetPass = false;
}
})();
diff --git a/src/utils/fileDropImport.ts b/src/utils/fileDropImport.ts
new file mode 100644
index 0000000..35ee838
--- /dev/null
+++ b/src/utils/fileDropImport.ts
@@ -0,0 +1,251 @@
+export type ExternalDropZoneKind = 'layers' | 'canvas';
+export type LayerDropPosition = 'above' | 'below' | 'inside';
+
+export interface LayerInsertTarget {
+ targetLayerId?: string;
+ position?: LayerDropPosition;
+}
+
+export interface ExternalFileDropTarget extends LayerInsertTarget {
+ zone: ExternalDropZoneKind;
+}
+
+export const MAX_DROPPED_IMAGE_BYTES = 100 * 1024 * 1024; // 100 MB safety ceiling per image
+export const MAX_DROPPED_IMAGE_FILES = 32;
+
+const EXTENSION_TO_MIME: Record<string, string> = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.webp': 'image/webp',
+ '.bmp': 'image/bmp',
+ '.gif': 'image/gif',
+ '.svg': 'image/svg+xml',
+ '.avif': 'image/avif',
+ '.ico': 'image/x-icon',
+};
+
+const ALLOWED_MIME_TYPES = new Set<string>([
+ ...Object.values(EXTENSION_TO_MIME),
+ 'image/vnd.microsoft.icon',
+ 'image/pjpeg',
+]);
+
+const INTERNAL_DOCK_MIME = 'application/x-inkstudio-dock-panel';
+
+export function extractFilenameFromPath(filePath: string): string {
+ const normalized = filePath.replace(/\\/g, '/');
+ const idx = normalized.lastIndexOf('/');
+ return idx >= 0 ? normalized.slice(idx + 1) : normalized;
+}
+
+export function getExtensionLower(filenameOrPath: string): string {
+ const name = extractFilenameFromPath(filenameOrPath);
+ const dot = name.lastIndexOf('.');
+ if (dot <= 0 || dot === name.length - 1) return '';
+ return name.slice(dot).toLowerCase();
+}
+
+export function isSupportedImageExtension(filenameOrPath: string): boolean {
+ const ext = getExtensionLower(filenameOrPath);
+ return ext !== '' && Object.prototype.hasOwnProperty.call(EXTENSION_TO_MIME, ext);
+}
+
+export function getMimeTypeForFilename(filenameOrPath: string): string {
+ const ext = getExtensionLower(filenameOrPath);
+ return EXTENSION_TO_MIME[ext] || 'application/octet-stream';
+}
+
+export function isSupportedImageFile(file: File): boolean {
+ if (!file || typeof file.name !== 'string') return false;
+ if (isSupportedImageExtension(file.name)) return true;
+ if (file.type && ALLOWED_MIME_TYPES.has(file.type.toLowerCase())) return true;
+ return false;
+}
+
+export function sanitizeImportedLayerName(filenameOrPath: string): string {
+ const base = extractFilenameFromPath(filenameOrPath);
+ const withoutExt = base.replace(/\.[^/.]+$/, '');
+ let cleaned = '';
+ for (let i = 0; i < withoutExt.length; i++) {
+ const code = withoutExt.charCodeAt(i);
+ if (code >= 0x20 && code !== 0x7f) {
+ cleaned += withoutExt[i];
+ }
+ }
+ const trimmed = cleaned.trim().slice(0, 80);
+ return trimmed || 'Imported Image';
+}
+
+export function isExternalFileDrag(dataTransfer: DataTransfer | null | undefined): boolean {
+ if (!dataTransfer) return false;
+ const types = Array.from(dataTransfer.types || []);
+ if (types.includes(INTERNAL_DOCK_MIME)) return false;
+ if (types.includes('Files')) return true;
+ return Boolean(dataTransfer.files && dataTransfer.files.length > 0);
+}
+
+export interface FilteredFilesResult {
+ accepted: File[];
+ rejectedCount: number;
+ oversizedCount: number;
+ truncatedCount: number;
+}
+
+export function filterDroppedImageFiles(files: Iterable<File>): FilteredFilesResult {
+ const accepted: File[] = [];
+ let rejectedCount = 0;
+ let oversizedCount = 0;
+ let truncatedCount = 0;
+
+ for (const file of files) {
+ if (!isSupportedImageFile(file)) {
+ rejectedCount++;
+ continue;
+ }
+ if (file.size === 0) {
+ rejectedCount++;
+ continue;
+ }
+ if (file.size > MAX_DROPPED_IMAGE_BYTES) {
+ oversizedCount++;
+ continue;
+ }
+ if (accepted.length >= MAX_DROPPED_IMAGE_FILES) {
+ truncatedCount++;
+ continue;
+ }
+ accepted.push(file);
+ }
+
+ return { accepted, rejectedCount, oversizedCount, truncatedCount };
+}
+
+export interface FilteredPathsResult {
+ accepted: string[];
+ rejectedCount: number;
+ truncatedCount: number;
+}
+
+export function filterDroppedImagePaths(paths: readonly string[]): FilteredPathsResult {
+ const accepted: string[] = [];
+ let rejectedCount = 0;
+ let truncatedCount = 0;
+
+ for (const rawPath of paths) {
+ if (!rawPath || rawPath.includes('\0') || !isSupportedImageExtension(rawPath)) {
+ rejectedCount++;
+ continue;
+ }
+ if (accepted.length >= MAX_DROPPED_IMAGE_FILES) {
+ truncatedCount++;
+ continue;
+ }
+ accepted.push(rawPath);
+ }
+
+ return { accepted, rejectedCount, truncatedCount };
+}
+
+function resolveLayerRowTarget(
+ element: Element,
+ clientY: number
+): LayerInsertTarget {
+ const row = element.closest('[data-layer-id]') as HTMLElement | null;
+ if (!row) return {};
+ const targetLayerId = row.dataset.layerId;
+ if (!targetLayerId) return {};
+
+ const isFolder = row.dataset.layerFolder === 'true';
+ const rect = row.getBoundingClientRect();
+ if (rect.height <= 0) {
+ return { targetLayerId, position: isFolder ? 'inside' : 'above' };
+ }
+
+ const ratio = (clientY - rect.top) / rect.height;
+ if (isFolder) {
+ if (ratio < 0.25) return { targetLayerId, position: 'above' };
+ if (ratio > 0.75) return { targetLayerId, position: 'below' };
+ return { targetLayerId, position: 'inside' };
+ }
+ return { targetLayerId, position: ratio < 0.5 ? 'above' : 'below' };
+}
+
+export function resolveDropZoneFromElement(
+ element: Element | null,
+ clientY: number
+): ExternalFileDropTarget | null {
+ if (!element) return null;
+ if (element.closest('[data-testid="sub-view-panel"]')) return null;
+
+ const zoneEl = element.closest('[data-drop-zone]') as HTMLElement | null;
+ if (!zoneEl) return null;
+
+ const zone = zoneEl.dataset.dropZone;
+ if (zone === 'layers') {
+ const rowTarget = resolveLayerRowTarget(element, clientY);
+ return { zone: 'layers', ...rowTarget };
+ }
+ if (zone === 'canvas') {
+ return { zone: 'canvas' };
+ }
+ return null;
+}
+
+export function resolveDropZoneAtPoint(
+ clientX: number,
+ clientY: number
+): ExternalFileDropTarget | null {
+ if (typeof document === 'undefined' || typeof document.elementFromPoint !== 'function') {
+ return null;
+ }
+ const el = document.elementFromPoint(clientX, clientY);
+ return resolveDropZoneFromElement(el, clientY);
+}
+
+export function isSameDropTarget(
+ a: ExternalFileDropTarget | null,
+ b: ExternalFileDropTarget | null
+): boolean {
+ if (a === b) return true;
+ if (!a || !b) return false;
+ return (
+ a.zone === b.zone &&
+ a.targetLayerId === b.targetLayerId &&
+ a.position === b.position
+ );
+}
+
+export async function readTauriDroppedImageFile(path: string): Promise<File> {
+ if (!path || path.includes('\0') || !isSupportedImageExtension(path)) {
+ throw new Error('Unsupported image path');
+ }
+ const { invoke } = await import('@tauri-apps/api/core');
+ let bytes: Uint8Array;
+ try {
+ const buf = await invoke<ArrayBuffer>('read_file_binary', { path });
+ bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
+ } catch (err) {
+ // Fallback for older backend binaries that only expose read_file_from_disk
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('unknown')) {
+ const arr = await invoke<number[]>('read_file_from_disk', { path });
+ bytes = new Uint8Array(arr);
+ } else {
+ throw err;
+ }
+ }
+
+ if (bytes.byteLength === 0) {
+ throw new Error('Image file is empty');
+ }
+ if (bytes.byteLength > MAX_DROPPED_IMAGE_BYTES) {
+ throw new Error('Image file exceeds 100 MB safety limit');
+ }
+
+ const filename = extractFilenameFromPath(path);
+ const mime = getMimeTypeForFilename(filename);
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ return new File([copy.buffer], filename, { type: mime });
+}
diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.ts
index 3f89672..2f35011 100644
--- a/src/utils/imageLoader.ts
+++ b/src/utils/imageLoader.ts
@@ -99,7 +99,7 @@ export async function openFile(file: File): Promise<LoadedDocument> {
return await parsePsdFile(buffer, file.name);
}
- if (ext === '.clip' || ext === '.csp') {
+ if (ext === '.clip' || ext === '.csp' || ext === '.lip') {
const { parseCspFile } = await import('./cspParser');
const buffer = await file.arrayBuffer();
return await parseCspFile(buffer, file.name);
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index eb07048..b417f22 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -10,6 +10,7 @@
*/
import { TileDelta } from '../types/editor';
+import { yieldToMain } from './asyncCompression';
export const TILE_SIZE = 256;
export const TILE_PIXELS = TILE_SIZE * TILE_SIZE; // 65,536 pixels
@@ -770,14 +771,23 @@ export function unpackTileWriteBatch(buffer: Uint8Array | ArrayBuffer): TileWrit
* Direct raw binary IPC with high-throughput LZ4 compression and atomic file index tables.
*/
export class TauriScratchDiskDriver implements IScratchDiskDriver {
+ private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;
+
+ private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
+ if (!this.invokePromise) {
+ this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
+ }
+ return this.invokePromise;
+ }
+
public async init(sessionId: string): Promise<void> {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
await invoke('scratch_disk_init', { sessionId });
}
public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
if (tiles.length === 0) return 0;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
const packed = packTileWriteBatch(tiles);
return invoke<number>('scratch_disk_write_tiles', packed, {
headers: {
@@ -787,7 +797,7 @@ export class TauriScratchDiskDriver implements IScratchDiskDriver {
}
public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
const raw = await invoke<ArrayBuffer | Uint8Array | number[]>('scratch_disk_read_tile', undefined, {
headers: {
'x-session-id': encodeURIComponent(sessionId),
@@ -802,7 +812,7 @@ export class TauriScratchDiskDriver implements IScratchDiskDriver {
}
public async clear(sessionId: string): Promise<void> {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
await invoke('scratch_disk_clear', { sessionId });
}
}
@@ -1025,10 +1035,12 @@ export class TileMemoryManager {
return this.evictionPromise;
}
+ private static readonly MAX_EVICT_BATCH_TILES = 32;
+
private async performEvictionPass(): Promise<number> {
// 1. First drop any in-memory LOD > 0 tiles (they can always be re-downsampled on demand with 0 IO)
let droppedLodBytes = 0;
- for (const tile of this.grid.getAllTiles()) {
+ for (const tile of this.grid.tilesIterable()) {
if (tile.lod > 0 && tile.data !== null) {
this.activeBytes -= tile.data.byteLength;
droppedLodBytes += tile.data.byteLength;
@@ -1044,7 +1056,7 @@ export class TileMemoryManager {
// 2. Gather candidate LOD 0 tiles with active data
const candidates: TileBuffer[] = [];
- for (const tile of this.grid.getAllTiles()) {
+ for (const tile of this.grid.tilesIterable()) {
if (tile.lod === 0 && tile.data !== null) {
candidates.push(tile);
}
@@ -1114,39 +1126,55 @@ export class TileMemoryManager {
}
if (toEvict.length > 0) {
- await this.evictTiles(toEvict);
- return toEvict.length;
+ try {
+ await this.evictTiles(toEvict);
+ return toEvict.length;
+ } catch (err) {
+ console.warn('[TileMemoryManager] Eviction write failed; aborting pass:', err);
+ return 0;
+ }
}
return droppedLodBytes > 0 ? 1 : 0;
}
public async evictTiles(tiles: TileBuffer[]): Promise<void> {
- const payloads: TileWritePayload[] = [];
- const validTiles: TileBuffer[] = [];
-
- for (const tile of tiles) {
- if (tile.data !== null) {
- payloads.push({
- layerId: tile.layerId,
- tileX: tile.tileX,
- tileY: tile.tileY,
- data: tile.data,
- });
- validTiles.push(tile);
+ if (tiles.length === 0) return;
+
+ const batchSize = TileMemoryManager.MAX_EVICT_BATCH_TILES;
+ for (let start = 0; start < tiles.length; start += batchSize) {
+ const end = Math.min(tiles.length, start + batchSize);
+ const payloads: TileWritePayload[] = [];
+ const validTiles: TileBuffer[] = [];
+
+ for (let i = start; i < end; i++) {
+ const tile = tiles[i];
+ if (tile.data !== null) {
+ payloads.push({
+ layerId: tile.layerId,
+ tileX: tile.tileX,
+ tileY: tile.tileY,
+ data: tile.data,
+ });
+ validTiles.push(tile);
+ }
}
- }
- if (payloads.length > 0) {
- await this.driver.writeTiles(this.sessionId, payloads);
- for (const tile of validTiles) {
- if (tile.data) {
- this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
- tile.data = null;
- tile.isPagedToDisk = true;
- tile.dirty = false;
+ if (payloads.length > 0) {
+ await this.driver.writeTiles(this.sessionId, payloads);
+ for (const tile of validTiles) {
+ if (tile.data) {
+ this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
+ tile.data = null;
+ tile.isPagedToDisk = true;
+ tile.dirty = false;
+ }
}
}
+
+ if (end < tiles.length) {
+ await yieldToMain();
+ }
}
}
@@ -1159,7 +1187,7 @@ export class TileMemoryManager {
let freed = 0;
// 1. Drop regenerable LOD > 0 tiles first (zero disk I/O)
- for (const tile of this.grid.getAllTiles()) {
+ for (const tile of this.grid.tilesIterable()) {
if (tile.lod > 0 && tile.data !== null) {
const sz = tile.data.byteLength;
this.activeBytes = Math.max(0, this.activeBytes - sz);
@@ -1174,7 +1202,7 @@ export class TileMemoryManager {
// 2. Evict LOD 0 tiles oldest-first to scratch disk
const lod0: TileBuffer[] = [];
- for (const tile of this.grid.getAllTiles()) {
+ for (const tile of this.grid.tilesIterable()) {
if (tile.lod === 0 && tile.data !== null) {
lod0.push(tile);
}
@@ -3171,6 +3199,10 @@ export class SparseTileGrid {
this.notifyChange(true);
}
+ public tilesIterable(): IterableIterator<TileBuffer> {
+ return this.tiles.values();
+ }
+
public getAllTiles(): TileBuffer[] {
return Array.from(this.tiles.values());
}
@@ -3224,28 +3256,39 @@ const BYTE_TO_FORMAT: TileFormat[] = [
'color-32bit',
];
+const _sharedTileEncoder = new TextEncoder();
+
+function encodeLayerIdCached(cache: Map<string, Uint8Array>, layerId: string): Uint8Array {
+ let bytes = cache.get(layerId);
+ if (!bytes) {
+ bytes = _sharedTileEncoder.encode(layerId);
+ cache.set(layerId, bytes);
+ }
+ return bytes;
+}
+
export function serializeSparseTileGrid(grid: SparseTileGrid): Uint8Array {
- const encoder = new TextEncoder();
- const tiles = grid.getAllTiles().filter((t) => (t.lod ?? 0) === 0);
+ const layerKeyCache = new Map<string, Uint8Array>();
const layerFormats = grid.getAllLayerFormats();
let totalBytes = 4 + 1 + 4;
const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
for (const [layerId, fmt] of layerFormats.entries()) {
- const keyBytes = encoder.encode(layerId);
+ const keyBytes = encodeLayerIdCached(layerKeyCache, layerId);
encodedFormats.push({ keyBytes, format: fmt });
totalBytes += 2 + keyBytes.length + 1;
}
totalBytes += 4;
- const encodedTiles: Array<{ keyBytes: Uint8Array; tile: TileBuffer }> = [];
- for (let i = 0; i < tiles.length; i++) {
- const t = tiles[i];
- const keyBytes = encoder.encode(t.layerId);
- encodedTiles.push({ keyBytes, tile: t });
- const dataLen = t.data ? t.data.byteLength : 0;
+ const encodedTiles: Array<{ keyBytes: Uint8Array; tile: TileBuffer; data: Uint8Array | null }> = [];
+ for (const t of grid.tilesIterable()) {
+ if ((t.lod ?? 0) !== 0) continue;
+ const keyBytes = encodeLayerIdCached(layerKeyCache, t.layerId);
+ const data = t.data;
+ encodedTiles.push({ keyBytes, tile: t, data });
+ const dataLen = data ? data.byteLength : 0;
totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
}
@@ -3288,11 +3331,12 @@ export function serializeSparseTileGrid(grid: SparseTileGrid): Uint8Array {
view.setUint32(offset, t.version, true);
offset += 4;
- const dataLen = t.data ? t.data.byteLength : 0;
+ const data = item.data;
+ const dataLen = data ? data.byteLength : 0;
view.setUint32(offset, dataLen, true);
offset += 4;
- if (t.data) {
- out.set(t.data, offset);
+ if (data) {
+ out.set(data, offset);
offset += dataLen;
}
}
@@ -3300,6 +3344,120 @@ export function serializeSparseTileGrid(grid: SparseTileGrid): Uint8Array {
return out;
}
+/**
+ * Time-sliced asynchronous SparseTileGrid serializer for background recovery checkpoints.
+ * Yields to the browser event loop every ~4ms and supports cooperative cancellation
+ * if the user resumes drawing mid-snapshot. Produces identical INKG v1 output.
+ */
+export async function serializeSparseTileGridAsync(
+ grid: SparseTileGrid,
+ options?: { shouldAbort?: () => boolean; chunkBudgetMs?: number }
+): Promise<Uint8Array | null> {
+ if (options?.shouldAbort?.()) return null;
+
+ const budgetMs = options?.chunkBudgetMs ?? 4;
+ const layerKeyCache = new Map<string, Uint8Array>();
+ const layerFormats = grid.getAllLayerFormats();
+
+ let totalBytes = 4 + 1 + 4;
+
+ const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
+ for (const [layerId, fmt] of layerFormats.entries()) {
+ const keyBytes = encodeLayerIdCached(layerKeyCache, layerId);
+ encodedFormats.push({ keyBytes, format: fmt });
+ totalBytes += 2 + keyBytes.length + 1;
+ }
+
+ totalBytes += 4;
+
+ // Capture immutable per-tile references (data ref + metadata) before yielding
+ const encodedTiles: Array<{
+ keyBytes: Uint8Array;
+ tileX: number;
+ tileY: number;
+ formatByte: number;
+ version: number;
+ data: Uint8Array | null;
+ }> = [];
+
+ for (const t of grid.tilesIterable()) {
+ if ((t.lod ?? 0) !== 0) continue;
+ const keyBytes = encodeLayerIdCached(layerKeyCache, t.layerId);
+ const data = t.data;
+ encodedTiles.push({
+ keyBytes,
+ tileX: t.tileX,
+ tileY: t.tileY,
+ formatByte: FORMAT_TO_BYTE[t.format] ?? 2,
+ version: t.version,
+ data,
+ });
+ const dataLen = data ? data.byteLength : 0;
+ totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
+ }
+
+ if (options?.shouldAbort?.()) return null;
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x49; // 'I'
+ out[offset++] = 0x4e; // 'N'
+ out[offset++] = 0x4b; // 'K'
+ out[offset++] = 0x47; // 'G'
+ out[offset++] = 1; // Version
+
+ view.setUint32(offset, encodedFormats.length, true);
+ offset += 4;
+
+ for (const item of encodedFormats) {
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+ out[offset++] = FORMAT_TO_BYTE[item.format] ?? 2;
+ }
+
+ view.setUint32(offset, encodedTiles.length, true);
+ offset += 4;
+
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ let sliceStart = now();
+
+ for (let i = 0; i < encodedTiles.length; i++) {
+ const item = encodedTiles[i];
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+
+ view.setInt32(offset, item.tileX, true);
+ offset += 4;
+ view.setInt32(offset, item.tileY, true);
+ offset += 4;
+ out[offset++] = item.formatByte;
+ view.setUint32(offset, item.version, true);
+ offset += 4;
+
+ const dataLen = item.data ? item.data.byteLength : 0;
+ view.setUint32(offset, dataLen, true);
+ offset += 4;
+ if (item.data) {
+ out.set(item.data, offset);
+ offset += dataLen;
+ }
+
+ if ((i & 15) === 15 && i + 1 < encodedTiles.length && now() - sliceStart >= budgetMs) {
+ await yieldToMain();
+ if (options?.shouldAbort?.()) return null;
+ sliceStart = now();
+ }
+ }
+
+ return out;
+}
+
export function deserializeSparseTileGrid(grid: SparseTileGrid, buffer: Uint8Array): void {
if (buffer.byteLength < 9) {
throw new Error('Invalid SparseTileGrid buffer: too short');
@@ -3379,14 +3537,13 @@ export function deserializeSparseTileGrid(grid: SparseTileGrid, buffer: Uint8Arr
}
export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
- const encoder = new TextEncoder();
let totalBytes = 2 + 1 + 4;
- const encodedKeys: Uint8Array[] = [];
+ const encodedKeys: Uint8Array[] = new Array(deltas.length);
for (let i = 0; i < deltas.length; i++) {
const d = deltas[i];
- const keyBytes = encoder.encode(d.key);
- encodedKeys.push(keyBytes);
+ const keyBytes = _sharedTileEncoder.encode(d.key);
+ encodedKeys[i] = keyBytes;
totalBytes += 2 + keyBytes.length;
totalBytes += 1;
@@ -3445,6 +3602,88 @@ export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
return out;
}
+/**
+ * Time-sliced asynchronous TileDelta serializer for large multi-tile operations
+ * (full-canvas fills, filters, transforms, clears). Yields every ~4ms so UI stays responsive.
+ */
+export async function serializeTileDeltasAsync(
+ deltas: TileDelta[],
+ chunkBudgetMs: number = 4
+): Promise<Uint8Array> {
+ if (deltas.length <= 16) {
+ return serializeTileDeltas(deltas);
+ }
+
+ let totalBytes = 2 + 1 + 4;
+ const encodedKeys: Uint8Array[] = new Array(deltas.length);
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = _sharedTileEncoder.encode(d.key);
+ encodedKeys[i] = keyBytes;
+
+ totalBytes += 2 + keyBytes.length + 1 + 1 + 1;
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ totalBytes += 4 + d.beforeData.byteLength;
+ }
+ if (d.afterData && d.afterData.byteLength > 0) {
+ totalBytes += 4 + d.afterData.byteLength;
+ }
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x54; // 'T'
+ out[offset++] = 0x44; // 'D'
+ out[offset++] = 1; // Version
+ view.setUint32(offset, deltas.length, true);
+ offset += 4;
+
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ let sliceStart = now();
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = encodedKeys[i];
+
+ view.setUint16(offset, keyBytes.length, true);
+ offset += 2;
+ out.set(keyBytes, offset);
+ offset += keyBytes.length;
+
+ out[offset++] = FORMAT_TO_BYTE[d.format] ?? 2;
+
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.beforeData.byteLength, true);
+ offset += 4;
+ out.set(d.beforeData, offset);
+ offset += d.beforeData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+
+ if (d.afterData && d.afterData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.afterData.byteLength, true);
+ offset += 4;
+ out.set(d.afterData, offset);
+ offset += d.afterData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+
+ if ((i & 7) === 7 && i + 1 < deltas.length && now() - sliceStart >= chunkBudgetMs) {
+ await yieldToMain();
+ sliceStart = now();
+ }
+ }
+
+ return out;
+}
+
export function deserializeTileDeltas(buffer: Uint8Array): TileDelta[] {
if (buffer.byteLength < 7) {
throw new Error('Invalid TileDelta buffer: too short');
diff --git a/src/utils/transformEngine.ts b/src/utils/transformEngine.ts
index f7b10a3..40a5a84 100644
--- a/src/utils/transformEngine.ts
+++ b/src/utils/transformEngine.ts
@@ -131,6 +131,59 @@ export function evaluateMeshSurface(
};
}
+/**
+ * Offsets all three edges of a triangle strictly outward along their unit normals
+ * by `expand` pixels (with miter clamping for acute vertices).
+ * Returns null for degenerate triangles.
+ */
+export function expandTriangleOutward(
+ dx0: number,
+ dy0: number,
+ dx1: number,
+ dy1: number,
+ dx2: number,
+ dy2: number,
+ expand = 0.75
+): [number, number, number, number, number, number] | null {
+ const e0x = dx1 - dx0;
+ const e0y = dy1 - dy0;
+ const e1x = dx2 - dx1;
+ const e1y = dy2 - dy1;
+ const e2x = dx0 - dx2;
+ const e2y = dy0 - dy2;
+
+ const area2 = e0x * (dy2 - dy0) - e0y * (dx2 - dx0);
+ if (Math.abs(area2) < 1e-6) return null;
+
+ const l0 = Math.hypot(e0x, e0y);
+ const l1 = Math.hypot(e1x, e1y);
+ const l2 = Math.hypot(e2x, e2y);
+ if (l0 < 1e-6 || l1 < 1e-6 || l2 < 1e-6) return null;
+
+ const w = area2 > 0 ? 1 : -1;
+ // Outward unit normals for each edge in y-down screen coordinates
+ const n0x = (w * e0y) / l0;
+ const n0y = (-w * e0x) / l0;
+ const n1x = (w * e1y) / l1;
+ const n1y = (-w * e1x) / l1;
+ const n2x = (w * e2y) / l2;
+ const n2y = (-w * e2x) / l2;
+
+ // Miter intersection of each vertex's two adjacent offset edges
+ const d0 = Math.max(0.05, 1 + n2x * n0x + n2y * n0y);
+ const d1 = Math.max(0.05, 1 + n0x * n1x + n0y * n1y);
+ const d2 = Math.max(0.05, 1 + n1x * n2x + n1y * n2y);
+
+ return [
+ dx0 + (expand * (n2x + n0x)) / d0,
+ dy0 + (expand * (n2y + n0y)) / d0,
+ dx1 + (expand * (n0x + n1x)) / d1,
+ dy1 + (expand * (n0y + n1y)) / d1,
+ dx2 + (expand * (n1x + n2x)) / d2,
+ dy2 + (expand * (n1y + n2y)) / d2,
+ ];
+}
+
/**
* Renders an affine-mapped triangle from sourceCanvas onto destination context.
*/
@@ -151,6 +204,9 @@ export function drawAffineTriangle(
const det = du1 * dv2 - du2 * dv1;
if (Math.abs(det) < 1e-6) return;
+ const expanded = expandTriangleOutward(dx0, dy0, dx1, dy1, dx2, dy2, 0.75);
+ if (!expanded) return;
+
const dx1_0 = dx1 - dx0;
const dx2_0 = dx2 - dx0;
const dy1_0 = dy1 - dy0;
@@ -166,21 +222,9 @@ export function drawAffineTriangle(
ctx.save();
ctx.beginPath();
- // Expand triangle slightly towards centroid to avoid subpixel seam artifacts
- const cx = (dx0 + dx1 + dx2) / 3;
- const cy = (dy0 + dy1 + dy2) / 3;
- const expand = 0.5;
-
- const ex0 = dx0 + Math.sign(dx0 - cx) * expand;
- const ey0 = dy0 + Math.sign(dy0 - cy) * expand;
- const ex1 = dx1 + Math.sign(dx1 - cx) * expand;
- const ey1 = dy1 + Math.sign(dy1 - cy) * expand;
- const ex2 = dx2 + Math.sign(dx2 - cx) * expand;
- const ey2 = dy2 + Math.sign(dy2 - cy) * expand;
-
- ctx.moveTo(ex0, ey0);
- ctx.lineTo(ex1, ey1);
- ctx.lineTo(ex2, ey2);
+ ctx.moveTo(expanded[0], expanded[1]);
+ ctx.lineTo(expanded[2], expanded[3]);
+ ctx.lineTo(expanded[4], expanded[5]);
ctx.closePath();
ctx.clip();
@@ -189,6 +233,310 @@ export function drawAffineTriangle(
ctx.restore();
}
+const MESH_VERTEX_SHADER = `
+ attribute vec2 a_pos;
+ attribute vec2 a_uv;
+ uniform vec2 u_origin;
+ uniform vec2 u_size;
+ varying vec2 v_uv;
+ void main() {
+ vec2 norm = (a_pos - u_origin) / u_size;
+ gl_Position = vec4(norm.x * 2.0 - 1.0, 1.0 - norm.y * 2.0, 0.0, 1.0);
+ v_uv = a_uv;
+ }
+`;
+
+const MESH_FRAGMENT_SHADER = `
+ precision highp float;
+ uniform sampler2D u_tex;
+ varying vec2 v_uv;
+ void main() {
+ gl_FragColor = texture2D(u_tex, v_uv);
+ }
+`;
+
+class WebGlMeshWarpRenderer {
+ private static instance: WebGlMeshWarpRenderer | null = null;
+ private canvas: HTMLCanvasElement | null = null;
+ private gl: WebGLRenderingContext | null = null;
+ private program: WebGLProgram | null = null;
+ private vertexBuffer: WebGLBuffer | null = null;
+ private texture: WebGLTexture | null = null;
+ private posLoc = -1;
+ private uvLoc = -1;
+ private originLoc: WebGLUniformLocation | null = null;
+ private sizeLoc: WebGLUniformLocation | null = null;
+ private texLoc: WebGLUniformLocation | null = null;
+ private maxDim = 0;
+ private vertexData = new Float32Array(0);
+ private ready = false;
+
+ static getInstance(): WebGlMeshWarpRenderer {
+ if (!WebGlMeshWarpRenderer.instance) {
+ WebGlMeshWarpRenderer.instance = new WebGlMeshWarpRenderer();
+ }
+ return WebGlMeshWarpRenderer.instance;
+ }
+
+ private constructor() {
+ this.init();
+ }
+
+ private init(): void {
+ this.ready = false;
+ if (typeof document === 'undefined') return;
+ try {
+ const canvas = document.createElement('canvas');
+ const attrs: WebGLContextAttributes = {
+ alpha: true,
+ premultipliedAlpha: true,
+ antialias: false,
+ depth: false,
+ stencil: false,
+ preserveDrawingBuffer: false,
+ };
+ const gl = (canvas.getContext('webgl2', attrs) ||
+ canvas.getContext('webgl', attrs)) as WebGLRenderingContext | null;
+ if (!gl) return;
+
+ const vs = gl.createShader(gl.VERTEX_SHADER);
+ const fs = gl.createShader(gl.FRAGMENT_SHADER);
+ if (!vs || !fs) return;
+
+ gl.shaderSource(vs, MESH_VERTEX_SHADER);
+ gl.compileShader(vs);
+ gl.shaderSource(fs, MESH_FRAGMENT_SHADER);
+ gl.compileShader(fs);
+ if (
+ !gl.getShaderParameter(vs, gl.COMPILE_STATUS) ||
+ !gl.getShaderParameter(fs, gl.COMPILE_STATUS)
+ ) {
+ gl.deleteShader(vs);
+ gl.deleteShader(fs);
+ return;
+ }
+
+ const program = gl.createProgram();
+ if (!program) {
+ gl.deleteShader(vs);
+ gl.deleteShader(fs);
+ return;
+ }
+ gl.attachShader(program, vs);
+ gl.attachShader(program, fs);
+ gl.linkProgram(program);
+ gl.deleteShader(vs);
+ gl.deleteShader(fs);
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+ gl.deleteProgram(program);
+ return;
+ }
+
+ const vertexBuffer = gl.createBuffer();
+ const texture = gl.createTexture();
+ const posLoc = gl.getAttribLocation(program, 'a_pos');
+ const uvLoc = gl.getAttribLocation(program, 'a_uv');
+ if (!vertexBuffer || !texture || posLoc < 0 || uvLoc < 0) {
+ if (vertexBuffer) gl.deleteBuffer(vertexBuffer);
+ if (texture) gl.deleteTexture(texture);
+ gl.deleteProgram(program);
+ return;
+ }
+
+ const maxTex = gl.getParameter(gl.MAX_TEXTURE_SIZE) as number;
+ const maxVp = gl.getParameter(gl.MAX_VIEWPORT_DIMS) as Int32Array | number[] | null;
+ const maxVpDim = maxVp ? Math.min(maxVp[0], maxVp[1]) : maxTex;
+
+ this.canvas = canvas;
+ this.gl = gl;
+ this.program = program;
+ this.vertexBuffer = vertexBuffer;
+ this.texture = texture;
+ this.posLoc = posLoc;
+ this.uvLoc = uvLoc;
+ this.originLoc = gl.getUniformLocation(program, 'u_origin');
+ this.sizeLoc = gl.getUniformLocation(program, 'u_size');
+ this.texLoc = gl.getUniformLocation(program, 'u_tex');
+ this.maxDim = Math.min(maxTex || 4096, maxVpDim || 4096);
+ this.ready = true;
+ } catch {
+ this.ready = false;
+ }
+ }
+
+ renderGrid(
+ ctx: CanvasRenderingContext2D,
+ sourceCanvas: HTMLCanvasElement,
+ grid: Point2D[][],
+ totalRows: number,
+ totalCols: number
+ ): boolean {
+ if (!this.ready || !this.gl || !this.canvas || !this.program || !this.vertexBuffer || !this.texture) {
+ return false;
+ }
+ const gl = this.gl;
+ if (gl.isContextLost()) {
+ this.ready = false;
+ return false;
+ }
+
+ const sw = sourceCanvas.width;
+ const sh = sourceCanvas.height;
+ if (sw > this.maxDim || sh > this.maxDim) return false;
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (let j = 0; j <= totalRows; j++) {
+ const row = grid[j];
+ for (let i = 0; i <= totalCols; i++) {
+ const p = row[i];
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y)) return false;
+ if (p.x < minX) minX = p.x;
+ if (p.y < minY) minY = p.y;
+ if (p.x > maxX) maxX = p.x;
+ if (p.y > maxY) maxY = p.y;
+ }
+ }
+
+ let originX = Math.floor(minX) - 1;
+ let originY = Math.floor(minY) - 1;
+ let endX = Math.ceil(maxX) + 1;
+ let endY = Math.ceil(maxY) + 1;
+
+ if (
+ ctx.canvas &&
+ ctx.canvas.width > 0 &&
+ ctx.canvas.height > 0 &&
+ typeof ctx.getTransform === 'function'
+ ) {
+ const m = ctx.getTransform();
+ if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && m.e === 0 && m.f === 0) {
+ originX = Math.max(0, originX);
+ originY = Math.max(0, originY);
+ endX = Math.min(ctx.canvas.width, endX);
+ endY = Math.min(ctx.canvas.height, endY);
+ }
+ }
+
+ const outW = endX - originX;
+ const outH = endY - originY;
+ if (outW <= 0 || outH <= 0) return true;
+ if (outW > this.maxDim || outH > this.maxDim) return false;
+
+ const vertexCount = totalRows * totalCols * 6;
+ const neededFloats = vertexCount * 4;
+ if (this.vertexData.length < neededFloats) {
+ this.vertexData = new Float32Array(neededFloats);
+ }
+
+ const buf = this.vertexData;
+ let offset = 0;
+ for (let j = 0; j < totalRows; j++) {
+ const v0 = j / totalRows;
+ const v1 = (j + 1) / totalRows;
+ const row0 = grid[j];
+ const row1 = grid[j + 1];
+ for (let i = 0; i < totalCols; i++) {
+ const u0 = i / totalCols;
+ const u1 = (i + 1) / totalCols;
+ const p00 = row0[i];
+ const p10 = row0[i + 1];
+ const p11 = row1[i + 1];
+ const p01 = row1[i];
+
+ // Triangle 1: (0,0) - (1,0) - (0,1)
+ buf[offset++] = p00.x; buf[offset++] = p00.y; buf[offset++] = u0; buf[offset++] = v0;
+ buf[offset++] = p10.x; buf[offset++] = p10.y; buf[offset++] = u1; buf[offset++] = v0;
+ buf[offset++] = p01.x; buf[offset++] = p01.y; buf[offset++] = u0; buf[offset++] = v1;
+
+ // Triangle 2: (1,0) - (1,1) - (0,1)
+ buf[offset++] = p10.x; buf[offset++] = p10.y; buf[offset++] = u1; buf[offset++] = v0;
+ buf[offset++] = p11.x; buf[offset++] = p11.y; buf[offset++] = u1; buf[offset++] = v1;
+ buf[offset++] = p01.x; buf[offset++] = p01.y; buf[offset++] = u0; buf[offset++] = v1;
+ }
+ }
+
+ if (this.canvas.width !== outW) this.canvas.width = outW;
+ if (this.canvas.height !== outH) this.canvas.height = outH;
+
+ gl.viewport(0, 0, outW, outH);
+ gl.useProgram(this.program);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.texture);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+
+ gl.uniform1i(this.texLoc, 0);
+ gl.uniform2f(this.originLoc, originX, originY);
+ gl.uniform2f(this.sizeLoc, outW, outH);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, buf.subarray(0, neededFloats), gl.STREAM_DRAW);
+ gl.enableVertexAttribArray(this.posLoc);
+ gl.vertexAttribPointer(this.posLoc, 2, gl.FLOAT, false, 16, 0);
+ gl.enableVertexAttribArray(this.uvLoc);
+ gl.vertexAttribPointer(this.uvLoc, 2, gl.FLOAT, false, 16, 8);
+
+ gl.disable(gl.CULL_FACE);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.drawArrays(gl.TRIANGLES, 0, vertexCount);
+
+ ctx.drawImage(this.canvas, originX, originY);
+ return true;
+ }
+}
+
+function renderDeformedGrid(
+ ctx: CanvasRenderingContext2D,
+ sourceCanvas: HTMLCanvasElement,
+ grid: Point2D[][],
+ totalRows: number,
+ totalCols: number
+): void {
+ if (WebGlMeshWarpRenderer.getInstance().renderGrid(ctx, sourceCanvas, grid, totalRows, totalCols)) {
+ return;
+ }
+
+ const sw = sourceCanvas.width;
+ const sh = sourceCanvas.height;
+ for (let j = 0; j < totalRows; j++) {
+ const v0 = (j / totalRows) * sh;
+ const v1 = ((j + 1) / totalRows) * sh;
+ for (let i = 0; i < totalCols; i++) {
+ const u0 = (i / totalCols) * sw;
+ const u1 = ((i + 1) / totalCols) * sw;
+
+ const p00 = grid[j][i];
+ const p10 = grid[j][i + 1];
+ const p11 = grid[j + 1][i + 1];
+ const p01 = grid[j + 1][i];
+
+ drawAffineTriangle(
+ ctx, sourceCanvas,
+ u0, v0, u1, v0, u0, v1,
+ p00.x, p00.y, p10.x, p10.y, p01.x, p01.y
+ );
+
+ drawAffineTriangle(
+ ctx, sourceCanvas,
+ u1, v0, u1, v1, u0, v1,
+ p10.x, p10.y, p11.x, p11.y, p01.x, p01.y
+ );
+ }
+ }
+}
+
/**
* Renders sourceCanvas deformed into a Perspective Quad using homography triangle slicing.
*/
@@ -200,11 +548,10 @@ export function renderPerspectiveQuad(
): void {
const sw = sourceCanvas.width;
const sh = sourceCanvas.height;
- if (sw <= 0 || sh <= 0) return;
+ if (sw <= 0 || sh <= 0 || subdivisions <= 0) return;
const homography = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);
- // Precompute grid vertices
const grid: Point2D[][] = [];
for (let j = 0; j <= subdivisions; j++) {
const row: Point2D[] = [];
@@ -216,34 +563,7 @@ export function renderPerspectiveQuad(
grid.push(row);
}
- // Draw two triangles for each quad cell
- for (let j = 0; j < subdivisions; j++) {
- const v0 = (j / subdivisions) * sh;
- const v1 = ((j + 1) / subdivisions) * sh;
- for (let i = 0; i < subdivisions; i++) {
- const u0 = (i / subdivisions) * sw;
- const u1 = ((i + 1) / subdivisions) * sw;
-
- const p00 = grid[j][i];
- const p10 = grid[j][i + 1];
- const p11 = grid[j + 1][i + 1];
- const p01 = grid[j + 1][i];
-
- // Triangle 1: (0,0) - (1,0) - (0,1)
- drawAffineTriangle(
- ctx, sourceCanvas,
- u0, v0, u1, v0, u0, v1,
- p00.x, p00.y, p10.x, p10.y, p01.x, p01.y
- );
-
- // Triangle 2: (1,0) - (1,1) - (0,1)
- drawAffineTriangle(
- ctx, sourceCanvas,
- u1, v0, u1, v1, u0, v1,
- p10.x, p10.y, p11.x, p11.y, p01.x, p01.y
- );
- }
- }
+ renderDeformedGrid(ctx, sourceCanvas, grid, subdivisions, subdivisions);
}
/**
@@ -257,7 +577,7 @@ export function renderMeshWarp(
): void {
const sw = sourceCanvas.width;
const sh = sourceCanvas.height;
- if (sw <= 0 || sh <= 0) return;
+ if (sw <= 0 || sh <= 0 || subPerCell <= 0) return;
const rows = meshPoints.length;
const cols = meshPoints[0]?.length || 0;
@@ -266,7 +586,6 @@ export function renderMeshWarp(
const totalCols = (cols - 1) * subPerCell;
const totalRows = (rows - 1) * subPerCell;
- // Precompute evaluated surface vertices
const grid: Point2D[][] = [];
for (let j = 0; j <= totalRows; j++) {
const row: Point2D[] = [];
@@ -278,34 +597,7 @@ export function renderMeshWarp(
grid.push(row);
}
- // Draw triangles for each sub-cell
- for (let j = 0; j < totalRows; j++) {
- const v0 = (j / totalRows) * sh;
- const v1 = ((j + 1) / totalRows) * sh;
- for (let i = 0; i < totalCols; i++) {
- const u0 = (i / totalCols) * sw;
- const u1 = ((i + 1) / totalCols) * sw;
-
- const p00 = grid[j][i];
- const p10 = grid[j][i + 1];
- const p11 = grid[j + 1][i + 1];
- const p01 = grid[j + 1][i];
-
- // Triangle 1: (0,0) - (1,0) - (0,1)
- drawAffineTriangle(
- ctx, sourceCanvas,
- u0, v0, u1, v0, u0, v1,
- p00.x, p00.y, p10.x, p10.y, p01.x, p01.y
- );
-
- // Triangle 2: (1,0) - (1,1) - (0,1)
- drawAffineTriangle(
- ctx, sourceCanvas,
- u1, v0, u1, v1, u0, v1,
- p10.x, p10.y, p11.x, p11.y, p01.x, p01.y
- );
- }
- }
+ renderDeformedGrid(ctx, sourceCanvas, grid, totalRows, totalCols);
}
/**
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
index 894dab6..d8a0f83 100644
--- a/src/utils/undoCache.ts
+++ b/src/utils/undoCache.ts
@@ -8,7 +8,8 @@
import { zlibSync, unzlibSync } from 'fflate';
import { TileDelta, HistoryItem } from '../types/editor';
-import { serializeTileDeltas, deserializeTileDeltas } from './tileEngine';
+import { serializeTileDeltas, serializeTileDeltasAsync, deserializeTileDeltas } from './tileEngine';
+import { zlibAsync, unzlibAsync, yieldToMain } from './asyncCompression';
export const MAX_RAM_UNDO_STEPS = 15;
const MAX_DECOMPRESSED_UNDO_BYTES = 128 * 1024 * 1024;
@@ -47,11 +48,46 @@ export function decompressTileDeltasPayload(payload: Uint8Array): TileDelta[] {
return deserializeTileDeltas(payload);
}
+/**
+ * Off-main-thread async variant of compressTileDeltasPayload (uses pooled Web Worker).
+ */
+export async function compressTileDeltasPayloadAsync(deltas: TileDelta[]): Promise<Uint8Array> {
+ const serialized = await serializeTileDeltasAsync(deltas);
+ return zlibAsync(serialized, { level: 1, transfer: true });
+}
+
+/**
+ * Off-main-thread async variant of decompressTileDeltasPayload (uses pooled Web Worker).
+ */
+export async function decompressTileDeltasPayloadAsync(payload: Uint8Array): Promise<TileDelta[]> {
+ if (payload.length >= 2 && payload[0] === 0x78) {
+ try {
+ const raw = await unzlibAsync(payload, { maxOutputBytes: MAX_DECOMPRESSED_UNDO_BYTES });
+ if (raw.byteLength <= MAX_DECOMPRESSED_UNDO_BYTES) {
+ return deserializeTileDeltas(raw);
+ }
+ } catch {
+ // Fallback if byte 0 happened to be 0x78 in an uncompressed stream
+ }
+ }
+ return deserializeTileDeltas(payload);
+}
+
export class UndoCacheManager {
private sessionId: string;
private ramItems: Set<string> = new Set();
private diskCachedIds: Set<string> = new Set();
private compressedRamCache: Map<string, Uint8Array> = new Map();
+ private inFlightOffloads: Map<string, Promise<void>> = new Map();
+ private keepInRamIds: Set<string> = new Set();
+ private invokePromise: Promise<typeof import('@tauri-apps/api/core').invoke> | null = null;
+
+ private getInvoke(): Promise<typeof import('@tauri-apps/api/core').invoke> {
+ if (!this.invokePromise) {
+ this.invokePromise = import('@tauri-apps/api/core').then((m) => m.invoke);
+ }
+ return this.invokePromise;
+ }
constructor(sessionId?: string) {
this.sessionId = sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
@@ -131,51 +167,77 @@ export class UndoCacheManager {
public async offloadAllToDisk(allHistory: HistoryItem[], maxCount?: number): Promise<number> {
this.pruneOrphanedIds(allHistory);
let offloaded = 0;
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ let sliceStart = now();
+
for (const item of allHistory) {
if (maxCount !== undefined && offloaded >= maxCount) break;
if (item.tileDeltas && item.tileDeltas.length > 0) {
await this.offloadToDisk(item);
this.ramItems.delete(item.id);
offloaded++;
+ if (now() - sliceStart >= 16) {
+ await yieldToMain();
+ sliceStart = now();
+ }
}
}
return offloaded;
}
/**
- * Offload a single history item's tile deltas to disk via Tauri IPC (with fast zlib compression),
+ * Offload a single history item's tile deltas to disk via Tauri IPC (with off-main-thread Worker zlib),
* or to a compact zlib-compressed RAM buffer when running in a browser environment.
*/
public async offloadToDisk(item: HistoryItem): Promise<void> {
if (!item.tileDeltas || item.tileDeltas.length === 0) return;
- const compressed = compressTileDeltasPayload(item.tileDeltas);
+ const existing = this.inFlightOffloads.get(item.id);
+ if (existing) {
+ return existing;
+ }
- if (isTauriEnvironment()) {
- try {
- const { invoke } = await import('@tauri-apps/api/core');
- const payload =
- compressed.byteOffset === 0 && compressed.byteLength === compressed.buffer.byteLength
- ? compressed
- : compressed.slice();
- await invoke('save_undo_tile_cache', payload, {
- headers: {
- 'x-session-id': encodeURIComponent(this.sessionId),
- 'x-state-id': encodeURIComponent(item.id),
- },
- });
- this.diskCachedIds.add(item.id);
+ this.keepInRamIds.delete(item.id);
+ const deltasToOffload = item.tileDeltas;
+
+ const job = (async () => {
+ const compressed = await compressTileDeltasPayloadAsync(deltasToOffload);
+
+ if (isTauriEnvironment()) {
+ try {
+ const invoke = await this.getInvoke();
+ const payload =
+ compressed.byteOffset === 0 && compressed.byteLength === compressed.buffer.byteLength
+ ? compressed
+ : compressed.slice();
+ await invoke('save_undo_tile_cache', payload, {
+ headers: {
+ 'x-session-id': encodeURIComponent(this.sessionId),
+ 'x-state-id': encodeURIComponent(item.id),
+ },
+ });
+ this.diskCachedIds.add(item.id);
+ if (!this.keepInRamIds.delete(item.id)) {
+ this.ramItems.delete(item.id);
+ item.tileDeltas = undefined;
+ }
+ return;
+ } catch (err) {
+ console.warn('[UndoCache] Failed to offload tile deltas to disk, using compressed RAM fallback:', err);
+ }
+ }
+
+ this.compressedRamCache.set(item.id, compressed);
+ if (!this.keepInRamIds.delete(item.id)) {
this.ramItems.delete(item.id);
item.tileDeltas = undefined;
- return;
- } catch (err) {
- console.warn('[UndoCache] Failed to offload tile deltas to disk, using compressed RAM fallback:', err);
}
- }
+ })().finally(() => {
+ this.inFlightOffloads.delete(item.id);
+ });
- this.compressedRamCache.set(item.id, compressed);
- this.ramItems.delete(item.id);
- item.tileDeltas = undefined;
+ this.inFlightOffloads.set(item.id, job);
+ return job;
}
/**
@@ -183,12 +245,23 @@ export class UndoCacheManager {
*/
public async resolveDeltas(item: HistoryItem): Promise<TileDelta[] | null> {
if (item.tileDeltas && item.tileDeltas.length > 0) {
+ if (this.inFlightOffloads.has(item.id)) {
+ this.keepInRamIds.add(item.id);
+ }
return item.tileDeltas;
}
+ const inFlight = this.inFlightOffloads.get(item.id);
+ if (inFlight) {
+ await inFlight;
+ if (item.tileDeltas && item.tileDeltas.length > 0) {
+ return item.tileDeltas;
+ }
+ }
+
const compressedInRam = this.compressedRamCache.get(item.id);
if (compressedInRam) {
- const deltas = decompressTileDeltasPayload(compressedInRam);
+ const deltas = await decompressTileDeltasPayloadAsync(compressedInRam);
this.compressedRamCache.delete(item.id);
item.tileDeltas = deltas;
this.ramItems.add(item.id);
@@ -197,7 +270,7 @@ export class UndoCacheManager {
if (this.diskCachedIds.has(item.id) && isTauriEnvironment()) {
try {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
const rawData = await invoke<ArrayBuffer | Uint8Array | number[]>('load_undo_tile_cache', undefined, {
headers: {
'x-session-id': encodeURIComponent(this.sessionId),
@@ -212,7 +285,7 @@ export class UndoCacheManager {
? new Uint8Array(rawData)
: new Uint8Array(rawData);
if (u8.length > 0) {
- const deltas = decompressTileDeltasPayload(u8);
+ const deltas = await decompressTileDeltasPayloadAsync(u8);
item.tileDeltas = deltas;
this.ramItems.add(item.id);
return deltas;
@@ -233,9 +306,11 @@ export class UndoCacheManager {
this.ramItems.clear();
this.diskCachedIds.clear();
this.compressedRamCache.clear();
+ this.inFlightOffloads.clear();
+ this.keepInRamIds.clear();
if (isTauriEnvironment()) {
try {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await this.getInvoke();
await invoke('clear_undo_tile_cache', { sessionId: this.sessionId });
} catch (err) {
console.warn('[UndoCache] Failed to clear disk cache:', err);
diff --git a/src/workers/compression.worker.ts b/src/workers/compression.worker.ts
new file mode 100644
index 0000000..87014ec
--- /dev/null
+++ b/src/workers/compression.worker.ts
@@ -0,0 +1,63 @@
+import { deflateSync, inflateSync, zlibSync, unzlibSync } from 'fflate';
+
+export type CompressionOp = 'deflate' | 'inflate' | 'zlib' | 'unzlib';
+
+export interface CompressionRequest {
+ id: number;
+ op: CompressionOp;
+ data: Uint8Array;
+ level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
+ maxOutputBytes?: number;
+}
+
+export interface CompressionResponse {
+ id: number;
+ ok: boolean;
+ data?: Uint8Array;
+ error?: string;
+}
+
+interface WorkerScopeLike {
+ onmessage: ((event: MessageEvent<CompressionRequest>) => void) | null;
+ postMessage(message: CompressionResponse, transfer?: Transferable[]): void;
+}
+
+const scope = self as unknown as WorkerScopeLike;
+
+scope.onmessage = (event: MessageEvent<CompressionRequest>) => {
+ const { id, op, data, level, maxOutputBytes } = event.data;
+ try {
+ let result: Uint8Array;
+ if (op === 'deflate') {
+ result = deflateSync(data, { level: level ?? 1 });
+ } else if (op === 'zlib') {
+ result = zlibSync(data, { level: level ?? 1 });
+ } else if (op === 'inflate') {
+ result = inflateSync(data);
+ } else {
+ result = unzlibSync(data);
+ }
+
+ if (maxOutputBytes !== undefined && result.byteLength > maxOutputBytes) {
+ scope.postMessage({
+ id,
+ ok: false,
+ error: `Decompressed payload exceeds safety ceiling (${maxOutputBytes} bytes)`,
+ });
+ return;
+ }
+
+ const exact =
+ result.byteOffset === 0 && result.byteLength === result.buffer.byteLength
+ ? result
+ : result.slice();
+
+ scope.postMessage({ id, ok: true, data: exact }, [exact.buffer as ArrayBuffer]);
+ } catch (err) {
+ scope.postMessage({
+ id,
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+};