Skip to content

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

some improvements

sora223c23852c86
diff --git a/src/App.tsx b/src/App.tsx
index d27af7f..47573d9 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -100,7 +100,8 @@ import {
screenToCanvas,
sampleCompositedColor,
} from './utils/canvasUtils';
-import { globalTileGrid, globalTileMemoryManager } from './utils/tileEngine';
+import { globalTileGrid } from './utils/tileEngine';
+import { documentStore } from './utils/documentStore';
import { getNextCollabLayerName } from './hooks/useLayerManager';
import { drawPencilDot, drawPencilBezierSegment, PencilGrade } from './utils/pencilEngine';
import { Point } from './types/editor';
@@ -578,6 +579,12 @@ export function App() {
} as BrushSettings;
});
+ // Active document's isolated SparseTileGrid (instant O(1) switch across tabs)
+ const activeTileGrid = useMemo(
+ () => (activeDocumentId ? documentStore.getOrCreateSession(activeDocumentId).tileGrid : globalTileGrid),
+ [activeDocumentId]
+ );
+
// Layer Management System
const {
layers,
@@ -590,6 +597,8 @@ export function App() {
groupSelectedLayers,
activeLayer,
layerCanvasesRef,
+ materializeLayerCanvas,
+ releaseLayerCanvas,
registerLayerCanvas,
updateLayerThumbnail,
addLayer,
@@ -619,6 +628,7 @@ export function App() {
setDefaultToneFrequency,
clearDocument,
loadDocument,
+ switchDocumentSession,
layerSourceCanvasesRef,
toggleTone,
setToneFrequency,
@@ -646,7 +656,7 @@ export function App() {
addAdjustmentLayer,
updateAdjustmentData,
updateLayerStyles,
- } = useLayerManager({ dimensions, activeSessionId: activeDocumentId });
+ } = useLayerManager({ dimensions, activeSessionId: activeDocumentId, tileGrid: activeTileGrid });
// Synchronize active document recovery session and WAL periodic checkpointing
const recoveryStateRef = useRef({
@@ -698,7 +708,7 @@ export function App() {
try {
const thumbW = 120;
const thumbH = Math.max(68, Math.round((dims.height / Math.max(1, dims.width)) * thumbW));
- const dataUrl = globalTileGrid.generateThumbnail(targetLayerId, thumbW, thumbH, dims);
+ const dataUrl = documentStore.getActiveTileGrid().generateThumbnail(targetLayerId, thumbW, thumbH, dims);
const commaIdx = dataUrl.indexOf(',');
if (commaIdx < 0) return null;
const b64 = dataUrl.slice(commaIdx + 1);
@@ -851,15 +861,25 @@ export function App() {
showToast('Select an unlocked raster layer to apply filter');
return;
}
+ const grid = documentStore.getActiveTileGrid();
const isTone = Boolean(activeLayer.toneEnabled && layerSourceCanvasesRef.current?.get(activeLayerId));
const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
- const targetCanvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
- if (!targetCanvas || !displayCanvas) return;
- const ctx = get2DContext(targetCanvas);
- if (!ctx) return;
- const beforeImageData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
+ const width = dimensions.width;
+ const height = dimensions.height;
+ if (width <= 0 || height <= 0) return;
+
+ let beforeImageData: ImageData;
+ if (isTone && sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (!sCtx) return;
+ beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
+ } else {
+ const raw = grid.readImageData(activeLayerId, 0, 0, width, height);
+ beforeImageData = new ImageData(new Uint8ClampedArray(raw.data), width, height);
+ }
+
const rawFiltered = applyFilter(
new ImageData(new Uint8ClampedArray(beforeImageData.data), beforeImageData.width, beforeImageData.height),
type,
@@ -868,9 +888,9 @@ export function App() {
let finalImageData = rawFiltered;
if (selection) {
- const selMask = createSelectionMask(selection, targetCanvas.width, targetCanvas.height);
+ const selMask = createSelectionMask(selection, width, height);
if (selMask) {
- finalImageData = new ImageData(new Uint8ClampedArray(beforeImageData.data), targetCanvas.width, targetCanvas.height);
+ finalImageData = new ImageData(new Uint8ClampedArray(beforeImageData.data), width, height);
const src = beforeImageData.data;
const flt = rawFiltered.data;
const dst = finalImageData.data;
@@ -895,18 +915,25 @@ export function App() {
}
}
- ctx.putImageData(finalImageData, 0, 0);
-
- if (!isTone && sourceCanvas) {
- get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
- }
+ const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
if (isTone && sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600);
+ get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
+ const effDisplay = displayCanvas || materializeLayerCanvas(activeLayerId);
+ if (effDisplay) {
+ applyLayerEffects(sourceCanvas, effDisplay, activeLayer, dimensions.dpi ?? 600);
+ grid.ingestCanvas(activeLayerId, effDisplay, targetFormat);
+ }
} else {
- const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
- globalTileGrid.writeImageData(activeLayerId, finalImageData, 0, 0, targetFormat);
+ grid.writeImageData(activeLayerId, finalImageData, 0, 0, targetFormat);
+ if (displayCanvas) {
+ get2DContext(displayCanvas)?.putImageData(finalImageData, 0, 0);
+ releaseLayerCanvas(activeLayerId);
+ }
+ if (sourceCanvas) {
+ get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
+ }
}
pushHistoryStepRef.current?.(
@@ -916,11 +943,11 @@ export function App() {
finalImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
showToast(`Filter applied: ${type.replace('-', ' ')}`);
},
- [hasOpenDocument, activeLayer, activeLayerId, selection, dimensions.dpi, layerCanvasesRef, layerSourceCanvasesRef, colorMode, updateLayerThumbnail, showToast]
+ [hasOpenDocument, activeLayer, activeLayerId, selection, dimensions.width, dimensions.height, dimensions.dpi, layerCanvasesRef, layerSourceCanvasesRef, materializeLayerCanvas, releaseLayerCanvas, colorMode, updateLayerThumbnail, showToast]
);
const {
@@ -1169,9 +1196,9 @@ export function App() {
if (ctx) {
renderVectorStroke(ctx, msg.vectorStroke);
const fullData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
- globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, targetFormat);
+ documentStore.getActiveTileGrid().writeImageData(targetLayerId, fullData, 0, 0, targetFormat);
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(targetLayerId, true);
} else {
const ctx = get2DContext(targetCanvas);
@@ -1250,10 +1277,10 @@ export function App() {
if (dirtyW > 0 && dirtyH > 0) {
const afterData = ctx.getImageData(dirtyX, dirtyY, dirtyW, dirtyH);
- globalTileGrid.writeImageData(targetLayerId, afterData, dirtyX, dirtyY, targetFormat);
+ documentStore.getActiveTileGrid().writeImageData(targetLayerId, afterData, dirtyX, dirtyY, targetFormat);
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(targetLayerId, true);
}
}
@@ -1337,12 +1364,12 @@ export function App() {
if (isBg) {
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, targetCanvas.width, targetCanvas.height);
- globalTileGrid.ingestCanvas(layerId, targetCanvas, 'color-32bit');
+ documentStore.getActiveTileGrid().ingestCanvas(layerId, targetCanvas, 'color-32bit');
} else {
ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
- globalTileGrid.clearLayer(layerId);
+ documentStore.getActiveTileGrid().clearLayer(layerId);
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(layerId, true);
}
}
@@ -1551,6 +1578,8 @@ export function App() {
navigation,
activeLayerId,
activeSessionId: activeDocumentId,
+ tileGrid: activeTileGrid,
+ materializeLayerCanvas,
activeLayerLocked: activeLayer?.locked ?? false,
activeLayerVisible: activeLayer ? isLayerEffectivelyVisible(activeLayer) : true,
layerCanvasesRef,
@@ -1779,9 +1808,9 @@ export function App() {
} else {
const lyr = layers.find((l) => l.id === targetLayerId);
const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(targetLayerId, afterData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().writeImageData(targetLayerId, afterData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}
updateLayerThumbnail(targetLayerId, true);
@@ -1811,7 +1840,7 @@ export function App() {
afterData,
targetLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}
}
setSelection(null);
@@ -1888,7 +1917,7 @@ export function App() {
afterImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}, [selection, getActiveCanvas, activeLayerId, layerCanvasesRef, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
const handleFillSelectionColor = useCallback(() => {
@@ -2107,52 +2136,29 @@ export function App() {
handleCommitFloatingSelection();
}
+ const grid = documentStore.getActiveTileGrid();
let targetLayerId = activeLayerId;
let targetLayer = layers.find((l) => l.id === targetLayerId);
- let displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ let hasPixels = grid.hasLayerTiles(targetLayerId);
- // Verify if target layer has pixels, or if user is accidentally on an empty layer
- let hasPixels = false;
- if (displayCanvas) {
- const dCtx = get2DContext(displayCanvas);
- if (dCtx) {
- const dData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height).data;
- for (let i = 3; i < dData.length; i += 4) {
- if (dData[i] > 0) {
- hasPixels = true;
- break;
- }
- }
- }
- }
-
- // If active layer is completely empty, check if another visible raster layer has artwork (e.g. image layer below)
if (!hasPixels) {
- const candidate = layers.find((l) => {
- if (l.id === targetLayerId || l.type !== 'raster' || !l.visible) return false;
- const c = layerCanvasesRef.current.get(l.id);
- if (!c) return false;
- const cCtx = get2DContext(c);
- if (!cCtx) return false;
- const cData = cCtx.getImageData(0, 0, c.width, c.height).data;
- for (let j = 3; j < cData.length; j += 4) {
- if (cData[j] > 0) return true;
- }
- return false;
- });
-
+ const candidate = layers.find(
+ (l) => l.id !== targetLayerId && l.type === 'raster' && l.visible && grid.hasLayerTiles(l.id)
+ );
if (candidate) {
targetLayerId = candidate.id;
targetLayer = candidate;
- displayCanvas = layerCanvasesRef.current.get(candidate.id);
setActiveLayerId(candidate.id);
showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
+ hasPixels = true;
} else {
showToast('Selected layer is empty. Draw or open an image first.');
return;
}
}
+ const displayCanvas = materializeLayerCanvas(targetLayerId);
+
const isTone = Boolean(targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
@@ -2233,8 +2239,8 @@ export function App() {
if (displayCanvas) {
const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
}
},
[layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]
@@ -2283,7 +2289,10 @@ export function App() {
finalData,
targetLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ if (!isTone) {
+ releaseLayerCanvas(targetLayerId);
+ }
const resetState = {
isOpen: false,
@@ -2305,6 +2314,7 @@ export function App() {
updateLayerThumbnail,
getTonalLabel,
pushHistoryStep,
+ releaseLayerCanvas,
showToast,
]
);
@@ -2333,8 +2343,11 @@ export function App() {
}
if (displayCanvas) {
const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
+ if (!isTone) {
+ releaseLayerCanvas(targetLayerId);
+ }
}
}
}
@@ -2350,7 +2363,7 @@ export function App() {
};
tonalModalStateRef.current = resetState;
setTonalModalState(resetState);
- }, [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]);
+ }, [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi, releaseLayerCanvas]);
const handleApplyReverseGradient = useCallback(() => {
if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
@@ -2476,8 +2489,8 @@ export function App() {
floatCanvas = lifted.floatingCanvas;
beforeData = lifted.beforeImageData;
const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
}
@@ -2597,10 +2610,10 @@ export function App() {
}
}
const isMono = colorMode === 'monochrome' || lyr.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(lyr.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().ingestCanvas(lyr.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
updateLayerThumbnail(lyr.id, true);
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
setTransformSession({
@@ -2672,8 +2685,8 @@ export function App() {
}
const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
@@ -2756,7 +2769,7 @@ export function App() {
const beforeDataForLayer = transformSession.layerBeforeImages?.get(lId);
const afterDataForLayer = cCtx.getImageData(0, 0, c.width, c.height);
const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
if (beforeDataForLayer) {
pushHistoryStep(
'transform',
@@ -2769,7 +2782,7 @@ export function App() {
updateLayerThumbnail(lId, true);
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
setTransformSession(null);
setTool('brush');
return;
@@ -2833,7 +2846,7 @@ export function App() {
afterImageData,
transformSession.layerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(transformSession.layerId, true);
setTransformSession(null);
@@ -2876,11 +2889,11 @@ export function App() {
}
}
const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
updateLayerThumbnail(lId, true);
}
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
setTransformSession(null);
setTool('brush');
return;
@@ -2911,8 +2924,8 @@ export function App() {
}
}
const isMono = colorMode === 'monochrome' || layer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(transformSession.layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(transformSession.layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(transformSession.layerId, true);
}
setTransformSession(null);
@@ -2972,7 +2985,7 @@ export function App() {
afterImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
setTextSession(null);
}, [textSession, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
@@ -3009,7 +3022,7 @@ export function App() {
afterImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
setActiveBalloon(null);
}, [activeBalloon, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
@@ -3044,7 +3057,7 @@ export function App() {
const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
updateLayerThumbnail(activeLayerId, true);
pushHistoryStep('brush', `Manga Effect (${type})`, beforeImageData, afterImageData, activeLayerId);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
showToast(`Applied manga ${type} lines`);
},
[getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep, showToast]
@@ -3185,10 +3198,10 @@ export function App() {
if (dCtx && dirty.width > 0 && dirty.height > 0) {
const subData = dCtx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(activeLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().writeImageData(activeLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
}
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}
liquifyRafIdRef.current = requestAnimationFrame(tick);
@@ -3261,9 +3274,9 @@ export function App() {
} else if (dirty.width > 0 && dirty.height > 0) {
const subData = ctx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(targetLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().writeImageData(targetLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}
startLiquifyLoop(canvas, sourceCanvas, isTone);
}
@@ -3430,8 +3443,8 @@ export function App() {
const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
if (lifted) {
const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
const floatingObj = {
canvas: lifted.floatingCanvas,
@@ -3548,7 +3561,7 @@ export function App() {
afterImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
return;
}
@@ -3685,8 +3698,8 @@ export function App() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderVectorLayer(ctx, newStrokes);
const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
}
}
@@ -3756,10 +3769,10 @@ export function App() {
if (cCtx) {
const subData = cCtx.getImageData(overallDirty.x, overallDirty.y, overallDirty.width, overallDirty.height);
const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(targetLayerId, subData, overallDirty.x, overallDirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().writeImageData(targetLayerId, subData, overallDirty.x, overallDirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
}
}
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
if (!liquifyDirtyRectRef.current) {
liquifyDirtyRectRef.current = overallDirty;
} else {
@@ -3931,7 +3944,7 @@ export function App() {
afterImageData,
targetLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
updateLayerThumbnail(targetLayerId, true);
}
}
@@ -4037,7 +4050,7 @@ export function App() {
afterImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
return;
}
@@ -4084,7 +4097,7 @@ export function App() {
afterImageData,
activeLayerId
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}
return;
}
@@ -4102,7 +4115,7 @@ export function App() {
undefined,
{ before: vectorEditBeforeStrokesRef.current, after: [...activeLayer.vectorStrokes] }
);
- globalTileGrid.notifyChange(true);
+ documentStore.getActiveTileGrid().notifyChange(true);
}
return;
}
@@ -4175,19 +4188,20 @@ export function App() {
}
const defaultFreq = options.defaultFrequency ?? 60;
+ const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
newDims,
options.backgroundColor,
options.colorMode,
- defaultFreq
+ defaultFreq,
+ newDocId
);
needsAdaptiveFitRef.current = true;
pendingFitDimsRef.current = newDims;
resetZoomAndCenter(newDims);
- resetHistory();
+ resetHistory(newDocId);
// Add to document tabs (empty perspective ruler by default)
- const newDocId = `doc-${Date.now()}`;
const newDoc: DocumentTab = {
id: newDocId,
name,
@@ -4222,6 +4236,7 @@ export function App() {
const initColorMode = appSettings.defaultColorMode || 'color';
const initBg = appSettings.defaultBgColor || '#ffffff';
const initName = 'Untitled*';
+ const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
setDimensions(initDims);
setColorMode(initColorMode);
setDocumentName(initName);
@@ -4229,13 +4244,13 @@ export function App() {
initDims,
initBg,
initColorMode,
- 60
+ 60,
+ newDocId
);
needsAdaptiveFitRef.current = true;
pendingFitDimsRef.current = initDims;
resetZoomAndCenter(initDims);
- resetHistory();
- const newDocId = `doc-${Date.now()}`;
+ resetHistory(newDocId);
setDocuments([
{
id: newDocId,
@@ -4363,7 +4378,7 @@ export function App() {
const handleUpdateSettings = useCallback((newSettings: AppSettings) => {
setAppSettings(newSettings);
saveAppSettings(newSettings);
- globalTileMemoryManager.setBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
+ documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
setBrushSettings((prev) => ({
...prev,
stabilization: newSettings.defaultStabilization,
@@ -4372,9 +4387,9 @@ export function App() {
}));
}, []);
- // Synchronize initial tile memory budget
+ // Synchronize initial tile memory budget (shared across all open documents)
useEffect(() => {
- globalTileMemoryManager.setBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
+ documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
}, [appSettings.tileMemoryBudgetMb]);
// File loading handler
@@ -4414,19 +4429,19 @@ export function App() {
setLoadingStatus(`Loading ${file.name}...`);
const doc = await openFile(file);
+ const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
setDimensions(doc.dimensions);
setColorMode(doc.colorMode);
setDocumentName(doc.name);
setSavedFileInfo(null); // Reset handle on new import
- loadDocument(doc);
+ loadDocument(doc, newDocId);
needsAdaptiveFitRef.current = true;
pendingFitDimsRef.current = doc.dimensions;
resetZoomAndCenter(doc.dimensions);
- resetHistory();
+ resetHistory(newDocId);
- // Create document tab
- const newDocId = `doc-${Date.now()}`;
+ // Create document tab (pixel storage lives in DocumentStore's isolated SparseTileGrid)
const newDoc: DocumentTab = {
id: newDocId,
name: doc.name,
@@ -4469,18 +4484,13 @@ export function App() {
[loadDocument, resetHistory, resetZoomAndCenter, showToast]
);
- // Keep active document tab's layers in sync
+ // Keep active document tab's metadata in sync (without copying full HTMLCanvasElements into state)
useEffect(() => {
if (!activeDocumentId) return;
setDocuments((prev) => {
const curr = prev.find((d) => d.id === activeDocumentId);
if (!curr) return prev;
- if (
- curr.layers === layers &&
- curr.activeLayerId === activeLayerId &&
- curr.layerCanvasesMap &&
- curr.layerCanvasesMap.size === layerCanvasesRef.current.size
- ) {
+ if (curr.layers === layers && curr.activeLayerId === activeLayerId) {
return prev;
}
return prev.map((d) =>
@@ -4489,19 +4499,21 @@ export function App() {
...d,
layers,
activeLayerId,
- layerCanvasesMap: new Map(layerCanvasesRef.current),
}
: d
);
});
- }, [layers, activeLayerId, activeDocumentId, layerCanvasesRef]);
+ }, [layers, activeLayerId, activeDocumentId]);
- // Tab selection, close, and rename handlers
+ // Tab selection, close, and rename handlers — O(1) SparseTileGrid switch without clearing or re-slicing
const handleSelectDocument = useCallback(
(id: string) => {
+ if (id === activeDocumentId) {
+ setAppView('workspace');
+ return;
+ }
const doc = documents.find((d) => d.id === id);
if (!doc) return;
- setActiveDocumentId(id);
setAppView('workspace');
setDimensions(doc.dimensions);
setColorMode(doc.colorMode);
@@ -4518,21 +4530,14 @@ export function App() {
} else {
setSavedFileInfo(null);
}
- if (doc.layers && doc.layers.length > 0) {
- loadDocument({
- dimensions: doc.dimensions,
- colorMode: doc.colorMode,
- name: doc.name,
- layers: doc.layers,
- layerCanvases: doc.layerCanvasesMap,
- });
- }
+ switchDocumentSession(id, doc.layers || [], doc.activeLayerId || '', doc.dimensions);
+ setActiveDocumentId(id);
setPerspectiveRuler(doc.perspectiveRuler ?? null);
needsAdaptiveFitRef.current = true;
pendingFitDimsRef.current = doc.dimensions;
resetZoomAndCenter(doc.dimensions);
},
- [documents, loadDocument, resetZoomAndCenter]
+ [activeDocumentId, documents, resetZoomAndCenter, setDefaultToneFrequency, switchDocumentSession]
);
const handleCloseDocument = useCallback(
@@ -4542,7 +4547,6 @@ export function App() {
if (id === activeDocumentId) {
if (next.length > 0) {
const nextActive = next[next.length - 1];
- setActiveDocumentId(nextActive.id);
setDimensions(nextActive.dimensions);
setColorMode(nextActive.colorMode);
setDocumentName(nextActive.name);
@@ -4557,25 +4561,26 @@ export function App() {
setSavedFileInfo(null);
}
if (nextActive.layers && nextActive.layers.length > 0) {
- loadDocument({
- dimensions: nextActive.dimensions,
- colorMode: nextActive.colorMode,
- name: nextActive.name,
- layers: nextActive.layers,
- layerCanvases: nextActive.layerCanvasesMap,
- });
+ switchDocumentSession(
+ nextActive.id,
+ nextActive.layers,
+ nextActive.activeLayerId || '',
+ nextActive.dimensions
+ );
+ setActiveDocumentId(nextActive.id);
needsAdaptiveFitRef.current = true;
pendingFitDimsRef.current = nextActive.dimensions;
resetZoomAndCenter(nextActive.dimensions);
} else {
+ setActiveDocumentId(nextActive.id);
clearDocument();
}
} else {
+ documentStore.setActiveDocument(null);
setActiveDocumentId(null);
setDocumentName('');
setSavedFileInfo(null);
clearDocument();
- resetHistory();
setPerspectiveRuler(null);
setAppView('home');
}
@@ -4583,10 +4588,12 @@ export function App() {
return next;
});
if (id) {
+ // Dispose isolated SparseTileGrid, scratch disk tiles, Undo cache, and temporary buffers
+ documentStore.closeSession(id).catch(console.warn);
recoveryService.closeSession(id).catch(console.warn);
}
},
- [activeDocumentId, clearDocument, loadDocument, resetHistory]
+ [activeDocumentId, clearDocument, resetZoomAndCenter, switchDocumentSession]
);
// Fault-Tolerant Crash Recovery Restore Handler
@@ -4594,8 +4601,9 @@ export function App() {
async (session: CrashedSessionInfo) => {
try {
const replayData = await recoveryService.loadSessionData(session.session_id);
+ const restoredSession = documentStore.getOrCreateSession(session.session_id);
const { manifest, replayedStrokesCount, replayedMutationsCount } =
- recoveryService.replaySessionData(replayData, globalTileGrid);
+ recoveryService.replaySessionData(replayData, restoredSession.tileGrid);
const restoredDims: CanvasDimensions = {
width: manifest.width,
@@ -4603,26 +4611,17 @@ export function App() {
dpi: manifest.dpi,
};
- // Reconstruct layer canvases backing buffers
- const restoredLayerCanvases = new Map<string, HTMLCanvasElement>();
- for (const layer of manifest.layers) {
- if (layer.type === 'raster' || layer.type === 'vector' || layer.type === 'frame') {
- const canvas = document.createElement('canvas');
- canvas.width = restoredDims.width;
- canvas.height = restoredDims.height;
- globalTileGrid.renderLayerToCanvas(layer.id, canvas);
- restoredLayerCanvases.set(layer.id, canvas);
- }
- }
-
- // Load document into useLayerManager
- loadDocument({
- name: manifest.documentName,
- dimensions: restoredDims,
- colorMode: manifest.colorMode,
- layers: manifest.layers,
- layerCanvases: restoredLayerCanvases,
- });
+ // Bind document directly to the replayed SparseTileGrid (zero full-canvas reconstruction!)
+ loadDocument(
+ {
+ name: manifest.documentName,
+ dimensions: restoredDims,
+ colorMode: manifest.colorMode,
+ layers: manifest.layers,
+ },
+ session.session_id,
+ true
+ );
if (manifest.activeLayerId) {
setActiveLayerId(manifest.activeLayerId);
}
@@ -4639,7 +4638,6 @@ export function App() {
colorMode: manifest.colorMode,
layers: manifest.layers,
activeLayerId: manifest.activeLayerId || manifest.layers[0]?.id || '',
- layerCanvasesMap: restoredLayerCanvases,
};
setDocuments((prev) => {
@@ -4652,7 +4650,7 @@ export function App() {
needsAdaptiveFitRef.current = true;
pendingFitDimsRef.current = restoredDims;
resetZoomAndCenter(restoredDims);
- resetHistory();
+ resetHistory(session.session_id);
// Push undo history entry
pushHistoryStep(
@@ -4664,7 +4662,7 @@ export function App() {
);
// Invalidate GPU textures & trigger compositor
- globalTileGrid.notifyChange(true);
+ restoredSession.tileGrid.notifyChange(true);
setIsRecoveryModalOpen(false);
setCrashedSessions((prev) => prev.filter((s) => s.session_id !== session.session_id));
@@ -4733,6 +4731,7 @@ export function App() {
colorMode,
layers,
layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
getEffectiveOpacity,
isLayerEffectivelyVisible,
tabId: activeDocumentId || undefined,
@@ -4832,6 +4831,7 @@ export function App() {
colorMode,
layers,
layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
getEffectiveOpacity,
isLayerEffectivelyVisible,
tabId: activeDocumentId || undefined,
@@ -4883,6 +4883,7 @@ export function App() {
colorMode,
layers,
layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
getEffectiveOpacity,
isLayerEffectivelyVisible,
};
@@ -6835,6 +6836,7 @@ export function App() {
layers={layers}
activeLayerId={activeLayerId}
colorMode={colorMode}
+ tileGrid={activeTileGrid}
layerCanvasesRef={layerCanvasesRef}
registerLayerCanvas={registerLayerCanvas}
getEffectiveOpacity={getEffectiveOpacity}
@@ -7136,7 +7138,8 @@ export function App() {
layerCanvasesRef.current,
getEffectiveOpacity,
isLayerEffectivelyVisible,
- false
+ false,
+ documentStore.getActiveTileGrid()
)
}
canvasWidth={dimensions.width}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 90ba38c..d97f187 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -22,7 +22,7 @@ import { PerspectiveRulerOverlay } from './PerspectiveRulerOverlay';
import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
import { Local3DContainer } from './Local3DContainer';
import { ViewportCompositor } from '../utils/compositor';
-import { globalTileGrid } from '../utils/tileEngine';
+import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';
import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../utils/brushOutline';
import { preloadTipImage } from '../utils/brushStorage';
import { Smartphone, Archive } from 'lucide-react';
@@ -123,6 +123,7 @@ interface CanvasAreaProps {
onViewportReady?: (viewport: HTMLDivElement) => void;
activeLayerId?: string;
colorMode?: CanvasColorMode;
+ tileGrid?: SparseTileGrid;
}
export function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
@@ -227,7 +228,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onPointerLeave,
layers,
layerCanvasesRef,
- registerLayerCanvas,
+ registerLayerCanvas: _registerLayerCanvas,
getEffectiveOpacity: _getEffectiveOpacity,
isLayerEffectivelyVisible: _isLayerEffectivelyVisible,
interactionRef,
@@ -282,7 +283,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
softProofSettings,
activeLayerId,
colorMode = 'color',
+ tileGrid = globalTileGrid,
}) => {
+ const tileGridRef = useRef<SparseTileGrid>(tileGrid);
+ tileGridRef.current = tileGrid;
const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;
const localPredictedCanvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -692,7 +696,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
flipY: cam.flipY,
},
rp.dimensions,
- globalTileGrid,
+ tileGridRef.current,
buildCompositorOptions(rp, dpr)
);
}
@@ -758,7 +762,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
flipY: rp.flipY,
},
rp.dimensions,
- globalTileGrid,
+ tileGridRef.current,
buildCompositorOptions(rp, dpr)
);
}
@@ -822,26 +826,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
compositorRef.current = new ViewportCompositor(vCanvas);
}
- // Ingest unindexed layer canvases into globalTileGrid
- if (layerCanvasesRef?.current) {
- for (const layer of layers) {
- if (layer.type === 'raster' || layer.type === 'vector' || layer.type === 'frame') {
- let c = layerCanvasesRef.current.get(layer.id);
- if (!c) {
- c = document.createElement('canvas');
- c.width = dimensions.width;
- c.height = dimensions.height;
- registerLayerCanvas(layer.id, c);
- }
- if (c && !globalTileGrid.isLayerIngested(layer.id)) {
- const isBg = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
- const isMono = !isBg && (layer.expressionColor === 'monochrome' || colorMode === 'monochrome');
- globalTileGrid.ingestCanvas(layer.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- }
- }
- }
-
const dpr = window.devicePixelRatio || 1;
const rp = renderParamsRef.current;
compositorRef.current.render(
@@ -854,14 +838,15 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
flipY: rp.flipY,
},
dimensions,
- globalTileGrid,
+ tileGrid,
buildCompositorOptions(rp, dpr)
);
- }, [effectiveLayers, layers, pan, zoom, rotation, flipX, flipY, dimensions, showCheckerboard, layerCanvasesRef, registerLayerCanvas, onionSkinFrames, softProofSettings, activeLayerId, brushSettings.opacity, colorMode]);
+ }, [effectiveLayers, layers, pan, zoom, rotation, flipX, flipY, dimensions, showCheckerboard, onionSkinFrames, softProofSettings, activeLayerId, brushSettings.opacity, colorMode, tileGrid]);
- // Event-Driven Compositor Invalidation via SparseTileGrid subscription
+ // Event-Driven Compositor Invalidation via active document's SparseTileGrid subscription
useEffect(() => {
let rafId: number | null = null;
+ const activeGrid = tileGrid;
const renderCompositor = () => {
if (compositorRef.current) {
const dpr = window.devicePixelRatio || 1;
@@ -876,7 +861,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
flipY: rp.flipY,
},
rp.dimensions,
- globalTileGrid,
+ activeGrid,
buildCompositorOptions(rp, dpr)
);
}
@@ -898,12 +883,12 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
});
};
- const unsubscribe = globalTileGrid.subscribe(handleGridChange);
+ const unsubscribe = activeGrid.subscribe(handleGridChange);
return () => {
unsubscribe();
if (rafId !== null) cancelAnimationFrame(rafId);
};
- }, []);
+ }, [tileGrid]);
useEffect(() => {
return () => {
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index de453e2..7b1f503 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -15,8 +15,9 @@ import {
VectorStroke,
VectorKnot,
} from '../types/editor';
-import { globalTileGrid, TILE_SIZE, TileFormat } from '../utils/tileEngine';
-import { globalUndoCache } from '../utils/undoCache';
+import { SparseTileGrid, globalTileGrid, TILE_SIZE, TileFormat, releaseTemporaryCanvas } from '../utils/tileEngine';
+import { UndoCacheManager, globalUndoCache } from '../utils/undoCache';
+import { documentStore } from '../utils/documentStore';
import { recoveryService } from '../services/recoveryService';
import {
applyVectorEraser,
@@ -185,6 +186,8 @@ interface UseCanvasDrawingProps {
perspectiveRuler?: PerspectiveRuler | null;
onActiveConstraintAxisChange?: (axis: ConstraintAxis | null) => void;
activeSessionId?: string | null;
+ tileGrid?: SparseTileGrid;
+ materializeLayerCanvas?: (layerId: string) => HTMLCanvasElement | null;
}
export function useCanvasDrawing({
@@ -203,6 +206,8 @@ export function useCanvasDrawing({
navigation,
activeLayerId,
activeSessionId,
+ tileGrid,
+ materializeLayerCanvas,
activeLayerLocked = false,
activeLayerVisible = true,
layerCanvasesRef,
@@ -428,14 +433,79 @@ export function useCanvasDrawing({
const clearDraftRafRef = useRef<number | null>(null);
- // Undo / Redo history stack of rich history items
- const historyRef = useRef<HistoryItem[]>([]);
- const historyIndexRef = useRef<number>(-1);
+ // Per-document isolated tile grid, undo cache, and history stack bound to activeSessionId
+ const activeSessionIdRef = useRef<string | null>(activeSessionId ?? null);
+ const activeTileGridRef = useRef<SparseTileGrid>(
+ tileGrid ?? (activeSessionId ? documentStore.getOrCreateSession(activeSessionId).tileGrid : globalTileGrid)
+ );
+ const activeUndoCacheRef = useRef<UndoCacheManager>(
+ activeSessionId ? documentStore.getOrCreateSession(activeSessionId).undoCache : globalUndoCache
+ );
+
+ // Undo / Redo history stack of rich history items (synchronized with active TileGridSession)
+ const initialSession = activeSessionId ? documentStore.getOrCreateSession(activeSessionId) : null;
+ const historyRef = useRef<HistoryItem[]>(initialSession ? initialSession.history : []);
+ const historyIndexRef = useRef<number>(initialSession ? initialSession.historyIndex : -1);
const [historyList, setHistoryList] = useState<HistoryItemMeta[]>([]);
const [historyIndex, setHistoryIndex] = useState<number>(-1);
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);
+ // Keep tileGridRef fresh if caller passes an explicit grid
+ if (tileGrid) {
+ activeTileGridRef.current = tileGrid;
+ } else if (activeSessionId) {
+ const sess = documentStore.getOrCreateSession(activeSessionId);
+ activeTileGridRef.current = sess.tileGrid;
+ activeUndoCacheRef.current = sess.undoCache;
+ }
+
+ // Non-allocating lookup of an already-materialized canvas (or active mask canvas)
+ const getCachedLayerCanvas = useCallback(
+ (layerId?: string): HTMLCanvasElement | null => {
+ const targetId = layerId || activeLayerIdRef.current || activeLayerId;
+ if (isMaskModeRef.current && (!layerId || layerId === activeLayerIdRef.current)) {
+ const activeLayer = layersRef.current?.find((l) => l.id === targetId);
+ if (activeLayer?.maskCanvas) {
+ return activeLayer.maskCanvas;
+ }
+ }
+ return layerCanvasesRef.current.get(targetId) || null;
+ },
+ [activeLayerId, layerCanvasesRef]
+ );
+
+ // Public getter used by legacy canvas-based tools in App.tsx (materializes on demand from SparseTileGrid)
+ const getActiveCanvas = useCallback(() => {
+ const targetId = activeLayerIdRef.current || activeLayerId;
+ if (isMaskModeRef.current) {
+ const activeLayer = layersRef.current?.find((l) => l.id === targetId);
+ if (activeLayer?.maskCanvas) {
+ return activeLayer.maskCanvas;
+ }
+ }
+ const existing = layerCanvasesRef.current.get(targetId);
+ if (existing) return existing;
+ if (targetId && materializeLayerCanvas) {
+ return materializeLayerCanvas(targetId);
+ }
+ return (
+ layerCanvasesRef.current.get('layer-1') ||
+ layerCanvasesRef.current.values().next().value ||
+ null
+ );
+ }, [activeLayerId, layerCanvasesRef, materializeLayerCanvas]);
+
+ const persistSessionHistory = useCallback((docId?: string | null) => {
+ const targetDocId = docId !== undefined ? docId : activeSessionIdRef.current;
+ if (!targetDocId) return;
+ const sess = documentStore.getSession(targetDocId);
+ if (sess) {
+ sess.history = historyRef.current;
+ sess.historyIndex = historyIndexRef.current;
+ }
+ }, []);
+
// Real-time hover / draw stats dispatched via lightweight custom events without triggering React re-renders
const statRafRef = useRef<number | null>(null);
const pendingStatRef = useRef<{ x: number | null; y: number | null; pressure: number } | null>(null);
@@ -494,22 +564,6 @@ export function useCanvasDrawing({
}
}, []);
- const getActiveCanvas = useCallback(() => {
- const targetId = activeLayerIdRef.current || activeLayerId;
- if (isMaskModeRef.current) {
- const activeLayer = layersRef.current?.find((l) => l.id === targetId);
- if (activeLayer?.maskCanvas) {
- return activeLayer.maskCanvas;
- }
- }
- return (
- layerCanvasesRef.current.get(targetId) ||
- layerCanvasesRef.current.get('layer-1') ||
- layerCanvasesRef.current.values().next().value ||
- null
- );
- }, [activeLayerId, layerCanvasesRef]);
-
const syncHistoryState = useCallback(() => {
const idx = historyIndexRef.current;
const len = historyRef.current.length;
@@ -529,40 +583,35 @@ export function useCanvasDrawing({
);
}, []);
- const ensureInitialHistory = useCallback(
- (canvas: HTMLCanvasElement, _ctx: CanvasRenderingContext2D) => {
- if (historyRef.current.length === 0) {
- const now = Date.now();
- const isMono = !isBackgroundLayerId(activeLayerIdRef.current) && colorModeRef.current === 'monochrome';
- if (!globalTileGrid.isLayerIngested(activeLayerIdRef.current)) {
- globalTileGrid.ingestCanvas(activeLayerIdRef.current, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- const isLarge = canvas.width * canvas.height > 1024 * 1024;
- const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * 60));
- const initialThumb = isLarge
- ? globalTileGrid.generateThumbnail(activeLayerIdRef.current, 60, targetH, { width: canvas.width, height: canvas.height })
- : createCanvasThumbnail(canvas, !isBackgroundLayerId(activeLayerIdRef.current));
-
- const initialItem: HistoryItem = {
- id: `hist-init-${now}`,
- type: 'initial',
- label: 'New Document',
- timestamp: now,
- timeFormatted: formatTime(now),
- thumbnailUrl: initialThumb,
- imageData: undefined,
- beforeImageData: null,
- afterImageData: null,
- layerId: activeLayerIdRef.current,
- };
+ const ensureInitialHistory = useCallback(() => {
+ if (historyRef.current.length === 0) {
+ const now = Date.now();
+ const targetLayerId = activeLayerIdRef.current;
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
+ const initialThumb = targetLayerId
+ ? createCanvasThumbnail({ grid, layerId: targetLayerId, dimensions: dims }, !isBackgroundLayerId(targetLayerId))
+ : '';
- historyRef.current = [initialItem];
- historyIndexRef.current = 0;
- syncHistoryState();
- }
- },
- [syncHistoryState]
- );
+ const initialItem: HistoryItem = {
+ id: `hist-init-${now}`,
+ type: 'initial',
+ label: 'New Document',
+ timestamp: now,
+ timeFormatted: formatTime(now),
+ thumbnailUrl: initialThumb,
+ imageData: undefined,
+ beforeImageData: null,
+ afterImageData: null,
+ layerId: targetLayerId,
+ };
+
+ historyRef.current = [initialItem];
+ historyIndexRef.current = 0;
+ persistSessionHistory();
+ syncHistoryState();
+ }
+ }, [persistSessionHistory, syncHistoryState]);
const pushHistoryStep = useCallback(
(
@@ -579,11 +628,15 @@ export function useCanvasDrawing({
isMaskEdit?: boolean
) => {
const now = Date.now();
- const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
+ const docId = activeSessionIdRef.current;
+ const undoCache = activeUndoCacheRef.current;
let tileDeltas = explicitTileDeltas;
- const effectiveDirtyRect = dirtyRect || (canvas ? { x: 0, y: 0, width: canvas.width, height: canvas.height } : undefined);
+ const effectiveDirtyRect =
+ dirtyRect || (dims.width > 0 && dims.height > 0 ? { x: 0, y: 0, width: dims.width, height: dims.height } : undefined);
// Automatically convert ImageData change into minimal SparseTileGrid TileDeltas (skip for mask edits)
if (!isMaskEdit && !tileDeltas && effectiveDirtyRect && (beforeData || afterData)) {
@@ -594,20 +647,20 @@ export function useCanvasDrawing({
if (beforeData) {
const bx = beforeData.width === effectiveDirtyRect.width && beforeData.height === effectiveDirtyRect.height ? effectiveDirtyRect.x : 0;
const by = beforeData.width === effectiveDirtyRect.width && beforeData.height === effectiveDirtyRect.height ? effectiveDirtyRect.y : 0;
- globalTileGrid.writeImageData(targetLayerId, beforeData, bx, by, targetFormat);
+ grid.writeImageData(targetLayerId, beforeData, bx, by, targetFormat);
}
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(targetLayerId, effectiveDirtyRect);
+ const beforeSnapshot = grid.snapshotTilesInRect(targetLayerId, effectiveDirtyRect);
if (afterData) {
const ax = afterData.width === effectiveDirtyRect.width && afterData.height === effectiveDirtyRect.height ? effectiveDirtyRect.x : 0;
const ay = afterData.width === effectiveDirtyRect.width && afterData.height === effectiveDirtyRect.height ? effectiveDirtyRect.y : 0;
- globalTileGrid.writeImageData(targetLayerId, afterData, ax, ay, targetFormat);
+ grid.writeImageData(targetLayerId, afterData, ax, ay, targetFormat);
} else if (actionType === 'clear') {
- globalTileGrid.clearLayer(targetLayerId);
+ grid.clearLayer(targetLayerId);
}
- tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, effectiveDirtyRect);
+ tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, effectiveDirtyRect);
}
const hasDeltas = Boolean(tileDeltas && tileDeltas.length > 0);
@@ -643,35 +696,39 @@ export function useCanvasDrawing({
historyRef.current = newHistory;
historyIndexRef.current = newHistory.length - 1;
+ persistSessionHistory(docId);
- if (canvas) {
- const isLarge = canvas.width * canvas.height > 1024 * 1024 && globalTileGrid.isLayerIngested(targetLayerId);
+ if (dims.width > 0 && dims.height > 0) {
+ const isLarge = dims.width * dims.height > 1024 * 1024;
if (isLarge && hasDeltas) {
const existingLayerThumb = layersRef.current?.find((l) => l.id === targetLayerId)?.thumbnailUrl || '';
item.thumbnailUrl = existingLayerThumb;
} else {
- const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * 60));
- item.thumbnailUrl = isLarge
- ? globalTileGrid.generateThumbnail(targetLayerId, 60, targetH, { width: canvas.width, height: canvas.height })
- : createCanvasThumbnail(canvas, !isBackgroundLayerId(targetLayerId));
+ item.thumbnailUrl = createCanvasThumbnail(
+ { grid, layerId: targetLayerId, dimensions: dims },
+ !isBackgroundLayerId(targetLayerId)
+ );
}
}
syncHistoryState();
- // Seamless LRU disk cache offloading via Tauri v2 Rust IPC
+ // Per-document LRU disk cache offloading with shared RAM budget across all open tabs
if (tileDeltas && tileDeltas.length > 0) {
- globalUndoCache.registerStep(item, historyRef.current).catch((err) => {
+ const registerPromise = docId
+ ? documentStore.registerUndoStep(docId, item)
+ : undoCache.registerStep(item, historyRef.current);
+ registerPromise.catch((err) => {
console.warn('[History] LRU cache registration failed:', err);
});
}
// Non-blocking WAL journaling for crash recovery
if ((tileDeltas && tileDeltas.length > 0) || vectorDelta) {
- const sessionKey = activeSessionId || recoveryService.getCurrentSessionId() || 'default-session';
+ const sessionKey = docId || recoveryService.getCurrentSessionId() || 'default-session';
recoveryService.logStrokeDelta(sessionKey, tileDeltas, vectorDelta, targetLayerId);
}
},
- [getActiveCanvas, layerCanvasesRef, syncHistoryState]
+ [persistSessionHistory, syncHistoryState]
);
// Background history serialization queue to eliminate main-thread hitches on stroke lift-off
@@ -754,7 +811,7 @@ export function useCanvasDrawing({
}
clearPredictedCanvas();
if (clearedActiveDraft) {
- globalTileGrid.notifyChange(true);
+ activeTileGridRef.current.notifyChange(true);
}
strokePipelineRef.current.abortStroke();
frameGpuDabsRef.current.length = 0;
@@ -786,6 +843,10 @@ export function useCanvasDrawing({
const currentIndex = historyIndexRef.current;
if (targetIndex === currentIndex) return;
+ const grid = activeTileGridRef.current;
+ const undoCache = activeUndoCacheRef.current;
+ const dims = dimensionsRef.current;
+
if (targetIndex < currentIndex) {
// Rolling back (undoing) in reverse chronological order
for (let i = currentIndex; i > targetIndex; i--) {
@@ -796,7 +857,7 @@ export function useCanvasDrawing({
const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
- const deltas = await globalUndoCache.resolveDeltas(item);
+ const deltas = await undoCache.resolveDeltas(item);
// Restore mask canvas if mask edit
if (item.isMaskEdit && targetLayer?.maskCanvas) {
@@ -808,21 +869,27 @@ export function useCanvasDrawing({
targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
onUpdateMaskThumbnailRef.current?.(targetLayerId);
}
- } else if (item.vectorStrokesDelta && targetLayer && canvas) {
+ } else if (item.vectorStrokesDelta && targetLayer) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
- const cCtx = get2DContext(canvas);
+ const tempVec = canvas || document.createElement('canvas');
+ if (!canvas) {
+ tempVec.width = dims.width;
+ tempVec.height = dims.height;
+ }
+ const cCtx = get2DContext(tempVec);
if (cCtx) {
- cCtx.clearRect(0, 0, canvas.width, canvas.height);
+ cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const fullData = cCtx.getImageData(0, 0, canvas.width, canvas.height);
const isMono = targetLayer.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.clearLayer(targetLayerId);
+ grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
}
+ if (!canvas) releaseTemporaryCanvas(tempVec);
} else if (deltas && deltas.length > 0) {
- globalTileGrid.applyTileDeltas(deltas, 'undo');
+ grid.applyTileDeltas(deltas, 'undo');
if (isToneStep && sourceCanvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
if (canvas && targetLayer) {
applyLayerEffects(
sourceCanvas,
@@ -833,9 +900,9 @@ export function useCanvasDrawing({
);
}
} else if (canvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
if (sourceCanvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
}
}
} else if (isToneStep && sourceCanvas) {
@@ -865,50 +932,30 @@ export function useCanvasDrawing({
);
}
} else {
- // Direct canvas restoration for monochrome, color, gray, normal pen, eraser, etc.
- if (canvas) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- if (item.dirtyRect && item.beforeImageData && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height) {
- cCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
- } else if (item.beforeImageData) {
- cCtx.putImageData(item.beforeImageData, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- cCtx.fillStyle = '#ffffff';
- cCtx.fillRect(0, 0, canvas.width, canvas.height);
- } else {
- cCtx.clearRect(0, 0, canvas.width, canvas.height);
- }
- }
- const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
- globalTileGrid.ingestCanvas(targetLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (item.beforeImageData) {
+ const bx = item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height ? item.dirtyRect.x : 0;
+ const by = item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
+ grid.writeImageData(targetLayerId, item.beforeImageData, bx, by, targetFormat);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ grid.fillLayerSolidWhite(targetLayerId, dims.width, dims.height, 'color-32bit');
+ } else {
+ grid.clearLayer(targetLayerId);
}
}
- // Keep sourceCanvas synchronized if present
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (item.dirtyRect && item.beforeImageData && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height) {
- sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
- } else if (item.beforeImageData) {
- sCtx.putImageData(item.beforeImageData, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
}
}
- if (canvas) {
- onUpdateLayerThumbnail(targetLayerId);
- }
+ onUpdateLayerThumbnail(targetLayerId);
}
}
} else {
@@ -922,7 +969,7 @@ export function useCanvasDrawing({
const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
- const deltas = await globalUndoCache.resolveDeltas(item);
+ const deltas = await undoCache.resolveDeltas(item);
// Restore mask canvas if mask edit
if (item.isMaskEdit && targetLayer?.maskCanvas) {
@@ -934,21 +981,27 @@ export function useCanvasDrawing({
targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
onUpdateMaskThumbnailRef.current?.(targetLayerId);
}
- } else if (item.vectorStrokesDelta && targetLayer && canvas) {
+ } else if (item.vectorStrokesDelta && targetLayer) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.after;
- const cCtx = get2DContext(canvas);
+ const tempVec = canvas || document.createElement('canvas');
+ if (!canvas) {
+ tempVec.width = dims.width;
+ tempVec.height = dims.height;
+ }
+ const cCtx = get2DContext(tempVec);
if (cCtx) {
- cCtx.clearRect(0, 0, canvas.width, canvas.height);
+ cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const fullData = cCtx.getImageData(0, 0, canvas.width, canvas.height);
const isMono = targetLayer.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.clearLayer(targetLayerId);
+ grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
}
+ if (!canvas) releaseTemporaryCanvas(tempVec);
} else if (deltas && deltas.length > 0) {
- globalTileGrid.applyTileDeltas(deltas, 'redo');
+ grid.applyTileDeltas(deltas, 'redo');
if (isToneStep && sourceCanvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
if (canvas && targetLayer) {
applyLayerEffects(
sourceCanvas,
@@ -959,9 +1012,9 @@ export function useCanvasDrawing({
);
}
} else if (canvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
if (sourceCanvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
}
}
} else if (isToneStep && sourceCanvas) {
@@ -991,57 +1044,38 @@ export function useCanvasDrawing({
);
}
} else {
- // Direct canvas restoration for monochrome, color, gray, normal pen, eraser, etc.
- if (canvas) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- if (item.dirtyRect && dataToApply && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height) {
- cCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
- } else if (dataToApply) {
- cCtx.putImageData(dataToApply, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- cCtx.fillStyle = '#ffffff';
- cCtx.fillRect(0, 0, canvas.width, canvas.height);
- } else {
- cCtx.clearRect(0, 0, canvas.width, canvas.height);
- }
- }
- const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
- globalTileGrid.ingestCanvas(targetLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (dataToApply) {
+ const ax = item.dirtyRect && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height ? item.dirtyRect.x : 0;
+ const ay = item.dirtyRect && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
+ grid.writeImageData(targetLayerId, dataToApply, ax, ay, targetFormat);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ grid.fillLayerSolidWhite(targetLayerId, dims.width, dims.height, 'color-32bit');
+ } else {
+ grid.clearLayer(targetLayerId);
}
}
- // Keep sourceCanvas synchronized if present
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (item.dirtyRect && dataToApply && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height) {
- sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
- } else if (dataToApply) {
- sCtx.putImageData(dataToApply, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
}
}
- if (canvas) {
- onUpdateLayerThumbnail(targetLayerId);
- }
+ onUpdateLayerThumbnail(targetLayerId);
}
}
}
historyIndexRef.current = targetIndex;
+ persistSessionHistory();
syncHistoryState();
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
});
historyQueueRef.current = nextOp.catch((err) => {
console.warn('[History] Error during jumpToHistoryIndex:', err);
@@ -1097,36 +1131,44 @@ export function useCanvasDrawing({
const item = history[targetItemIdx];
const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const grid = activeTileGridRef.current;
+ const undoCache = activeUndoCacheRef.current;
+ const dims = dimensionsRef.current;
// Revert vector strokes if vector delta exists
- if (item.vectorStrokesDelta && targetLayer && canvas) {
+ if (item.vectorStrokesDelta && targetLayer) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
- const cCtx = get2DContext(canvas);
+ const tempVec = canvas || document.createElement('canvas');
+ if (!canvas) {
+ tempVec.width = dims.width;
+ tempVec.height = dims.height;
+ }
+ const cCtx = get2DContext(tempVec);
if (cCtx) {
- cCtx.clearRect(0, 0, canvas.width, canvas.height);
+ cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const fullData = cCtx.getImageData(0, 0, canvas.width, canvas.height);
const isMono = targetLayer.expressionColor === 'monochrome';
- globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.clearLayer(targetLayerId);
+ grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
}
+ if (!canvas) releaseTemporaryCanvas(tempVec);
} else {
// Revert tile deltas or image data
- const deltas = await globalUndoCache.resolveDeltas(item);
+ const deltas = await undoCache.resolveDeltas(item);
if (deltas && deltas.length > 0) {
- globalTileGrid.applyTileDeltas(deltas, 'undo');
+ grid.applyTileDeltas(deltas, 'undo');
if (canvas) {
- globalTileGrid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
}
- } else if (canvas && item.beforeImageData) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- if (item.dirtyRect) {
- cCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
- } else {
- cCtx.putImageData(item.beforeImageData, 0, 0);
- }
+ } else if (item.beforeImageData) {
+ const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
+ const bx = item.dirtyRect ? item.dirtyRect.x : 0;
+ const by = item.dirtyRect ? item.dirtyRect.y : 0;
+ grid.writeImageData(targetLayerId, item.beforeImageData, bx, by, isMono ? 'monochrome-1bit' : 'color-32bit');
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
}
}
}
@@ -1134,25 +1176,29 @@ export function useCanvasDrawing({
// Remove the undone item from history
historyRef.current.splice(targetItemIdx, 1);
historyIndexRef.current = Math.min(historyIndexRef.current - 1, historyRef.current.length - 1);
+ persistSessionHistory();
syncHistoryState();
- if (canvas) {
- onUpdateLayerThumbnail(targetLayerId);
- }
- globalTileGrid.notifyChange(true);
+ onUpdateLayerThumbnail(targetLayerId);
+ grid.notifyChange(true);
},
- [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
+ [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, layerCanvasesRef, onUpdateLayerThumbnail, persistSessionHistory, syncHistoryState]
);
- // Clear active layer action
+ // Clear active layer action directly via SparseTileGrid (zero full-canvas getImageData)
const clearCanvas = useCallback(() => {
- const canvas = getActiveCanvas();
- if (!canvas || activeLayerLocked) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
+ if (!activeLayerId || activeLayerLocked) return;
+ const dims = dimensionsRef.current;
+ if (dims.width <= 0 || dims.height <= 0) return;
- const beforeData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const grid = activeTileGridRef.current;
const activeLayer = layersRef.current?.find((l) => l.id === activeLayerId);
+ const isBg = isBackgroundLayerId(activeLayerId);
+ const fullRect = { x: 0, y: 0, width: dims.width, height: dims.height };
+
+ const beforeSnapshot = isBg
+ ? grid.snapshotTilesInRect(activeLayerId, fullRect)
+ : grid.snapshotLayerTiles(activeLayerId);
let vectorDelta: { before: VectorStroke[]; after: VectorStroke[] } | undefined;
if (activeLayer?.type === 'vector') {
@@ -1161,12 +1207,26 @@ export function useCanvasDrawing({
vectorDelta = { before: beforeStrokes, after: [] };
}
- const isBg = isBackgroundLayerId(activeLayerId);
if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
+ grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');
} else {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
+ grid.clearLayer(activeLayerId);
+ grid.markLayerIngested(activeLayerId);
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, activeLayerId, isBg ? fullRect : undefined);
+
+ const canvas = layerCanvasesRef.current.get(activeLayerId);
+ if (canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ if (isBg) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ } else {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ }
+ }
}
const sourceCanvas = layerSourceCanvasesRef?.current?.get(activeLayerId);
@@ -1182,39 +1242,60 @@ export function useCanvasDrawing({
}
}
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
onUpdateLayerThumbnail(activeLayerId);
pushHistoryStep(
'clear',
'Clear Layer',
- beforeData,
- afterData,
+ null,
+ null,
activeLayerId,
- {
- x: 0,
- y: 0,
- width: canvas.width,
- height: canvas.height,
- },
- undefined,
+ fullRect,
+ tileDeltas,
vectorDelta
);
- globalTileGrid.notifyChange(true);
- }, [activeLayerId, activeLayerLocked, getActiveCanvas, layerSourceCanvasesRef, onUpdateLayerThumbnail, pushHistoryStep]);
+ grid.notifyChange(true);
+ }, [activeLayerId, activeLayerLocked, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, pushHistoryStep]);
- // Initialize canvas first history state as soon as canvas is mounted
+ // Isolate and swap per-document history & UndoCacheManager when activeSessionId changes
useEffect(() => {
- if (historyRef.current.length > 0) return;
- const canvas =
- layerCanvasesRef.current.get(activeLayerId) ||
- layerCanvasesRef.current.get('layer-1') ||
- layerCanvasesRef.current.values().next().value;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
+ const prevDocId = activeSessionIdRef.current;
+ const nextDocId = activeSessionId ?? null;
+ if (prevDocId === nextDocId) return;
+
+ // Flush any pending history tasks for the previous document BEFORE switching refs
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStroke();
+ }
+ if (prevDocId) {
+ persistSessionHistory(prevDocId);
+ }
- ensureInitialHistory(canvas, ctx);
- }, [activeLayerId, ensureInitialHistory, layerCanvasesRef]);
+ activeSessionIdRef.current = nextDocId;
+ lastStrokeEndRef.current = null;
+
+ if (nextDocId) {
+ const sess = documentStore.getOrCreateSession(nextDocId);
+ activeTileGridRef.current = tileGrid ?? sess.tileGrid;
+ activeUndoCacheRef.current = sess.undoCache;
+ historyRef.current = sess.history;
+ historyIndexRef.current = sess.historyIndex;
+ } else {
+ activeTileGridRef.current = tileGrid ?? globalTileGrid;
+ activeUndoCacheRef.current = globalUndoCache;
+ historyRef.current = [];
+ historyIndexRef.current = -1;
+ }
+
+ syncHistoryState();
+ }, [activeSessionId, tileGrid, abortActiveStroke, flushPendingHistoryTasks, persistSessionHistory, syncHistoryState]);
+
+ // Initialize document's first history state as soon as an active layer exists (no full canvas needed)
+ useEffect(() => {
+ if (historyRef.current.length > 0) return;
+ if (!activeLayerId || dimensions.width <= 0 || dimensions.height <= 0) return;
+ ensureInitialHistory();
+ }, [activeLayerId, activeSessionId, dimensions.width, dimensions.height, ensureInitialHistory]);
// Convert client pointer event coordinates to canvas pixel space
const getCanvasPoint = useCallback(
@@ -1782,7 +1863,7 @@ export function useCanvasDrawing({
const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
const isVectorOrToneOrMask = activeLayer?.type === 'vector' || isToneStrokeRef.current || isMaskModeRef.current;
const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
- const canvas = getActiveCanvas();
+ const canvas = getCachedLayerCanvas();
const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
@@ -1975,7 +2056,7 @@ export function useCanvasDrawing({
if (liveNeedsNotifyRef.current) {
liveNeedsNotifyRef.current = false;
- globalTileGrid.notifyChange();
+ activeTileGridRef.current.notifyChange();
}
// Update ephemeral predicted stroke overlay throttled to rAF
@@ -1993,7 +2074,7 @@ export function useCanvasDrawing({
clearPredictedCanvas,
effectiveDraftCanvasRef,
emitLiveSegment,
- getActiveCanvas,
+ getCachedLayerCanvas,
getViewportRect,
renderPredictedStroke,
resolveStrokeColor,
@@ -2010,8 +2091,12 @@ export function useCanvasDrawing({
}
flushPendingHistoryTasks();
- const canvas = getActiveCanvas();
- if (!canvas) return;
+ const dims = dimensionsRef.current;
+ const currentLayerIdCheck = activeLayerIdRef.current;
+ if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
+
+ const canvas = getCachedLayerCanvas();
+ if (isMaskModeRef.current && !canvas) return;
if (viewportRef.current) {
cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
@@ -2019,7 +2104,6 @@ export function useCanvasDrawing({
const vRect = getViewportRect();
if (!vRect) return;
- const dims = dimensionsRef.current;
const draftCanvas = effectiveDraftCanvasRef?.current;
if (!draftCanvas) return;
@@ -2108,12 +2192,16 @@ export function useCanvasDrawing({
if (isTone) {
let sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId) || null;
- if (!sourceCanvas && canvas) {
+ if (!sourceCanvas) {
sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = canvas.width;
- sourceCanvas.height = canvas.height;
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(canvas, 0, 0);
+ sourceCanvas.width = dims.width;
+ sourceCanvas.height = dims.height;
+ if (canvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ sCtx?.drawImage(canvas, 0, 0);
+ } else {
+ activeTileGridRef.current.renderLayerToCanvas(currentLayerId, sourceCanvas);
+ }
layerSourceCanvasesRef?.current?.set(currentLayerId, sourceCanvas);
}
}
@@ -2264,11 +2352,11 @@ export function useCanvasDrawing({
isWetColorStrokeRef.current = isWetColor;
liveNeedsNotifyRef.current = false;
- if (isWetColor && canvas) {
+ if (isWetColor) {
layerPixelSamplerRef.current = new LayerPixelSampler(
- canvas,
+ canvas || dims,
currentLayerId,
- globalTileGrid
+ activeTileGridRef.current
);
activeReservoirRef.current = new PaintReservoir(strokeColor);
} else {
@@ -2432,7 +2520,7 @@ export function useCanvasDrawing({
(draftCanvas as any).__draftHasContent = true;
(draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
- globalTileGrid.notifyChange();
+ activeTileGridRef.current.notifyChange();
liveNeedsNotifyRef.current = false;
if (pipeline.getPendingCount() > 0 && drawRafIdRef.current === null) {
@@ -2451,7 +2539,7 @@ export function useCanvasDrawing({
emitLiveSegment,
flushPendingHistoryTasks,
flushPendingPoints,
- getActiveCanvas,
+ getCachedLayerCanvas,
getCanvasPoint,
getViewportRect,
layerSourceCanvasesRef,
@@ -2640,9 +2728,11 @@ export function useCanvasDrawing({
flushPendingPoints();
const bs = brushSettingsRef.current;
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
const endPoint = getCanvasPoint(e);
const draftCanvas = effectiveDraftCanvasRef?.current;
- const canvas = getActiveCanvas();
+ const canvas = getCachedLayerCanvas();
if (canvas) {
(canvas as any).__isBlank = false;
(canvas as any).__isSolidWhite = false;
@@ -2749,7 +2839,7 @@ export function useCanvasDrawing({
};
}
- if (activeLayer?.type === 'vector' && canvas && allPoints.length > 0) {
+ if (activeLayer?.type === 'vector' && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
const knots: VectorKnot[] = allPoints.map((pt, idx) => ({
x: pt.x,
y: pt.y,
@@ -2768,8 +2858,8 @@ export function useCanvasDrawing({
let minX = mergedDirty ? mergedDirty.minX : 0;
let minY = mergedDirty ? mergedDirty.minY : 0;
- let maxX = mergedDirty ? mergedDirty.maxX : canvas.width;
- let maxY = mergedDirty ? mergedDirty.maxY : canvas.height;
+ let maxX = mergedDirty ? mergedDirty.maxX : dims.width;
+ let maxY = mergedDirty ? mergedDirty.maxY : dims.height;
for (const st of prevStrokes) {
if (st.bounds) {
minX = Math.min(minX, st.bounds.minX);
@@ -2781,16 +2871,21 @@ export function useCanvasDrawing({
const vPad = Math.ceil(Math.max(16, (bs.size || 10)));
const vx = Math.max(0, Math.floor(minX - vPad));
const vy = Math.max(0, Math.floor(minY - vPad));
- const vw = Math.max(0, Math.min(canvas.width, Math.ceil(maxX + vPad)) - vx);
- const vh = Math.max(0, Math.min(canvas.height, Math.ceil(maxY + vPad)) - vy);
-
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- renderVectorLayer(ctx, updatedStrokes);
- if (vw > 0 && vh > 0) {
- const subData = ctx.getImageData(vx, vy, vw, vh);
- globalTileGrid.writeImageData(
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX + vPad)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY + vPad)) - vy);
+
+ if (vw > 0 && vh > 0) {
+ const tempVec = document.createElement('canvas');
+ tempVec.width = vw;
+ tempVec.height = vh;
+ const vCtx = get2DContext(tempVec);
+ if (vCtx) {
+ vCtx.save();
+ vCtx.translate(-vx, -vy);
+ renderVectorLayer(vCtx, updatedStrokes);
+ vCtx.restore();
+ const subData = vCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
currentLayerId,
subData,
vx,
@@ -2798,6 +2893,10 @@ export function useCanvasDrawing({
isMonochrome ? 'monochrome-1bit' : 'color-32bit'
);
}
+ releaseTemporaryCanvas(tempVec);
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, { x: vx, y: vy, width: vw, height: vh });
+ }
}
pushHistoryStep(
@@ -2806,7 +2905,7 @@ export function useCanvasDrawing({
null,
null,
currentLayerId,
- vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: canvas.width, height: canvas.height },
+ vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: dims.width, height: dims.height },
undefined,
{ before: prevStrokes, after: updatedStrokes },
undefined,
@@ -2834,15 +2933,19 @@ export function useCanvasDrawing({
const vPad = Math.ceil(Math.max(16, (bs.size || 10)));
const vx = Math.max(0, Math.floor(bounds.minX - vPad));
const vy = Math.max(0, Math.floor(bounds.minY - vPad));
- const vw = Math.max(0, Math.min(canvas.width, Math.ceil(bounds.maxX + vPad)) - vx);
- const vh = Math.max(0, Math.min(canvas.height, Math.ceil(bounds.maxY + vPad)) - vy);
-
- const ctx = get2DContext(canvas);
- if (ctx) {
- renderVectorStroke(ctx, newStroke);
- if (vw > 0 && vh > 0) {
- const subData = ctx.getImageData(vx, vy, vw, vh);
- globalTileGrid.writeImageData(
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(bounds.maxX + vPad)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(bounds.maxY + vPad)) - vy);
+
+ if (vw > 0 && vh > 0) {
+ const tempVec = grid.createRegionCanvas(currentLayerId, { x: vx, y: vy, width: vw, height: vh });
+ const vCtx = tempVec ? get2DContext(tempVec) : null;
+ if (tempVec && vCtx) {
+ vCtx.save();
+ vCtx.translate(-vx, -vy);
+ renderVectorStroke(vCtx, newStroke);
+ vCtx.restore();
+ const subData = vCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
currentLayerId,
subData,
vx,
@@ -2850,6 +2953,10 @@ export function useCanvasDrawing({
isMonochrome ? 'monochrome-1bit' : 'color-32bit'
);
}
+ releaseTemporaryCanvas(tempVec);
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, { x: vx, y: vy, width: vw, height: vh });
+ }
}
pushHistoryStep(
@@ -2858,14 +2965,14 @@ export function useCanvasDrawing({
null,
null,
currentLayerId,
- vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: canvas.width, height: canvas.height },
+ vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: dims.width, height: dims.height },
undefined,
{ before: prevStrokes, after: updatedStrokes },
undefined,
currentStrokeIdRef.current || undefined
);
}
- } else if (canvas && mergedDirty && allPoints.length > 0) {
+ } else if (mergedDirty && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
const hasWetEdge =
!isMonochrome &&
!isEraser &&
@@ -2873,8 +2980,8 @@ export function useCanvasDrawing({
(bs.wetEdge ?? 0) > 0.01;
const clampedBakeRect = computeClampedBakeDirtyRect(
mergedDirty,
- canvas.width,
- canvas.height,
+ dims.width,
+ dims.height,
bs.size || 10,
hasWetEdge ? (bs.wetEdge ?? 0) : 0,
bs.wetEdgeRadius ?? 3.0
@@ -2882,34 +2989,34 @@ export function useCanvasDrawing({
if (clampedBakeRect) {
const { x: sx, y: sy, width: dw, height: dh } = clampedBakeRect;
- const ctx = get2DContext(canvas);
- if (ctx) {
- let label = 'Brush Stroke';
- if (bs.isTransparentInk) {
- label = 'Transparent Ink';
- } else if (currentTool === 'eraser') {
- label = 'Eraser';
- } else if (bs.brushName) {
- label = bs.brushName;
- } else if (bs.preset === 'pencil-f') {
- label = 'Pencil (F)';
- } else if (bs.preset === 'pencil-2b') {
- label = 'Pencil (2B)';
- } else if (bs.preset === 'pencil-4b') {
- label = 'Pencil (4B)';
- } else if (bs.preset === 'pencil-hb') {
- label = 'Pencil (HB)';
- } else {
- label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
- }
+ let label = 'Brush Stroke';
+ if (bs.isTransparentInk) {
+ label = 'Transparent Ink';
+ } else if (currentTool === 'eraser') {
+ label = 'Eraser';
+ } else if (bs.brushName) {
+ label = bs.brushName;
+ } else if (bs.preset === 'pencil-f') {
+ label = 'Pencil (F)';
+ } else if (bs.preset === 'pencil-2b') {
+ label = 'Pencil (2B)';
+ } else if (bs.preset === 'pencil-4b') {
+ label = 'Pencil (4B)';
+ } else if (bs.preset === 'pencil-hb') {
+ label = 'Pencil (HB)';
+ } else {
+ label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
+ }
- const dirtyRect = clampedBakeRect;
- const toolForHistory = currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush');
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
- const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
- const activeSelection = selectionRef.current;
+ const dirtyRect = clampedBakeRect;
+ const toolForHistory = currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush');
+ const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
+ const activeSelection = selectionRef.current;
- if (isMaskModeRef.current) {
+ if (isMaskModeRef.current && canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
const maskBs: BrushSettings = {
...bs,
@@ -2966,114 +3073,115 @@ export function useCanvasDrawing({
true
);
});
- } else if (isToneLayer && sourceCanvas) {
- if (!globalTileGrid.isLayerIngested(currentLayerId)) {
- globalTileGrid.ingestCanvas(currentLayerId, sourceCanvas, targetFormat);
- }
- const sCtx = get2DContext(sourceCanvas);
- const beforeSelectionData =
- activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (sCtx) {
- sCtx.save();
- sCtx.beginPath();
- sCtx.rect(sx, sy, dw, dh);
- sCtx.clip();
- applySelectionCanvasClip(sCtx, activeSelection);
-
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
- if (!needsIsolatedBake) {
- renderCompleteStroke(sCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
+ }
+ } else if (isToneLayer && sourceCanvas) {
+ if (!grid.isLayerIngested(currentLayerId)) {
+ grid.ingestCanvas(currentLayerId, sourceCanvas, targetFormat);
+ }
+ const sCtx = get2DContext(sourceCanvas);
+ const beforeSelectionData =
+ activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (sCtx) {
+ sCtx.save();
+ sCtx.beginPath();
+ sCtx.rect(sx, sy, dw, dh);
+ sCtx.clip();
+ applySelectionCanvasClip(sCtx, activeSelection);
+
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(sCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
+ } else {
+ sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ sCtx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ sCtx.globalCompositeOperation = 'source-atop';
} else {
- sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- sCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- sCtx.globalCompositeOperation = 'source-atop';
- } else {
- sCtx.globalCompositeOperation = 'source-over';
- }
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtxBake) {
- bCtxBake.clearRect(0, 0, dw, dh);
- bCtxBake.save();
- bCtxBake.translate(-sx, -sy);
- renderCompleteStroke(
- bCtxBake,
- allPoints,
- { ...bs, opacity: 1.0, isTransparentInk: false, color: isEraser && !isBgEraser ? '#000000' : bs.color },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- sourceCanvas,
- false
- );
- bCtxBake.restore();
- sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
+ sCtx.globalCompositeOperation = 'source-over';
+ }
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtxBake) {
+ bCtxBake.clearRect(0, 0, dw, dh);
+ bCtxBake.save();
+ bCtxBake.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtxBake,
+ allPoints,
+ { ...bs, opacity: 1.0, isTransparentInk: false, color: isEraser && !isBgEraser ? '#000000' : bs.color },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ sourceCanvas,
+ false
+ );
+ bCtxBake.restore();
+ sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
- sCtx.restore();
- }
-
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
- applySelectionMaskToImageData(beforeSelectionData, afterData, sx, sy, activeSelection);
- sCtx.putImageData(afterData, sx, sy);
}
+ sCtx.restore();
+ }
- if (activeLayer) {
- const freq = activeLayer?.toneFrequency ?? 60;
- const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
- const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
- const fxX = Math.max(0, sx - cellMargin);
- const fxY = Math.max(0, sy - cellMargin);
- const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
- const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensionsRef.current.dpi ?? 600,
- { x: fxX, y: fxY, width: fxW, height: fxH }
- );
- }
+ const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
+ applySelectionMaskToImageData(beforeSelectionData, afterData, sx, sy, activeSelection);
+ sCtx.putImageData(afterData, sx, sy);
+ }
- if (afterData) {
- globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- }
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ if (activeLayer && canvas) {
+ const freq = activeLayer?.toneFrequency ?? 60;
+ const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
+ const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
+ const fxX = Math.max(0, sx - cellMargin);
+ const fxY = Math.max(0, sy - cellMargin);
+ const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
+ const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ activeLayer,
+ dimensionsRef.current.dpi ?? 600,
+ { x: fxX, y: fxY, width: fxW, height: fxH }
+ );
+ }
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
- } else {
- // Standard raster bake (single pointerup bake + SparseTileGrid write + Undo TileDelta)
- if (!globalTileGrid.isLayerIngested(currentLayerId)) {
- globalTileGrid.ingestCanvas(currentLayerId, canvas, targetFormat);
- }
+ if (afterData) {
+ grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ }
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ enqueueHistoryTask(() => {
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
+ } else {
+ // Tile-native raster bake using a temporary dirtyRect-sized canvas (zero full-layer canvas!)
+ const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect);
+ const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
+ if (regionCanvas && rCtx) {
const beforeSelectionData =
- activeSelection?.mask ? ctx.getImageData(sx, sy, dw, dh) : null;
+ activeSelection?.mask ? rCtx.getImageData(0, 0, dw, dh) : null;
- ctx.save();
- ctx.beginPath();
- ctx.rect(sx, sy, dw, dh);
- ctx.clip();
- applySelectionCanvasClip(ctx, activeSelection);
+ rCtx.save();
+ rCtx.translate(-sx, -sy);
+ rCtx.beginPath();
+ rCtx.rect(sx, sy, dw, dh);
+ rCtx.clip();
+ applySelectionCanvasClip(rCtx, activeSelection);
const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
if (!needsIsolatedBake) {
- renderCompleteStroke(ctx, allPoints, bs, currentTool, effectiveMode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
+ renderCompleteStroke(rCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, canvas || undefined, Boolean(activeLayer?.alphaLocked));
} else {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- ctx.globalCompositeOperation = 'destination-out';
+ rCtx.globalCompositeOperation = 'destination-out';
} else if (activeLayer?.alphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
+ rCtx.globalCompositeOperation = 'source-atop';
} else {
- ctx.globalCompositeOperation = 'source-over';
+ rCtx.globalCompositeOperation = 'source-over';
}
const bakeCanvas = getReusableBakeCanvas(dw, dh);
const bCtx = bakeCanvas.getContext('2d', { alpha: true, willReadFrequently: hasWetEdge });
@@ -3094,7 +3202,7 @@ export function useCanvasDrawing({
isEraser && !isBgEraser ? 'brush' : currentTool,
effectiveMode,
isBgEraser,
- canvas,
+ canvas || undefined,
false
);
bCtx.restore();
@@ -3111,16 +3219,16 @@ export function useCanvasDrawing({
bCtx.putImageData(bakeImg, 0, 0);
}
- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
}
- ctx.restore();
+ rCtx.restore();
if (beforeSelectionData && activeSelection?.mask) {
- const fullAfter = ctx.getImageData(sx, sy, dw, dh);
+ const fullAfter = rCtx.getImageData(0, 0, dw, dh);
applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
- ctx.putImageData(fullAfter, sx, sy);
+ rCtx.putImageData(fullAfter, 0, 0);
}
const useSparseTileSpans = dw * dh > 512 * 512 && touchedTilesRef.current.size > 0;
@@ -3142,34 +3250,35 @@ export function useCanvasDrawing({
txList.sort((a, b) => a - b);
let spanStart = txList[0];
let spanEnd = txList[0];
+ const pushClampedSpan = (s0: number, s1: number) => {
+ const rx = Math.max(sx, s0 * TILE_SIZE);
+ const ry = Math.max(sy, ty * TILE_SIZE);
+ const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
+ const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
+ const rw = rxEnd - rx;
+ const rh = ryEnd - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ };
for (let i = 1; i < txList.length; i++) {
if (txList[i] <= spanEnd + 1) {
spanEnd = txList[i];
} else {
- const rx = Math.max(0, spanStart * TILE_SIZE);
- const ry = Math.max(0, ty * TILE_SIZE);
- const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
- const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ pushClampedSpan(spanStart, spanEnd);
spanStart = txList[i];
spanEnd = txList[i];
}
}
- const rx = Math.max(0, spanStart * TILE_SIZE);
- const ry = Math.max(0, ty * TILE_SIZE);
- const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
- const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ pushClampedSpan(spanStart, spanEnd);
}
const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
for (let i = 0; i < spans.length; i++) {
const sp = spans[i];
- const subSnap = globalTileGrid.snapshotTilesInRect(currentLayerId, sp);
+ const subSnap = grid.snapshotTilesInRect(currentLayerId, sp);
for (const [k, v] of subSnap) {
if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
}
- const spanData = ctx.getImageData(sp.x, sp.y, sp.width, sp.height);
+ const spanData = rCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
if (isMonochrome) {
binarizeImageDataBuffer(
spanData,
@@ -3177,32 +3286,17 @@ export function useCanvasDrawing({
activeLayer?.monoExpressBlack ?? true,
activeLayer?.monoExpressWhite ?? true
);
- ctx.putImageData(spanData, sp.x, sp.y);
}
- globalTileGrid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
+ grid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
}
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- sCtx.clearRect(sp.x, sp.y, sp.width, sp.height);
- sCtx.drawImage(canvas, sp.x, sp.y, sp.width, sp.height, sp.x, sp.y, sp.width, sp.height);
- }
- }
- }
- }
-
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
enqueueHistoryTask(() => {
pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
});
} else {
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = ctx.getImageData(sx, sy, dw, dh);
+ const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = rCtx.getImageData(0, 0, dw, dh);
if (isMonochrome) {
binarizeImageDataBuffer(
afterData,
@@ -3210,27 +3304,28 @@ export function useCanvasDrawing({
activeLayer?.monoExpressBlack ?? true,
activeLayer?.monoExpressWhite ?? true
);
- ctx.putImageData(afterData, sx, sy);
}
-
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- sCtx.clearRect(sx, sy, dw, dh);
- sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
- }
- }
- }
-
- globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
enqueueHistoryTask(() => {
pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
});
}
+
+ // Release temporary dirtyRect canvas immediately
+ releaseTemporaryCanvas(regionCanvas);
+
+ // Synchronize any existing cached display/source canvases strictly within dirtyRect
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
+ }
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
+ }
+ }
}
}
}
@@ -3258,7 +3353,7 @@ export function useCanvasDrawing({
}
clearPredictedCanvas();
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
if (currentStrokeIdRef.current) {
onCollabStrokeFinishRef.current?.(
@@ -3295,7 +3390,7 @@ export function useCanvasDrawing({
if (isMaskModeRef.current) {
onUpdateMaskThumbnailRef.current?.(currentLayerId);
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
} else {
enqueueHistoryTask(() => {
onUpdateLayerThumbnail(currentLayerId);
@@ -3308,7 +3403,7 @@ export function useCanvasDrawing({
emitConstraintAxisChange,
enqueueHistoryTask,
flushPendingPoints,
- getActiveCanvas,
+ getCachedLayerCanvas,
getCanvasPoint,
layerSourceCanvasesRef,
markTouchedTiles,
@@ -3331,24 +3426,39 @@ export function useCanvasDrawing({
}
}, [dispatchPointerStat]);
- const resetHistory = useCallback(() => {
- historyRef.current = [];
- historyIndexRef.current = -1;
- lastStrokeEndRef.current = null;
- setHistoryList([]);
- setHistoryIndex(-1);
- setCanUndo(false);
- setCanRedo(false);
- globalUndoCache.clearCache().catch(() => {});
-
- // Re-seed initial history state after DOM canvas updates without heavy getImageData readback
- setTimeout(() => {
- const canvas = layerCanvasesRef.current.get(activeLayerId) || layerCanvasesRef.current.values().next().value;
- if (!canvas) return;
-
- const thumbnail = createCanvasThumbnail(canvas, !isBackgroundLayerId(activeLayerId));
- const now = Date.now();
+ const resetHistory = useCallback((targetDocumentId?: string) => {
+ flushPendingHistoryTasks();
+ const docId = targetDocumentId ?? activeSessionIdRef.current;
+ const sess = docId ? documentStore.getSession(docId) : null;
+ const targetCache = sess ? sess.undoCache : activeUndoCacheRef.current;
+ const targetGrid = sess ? sess.tileGrid : activeTileGridRef.current;
+
+ if (sess) {
+ sess.history = [];
+ sess.historyIndex = -1;
+ }
+ if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
+ historyRef.current = [];
+ historyIndexRef.current = -1;
+ lastStrokeEndRef.current = null;
+ setHistoryList([]);
+ setHistoryIndex(-1);
+ setCanUndo(false);
+ setCanRedo(false);
+ }
+
+ targetCache.clearCache().catch(() => {});
+
+ // Seed initial history state directly from SparseTileGrid LOD 3 (zero full canvas read)
+ const now = Date.now();
+ const dims = dimensionsRef.current;
+ const layerId = activeLayerIdRef.current || activeLayerId;
+ if (layerId && dims.width > 0 && dims.height > 0) {
+ const thumbnail = createCanvasThumbnail(
+ { grid: targetGrid, layerId, dimensions: dims },
+ !isBackgroundLayerId(layerId)
+ );
const initialItem: HistoryItem = {
id: `hist-init-${now}`,
type: 'initial',
@@ -3359,14 +3469,19 @@ export function useCanvasDrawing({
imageData: undefined,
beforeImageData: null,
afterImageData: null,
- layerId: activeLayerId,
+ layerId,
};
-
- historyRef.current = [initialItem];
- historyIndexRef.current = 0;
- syncHistoryState();
- }, 60);
- }, [activeLayerId, layerCanvasesRef, syncHistoryState]);
+ if (sess) {
+ sess.history = [initialItem];
+ sess.historyIndex = 0;
+ }
+ if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
+ historyRef.current = [initialItem];
+ historyIndexRef.current = 0;
+ syncHistoryState();
+ }
+ }
+ }, [activeLayerId, flushPendingHistoryTasks, syncHistoryState]);
return {
interactionRef,
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index 5250449..1ac5d2e 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -4,12 +4,14 @@ import { ResizeCanvasOptions } from '../types/settings';
import { createCanvasThumbnail, get2DContext } from '../utils/canvasUtils';
import { applyLayerEffects, applyExpressionColorToImageData } from '../utils/layerEffectsEngine';
import { HalftoneDotShape } from '../utils/screentoneEngine';
-import { globalTileGrid } from '../utils/tileEngine';
+import { SparseTileGrid, globalTileGrid, releaseTemporaryCanvas } from '../utils/tileEngine';
+import { documentStore } from '../utils/documentStore';
import { recoveryService } from '../services/recoveryService';
interface UseLayerManagerProps {
dimensions: CanvasDimensions;
activeSessionId?: string | null;
+ tileGrid?: SparseTileGrid;
}
export function isBackgroundLayerId(id: string): boolean {
@@ -343,20 +345,53 @@ export function computeBatchLock(
return layers.map((l) => (selectedSet.has(l.id) ? { ...l, locked: newLocked } : l));
}
-export function useLayerManager({ dimensions: _dimensions, activeSessionId }: UseLayerManagerProps) {
- // Store canvas DOM elements for each raster layer by layer ID
- const layerCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(new Map());
+export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileGrid }: UseLayerManagerProps) {
+ // Active document's SparseTileGrid (isolated per document tab)
+ const activeTileGridRef = useRef<SparseTileGrid>(
+ tileGrid ?? (activeSessionId ? documentStore.getOrCreateSession(activeSessionId).tileGrid : globalTileGrid)
+ );
+ if (tileGrid) {
+ activeTileGridRef.current = tileGrid;
+ } else if (activeSessionId) {
+ activeTileGridRef.current = documentStore.getOrCreateSession(activeSessionId).tileGrid;
+ }
+
+ // Lazy canvas map: ONLY holds canvases explicitly materialized by legacy tools / effects.
+ // Empty and unmodified layers NEVER allocate full-size HTMLCanvasElements here.
+ const layerCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(
+ activeSessionId ? documentStore.getOrCreateSession(activeSessionId).layerCanvases : new Map()
+ );
- // Store original offscreen raster source canvases for non-destructive screentone processing
- const layerSourceCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(new Map());
+ // Store original offscreen raster source canvases strictly for layers with non-destructive effects
+ const layerSourceCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(
+ activeSessionId ? documentStore.getOrCreateSession(activeSessionId).layerSourceCanvases : new Map()
+ );
+
+ const dimensionsRef = useRef<CanvasDimensions>(_dimensions);
+ dimensionsRef.current = _dimensions;
+
+ const activeSessionIdRef = useRef<string | null>(activeSessionId ?? null);
+ if (activeSessionId !== undefined && activeSessionId !== activeSessionIdRef.current) {
+ activeSessionIdRef.current = activeSessionId;
+ if (activeSessionId) {
+ const sess = documentStore.getOrCreateSession(activeSessionId);
+ activeTileGridRef.current = tileGrid ?? sess.tileGrid;
+ layerCanvasesRef.current = sess.layerCanvases;
+ layerSourceCanvasesRef.current = sess.layerSourceCanvases;
+ } else {
+ activeTileGridRef.current = tileGrid ?? globalTileGrid;
+ layerCanvasesRef.current = new Map();
+ layerSourceCanvasesRef.current = new Map();
+ }
+ }
// Default canvas tone frequency (20 to 85 LPI, default: 60)
const defaultToneFrequencyRef = useRef<number>(60);
- // Pending copy queue: targetId -> sourceId
+ // Pending copy queue: targetId -> sourceId (used only when legacy caller mounts a DOM canvas)
const pendingCanvasCopiesRef = useRef<Map<string, string>>(new Map());
- // Pending initial canvas or fill color queue: layerId -> HTMLCanvasElement | HTMLImageElement | string
+ // Pending initial canvas or fill color queue
const pendingInitialDataRef = useRef<Map<string, HTMLCanvasElement | HTMLImageElement | string>>(new Map());
// Default initial layers: starts empty until a document is created or opened
@@ -426,30 +461,52 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setSelectedLayerIds(res.nextSelectedIds);
}, [setSelectedLayerIds]);
- // Register or unregister canvas element for a layer
+ // Materialize a full-layer canvas on demand from SparseTileGrid (strictly for legacy tools/effects)
+ const materializeLayerCanvas = useCallback((id: string): HTMLCanvasElement | null => {
+ const existing = layerCanvasesRef.current.get(id);
+ if (existing) return existing;
+ if (typeof document === 'undefined') return null;
+ const dims = dimensionsRef.current;
+ if (dims.width <= 0 || dims.height <= 0) return null;
+
+ const canvas = document.createElement('canvas');
+ canvas.width = dims.width;
+ canvas.height = dims.height;
+ const grid = activeTileGridRef.current;
+ if (grid.hasLayerTiles(id)) {
+ grid.renderLayerToCanvas(id, canvas);
+ }
+ layerCanvasesRef.current.set(id, canvas);
+ return canvas;
+ }, []);
+
+ // Release a transiently materialized display canvas (SparseTileGrid remains authoritative)
+ const releaseLayerCanvas = useCallback((id: string) => {
+ if (layerSourceCanvasesRef.current.has(id)) return;
+ const existing = layerCanvasesRef.current.get(id);
+ if (existing) {
+ releaseTemporaryCanvas(existing);
+ layerCanvasesRef.current.delete(id);
+ }
+ }, []);
+
+ // Register or unregister canvas element for a layer (on-demand only; empty layers do not call this)
const registerLayerCanvas = useCallback((id: string, canvas: HTMLCanvasElement | null) => {
+ const grid = activeTileGridRef.current;
if (canvas) {
if (layerCanvasesRef.current.get(id) === canvas) {
- return; // Already registered with same canvas element, avoid re-running
+ return; // Already registered with same canvas element
}
layerCanvasesRef.current.set(id, canvas);
- // Check if this new canvas was duplicated from another layer
const sourceId = pendingCanvasCopiesRef.current.get(id);
if (sourceId) {
- const sourceCanvas = layerCanvasesRef.current.get(sourceId);
- if (sourceCanvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(sourceCanvas, 0, 0);
- }
- }
+ grid.cloneLayer(sourceId, id);
+ grid.renderLayerToCanvas(id, canvas);
pendingCanvasCopiesRef.current.delete(id);
}
- // Check if this new canvas has pending initial content (from loaded file or new canvas background)
const initialData = pendingInitialDataRef.current.get(id);
if (initialData) {
const ctx = get2DContext(canvas);
@@ -470,83 +527,66 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
}
}
pendingInitialDataRef.current.delete(id);
- } else if (isBackgroundLayerId(id)) {
- // If it's the background layer and uninitialized, fill with solid white
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- (canvas as any).__isSolidWhite = true;
- }
} else if (!sourceId) {
- if (globalTileGrid.isLayerIngested(id)) {
- globalTileGrid.renderLayerToCanvas(id, canvas);
+ if (grid.hasLayerTiles(id)) {
+ grid.renderLayerToCanvas(id, canvas);
+ } else if (isBackgroundLayerId(id)) {
+ grid.fillLayerSolidWhite(id, canvas.width, canvas.height, 'color-32bit');
+ grid.renderLayerToCanvas(id, canvas);
} else {
(canvas as any).__isBlank = true;
}
}
- // Ingest into globalTileGrid if unindexed or if freshly copied/initialized
- if (!globalTileGrid.isLayerIngested(id) || sourceId || initialData) {
+ if (!grid.isLayerIngested(id) || sourceId || initialData) {
const layer = layersRef.current.find((l) => l.id === id);
const isMono = layer?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.ingestCanvas(id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
}
- // Defer initial thumbnail generation to avoid triggering re-render during ref attachment
requestAnimationFrame(() => {
- const c = layerCanvasesRef.current.get(id);
- if (c) {
- const targetW = 60;
- const targetH = Math.max(38, Math.round((c.height / Math.max(1, c.width)) * targetW));
- const thumb = (c.width * c.height > 1024 * 1024 && globalTileGrid.isLayerIngested(id))
- ? globalTileGrid.generateThumbnail(id, targetW, targetH, { width: c.width, height: c.height })
- : createCanvasThumbnail(c, !isBackgroundLayerId(id));
+ const dims = dimensionsRef.current;
+ const thumb = createCanvasThumbnail(
+ { grid: activeTileGridRef.current, layerId: id, dimensions: dims },
+ !isBackgroundLayerId(id)
+ );
+ if (thumb) {
setLayers((prev) =>
prev.map((l) => (l.id === id && !l.thumbnailUrl ? { ...l, thumbnailUrl: thumb } : l))
);
}
});
} else {
+ const existing = layerCanvasesRef.current.get(id);
+ if (existing) releaseTemporaryCanvas(existing);
layerCanvasesRef.current.delete(id);
- globalTileGrid.clearLayer(id);
+ grid.clearLayer(id);
}
}, []);
- // Automatically instantiate and manage offscreen backing canvases for all layers
- useEffect(() => {
- layers.forEach((layer) => {
- if ((layer.type === 'raster' || layer.type === 'vector' || layer.type === 'frame') && !layerCanvasesRef.current.has(layer.id)) {
- const offscreen = document.createElement('canvas');
- offscreen.width = _dimensions.width;
- offscreen.height = _dimensions.height;
- registerLayerCanvas(layer.id, offscreen);
- }
- });
+ const thumbDebounceTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
- // When a layer is removed, delete its canvas from layerCanvasesRef.current and clean up tile grid
- const currentLayerIds = new Set(layers.map((l) => l.id));
- for (const id of Array.from(layerCanvasesRef.current.keys())) {
- if (!currentLayerIds.has(id)) {
- layerCanvasesRef.current.delete(id);
- globalTileGrid.clearLayer(id);
+ // Cleanup debounce timers on unmount
+ useEffect(() => {
+ return () => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
}
- }
- }, [layers, _dimensions, registerLayerCanvas]);
-
- const thumbDebounceTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
+ thumbDebounceTimersRef.current.clear();
+ };
+ }, []);
- // Update a single layer's thumbnail after drawing or editing (debounced to avoid React re-renders during rapid sketching)
+ // Update a single layer's thumbnail directly from SparseTileGrid LOD 3 (zero full-canvas read)
const updateLayerThumbnail = useCallback((id: string, immediate: boolean = false) => {
+ const capturedGrid = activeTileGridRef.current;
+ const capturedDocId = activeSessionIdRef.current;
const run = () => {
- const canvas = layerCanvasesRef.current.get(id);
- const dims = canvas ? { width: canvas.width, height: canvas.height } : _dimensions;
- const targetW = 60;
- const targetH = Math.max(38, Math.round((dims.height / Math.max(1, dims.width)) * targetW));
- const isLarge = dims.width * dims.height > 1024 * 1024;
- const thumb = (isLarge && globalTileGrid.isLayerIngested(id))
- ? globalTileGrid.generateThumbnail(id, targetW, targetH, dims)
- : (canvas ? createCanvasThumbnail(canvas, !isBackgroundLayerId(id)) : globalTileGrid.generateThumbnail(id, targetW, targetH, dims));
+ if (capturedDocId !== activeSessionIdRef.current) return;
+ const dims = dimensionsRef.current;
+ const thumb = createCanvasThumbnail(
+ { grid: capturedGrid, layerId: id, dimensions: dims },
+ !isBackgroundLayerId(id)
+ );
if (!thumb) return;
@@ -661,6 +701,13 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
return nextLayers;
});
+ if (type === 'raster' || type === 'vector' || type === 'frame') {
+ const grid = activeTileGridRef.current;
+ const isMono = createdLayer.expressionColor === 'monochrome';
+ grid.setLayerFormat(id, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.markLayerIngested(id);
+ }
+
if (selectNewLayer) {
setActiveLayerId(id);
}
@@ -672,23 +719,30 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
// Add a layer that originated from a remote peer
const addRemoteLayer = useCallback(
(layerItem: LayerItem, initialDataUrl?: string) => {
+ const grid = activeTileGridRef.current;
+ const isMono = layerItem.expressionColor === 'monochrome';
+ grid.setLayerFormat(layerItem.id, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.markLayerIngested(layerItem.id);
+
if (initialDataUrl) {
const img = new Image();
img.onload = () => {
- const canvas = layerCanvasesRef.current.get(layerItem.id);
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(img, 0, 0);
- const isMono = layerItem.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(layerItem.id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
- updateLayerThumbnail(layerItem.id, true);
+ const dims = dimensionsRef.current;
+ const temp = document.createElement('canvas');
+ temp.width = dims.width || img.naturalWidth || img.width;
+ temp.height = dims.height || img.naturalHeight || img.height;
+ const ctx = get2DContext(temp);
+ if (ctx) {
+ ctx.drawImage(img, 0, 0);
+ grid.ingestCanvas(layerItem.id, temp, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
+ const existing = layerCanvasesRef.current.get(layerItem.id);
+ if (existing) {
+ grid.renderLayerToCanvas(layerItem.id, existing);
}
- } else {
- pendingInitialDataRef.current.set(layerItem.id, img);
+ updateLayerThumbnail(layerItem.id, true);
}
+ releaseTemporaryCanvas(temp);
};
img.src = initialDataUrl;
}
@@ -711,9 +765,18 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
// Delete a layer triggered remotely
const deleteRemoteLayer = useCallback((layerId: string) => {
setLayers((prev) => prev.filter((l) => l.id !== layerId));
+ const timer = thumbDebounceTimersRef.current.get(layerId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(layerId);
+ }
+ const display = layerCanvasesRef.current.get(layerId);
+ if (display) releaseTemporaryCanvas(display);
layerCanvasesRef.current.delete(layerId);
+ const source = layerSourceCanvasesRef.current.get(layerId);
+ if (source) releaseTemporaryCanvas(source);
layerSourceCanvasesRef.current.delete(layerId);
- globalTileGrid.clearLayer(layerId);
+ activeTileGridRef.current.clearLayer(layerId);
}, []);
// Sync entire document state from remote host
@@ -723,6 +786,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
layerDataUrls: Record<string, string>,
assignedLayerId?: string
) => {
+ const grid = activeTileGridRef.current;
setLayers(syncedLayers);
if (assignedLayerId) {
@@ -734,30 +798,31 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
}
}
- // Load snapshot images onto canvases
+ // Load snapshot images directly into SparseTileGrid without holding duplicate full canvases
syncedLayers.forEach((layer) => {
+ const isMono = layer.expressionColor === 'monochrome';
+ grid.setLayerFormat(layer.id, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.markLayerIngested(layer.id);
const dataUrl = layerDataUrls[layer.id];
if (dataUrl) {
const img = new Image();
img.onload = () => {
- const canvas = layerCanvasesRef.current.get(layer.id);
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(img, 0, 0);
- const isMono = layer.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(layer.id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
- updateLayerThumbnail(layer.id, true);
+ const dims = dimensionsRef.current;
+ const temp = document.createElement('canvas');
+ temp.width = dims.width || img.naturalWidth || img.width;
+ temp.height = dims.height || img.naturalHeight || img.height;
+ const ctx = get2DContext(temp);
+ if (ctx) {
+ ctx.drawImage(img, 0, 0);
+ grid.ingestCanvas(layer.id, temp, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
+ const existing = layerCanvasesRef.current.get(layer.id);
+ if (existing) {
+ grid.renderLayerToCanvas(layer.id, existing);
}
- } else {
- const offscreen = document.createElement('canvas');
- offscreen.width = img.naturalWidth || img.width;
- offscreen.height = img.naturalHeight || img.height;
- get2DContext(offscreen)?.drawImage(img, 0, 0);
- pendingInitialDataRef.current.set(layer.id, offscreen);
+ updateLayerThumbnail(layer.id, true);
}
+ releaseTemporaryCanvas(temp);
};
img.src = dataUrl;
}
@@ -771,12 +836,13 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setLayers((prev) => {
const sourceIdx = prev.findIndex((l) => l.id === id);
if (sourceIdx < 0) return prev;
+ const grid = activeTileGridRef.current;
const cloneSingleLayer = (source: LayerItem, newParentId: string | null, nameSuffix: string = ' Copy'): LayerItem => {
const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
if (source.type === 'raster' || source.type === 'vector' || source.type === 'frame') {
- pendingCanvasCopiesRef.current.set(newId, source.id);
+ grid.cloneLayer(source.id, newId);
const srcSource = layerSourceCanvasesRef.current.get(source.id);
if (srcSource) {
@@ -855,11 +921,28 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setLayers((prev) => {
const res = computeBatchDeleteLayers(prev, [id], activeLayerIdRef.current);
if (res.deletedIds.length === 0) return prev;
+ const grid = activeTileGridRef.current;
for (const delId of res.deletedIds) {
+ const timer = thumbDebounceTimersRef.current.get(delId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(delId);
+ }
+ const display = layerCanvasesRef.current.get(delId);
+ if (display) releaseTemporaryCanvas(display);
layerCanvasesRef.current.delete(delId);
+
+ const source = layerSourceCanvasesRef.current.get(delId);
+ if (source) releaseTemporaryCanvas(source);
layerSourceCanvasesRef.current.delete(delId);
- globalTileGrid.clearLayer(delId);
+
+ const deletedLayer = prev.find((l) => l.id === delId);
+ if (deletedLayer?.maskCanvas) {
+ releaseTemporaryCanvas(deletedLayer.maskCanvas);
+ }
+
+ grid.clearLayer(delId);
}
if (res.deletedIds.includes(activeLayerIdRef.current)) {
@@ -876,11 +959,28 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setLayers((prev) => {
const res = computeBatchDeleteLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);
if (res.deletedIds.length === 0) return prev;
+ const grid = activeTileGridRef.current;
+
+ for (const delId of res.deletedIds) {
+ const timer = thumbDebounceTimersRef.current.get(delId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(delId);
+ }
+ const display = layerCanvasesRef.current.get(delId);
+ if (display) releaseTemporaryCanvas(display);
+ layerCanvasesRef.current.delete(delId);
- for (const id of res.deletedIds) {
- layerCanvasesRef.current.delete(id);
- layerSourceCanvasesRef.current.delete(id);
- globalTileGrid.clearLayer(id);
+ const source = layerSourceCanvasesRef.current.get(delId);
+ if (source) releaseTemporaryCanvas(source);
+ layerSourceCanvasesRef.current.delete(delId);
+
+ const deletedLayer = prev.find((l) => l.id === delId);
+ if (deletedLayer?.maskCanvas) {
+ releaseTemporaryCanvas(deletedLayer.maskCanvas);
+ }
+
+ grid.clearLayer(delId);
}
setActiveLayerId(res.nextActiveId);
@@ -975,18 +1075,20 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
};
})
);
- globalTileGrid.notifyChange(true);
+ activeTileGridRef.current.notifyChange(true);
}, [_dimensions]);
// Remove or apply layer mask
const removeLayerMask = useCallback(
(layerId: string, apply: boolean = false) => {
+ const grid = activeTileGridRef.current;
setLayers((prev) =>
prev.map((l) => {
if (l.id !== layerId || !l.maskCanvas) return l;
if (apply) {
- const c = layerCanvasesRef.current.get(layerId);
+ const hadCanvas = layerCanvasesRef.current.has(layerId);
+ const c = hadCanvas ? layerCanvasesRef.current.get(layerId)! : materializeLayerCanvas(layerId);
if (c) {
const ctx = get2DContext(c);
const mCtx = get2DContext(l.maskCanvas);
@@ -1021,12 +1123,17 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
}
const isMono = l.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(layerId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.ingestCanvas(layerId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
updateLayerThumbnail(layerId, true);
}
+ if (!hadCanvas) {
+ releaseLayerCanvas(layerId);
+ }
}
}
+ releaseTemporaryCanvas(l.maskCanvas);
+
return {
...l,
maskCanvas: undefined,
@@ -1037,9 +1144,9 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
};
})
);
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
},
- [updateLayerThumbnail]
+ [materializeLayerCanvas, releaseLayerCanvas, updateLayerThumbnail]
);
// Toggle layer mask enabled state
@@ -1047,7 +1154,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setLayers((prev) =>
prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l))
);
- globalTileGrid.notifyChange(true);
+ activeTileGridRef.current.notifyChange(true);
}, []);
// Toggle mask linked state
@@ -1070,7 +1177,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
: l
)
);
- globalTileGrid.notifyChange(true);
+ activeTileGridRef.current.notifyChange(true);
};
if (immediate) {
@@ -1176,10 +1283,10 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
});
setActiveLayerId(id);
- globalTileGrid.notifyChange(true);
+ activeTileGridRef.current.notifyChange(true);
return createdLayer!;
},
- [activeLayerId]
+ [activeLayerId, setActiveLayerId]
);
// Update adjustment layer data
@@ -1187,7 +1294,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setLayers((prev) =>
prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l))
);
- globalTileGrid.notifyChange(true);
+ activeTileGridRef.current.notifyChange(true);
}, []);
// Ensure offscreen source canvas exists for non-destructive operations
@@ -1195,16 +1302,21 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
(id: string, copyFromDisplay = true, forceCopy = false) => {
let sourceCanvas = layerSourceCanvasesRef.current.get(id);
const displayCanvas = layerCanvasesRef.current.get(id);
- const targetW = displayCanvas?.width || _dimensions.width;
- const targetH = displayCanvas?.height || _dimensions.height;
+ const targetW = displayCanvas?.width || dimensionsRef.current.width;
+ const targetH = displayCanvas?.height || dimensionsRef.current.height;
+ const grid = activeTileGridRef.current;
if (!sourceCanvas) {
sourceCanvas = document.createElement('canvas');
sourceCanvas.width = targetW;
sourceCanvas.height = targetH;
- if (copyFromDisplay && displayCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(displayCanvas, 0, 0);
+ if (copyFromDisplay) {
+ if (displayCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ sCtx?.drawImage(displayCanvas, 0, 0);
+ } else if (grid.hasLayerTiles(id)) {
+ grid.renderLayerToCanvas(id, sourceCanvas);
+ }
}
layerSourceCanvasesRef.current.set(id, sourceCanvas);
} else {
@@ -1213,17 +1325,21 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
sourceCanvas.width = targetW;
sourceCanvas.height = targetH;
}
- if ((forceCopy || (copyFromDisplay && sizeMismatch)) && displayCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- sCtx.clearRect(0, 0, targetW, targetH);
- sCtx.drawImage(displayCanvas, 0, 0);
+ if (forceCopy || (copyFromDisplay && sizeMismatch)) {
+ if (displayCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ sCtx.clearRect(0, 0, targetW, targetH);
+ sCtx.drawImage(displayCanvas, 0, 0);
+ }
+ } else if (grid.hasLayerTiles(id)) {
+ grid.renderLayerToCanvas(id, sourceCanvas);
}
}
}
return sourceCanvas;
},
- [_dimensions]
+ []
);
const pendingEffectRendersRef = useRef<Map<string, { layer: LayerItem; dirtyRect?: DirtyRect }>>(new Map());
@@ -1236,18 +1352,22 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
effectRafIdRef.current = null;
const queue = new Map(pendingEffectRendersRef.current);
pendingEffectRendersRef.current.clear();
+ const grid = activeTileGridRef.current;
queue.forEach(({ layer: l, dirtyRect: rect }, id) => {
const sourceCanvas = ensureSourceCanvas(id, true, false);
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
if (sourceCanvas && displayCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, l, _dimensions.dpi ?? 600, rect);
+ applyLayerEffects(sourceCanvas, displayCanvas, l, dimensionsRef.current.dpi ?? 600, rect);
+ const isMono = l.expressionColor === 'monochrome';
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
updateLayerThumbnail(id, false);
}
});
});
}
- }, [_dimensions.dpi, ensureSourceCanvas, updateLayerThumbnail]);
+ }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
useEffect(() => {
return () => {
@@ -1282,13 +1402,14 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
toneDensityType: densityType,
};
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
+ const grid = activeTileGridRef.current;
if (displayCanvas) {
if (newEnabled) {
// Initialize sourceCanvas only if not already present; never force-overwrite existing continuous-tone source
const sourceCanvas = ensureSourceCanvas(id, true, false);
if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, _dimensions.dpi ?? 600);
+ applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
}
} else {
// Turning off tone: restore continuous raster from sourceCanvas
@@ -1297,9 +1418,12 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
sourceCanvas = ensureSourceCanvas(id, true, false);
}
if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, _dimensions.dpi ?? 600);
+ applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
}
}
+ const isMono = updatedLayer.expressionColor === 'monochrome';
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
updateLayerThumbnail(id, true);
}
@@ -1310,7 +1434,9 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');
if (newEnabled && !hasBg) {
const bgId = `layer-bg-${Date.now()}`;
- pendingInitialDataRef.current.set(bgId, '#ffffff');
+ const dims = dimensionsRef.current;
+ grid.fillLayerSolidWhite(bgId, dims.width, dims.height, 'color-32bit');
+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: dims }, false);
const bgLayer: LayerItem = {
id: bgId,
name: 'Background',
@@ -1320,14 +1446,14 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
blendMode: 'normal',
locked: true,
parentId: null,
- thumbnailUrl: '',
+ thumbnailUrl: bgThumb,
};
nextLayers = [...nextLayers, bgLayer];
}
return nextLayers;
});
- }, [_dimensions.dpi, ensureSourceCanvas, updateLayerThumbnail]);
+ }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
// Update screentone frequency (Lines / LPI, 20 to 85)
const setToneFrequency = useCallback((id: string, frequency: number) => {
@@ -1419,18 +1545,22 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
layerSubColor,
};
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
if (displayCanvas) {
const sourceCanvas = ensureSourceCanvas(id, true, false);
if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, _dimensions.dpi ?? 600);
+ applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
}
+ const grid = activeTileGridRef.current;
+ const isMono = updatedLayer.expressionColor === 'monochrome';
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
updateLayerThumbnail(id, true);
}
return prev.map((l) => (l.id === id ? updatedLayer : l));
});
- }, [_dimensions.dpi, ensureSourceCanvas, updateLayerThumbnail]);
+ }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
// Update Layer Color (Tint primary color)
const setLayerColor = useCallback((id: string, color: string) => {
@@ -1480,18 +1610,22 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
monoExpressWhite: target.monoExpressWhite ?? true,
};
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
if (displayCanvas) {
const sourceCanvas = ensureSourceCanvas(id, true, false);
if (sourceCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, _dimensions.dpi ?? 600);
+ applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
}
+ const grid = activeTileGridRef.current;
+ const isMono = updatedLayer.expressionColor === 'monochrome';
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
updateLayerThumbnail(id, true);
}
return prev.map((l) => (l.id === id ? updatedLayer : l));
});
- }, [_dimensions.dpi, ensureSourceCanvas, updateLayerThumbnail]);
+ }, [ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]);
// Update Monochrome Color threshold (1 - 255)
const setLayerMonoThreshold = useCallback((id: string, threshold: number) => {
@@ -1535,7 +1669,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const target = layers.find((l) => l.id === id);
if (!target || target.type === 'folder') return null;
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
let sourceCanvas = layerSourceCanvasesRef.current.get(id);
if (!displayCanvas) return null;
@@ -1554,14 +1688,15 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
sCtx.drawImage(displayCanvas, 0, 0);
+ const grid = activeTileGridRef.current;
const isMono = target.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
updateLayerThumbnail(id, true);
return { beforeImageData, afterImageData };
},
- [layers, ensureSourceCanvas, updateLayerThumbnail]
+ [layers, ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]
);
// Apply layer color tint permanently into layer pixel buffer
@@ -1570,7 +1705,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const target = layers.find((l) => l.id === id);
if (!target || target.type === 'folder' || !target.layerColorEnabled) return null;
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
let sourceCanvas = layerSourceCanvasesRef.current.get(id);
if (!displayCanvas) return null;
@@ -1593,14 +1728,15 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
prev.map((l) => (l.id === id ? { ...l, layerColorEnabled: false } : l))
);
+ const grid = activeTileGridRef.current;
const isMono = target.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
updateLayerThumbnail(id, true);
return { beforeImageData, afterImageData };
},
- [layers, ensureSourceCanvas, updateLayerThumbnail]
+ [layers, ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]
);
// Direct permanent conversion of any layer (including imported image) to Color, Gray, or Monochrome
@@ -1613,7 +1749,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const target = layers.find((l) => l.id === id);
if (!target || target.type === 'folder') return null;
- const displayCanvas = layerCanvasesRef.current.get(id);
+ const displayCanvas = materializeLayerCanvas(id);
if (!displayCanvas) return null;
const sourceCanvas = ensureSourceCanvas(id, true, false);
@@ -1638,24 +1774,25 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const sData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
applyExpressionColorToImageData(sData, targetMode, options);
sCtx.putImageData(sData, 0, 0);
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, _dimensions.dpi ?? 600);
+ applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
} else {
- applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, _dimensions.dpi ?? 600);
+ applyLayerEffects(sourceCanvas, displayCanvas, updatedLayer, dimensionsRef.current.dpi ?? 600);
sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
sCtx.drawImage(displayCanvas, 0, 0);
}
const afterImageData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height);
+ const grid = activeTileGridRef.current;
const isMono = targetMode === 'monochrome';
- globalTileGrid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- globalTileGrid.notifyChange(true);
+ grid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
setLayers((prev) => prev.map((l) => (l.id === id ? updatedLayer : l)));
updateLayerThumbnail(id, true);
return { beforeImageData, afterImageData };
},
- [layers, ensureSourceCanvas, _dimensions.dpi, updateLayerThumbnail]
+ [layers, ensureSourceCanvas, materializeLayerCanvas, updateLayerThumbnail]
);
// Rename a layer
@@ -1777,21 +1914,32 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
return isLayerEffectivelyVisible(parent);
}, [layers]);
- // Clear active layer content
+ // Clear active layer content directly in SparseTileGrid (zero forced full canvas allocation)
const clearActiveLayer = useCallback(() => {
- const canvas = layerCanvasesRef.current.get(activeLayerId);
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
const isBg = isBackgroundLayerId(activeLayerId);
+
if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- (canvas as any).__isSolidWhite = true;
+ grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');
} else {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- (canvas as any).__isBlank = true;
+ grid.clearLayer(activeLayerId);
+ grid.markLayerIngested(activeLayerId);
+ }
+
+ const canvas = layerCanvasesRef.current.get(activeLayerId);
+ if (canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ if (isBg) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ (canvas as any).__isSolidWhite = true;
+ } else {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ (canvas as any).__isBlank = true;
+ }
+ }
}
const sCanvas = layerSourceCanvasesRef.current.get(activeLayerId);
@@ -1807,37 +1955,96 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
}
}
- if (isBg) {
- globalTileGrid.ingestCanvas(activeLayerId, canvas, 'color-32bit');
- } else {
- globalTileGrid.clearLayer(activeLayerId);
- }
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
updateLayerThumbnail(activeLayerId);
}, [activeLayerId, updateLayerThumbnail]);
- // Reset layers to a fresh canvas with specified background color
+ // Switch active document tab in O(1): binds session's SparseTileGrid without clearing or re-slicing
+ const switchDocumentSession = useCallback(
+ (documentId: string, nextLayers: LayerItem[], nextActiveLayerId: string, nextDims?: CanvasDimensions) => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+
+ const session = documentStore.setActiveDocument(documentId) ?? documentStore.getOrCreateSession(documentId);
+ activeSessionIdRef.current = documentId;
+ activeTileGridRef.current = session.tileGrid;
+ layerCanvasesRef.current = session.layerCanvases;
+ layerSourceCanvasesRef.current = session.layerSourceCanvases;
+ if (nextDims) {
+ dimensionsRef.current = nextDims;
+ }
+
+ pendingCanvasCopiesRef.current.clear();
+ pendingInitialDataRef.current.clear();
+
+ setLayers(nextLayers);
+ layersRef.current = nextLayers;
+ const resolvedActiveId =
+ nextActiveLayerId && nextLayers.some((l) => l.id === nextActiveLayerId)
+ ? nextActiveLayerId
+ : (nextLayers.find((l) => l.type === 'raster')?.id || nextLayers[0]?.id || '');
+ setActiveLayerId(resolvedActiveId);
+ session.tileGrid.notifyChange(true);
+ },
+ [setActiveLayerId]
+ );
+
+ // Reset layers to a fresh canvas with specified background color (allocated directly in SparseTileGrid)
const resetToNewCanvas = useCallback(
- (_dims: CanvasDimensions, backgroundColor: string = '#ffffff', _mode: CanvasColorMode = 'color', defaultToneFrequency: number = 60) => {
+ (
+ _dims: CanvasDimensions,
+ backgroundColor: string = '#ffffff',
+ _mode: CanvasColorMode = 'color',
+ defaultToneFrequency: number = 60,
+ targetDocumentId?: string
+ ) => {
defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(defaultToneFrequency || 60)));
- for (const oldId of Array.from(layerCanvasesRef.current.keys())) {
- globalTileGrid.clearLayer(oldId);
+ dimensionsRef.current = _dims;
+
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
}
- for (const l of layersRef.current) {
- globalTileGrid.clearLayer(l.id);
+ thumbDebounceTimersRef.current.clear();
+
+ let grid = activeTileGridRef.current;
+ if (targetDocumentId) {
+ const session = documentStore.setActiveDocument(targetDocumentId) ?? documentStore.getOrCreateSession(targetDocumentId);
+ activeSessionIdRef.current = targetDocumentId;
+ activeTileGridRef.current = session.tileGrid;
+ layerCanvasesRef.current = session.layerCanvases;
+ layerSourceCanvasesRef.current = session.layerSourceCanvases;
+ grid = session.tileGrid;
}
+
+ grid.clearAll();
pendingCanvasCopiesRef.current.clear();
pendingInitialDataRef.current.clear();
+ for (const c of layerCanvasesRef.current.values()) releaseTemporaryCanvas(c);
layerCanvasesRef.current.clear();
+ for (const c of layerSourceCanvasesRef.current.values()) releaseTemporaryCanvas(c);
layerSourceCanvasesRef.current.clear();
- const bgId = `layer-bg-${Date.now()}`;
- const topId = `layer-1-${Date.now()}`;
+ const now = Date.now();
+ const bgId = `layer-bg-${now}`;
+ const topId = `layer-1-${now}`;
+ // Initialize background directly in SparseTileGrid without creating full-size HTMLCanvasElement
if (backgroundColor !== 'transparent') {
- pendingInitialDataRef.current.set(bgId, backgroundColor);
+ grid.fillLayerSolidColor(bgId, _dims.width, _dims.height, backgroundColor, 'color-32bit');
+ } else {
+ grid.setLayerFormat(bgId, 'color-32bit');
+ grid.markLayerIngested(bgId);
}
+ // Empty top layer: 0 tiles, 0 HTMLCanvasElement allocated
+ const topFormat = _mode === 'monochrome' ? 'monochrome-1bit' : 'color-32bit';
+ grid.setLayerFormat(topId, topFormat);
+ grid.markLayerIngested(topId);
+
+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dims }, false);
+
const initialLayers: LayerItem[] = [
{
id: topId,
@@ -1864,12 +2071,14 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
blendMode: 'normal',
locked: true,
parentId: null,
- thumbnailUrl: '',
+ thumbnailUrl: bgThumb,
},
];
setLayers(initialLayers);
+ layersRef.current = initialLayers;
setActiveLayerId(topId);
+ grid.notifyChange(true);
return { layers: initialLayers, activeLayerId: topId };
},
[setActiveLayerId]
@@ -1877,61 +2086,88 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
// Clear all layers and canvas references when no document is active
const clearDocument = useCallback(() => {
- for (const oldId of Array.from(layerCanvasesRef.current.keys())) {
- globalTileGrid.clearLayer(oldId);
- }
- for (const l of layersRef.current) {
- globalTileGrid.clearLayer(l.id);
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
}
+ thumbDebounceTimersRef.current.clear();
pendingCanvasCopiesRef.current.clear();
pendingInitialDataRef.current.clear();
- layerCanvasesRef.current.clear();
- layerSourceCanvasesRef.current.clear();
setLayers([]);
+ layersRef.current = [];
setActiveLayerId('');
- globalTileGrid.notifyChange(true);
}, [setActiveLayerId]);
- // Load an entire document (from PSD, CSP, or Image)
- const loadDocument = useCallback((doc: LoadedDocument) => {
- for (const oldId of Array.from(layerCanvasesRef.current.keys())) {
- globalTileGrid.clearLayer(oldId);
- }
- for (const l of layersRef.current) {
- globalTileGrid.clearLayer(l.id);
- }
- pendingCanvasCopiesRef.current.clear();
- pendingInitialDataRef.current.clear();
- layerCanvasesRef.current.clear();
- layerSourceCanvasesRef.current.clear();
-
- if (doc.layerCanvases) {
- doc.layerCanvases.forEach((c, id) => {
- layerCanvasesRef.current.set(id, c);
- pendingInitialDataRef.current.set(id, c);
- const layerMeta = doc.layers.find((l) => l.id === id);
- const isMono = layerMeta?.expressionColor === 'monochrome';
- globalTileGrid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- if (
- layerMeta &&
- (layerMeta.toneEnabled ||
- layerMeta.layerColorEnabled ||
- (layerMeta.expressionColor && layerMeta.expressionColor !== 'color'))
- ) {
- const sClone = document.createElement('canvas');
- sClone.width = c.width;
- sClone.height = c.height;
- get2DContext(sClone)?.drawImage(c, 0, 0);
- layerSourceCanvasesRef.current.set(id, sClone);
+ // Import an external document (from PSD, CSP, Image, or Crash Recovery) into its own isolated session.
+ // Temporary import canvases are immediately released after ingestion into SparseTileGrid.
+ const loadDocument = useCallback(
+ (doc: LoadedDocument, targetDocumentId?: string, skipIngest: boolean = false) => {
+ for (const timer of thumbDebounceTimersRef.current.values()) {
+ clearTimeout(timer);
+ }
+ thumbDebounceTimersRef.current.clear();
+
+ dimensionsRef.current = doc.dimensions;
+ let grid = activeTileGridRef.current;
+ if (targetDocumentId) {
+ const session = documentStore.setActiveDocument(targetDocumentId) ?? documentStore.getOrCreateSession(targetDocumentId);
+ activeSessionIdRef.current = targetDocumentId;
+ activeTileGridRef.current = session.tileGrid;
+ layerCanvasesRef.current = session.layerCanvases;
+ layerSourceCanvasesRef.current = session.layerSourceCanvases;
+ grid = session.tileGrid;
+ }
+
+ if (!skipIngest) {
+ grid.clearAll();
+ }
+ pendingCanvasCopiesRef.current.clear();
+ pendingInitialDataRef.current.clear();
+ for (const c of layerCanvasesRef.current.values()) releaseTemporaryCanvas(c);
+ layerCanvasesRef.current.clear();
+ for (const c of layerSourceCanvasesRef.current.values()) releaseTemporaryCanvas(c);
+ layerSourceCanvasesRef.current.clear();
+
+ for (const l of doc.layers) {
+ if (l.type === 'raster' || l.type === 'vector' || l.type === 'frame') {
+ const isMono = l.expressionColor === 'monochrome';
+ grid.setLayerFormat(l.id, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.markLayerIngested(l.id);
}
- });
- }
+ }
- setLayers(doc.layers);
- const topRaster = doc.layers.find((l) => l.type === 'raster');
- setActiveLayerId(topRaster ? topRaster.id : doc.layers[0]?.id || '');
- globalTileGrid.notifyChange(true);
- }, [setActiveLayerId]);
+ if (!skipIngest && doc.layerCanvases) {
+ doc.layerCanvases.forEach((c, id) => {
+ const layerMeta = doc.layers.find((l) => l.id === id);
+ const isMono = layerMeta?.expressionColor === 'monochrome';
+ grid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ const needsEffectBacking = Boolean(
+ layerMeta &&
+ (layerMeta.toneEnabled ||
+ layerMeta.layerColorEnabled ||
+ (layerMeta.expressionColor && layerMeta.expressionColor !== 'color'))
+ );
+ if (needsEffectBacking) {
+ const sClone = document.createElement('canvas');
+ sClone.width = c.width;
+ sClone.height = c.height;
+ get2DContext(sClone)?.drawImage(c, 0, 0);
+ layerSourceCanvasesRef.current.set(id, sClone);
+ layerCanvasesRef.current.set(id, c);
+ } else {
+ // Release temporary import canvas immediately — SparseTileGrid is authoritative
+ releaseTemporaryCanvas(c);
+ }
+ });
+ }
+
+ setLayers(doc.layers);
+ layersRef.current = doc.layers;
+ const topRaster = doc.layers.find((l) => l.type === 'raster');
+ setActiveLayerId(topRaster ? topRaster.id : doc.layers[0]?.id || '');
+ grid.notifyChange(true);
+ },
+ [setActiveLayerId]
+ );
// Internal Layer Clipboard
const layerClipboardRef = useRef<{
@@ -1942,7 +2178,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
canvas: HTMLCanvasElement;
} | null>(null);
- // Paste a canvas as a new raster layer
+ // Paste a canvas directly into SparseTileGrid as a new raster layer (no duplicate full canvas retained)
const pasteLayerFromCanvas = useCallback(
(
sourceCanvas: HTMLCanvasElement,
@@ -1953,15 +2189,13 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
layerOverrides?: Partial<LayerItem>
) => {
const newId = customId || `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const grid = activeTileGridRef.current;
+ const isMono = layerOverrides?.expressionColor === 'monochrome';
+ grid.ingestCanvas(newId, sourceCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ grid.notifyChange(true);
- // Clone offscreen canvas so modifications won't mutate source
- const clone = document.createElement('canvas');
- clone.width = sourceCanvas.width;
- clone.height = sourceCanvas.height;
- get2DContext(clone)?.drawImage(sourceCanvas, 0, 0);
-
- pendingInitialDataRef.current.set(newId, clone);
- const thumb = createCanvasThumbnail(clone, true);
+ const dims = dimensionsRef.current;
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);
setLayers((prev) => {
const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
@@ -1991,7 +2225,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setActiveLayerId(newId);
return newId;
},
- [activeLayerId]
+ [activeLayerId, setActiveLayerId]
);
// Fill selection with non-destructive Clip Studio Paint screentone layer
@@ -2086,15 +2320,17 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
toneDensityType: densityType,
};
- globalTileGrid.ingestCanvas(newId, sourceCanvas, 'color-32bit');
+ const grid = activeTileGridRef.current;
applyLayerEffects(sourceCanvas, displayCanvas, newLayer, _dimensions.dpi ?? 600, selection ? selection.bounds : undefined);
+ grid.ingestCanvas(newId, displayCanvas, 'color-32bit');
+ grid.notifyChange(true);
- const thumb = createCanvasThumbnail(displayCanvas, true);
+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: _dimensions }, true);
newLayer.thumbnailUrl = thumb;
- // Register both offscreen canvases synchronously
+ // Register both offscreen canvases synchronously for non-destructive tone updates
layerSourceCanvasesRef.current.set(newId, sourceCanvas);
- pendingInitialDataRef.current.set(newId, displayCanvas);
+ layerCanvasesRef.current.set(newId, displayCanvas);
setLayers((prev) => {
const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
@@ -2126,7 +2362,8 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');
if (!hasBg) {
const bgId = `layer-bg-${Date.now()}`;
- pendingInitialDataRef.current.set(bgId, '#ffffff');
+ grid.fillLayerSolidWhite(bgId, _dimensions.width, _dimensions.height, 'color-32bit');
+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: _dimensions }, false);
const bgLayer: LayerItem = {
id: bgId,
name: 'Background',
@@ -2136,7 +2373,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
blendMode: 'normal',
locked: true,
parentId: null,
- thumbnailUrl: '',
+ thumbnailUrl: bgThumb,
};
nextLayers = [...nextLayers, bgLayer];
}
@@ -2147,24 +2384,30 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
setActiveLayerId(newId);
return { id: newId, canvas: displayCanvas, sourceCanvas };
},
- [_dimensions, activeLayerId]
+ [_dimensions, activeLayerId, setActiveLayerId]
);
- // Copy selected layer (internal clipboard & system clipboard)
+ // Copy selected layer (internal clipboard & system clipboard) directly from SparseTileGrid
const copyLayer = useCallback(
(targetId?: string): LayerItem | null => {
const id = targetId || activeLayerId;
const targetLayer = layers.find((l) => l.id === id);
if (!targetLayer) return null;
- const canvas = layerCanvasesRef.current.get(id);
- if (!canvas) return null;
-
+ const dims = dimensionsRef.current;
+ const existingCanvas = layerCanvasesRef.current.get(id);
const clone = document.createElement('canvas');
- clone.width = canvas.width;
- clone.height = canvas.height;
- get2DContext(clone)?.drawImage(canvas, 0, 0);
+ clone.width = existingCanvas?.width || dims.width;
+ clone.height = existingCanvas?.height || dims.height;
+ if (existingCanvas) {
+ get2DContext(clone)?.drawImage(existingCanvas, 0, 0);
+ } else {
+ activeTileGridRef.current.renderLayerToCanvas(id, clone);
+ }
+ if (layerClipboardRef.current?.canvas) {
+ releaseTemporaryCanvas(layerClipboardRef.current.canvas);
+ }
layerClipboardRef.current = {
name: targetLayer.name,
type: targetLayer.type,
@@ -2231,6 +2474,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const newName = 'Pasted Image';
pasteLayerFromCanvas(offscreen, newName);
+ releaseTemporaryCanvas(offscreen);
return { success: true, layerName: newName };
}
}
@@ -2265,6 +2509,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const layerName = file.name.replace(/\.[^/.]+$/, '') || 'Pasted Image';
pasteLayerFromCanvas(offscreen, layerName);
+ releaseTemporaryCanvas(offscreen);
resolve(layerName);
};
img.onerror = () => reject(new Error('Failed to decode image file.'));
@@ -2317,40 +2562,66 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
}
const updatedThumbnails = new Map<string, string>();
-
- layerCanvasesRef.current.forEach((canvas, layerId) => {
- // Clone old contents
- const temp = document.createElement('canvas');
- temp.width = canvas.width;
- temp.height = canvas.height;
- const tempCtx = get2DContext(temp);
- tempCtx?.drawImage(canvas, 0, 0);
-
- // Resize actual canvas DOM element
- canvas.width = newW;
- canvas.height = newH;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- ctx.clearRect(0, 0, newW, newH);
-
- const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
- if (isBg && backgroundColor !== 'transparent') {
- ctx.fillStyle = backgroundColor;
- ctx.fillRect(0, 0, newW, newH);
+ const grid = activeTileGridRef.current;
+
+ // Resize every raster/vector/frame layer directly through SparseTileGrid,
+ // skipping empty layers completely (zero canvas allocation) and releasing temp canvases immediately.
+ for (const layer of layers) {
+ if (layer.type !== 'raster' && layer.type !== 'vector' && layer.type !== 'frame') continue;
+ const layerId = layer.id;
+ const isBg = isBackgroundLayerId(layerId);
+ const isMono = !isBg && layer.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+ const existingCanvas = layerCanvasesRef.current.get(layerId);
+ const hasContent = Boolean(existingCanvas) || grid.hasLayerTiles(layerId);
+
+ if (!hasContent) {
+ if (isBg && backgroundColor !== 'transparent') {
+ grid.fillLayerSolidColor(layerId, newW, newH, backgroundColor, 'color-32bit');
+ updatedThumbnails.set(layerId, createCanvasThumbnail({ grid, layerId, dimensions: newDims }, false));
+ } else {
+ grid.setLayerFormat(layerId, targetFormat);
+ grid.markLayerIngested(layerId);
+ }
+ continue;
}
- if (scaleContent) {
- ctx.drawImage(temp, 0, 0, temp.width, temp.height, 0, 0, newW, newH);
+ const oldTemp = document.createElement('canvas');
+ oldTemp.width = currentW;
+ oldTemp.height = currentH;
+ if (existingCanvas) {
+ get2DContext(oldTemp)?.drawImage(existingCanvas, 0, 0);
} else {
- ctx.drawImage(temp, offsetX, offsetY);
+ grid.renderLayerToCanvas(layerId, oldTemp);
}
- const thumb = createCanvasThumbnail(canvas, !isBg);
- updatedThumbnails.set(layerId, thumb);
- });
+ const resizedCanvas = existingCanvas || document.createElement('canvas');
+ resizedCanvas.width = newW;
+ resizedCanvas.height = newH;
+ const ctx = get2DContext(resizedCanvas);
+ if (ctx) {
+ ctx.clearRect(0, 0, newW, newH);
+ if (isBg && backgroundColor !== 'transparent') {
+ ctx.fillStyle = backgroundColor;
+ ctx.fillRect(0, 0, newW, newH);
+ }
+ if (scaleContent) {
+ ctx.drawImage(oldTemp, 0, 0, oldTemp.width, oldTemp.height, 0, 0, newW, newH);
+ } else {
+ ctx.drawImage(oldTemp, offsetX, offsetY);
+ }
+ grid.clearLayer(layerId);
+ grid.ingestCanvas(layerId, resizedCanvas, targetFormat);
+ }
- // Resize offscreen source canvases
+ releaseTemporaryCanvas(oldTemp);
+ if (!existingCanvas) {
+ releaseTemporaryCanvas(resizedCanvas);
+ }
+ updatedThumbnails.set(layerId, createCanvasThumbnail({ grid, layerId, dimensions: newDims }, !isBg));
+ }
+
+ // Resize offscreen source canvases (strictly for layers with active non-destructive effects)
layerSourceCanvasesRef.current.forEach((sCanvas, layerId) => {
const temp = document.createElement('canvas');
temp.width = sCanvas.width;
@@ -2360,20 +2631,20 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
sCanvas.width = newW;
sCanvas.height = newH;
const sCtx = get2DContext(sCanvas);
- if (!sCtx) return;
- sCtx.clearRect(0, 0, newW, newH);
-
- const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
- if (isBg && backgroundColor !== 'transparent') {
- sCtx.fillStyle = backgroundColor;
- sCtx.fillRect(0, 0, newW, newH);
- }
-
- if (scaleContent) {
- sCtx.drawImage(temp, 0, 0, temp.width, temp.height, 0, 0, newW, newH);
- } else {
- sCtx.drawImage(temp, offsetX, offsetY);
+ if (sCtx) {
+ sCtx.clearRect(0, 0, newW, newH);
+ const isBg = isBackgroundLayerId(layerId);
+ if (isBg && backgroundColor !== 'transparent') {
+ sCtx.fillStyle = backgroundColor;
+ sCtx.fillRect(0, 0, newW, newH);
+ }
+ if (scaleContent) {
+ sCtx.drawImage(temp, 0, 0, temp.width, temp.height, 0, 0, newW, newH);
+ } else {
+ sCtx.drawImage(temp, offsetX, offsetY);
+ }
}
+ releaseTemporaryCanvas(temp);
});
// Re-apply screentone and layer effects for layers that have them enabled, and resize mask canvases
@@ -2397,6 +2668,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
mCtx.drawImage(tempMask, offsetX, offsetY);
}
}
+ releaseTemporaryCanvas(tempMask);
updatedMasks.set(l.id, {
maskCanvas: l.maskCanvas,
maskThumb: createCanvasThumbnail(l.maskCanvas, false),
@@ -2408,20 +2680,15 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
const dCanvas = layerCanvasesRef.current.get(l.id);
if (sCanvas && dCanvas) {
applyLayerEffects(sCanvas, dCanvas, l, newDims.dpi ?? _dimensions.dpi ?? 600);
- const thumb = createCanvasThumbnail(dCanvas, true);
- updatedThumbnails.set(l.id, thumb);
+ const isMono = l.expressionColor === 'monochrome';
+ grid.clearLayer(l.id);
+ grid.ingestCanvas(l.id, dCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ updatedThumbnails.set(l.id, createCanvasThumbnail({ grid, layerId: l.id, dimensions: newDims }, true));
}
}
});
- // Re-ingest all resized canvases into globalTileGrid
- layerCanvasesRef.current.forEach((canvas, layerId) => {
- const l = layers.find((item) => item.id === layerId);
- const isMono = l?.expressionColor === 'monochrome';
- globalTileGrid.clearLayer(layerId);
- globalTileGrid.ingestCanvas(layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- });
- globalTileGrid.notifyChange(true);
+ grid.notifyChange(true);
setLayers((prev) =>
prev.map((l) => {
@@ -2471,6 +2738,8 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
activeLayer,
layerCanvasesRef,
layerSourceCanvasesRef,
+ materializeLayerCanvas,
+ releaseLayerCanvas,
ensureSourceCanvas,
toggleTone,
setToneFrequency,
@@ -2521,6 +2790,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId }: Us
},
clearDocument,
loadDocument,
+ switchDocumentSession,
addLayerMask,
removeLayerMask,
toggleLayerMask,
diff --git a/src/hooks/useMultiplayer.ts b/src/hooks/useMultiplayer.ts
index 99270e0..1881a20 100644
--- a/src/hooks/useMultiplayer.ts
+++ b/src/hooks/useMultiplayer.ts
@@ -13,7 +13,8 @@ import {
} from '../types/multiplayer';
import { multiplayerService } from '../services/multiplayerService';
import { LayerItem, CanvasDimensions, CanvasColorMode } from '../types/editor';
-import { globalTileGrid, TILE_SIZE, TileBuffer } from '../utils/tileEngine';
+import { TILE_SIZE, TileBuffer } from '../utils/tileEngine';
+import { documentStore } from '../utils/documentStore';
const PEER_COLORS = [
'#f43f5e', // Rose
@@ -195,9 +196,10 @@ export function useMultiplayer({
layerDataUrls: {},
});
- // Progressive Tile Streaming: stream active layer tiles progressively from sparse tile grid
+ // Progressive Tile Streaming: stream active layer tiles progressively from active document's sparse tile grid
+ const activeGrid = documentStore.getActiveTileGrid();
for (const layer of effectiveLayers) {
- const tiles = globalTileGrid.getLayerTiles(layer.id);
+ const tiles = activeGrid.getLayerTiles(layer.id);
for (const tile of tiles) {
multiplayerService.sendTileDelta(layer.id, tile);
}
@@ -375,17 +377,18 @@ export function useMultiplayer({
lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
lod: 0,
};
- globalTileGrid.setTile(tMsg.layerId, tMsg.tileX, tMsg.tileY, tile);
+ const activeGrid = documentStore.getActiveTileGrid();
+ activeGrid.setTile(tMsg.layerId, tMsg.tileX, tMsg.tileY, tile);
const canvas = layerCanvasesRef.current.get(tMsg.layerId);
if (canvas) {
- globalTileGrid.renderLayerToCanvas(tMsg.layerId, canvas, {
+ activeGrid.renderLayerToCanvas(tMsg.layerId, canvas, {
x: tMsg.tileX * TILE_SIZE,
y: tMsg.tileY * TILE_SIZE,
width: TILE_SIZE,
height: TILE_SIZE,
});
}
- globalTileGrid.notifyChange(true);
+ activeGrid.notifyChange(true);
break;
}
diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.ts
index 263f68c..958761b 100644
--- a/src/services/recoveryService.ts
+++ b/src/services/recoveryService.ts
@@ -20,6 +20,7 @@ import {
serializeSparseTileGrid,
deserializeSparseTileGrid,
} from '../utils/tileEngine';
+import { documentStore } from '../utils/documentStore';
export const WAL_MAGIC_BYTES = new Uint8Array([0x49, 0x4e, 0x4b, 0x57]); // 'INKW'
export const WAL_ENTRY_STROKE_TILE_DELTA = 1;
@@ -392,8 +393,9 @@ class RecoveryService {
}
try {
- // 1. Snapshot SparseTileGrid
- const rawSnapshot = serializeSparseTileGrid(globalTileGrid);
+ // 1. Snapshot SparseTileGrid for this specific document session
+ const targetGrid = documentStore.getSession(activeId)?.tileGrid ?? globalTileGrid;
+ const rawSnapshot = serializeSparseTileGrid(targetGrid);
const compressedSnapshot = deflateSync(rawSnapshot, { level: 4 });
// 2. Manifest JSON (strip DOM canvas elements before serializing)
diff --git a/src/utils/__tests__/documentIsolation.test.ts b/src/utils/__tests__/documentIsolation.test.ts
new file mode 100644
index 0000000..653fe32
--- /dev/null
+++ b/src/utils/__tests__/documentIsolation.test.ts
@@ -0,0 +1,343 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { DocumentStore } from '../documentStore';
+import {
+ InMemoryScratchDiskDriver,
+ SparseTileGrid,
+ TILE_SIZE,
+ BYTES_32BIT,
+} from '../tileEngine';
+import { LayerStackCacheTracker } from '../compositor';
+import { createCanvasThumbnail } from '../canvasUtils';
+import { computeBatchDeleteLayers } from '../../hooks/useLayerManager';
+import { HistoryItem, LayerItem } from '../../types/editor';
+
+function makeSolidPatch(width: number, height: number, r: number, g: number, b: number, a: number = 255) {
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let i = 0; i < data.length; i += 4) {
+ data[i] = r;
+ data[i + 1] = g;
+ data[i + 2] = b;
+ data[i + 3] = a;
+ }
+ return { data, width, height };
+}
+
+function createHistoryItem(id: string, layerId: string, deltas: HistoryItem['tileDeltas']): HistoryItem {
+ return {
+ id,
+ type: 'brush',
+ label: 'Stroke',
+ timestamp: Date.now(),
+ timeFormatted: '12:00:00',
+ thumbnailUrl: '',
+ layerId,
+ tileDeltas: deltas,
+ };
+}
+
+describe('Per-Document Isolation, Shared RAM Budgets & Sparse Tile Memory Optimization', () => {
+ let driver: InMemoryScratchDiskDriver;
+ let store: DocumentStore;
+
+ beforeEach(() => {
+ driver = new InMemoryScratchDiskDriver();
+ store = new DocumentStore({
+ totalTileBudgetMb: 2, // 2 MB shared budget for deterministic eviction tests
+ sharedUndoRamStepsBudget: 4,
+ scratchDiskDriver: driver,
+ offloadInactiveUndoOnSwitch: true,
+ });
+ });
+
+ afterEach(async () => {
+ await store.clearAllSessions();
+ });
+
+ it('isolates tiles and Undo state between two documents with identical layer IDs', async () => {
+ const docA = store.setActiveDocument('doc-A')!;
+ const docB = store.getOrCreateSession('doc-B');
+
+ // Draw red patch on doc-A:layer-1
+ const beforeA = docA.tileGrid.snapshotTilesInRect('layer-1', { x: 0, y: 0, width: 32, height: 32 });
+ docA.tileGrid.writeImageData('layer-1', makeSolidPatch(32, 32, 220, 20, 20, 255), 0, 0, 'color-32bit');
+ const deltasA = docA.tileGrid.computeDeltasFromSnapshot(beforeA, 'layer-1', { x: 0, y: 0, width: 32, height: 32 });
+ const stepA = createHistoryItem('hist-a-1', 'layer-1', deltasA);
+ docA.history.push(stepA);
+ docA.historyIndex = 0;
+ await store.registerUndoStep('doc-A', stepA);
+
+ // Switch to doc-B and draw blue patch on doc-B:layer-1
+ store.setActiveDocument('doc-B');
+ const beforeB = docB.tileGrid.snapshotTilesInRect('layer-1', { x: 0, y: 0, width: 32, height: 32 });
+ docB.tileGrid.writeImageData('layer-1', makeSolidPatch(32, 32, 10, 40, 240, 255), 0, 0, 'color-32bit');
+ const deltasB = docB.tileGrid.computeDeltasFromSnapshot(beforeB, 'layer-1', { x: 0, y: 0, width: 32, height: 32 });
+ const stepB = createHistoryItem('hist-b-1', 'layer-1', deltasB);
+ docB.history.push(stepB);
+ docB.historyIndex = 0;
+ await store.registerUndoStep('doc-B', stepB);
+
+ // Undo on doc-B must ONLY revert doc-B; doc-A remains red and untouched
+ const resolvedB = await docB.undoCache.resolveDeltas(stepB);
+ expect(resolvedB).not.toBeNull();
+ docB.tileGrid.applyTileDeltas(resolvedB!, 'undo');
+
+ const pixelB = docB.tileGrid.readImageData('layer-1', 5, 5, 1, 1).data;
+ expect(Array.from(pixelB)).toEqual([0, 0, 0, 0]);
+
+ const pixelA = docA.tileGrid.readImageData('layer-1', 5, 5, 1, 1).data;
+ expect(Array.from(pixelA)).toEqual([220, 20, 20, 255]);
+ expect(docA.history.length).toBe(1);
+
+ // Switch back to doc-A and verify its offloaded undo deltas restore cleanly and undo works
+ store.setActiveDocument('doc-A');
+ const resolvedA = await docA.undoCache.resolveDeltas(stepA);
+ expect(resolvedA).not.toBeNull();
+ docA.tileGrid.applyTileDeltas(resolvedA!, 'undo');
+
+ const pixelAAfterUndo = docA.tileGrid.readImageData('layer-1', 5, 5, 1, 1).data;
+ expect(Array.from(pixelAAfterUndo)).toEqual([0, 0, 0, 0]);
+
+ // Redo on doc-B independently restores blue without touching doc-A
+ docB.tileGrid.applyTileDeltas(resolvedB!, 'redo');
+ const pixelBAfterRedo = docB.tileGrid.readImageData('layer-1', 5, 5, 1, 1).data;
+ expect(Array.from(pixelBAfterRedo)).toEqual([10, 40, 240, 255]);
+ expect(Array.from(docA.tileGrid.readImageData('layer-1', 5, 5, 1, 1).data)).toEqual([0, 0, 0, 0]);
+ });
+
+ it('switches across 3 open A4 600 DPI (10+ layers) documents instantaneously with zero ingestCanvas or clearAll calls', () => {
+ const docs = ['doc-a4-1', 'doc-a4-2', 'doc-a4-3'].map((id, docIdx) => {
+ const session = store.getOrCreateSession(id);
+ for (let l = 0; l < 12; l++) {
+ const layerId = `layer-${l}`;
+ session.tileGrid.setLayerFormat(layerId, 'color-32bit');
+ session.tileGrid.markLayerIngested(layerId);
+ // Paint sparse stroke tiles in each layer on A4 600 DPI (4961 x 7016)
+ session.tileGrid.writeImageData(
+ layerId,
+ makeSolidPatch(64, 64, (docIdx + 1) * 50, l * 15, 200, 255),
+ l * 300,
+ l * 400,
+ 'color-32bit',
+ true
+ );
+ }
+ return session;
+ });
+
+ const ingestSpies = docs.map((s) => vi.spyOn(s.tileGrid, 'ingestCanvas'));
+ const clearAllSpies = docs.map((s) => vi.spyOn(s.tileGrid, 'clearAll'));
+ const clearLayerSpies = docs.map((s) => vi.spyOn(s.tileGrid, 'clearLayer'));
+
+ const t0 = performance.now();
+ for (let round = 0; round < 10; round++) {
+ store.setActiveDocument('doc-a4-1');
+ expect(store.getActiveTileGrid()).toBe(docs[0].tileGrid);
+ store.setActiveDocument('doc-a4-2');
+ expect(store.getActiveTileGrid()).toBe(docs[1].tileGrid);
+ store.setActiveDocument('doc-a4-3');
+ expect(store.getActiveTileGrid()).toBe(docs[2].tileGrid);
+ }
+ const elapsedMs = performance.now() - t0;
+
+ expect(elapsedMs).toBeLessThan(100);
+ for (const spy of ingestSpies) expect(spy).not.toHaveBeenCalled();
+ for (const spy of clearAllSpies) expect(spy).not.toHaveBeenCalled();
+ for (const spy of clearLayerSpies) expect(spy).not.toHaveBeenCalled();
+
+ // Verify each document retained its exact tiles intact
+ expect(docs[0].tileGrid.readImageData('layer-3', 910, 1210, 1, 1).data[0]).toBe(50);
+ expect(docs[1].tileGrid.readImageData('layer-3', 910, 1210, 1, 1).data[0]).toBe(100);
+ expect(docs[2].tileGrid.readImageData('layer-3', 910, 1210, 1, 1).data[0]).toBe(150);
+ });
+
+ it('automatically offloads inactive document Undo deltas and evicts inactive document tiles first under shared RAM budget', async () => {
+ // 1 MB shared budget = 4 RGBA tiles (256 KB each)
+ store.setTileBudgetMb(1);
+
+ const docA = store.setActiveDocument('doc-inactive')!;
+ // Allocate 3 RGBA tiles (768 KB) in docA
+ for (let tx = 0; tx < 3; tx++) {
+ const before = docA.tileGrid.snapshotTilesInRect('layer-1', { x: tx * TILE_SIZE, y: 0, width: 16, height: 16 });
+ docA.tileGrid.writeImageData('layer-1', makeSolidPatch(16, 16, 100 + tx, 50, 50, 255), tx * TILE_SIZE, 0, 'color-32bit');
+ const deltas = docA.tileGrid.computeDeltasFromSnapshot(before, 'layer-1', { x: tx * TILE_SIZE, y: 0, width: 16, height: 16 });
+ const item = createHistoryItem(`undo-a-${tx}`, 'layer-1', deltas);
+ docA.history.push(item);
+ docA.historyIndex = docA.history.length - 1;
+ await store.registerUndoStep('doc-inactive', item);
+ }
+
+ expect(docA.undoCache.getRamStepCount()).toBe(3);
+
+ // Switch to docB -> docA becomes inactive and its undo steps auto-offload
+ const docB = store.setActiveDocument('doc-active')!;
+ // Allow microtasks from setActiveDocument's offloadAllToDisk to settle
+ await new Promise((r) => setTimeout(r, 10));
+
+ expect(docA.undoCache.getRamStepCount()).toBe(0);
+ expect(docA.history.every((h) => h.tileDeltas === undefined)).toBe(true);
+ expect(docA.history.every((h) => docA.undoCache.isOffloaded(h.id))).toBe(true);
+
+ // Allocate 3 RGBA tiles (768 KB) in active docB -> total = 1.5 MB > 1 MB shared budget
+ for (let tx = 0; tx < 3; tx++) {
+ docB.tileGrid.writeImageData('layer-1', makeSolidPatch(16, 16, 20, 200, 20, 255), tx * TILE_SIZE, 0, 'color-32bit');
+ }
+
+ await store.enforceSharedTileBudget();
+
+ // Inactive docA must have been paged to scratch disk first; active docB stays in RAM
+ const statsA = docA.tileGrid.getMemoryStats();
+ const statsB = docB.tileGrid.getMemoryStats();
+ expect(statsA.pagedTileCount).toBeGreaterThan(0);
+ expect(statsB.activeTileCount).toBe(3);
+ expect(store.getTotalActiveTileBytes()).toBeLessThanOrEqual(store.getTileBudgetBytes());
+ });
+
+ it('allocates zero full-size HTMLCanvasElements and zero tile bytes for 20 empty raster layers on 6000x8000', () => {
+ const doc = store.setActiveDocument('doc-6000x8000')!;
+
+ // Create 20 new empty raster layers (no backing HTMLCanvasElement created)
+ const layers: LayerItem[] = [];
+ for (let i = 0; i < 20; i++) {
+ const id = `raster-empty-${i}`;
+ doc.tileGrid.setLayerFormat(id, 'color-32bit');
+ doc.tileGrid.markLayerIngested(id);
+ layers.push({
+ id,
+ name: `Layer ${i + 1}`,
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ });
+ }
+
+ expect(doc.layerCanvases.size).toBe(0);
+ expect(doc.layerSourceCanvases.size).toBe(0);
+ const stats = doc.tileGrid.getMemoryStats();
+ expect(stats.tileCount).toBe(0);
+ expect(stats.activeBytes).toBe(0);
+
+ // Drawing a small 40x40 stroke on layer 5 allocates ONLY 1 tile (256 KB), not 20 * 192 MB
+ doc.tileGrid.writeImageData('raster-empty-5', makeSolidPatch(40, 40, 0, 0, 0, 255), 100, 100, 'color-32bit');
+ const afterStroke = doc.tileGrid.getMemoryStats();
+ expect(afterStroke.tileCount).toBe(1);
+ expect(afterStroke.activeBytes).toBe(BYTES_32BIT);
+ expect(doc.layerCanvases.size).toBe(0);
+
+ // Batch-deleting layers cleans up tiles cleanly
+ const delRes = computeBatchDeleteLayers(layers, ['raster-empty-5', 'raster-empty-6'], 'raster-empty-5');
+ expect(delRes.deletedIds).toContain('raster-empty-5');
+ for (const delId of delRes.deletedIds) {
+ doc.clearLayerResources(delId);
+ }
+ expect(doc.tileGrid.getMemoryStats().tileCount).toBe(0);
+ expect(doc.tileGrid.getMemoryStats().activeBytes).toBe(0);
+ });
+
+ it('cleans up all tiles, undo cache, and temporary buffers when closing a document tab', async () => {
+ const doc = store.setActiveDocument('doc-closable')!;
+ const before = doc.tileGrid.snapshotTilesInRect('layer-1', { x: 0, y: 0, width: 64, height: 64 });
+ doc.tileGrid.writeImageData('layer-1', makeSolidPatch(64, 64, 255, 0, 128, 255), 0, 0, 'color-32bit');
+ const deltas = doc.tileGrid.computeDeltasFromSnapshot(before, 'layer-1', { x: 0, y: 0, width: 64, height: 64 });
+ const item = createHistoryItem('close-step-1', 'layer-1', deltas);
+ doc.history.push(item);
+ doc.historyIndex = 0;
+ await store.registerUndoStep('doc-closable', item);
+
+ // Attach a mock materialized canvas to verify width/height zeroing on close
+ const mockCanvas = { width: 4000, height: 6000 } as HTMLCanvasElement;
+ doc.layerCanvases.set('layer-1', mockCanvas);
+
+ await store.closeSession('doc-closable');
+
+ expect(store.hasSession('doc-closable')).toBe(false);
+ expect(doc.isDisposed()).toBe(true);
+ expect(doc.tileGrid.getMemoryStats().tileCount).toBe(0);
+ expect(doc.tileGrid.getMemoryStats().activeBytes).toBe(0);
+ expect(doc.undoCache.getRamStepCount()).toBe(0);
+ expect(doc.undoCache.getCompressedRamCount()).toBe(0);
+ expect(doc.layerCanvases.size).toBe(0);
+ expect(mockCanvas.width).toBe(0);
+ expect(mockCanvas.height).toBe(0);
+ });
+
+ it('builds and samples layer thumbnails directly from LOD 3 tiles without reading a full-size canvas', () => {
+ const grid = new SparseTileGrid();
+ // Write a 64x64 stroke on a 7016x9921 (600 DPI B4) layer
+ grid.writeImageData('ink-layer', makeSolidPatch(64, 64, 15, 25, 35, 255), 512, 512, 'color-32bit');
+
+ // Before thumbnail generation, LOD 3 has not been built yet
+ expect(grid.getLayerTiles('ink-layer', 3).length).toBe(0);
+
+ // Build LOD 3 tiles on demand via getOrBuildLod3Tiles & createCanvasThumbnail
+ const lod3Tiles = grid.getOrBuildLod3Tiles('ink-layer');
+ expect(lod3Tiles.length).toBe(1);
+ expect(lod3Tiles[0].lod).toBe(3);
+ expect(lod3Tiles[0].tileX).toBe(0);
+ expect(lod3Tiles[0].tileY).toBe(0);
+
+ // Verify createCanvasThumbnail accepts the SparseTileGrid descriptor cleanly (safe in Node & DOM)
+ const thumbSpy = vi.spyOn(grid, 'generateThumbnail');
+ createCanvasThumbnail({ grid, layerId: 'ink-layer', dimensions: { width: 7016, height: 9921 } }, true);
+ expect(thumbSpy).toHaveBeenCalledWith('ink-layer', 60, 85, { width: 7016, height: 9921 }, true);
+ });
+
+ it('invalidates ViewportCompositor LayerStackCacheTracker when switching SparseTileGrid instances', () => {
+ const tracker = new LayerStackCacheTracker();
+ const gridA = new SparseTileGrid();
+ const gridB = new SparseTileGrid();
+ expect(gridA.getGridId()).not.toBe(gridB.getGridId());
+
+ const layers: LayerItem[] = [
+ { id: 'layer-1', name: 'Layer 1', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: false, parentId: null },
+ { id: 'layer-bg', name: 'Background', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: true, parentId: null },
+ ];
+
+ const evalA = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-1',
+ viewportW: 1280,
+ viewportH: 720,
+ dpr: 1,
+ dimensions: { width: 2048, height: 2048, dpi: 300 },
+ transform: { pan: { x: 0, y: 0 }, zoom: 1, rotation: 0 },
+ getLayerContentVersion: () => 1,
+ gridEpoch: gridA.getGridEpoch(),
+ gridId: gridA.getGridId(),
+ });
+ expect(evalA.belowDirty).toBe(true);
+ tracker.commit(evalA.belowSignature, evalA.aboveSignature);
+
+ // Same grid -> cache stays clean
+ const evalA2 = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-1',
+ viewportW: 1280,
+ viewportH: 720,
+ dpr: 1,
+ dimensions: { width: 2048, height: 2048, dpi: 300 },
+ transform: { pan: { x: 0, y: 0 }, zoom: 1, rotation: 0 },
+ getLayerContentVersion: () => 1,
+ gridEpoch: gridA.getGridEpoch(),
+ gridId: gridA.getGridId(),
+ });
+ expect(evalA2.belowDirty).toBe(false);
+
+ // Switching to gridB (even with identical layer IDs and versions) immediately invalidates cache
+ const evalB = tracker.evaluate({
+ layers,
+ activeLayerId: 'layer-1',
+ viewportW: 1280,
+ viewportH: 720,
+ dpr: 1,
+ dimensions: { width: 2048, height: 2048, dpi: 300 },
+ transform: { pan: { x: 0, y: 0 }, zoom: 1, rotation: 0 },
+ getLayerContentVersion: () => 1,
+ gridEpoch: gridB.getGridEpoch(),
+ gridId: gridB.getGridId(),
+ });
+ expect(evalB.belowDirty).toBe(true);
+ });
+});
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index fcc0e93..cd6ea41 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -265,16 +265,37 @@ export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalComposi
}
}
+import type { SparseTileGrid } from './tileEngine';
+
+export interface TileThumbnailSource {
+ grid: SparseTileGrid;
+ layerId: string;
+ dimensions: { width: number; height: number };
+}
+
/**
* Generates an efficient mini thumbnail (60px wide) for layer and history preview.
+ * Supports direct LOD 3 sampling from SparseTileGrid without reading full-size canvases.
*/
-export function createCanvasThumbnail(canvas: HTMLCanvasElement, preserveAlpha: boolean = false): string {
+export function createCanvasThumbnail(
+ source: HTMLCanvasElement | TileThumbnailSource,
+ preserveAlpha: boolean = false
+): string {
try {
+ if (source && 'grid' in source && 'layerId' in source) {
+ const targetW = 60;
+ const docW = Math.max(1, source.dimensions.width);
+ const docH = Math.max(1, source.dimensions.height);
+ const targetH = Math.max(38, Math.round((docH / docW) * targetW));
+ return source.grid.generateThumbnail(source.layerId, targetW, targetH, source.dimensions, preserveAlpha);
+ }
+
+ const canvas = source;
if (!_sharedThumbCanvas) {
_sharedThumbCanvas = document.createElement('canvas');
}
const targetW = 60;
- const targetH = Math.max(38, Math.round((canvas.height / canvas.width) * targetW));
+ const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * targetW));
_sharedThumbCanvas.width = targetW;
_sharedThumbCanvas.height = targetH;
const tCtx = _sharedThumbCanvas.getContext('2d');
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index c7c3c7c..7738d58 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -231,27 +231,30 @@ export class LayerPixelSampler {
private tilesX: number = 1;
constructor(
- sourceCanvas: HTMLCanvasElement,
+ sourceCanvas: HTMLCanvasElement | { width: number; height: number } | null,
layerId?: string,
tileGrid: SparseTileGrid = globalTileGrid,
origTilesMap?: Map<number, ImageData>
) {
- this.width = sourceCanvas.width;
- this.height = sourceCanvas.height;
+ this.width = sourceCanvas?.width ?? 0;
+ this.height = sourceCanvas?.height ?? 0;
this.tilesX = Math.max(1, Math.ceil(this.width / TILE_SIZE));
this.origTilesMap = origTilesMap ?? null;
- this.sourceCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });
+ this.sourceCtx =
+ sourceCanvas && 'getContext' in sourceCanvas && typeof sourceCanvas.getContext === 'function'
+ ? sourceCanvas.getContext('2d', { willReadFrequently: true })
+ : null;
- // If a SparseTileGrid has tiles for this layer, or if the canvas is large (> 512x512),
- // or if an origTilesMap is provided for clean live sampling,
+ // If a SparseTileGrid has tiles for this layer, or if no source canvas is provided (tile-native layer),
+ // or if the canvas is large (> 512x512), or if an origTilesMap is provided for clean live sampling,
// use zero-stall on-demand 256x256 tile caching instead of a synchronous full-document getImageData!
- const hasGridTiles = Boolean(layerId && tileGrid && tileGrid.getLayerTiles(layerId).length > 0);
+ const hasGridTiles = Boolean(layerId && tileGrid && (tileGrid.hasLayerTiles(layerId) || tileGrid.isLayerIngested(layerId)));
const isLargeCanvas = this.width * this.height > 512 * 512;
- if (hasGridTiles || isLargeCanvas || Boolean(origTilesMap)) {
+ if (hasGridTiles || !this.sourceCtx || isLargeCanvas || Boolean(origTilesMap)) {
this.useLazyTiles = true;
this.layerId = layerId ?? null;
- this.tileGrid = hasGridTiles ? tileGrid : null;
+ this.tileGrid = layerId && tileGrid ? tileGrid : null;
// Allocate a minimal 1-pixel placeholder for legacy property access
this.data = new Uint8ClampedArray(4);
this.u32 = new Uint32Array(this.data.buffer);
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index d29bd51..93144c3 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -1358,6 +1358,7 @@ export interface LayerStackCacheInput {
getLayerContentVersion: (layerId: string) => number;
getMaskInvalidationEpoch?: (layerId: string) => number;
gridEpoch?: number;
+ gridId?: number;
}
export interface LayerStackCacheEvaluation {
@@ -1643,7 +1644,7 @@ export class LayerStackCacheTracker {
`${input.viewportW}x${input.viewportH}@${input.dpr}|` +
`${dimensions.width}x${dimensions.height}@${dimensions.dpi ?? 600}|` +
`${transform.pan.x},${transform.pan.y},${transform.zoom},${transform.rotation},` +
- `${transform.flipX ? 1 : 0},${transform.flipY ? 1 : 0}|ep:${input.gridEpoch ?? 0}`;
+ `${transform.flipX ? 1 : 0},${transform.flipY ? 1 : 0}|g:${input.gridId ?? 0}|ep:${input.gridEpoch ?? 0}`;
// Onion skin frames are baked into the below cache right after the artboard background
let onionSig = '';
@@ -2040,7 +2041,7 @@ export class ViewportCompositor {
this.onContextRestoredHandler = () => {
this.contextLost = false;
this.initGL();
- globalTileGrid.notifyChange(true);
+ (this.lastRenderedGrid || globalTileGrid).notifyChange(true);
};
canvas.addEventListener('webglcontextlost', this.onContextLostHandler, false);
canvas.addEventListener('webglcontextrestored', this.onContextRestoredHandler, false);
@@ -2885,7 +2886,8 @@ export class ViewportCompositor {
grid: SparseTileGrid,
batchTick: number
): number {
- const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0);
+ const gridId = typeof grid.getGridId === 'function' ? grid.getGridId() : 0;
+ const key = `${gridId}:${getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0)}`;
const accessTick = ++this.arrayAccessCounter;
let slot = this.arrayPoolByKey.get(key);
@@ -2954,7 +2956,8 @@ export class ViewportCompositor {
private getTileTexture(tile: TileBuffer, grid: SparseTileGrid): WebGLTexture | null {
if (!this.gl) return null;
const gl = this.gl;
- const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0);
+ const gridId = typeof grid.getGridId === 'function' ? grid.getGridId() : 0;
+ const key = `${gridId}:${getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0)}`;
const accessTick = ++this.textureAccessCounter;
let slot = this.activePoolByKey.get(key);
@@ -3177,6 +3180,8 @@ export class ViewportCompositor {
* 2. Baked Layer Stack Cache (`belowActiveCacheFbo` + `activeUnit` + `aboveActiveCacheFbo`)
* 3. TEXTURE_2D_ARRAY + gl.drawArraysInstanced tile batching
*/
+ private lastRenderedGrid: SparseTileGrid | null = null;
+
public render(
layers: LayerItem[],
transform: ViewportTransform,
@@ -3184,6 +3189,7 @@ export class ViewportCompositor {
grid: SparseTileGrid = globalTileGrid,
_options: CompositorOptions = { dimensions }
): void {
+ this.lastRenderedGrid = grid;
const gl = this.gl;
this.currentOptions = _options;
this.currentZoom = transform.zoom;
@@ -3263,6 +3269,7 @@ export class ViewportCompositor {
typeof grid.getLayerVersion === 'function' ? grid.getLayerVersion(id) : 0,
getMaskInvalidationEpoch: (id) => this.maskInvalidationEpochs.get(id) ?? 0,
gridEpoch: typeof grid.getGridEpoch === 'function' ? grid.getGridEpoch() : 0,
+ gridId: typeof grid.getGridId === 'function' ? grid.getGridId() : 0,
});
const { partition } = cacheEval;
diff --git a/src/utils/documentStore.ts b/src/utils/documentStore.ts
new file mode 100644
index 0000000..29a7252
--- /dev/null
+++ b/src/utils/documentStore.ts
@@ -0,0 +1,398 @@
+/**
+ * Per-Document Tile Grid & Undo Session Store
+ *
+ * Isolates SparseTileGrid, Undo history, and UndoCacheManager per open document tab.
+ * Enforces a shared RAM budget across all open documents, automatically offloading
+ * inactive documents' tiles and undo deltas to scratch disk without clearing or
+ * re-slicing tiles on tab switches.
+ */
+
+import { HistoryItem } from '../types/editor';
+import {
+ SparseTileGrid,
+ IScratchDiskDriver,
+ createDefaultScratchDiskDriver,
+ globalTileGrid,
+ releaseTemporaryCanvas,
+} from './tileEngine';
+import { UndoCacheManager, MAX_RAM_UNDO_STEPS } from './undoCache';
+
+export interface DocumentStoreOptions {
+ totalTileBudgetMb?: number;
+ sharedUndoRamStepsBudget?: number;
+ scratchDiskDriver?: IScratchDiskDriver;
+ offloadInactiveUndoOnSwitch?: boolean;
+}
+
+export class TileGridSession {
+ public readonly documentId: string;
+ public readonly tileGrid: SparseTileGrid;
+ public readonly undoCache: UndoCacheManager;
+ public history: HistoryItem[] = [];
+ public historyIndex: number = -1;
+ public readonly layerCanvases: Map<string, HTMLCanvasElement> = new Map();
+ public readonly layerSourceCanvases: Map<string, HTMLCanvasElement> = new Map();
+ public lastAccessedAt: number;
+ public isActive: boolean = false;
+ private disposed: boolean = false;
+
+ constructor(
+ documentId: string,
+ options?: {
+ budgetMb?: number;
+ driver?: IScratchDiskDriver;
+ onMemoryChanged?: () => void;
+ }
+ ) {
+ this.documentId = documentId;
+ this.lastAccessedAt = Date.now();
+ this.tileGrid = new SparseTileGrid({
+ sessionId: documentId,
+ budgetMb: options?.budgetMb ?? 1024,
+ driver: options?.driver,
+ onMemoryChanged: options?.onMemoryChanged,
+ });
+ this.undoCache = new UndoCacheManager(documentId);
+ }
+
+ public isDisposed(): boolean {
+ return this.disposed;
+ }
+
+ public touch(): void {
+ this.lastAccessedAt = Date.now();
+ }
+
+ /**
+ * Releases any transiently materialized display canvases (safe because SparseTileGrid
+ * is the authoritative pixel store; source canvases for non-destructive effects are preserved).
+ */
+ public releaseTransientDisplayCanvases(): number {
+ let released = 0;
+ for (const [layerId, canvas] of Array.from(this.layerCanvases.entries())) {
+ if (this.layerSourceCanvases.has(layerId)) continue;
+ releaseTemporaryCanvas(canvas);
+ this.layerCanvases.delete(layerId);
+ released++;
+ }
+ return released;
+ }
+
+ /**
+ * Releases a single layer's tiles and any temporary/source canvases.
+ */
+ public clearLayerResources(layerId: string): void {
+ const display = this.layerCanvases.get(layerId);
+ if (display) {
+ releaseTemporaryCanvas(display);
+ this.layerCanvases.delete(layerId);
+ }
+ const source = this.layerSourceCanvases.get(layerId);
+ if (source) {
+ releaseTemporaryCanvas(source);
+ this.layerSourceCanvases.delete(layerId);
+ }
+ this.tileGrid.clearLayer(layerId);
+ }
+
+ /**
+ * Resets history & clears this document's undo cache without affecting other documents.
+ */
+ public async resetHistory(): Promise<void> {
+ this.history = [];
+ this.historyIndex = -1;
+ await this.undoCache.clearCache();
+ }
+
+ /**
+ * Permanently disposes all tiles, scratch disk state, undo cache, and canvases for this tab.
+ */
+ public async dispose(): Promise<void> {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.isActive = false;
+
+ for (const canvas of this.layerCanvases.values()) {
+ releaseTemporaryCanvas(canvas);
+ }
+ this.layerCanvases.clear();
+
+ for (const canvas of this.layerSourceCanvases.values()) {
+ releaseTemporaryCanvas(canvas);
+ }
+ this.layerSourceCanvases.clear();
+
+ this.history = [];
+ this.historyIndex = -1;
+
+ this.tileGrid.clearAll();
+ const mm = this.tileGrid.getMemoryManager();
+ await Promise.all([
+ mm ? mm.clear().catch(() => {}) : Promise.resolve(),
+ this.undoCache.clearCache().catch(() => {}),
+ ]);
+ }
+}
+
+export class DocumentStore {
+ private sessions: Map<string, TileGridSession> = new Map();
+ private activeDocumentId: string | null = null;
+ private totalTileBudgetBytes: number;
+ private sharedUndoRamStepsBudget: number;
+ private driver: IScratchDiskDriver;
+ private offloadInactiveUndoOnSwitch: boolean;
+ private tileBudgetPromise: Promise<void> | null = null;
+ private needsAnotherTileBudgetPass: boolean = false;
+
+ constructor(options?: DocumentStoreOptions) {
+ const budgetMb = options?.totalTileBudgetMb ?? 1024;
+ this.totalTileBudgetBytes = Math.max(1, budgetMb) * 1024 * 1024;
+ this.sharedUndoRamStepsBudget = Math.max(1, options?.sharedUndoRamStepsBudget ?? MAX_RAM_UNDO_STEPS);
+ this.driver = options?.scratchDiskDriver || createDefaultScratchDiskDriver();
+ this.offloadInactiveUndoOnSwitch = options?.offloadInactiveUndoOnSwitch ?? true;
+ }
+
+ public getOrCreateSession(documentId: string): TileGridSession {
+ let session = this.sessions.get(documentId);
+ if (!session || session.isDisposed()) {
+ session = new TileGridSession(documentId, {
+ budgetMb: Math.max(1, Math.round(this.totalTileBudgetBytes / (1024 * 1024))),
+ driver: this.driver,
+ onMemoryChanged: () => {
+ void this.enforceSharedTileBudget();
+ },
+ });
+ this.sessions.set(documentId, session);
+ }
+ session.touch();
+ return session;
+ }
+
+ public getSession(documentId: string | null | undefined): TileGridSession | null {
+ if (!documentId) return null;
+ const session = this.sessions.get(documentId);
+ return session && !session.isDisposed() ? session : null;
+ }
+
+ public hasSession(documentId: string): boolean {
+ const s = this.sessions.get(documentId);
+ return Boolean(s && !s.isDisposed());
+ }
+
+ public getActiveDocumentId(): string | null {
+ return this.activeDocumentId;
+ }
+
+ public getActiveSession(): TileGridSession | null {
+ return this.getSession(this.activeDocumentId);
+ }
+
+ public getActiveTileGrid(): SparseTileGrid {
+ return this.getActiveSession()?.tileGrid ?? globalTileGrid;
+ }
+
+ public getAllSessions(): TileGridSession[] {
+ return Array.from(this.sessions.values()).filter((s) => !s.isDisposed());
+ }
+
+ /**
+ * Switches the active document session in O(1) without clearing or re-ingesting tiles.
+ * Schedules background offloading for inactive documents under shared RAM budgets.
+ */
+ public setActiveDocument(documentId: string | null): TileGridSession | null {
+ const prevId = this.activeDocumentId;
+ if (prevId && prevId !== documentId) {
+ const prevSession = this.sessions.get(prevId);
+ if (prevSession && !prevSession.isDisposed()) {
+ prevSession.isActive = false;
+ prevSession.touch();
+ prevSession.releaseTransientDisplayCanvases();
+ if (this.offloadInactiveUndoOnSwitch) {
+ void prevSession.undoCache.offloadAllToDisk(prevSession.history).catch(() => {});
+ }
+ }
+ }
+
+ this.activeDocumentId = documentId;
+ if (!documentId) {
+ return null;
+ }
+
+ const nextSession = this.getOrCreateSession(documentId);
+ nextSession.isActive = true;
+ nextSession.touch();
+
+ void this.enforceSharedTileBudget();
+ void this.enforceSharedUndoBudget();
+
+ return nextSession;
+ }
+
+ /**
+ * Updates the shared tile RAM budget across all open documents.
+ */
+ public setTileBudgetMb(mb: number): void {
+ const clampedMb = Math.max(1, mb);
+ this.totalTileBudgetBytes = clampedMb * 1024 * 1024;
+ for (const session of this.sessions.values()) {
+ session.tileGrid.getMemoryManager()?.setBudgetMb(clampedMb);
+ }
+ void this.enforceSharedTileBudget();
+ }
+
+ public getTileBudgetBytes(): number {
+ return this.totalTileBudgetBytes;
+ }
+
+ public setSharedUndoRamStepsBudget(steps: number): void {
+ this.sharedUndoRamStepsBudget = Math.max(1, steps);
+ void this.enforceSharedUndoBudget();
+ }
+
+ public getTotalActiveTileBytes(): number {
+ let total = 0;
+ for (const session of this.sessions.values()) {
+ if (session.isDisposed()) continue;
+ total += session.tileGrid.getMemoryManager()?.getActiveMemoryBytes() ?? 0;
+ }
+ return total;
+ }
+
+ public getTotalRamUndoSteps(): number {
+ let total = 0;
+ for (const session of this.sessions.values()) {
+ if (session.isDisposed()) continue;
+ total += session.undoCache.getRamStepCount();
+ }
+ return total;
+ }
+
+ /**
+ * Registers an Undo step on a specific document and enforces the shared Undo RAM budget,
+ * prioritizing offloading inactive documents first.
+ */
+ public async registerUndoStep(documentId: string, item: HistoryItem): Promise<void> {
+ const session = this.getSession(documentId);
+ if (!session) return;
+
+ await session.undoCache.registerStep(item, session.history, this.sharedUndoRamStepsBudget);
+ await this.enforceSharedUndoBudget();
+ }
+
+ /**
+ * Enforces the shared Undo RAM budget across all open documents.
+ * Inactive documents (oldest accessed first) are offloaded to scratch disk first.
+ */
+ public async enforceSharedUndoBudget(): Promise<void> {
+ let totalRamSteps = this.getTotalRamUndoSteps();
+ if (totalRamSteps <= this.sharedUndoRamStepsBudget) return;
+
+ // 1. Offload inactive documents first (oldest accessed first)
+ const inactive = this.getAllSessions()
+ .filter((s) => !s.isActive && s.undoCache.getRamStepCount() > 0)
+ .sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);
+
+ for (const session of inactive) {
+ if (totalRamSteps <= this.sharedUndoRamStepsBudget) break;
+ const excess = totalRamSteps - this.sharedUndoRamStepsBudget;
+ const offloaded = await session.undoCache.offloadAllToDisk(session.history, excess);
+ totalRamSteps -= offloaded;
+ }
+
+ // 2. If still over budget, offload oldest steps from active document
+ if (totalRamSteps > this.sharedUndoRamStepsBudget) {
+ const active = this.getActiveSession();
+ if (active) {
+ const excess = totalRamSteps - this.sharedUndoRamStepsBudget;
+ await active.undoCache.offloadAllToDisk(active.history, excess);
+ }
+ }
+ }
+
+ /**
+ * Enforces the shared Tile RAM budget across all open documents.
+ * Evicts tiles from inactive documents first (oldest accessed first) to scratch disk,
+ * only touching the active document if total active RAM still exceeds budget.
+ */
+ public async enforceSharedTileBudget(): Promise<void> {
+ if (this.tileBudgetPromise) {
+ this.needsAnotherTileBudgetPass = true;
+ return this.tileBudgetPromise;
+ }
+
+ if (this.getTotalActiveTileBytes() <= this.totalTileBudgetBytes) {
+ return;
+ }
+
+ 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;
+
+ // 1. Reclaim from inactive sessions first (LRU by lastAccessedAt)
+ const inactive = this.getAllSessions()
+ .filter((s) => !s.isActive)
+ .sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);
+
+ for (const session of inactive) {
+ if (bytesToFree <= 0) break;
+ const mm = session.tileGrid.getMemoryManager();
+ if (!mm || mm.getActiveMemoryBytes() <= 0) continue;
+ const freed = await mm.evictBytesToDisk(bytesToFree);
+ freedTotal += freed;
+ bytesToFree -= freed;
+ }
+
+ // 2. If still over budget, run active session's own frustum-aware eviction
+ if (this.getTotalActiveTileBytes() > this.totalTileBudgetBytes) {
+ const active = this.getActiveSession();
+ const mm = active?.tileGrid.getMemoryManager();
+ if (mm) {
+ const before = mm.getActiveMemoryBytes();
+ await mm.checkBudgetAndEvict();
+ freedTotal += Math.max(0, before - mm.getActiveMemoryBytes());
+ }
+ }
+
+ if (freedTotal <= 0 && !this.needsAnotherTileBudgetPass) {
+ break;
+ }
+ }
+ } finally {
+ this.tileBudgetPromise = null;
+ this.needsAnotherTileBudgetPass = false;
+ }
+ })();
+
+ return this.tileBudgetPromise;
+ }
+
+ /**
+ * Closes and permanently disposes a document session, cleaning up all tiles,
+ * scratch disk files, undo cache, and temporary canvases.
+ */
+ public async closeSession(documentId: string): Promise<void> {
+ const session = this.sessions.get(documentId);
+ if (!session) return;
+ this.sessions.delete(documentId);
+ if (this.activeDocumentId === documentId) {
+ this.activeDocumentId = null;
+ }
+ await session.dispose();
+ }
+
+ /**
+ * Disposes all open sessions (useful for cleanup and test isolation).
+ */
+ public async clearAllSessions(): Promise<void> {
+ const all = Array.from(this.sessions.values());
+ this.sessions.clear();
+ this.activeDocumentId = null;
+ await Promise.all(all.map((s) => s.dispose()));
+ }
+}
+
+export const documentStore = new DocumentStore();
diff --git a/src/utils/floodFill.ts b/src/utils/floodFill.ts
index 3269175..39204f0 100644
--- a/src/utils/floodFill.ts
+++ b/src/utils/floodFill.ts
@@ -49,14 +49,18 @@ export interface FloodFillOptions {
selectionMask?: Uint8Array | null;
}
+import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
+import { documentStore } from './documentStore';
+
/**
* Creates a flat composite canvas of all visible layers.
- * Used for "Refer to Other Layers" bucket fill.
+ * Reads directly from SparseTileGrid when a layer has no materialized backing canvas.
*/
export function compositeVisibleLayers(
layers: LayerItem[],
layerCanvasesMap: Map<string, HTMLCanvasElement>,
- dimensions: CanvasDimensions
+ dimensions: CanvasDimensions,
+ tileGrid?: SparseTileGrid
): HTMLCanvasElement {
const composite = document.createElement('canvas');
composite.width = dimensions.width;
@@ -64,11 +68,18 @@ export function compositeVisibleLayers(
const ctx = composite.getContext('2d');
if (!ctx) return composite;
+ const grid = tileGrid ?? documentStore.getActiveTileGrid();
+
// Render order is bottom to top (reverse of layers array)
const renderOrder = layers.slice().reverse();
for (const layer of renderOrder) {
if (layer.type === 'folder' || !layer.visible) continue;
- const lCanvas = layerCanvasesMap.get(layer.id);
+ let lCanvas = layerCanvasesMap.get(layer.id) || null;
+ let isTemp = false;
+ if (!lCanvas && grid && grid.hasLayerTiles(layer.id)) {
+ lCanvas = grid.exportLayerToCanvas(layer.id, dimensions.width, dimensions.height);
+ isTemp = true;
+ }
if (!lCanvas) continue;
ctx.save();
@@ -76,6 +87,10 @@ export function compositeVisibleLayers(
ctx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
ctx.drawImage(lCanvas, 0, 0);
ctx.restore();
+
+ if (isTemp) {
+ releaseTemporaryCanvas(lCanvas);
+ }
}
return composite;
@@ -88,11 +103,12 @@ export function compositeVisibleLayers(
export function compositeReferenceLayers(
layers: LayerItem[],
layerCanvasesMap: Map<string, HTMLCanvasElement>,
- dimensions: CanvasDimensions
+ dimensions: CanvasDimensions,
+ tileGrid?: SparseTileGrid
): HTMLCanvasElement {
const refLayers = layers.filter((l) => l.visible && l.isReference && l.type !== 'folder');
if (refLayers.length === 0) {
- return compositeVisibleLayers(layers, layerCanvasesMap, dimensions);
+ return compositeVisibleLayers(layers, layerCanvasesMap, dimensions, tileGrid);
}
const composite = document.createElement('canvas');
@@ -101,9 +117,16 @@ export function compositeReferenceLayers(
const ctx = composite.getContext('2d');
if (!ctx) return composite;
+ const grid = tileGrid ?? documentStore.getActiveTileGrid();
+
const renderOrder = refLayers.slice().reverse();
for (const layer of renderOrder) {
- const lCanvas = layerCanvasesMap.get(layer.id);
+ let lCanvas = layerCanvasesMap.get(layer.id) || null;
+ let isTemp = false;
+ if (!lCanvas && grid && grid.hasLayerTiles(layer.id)) {
+ lCanvas = grid.exportLayerToCanvas(layer.id, dimensions.width, dimensions.height);
+ isTemp = true;
+ }
if (!lCanvas) continue;
ctx.save();
@@ -111,6 +134,10 @@ export function compositeReferenceLayers(
ctx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
ctx.drawImage(lCanvas, 0, 0);
ctx.restore();
+
+ if (isTemp) {
+ releaseTemporaryCanvas(lCanvas);
+ }
}
return composite;
diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.ts
index 8cbb3b2..4388051 100644
--- a/src/utils/saveManager.ts
+++ b/src/utils/saveManager.ts
@@ -8,6 +8,8 @@ import { getCanvasCompositeOperation } from './canvasUtils';
import { groupLayersForCompositing } from './compositor';
import { applyAdjustment } from './tonalEngine';
import { recoveryService } from '../services/recoveryService';
+import { SparseTileGrid, releaseTemporaryCanvas } from './tileEngine';
+import { documentStore } from './documentStore';
export interface SavedFileInfo {
handle?: any; // FileSystemFileHandle
@@ -21,6 +23,7 @@ export interface SaveDocumentData {
colorMode: CanvasColorMode;
layers: LayerItem[];
layerCanvasesMap: Map<string, HTMLCanvasElement>;
+ tileGrid?: SparseTileGrid;
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
tabId?: string;
@@ -44,6 +47,27 @@ function toAgPsdBlendMode(mode: BlendMode): any {
}
}
+/**
+ * Resolves a layer's canvas from either the map or temporarily from SparseTileGrid.
+ * Returns `{ canvas, isTemporary }` so caller immediately releases temporary canvases.
+ */
+function acquireLayerExportCanvas(
+ layerId: string,
+ dimensions: CanvasDimensions,
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ tileGrid?: SparseTileGrid
+): { canvas: HTMLCanvasElement | null; isTemporary: boolean } {
+ const existing = layerCanvasesMap.get(layerId);
+ if (existing) {
+ return { canvas: existing, isTemporary: false };
+ }
+ if (tileGrid && tileGrid.hasLayerTiles(layerId)) {
+ const temp = tileGrid.exportLayerToCanvas(layerId, dimensions.width, dimensions.height);
+ return { canvas: temp, isTemporary: true };
+ }
+ return { canvas: null, isTemporary: false };
+}
+
/**
* Composites all visible layers with their blend modes and opacities onto a single canvas.
*/
@@ -53,7 +77,8 @@ export function compositeCanvas(
layerCanvasesMap: Map<string, HTMLCanvasElement>,
getEffectiveOpacity: (layer: LayerItem) => number,
isLayerEffectivelyVisible: (layer: LayerItem) => boolean,
- fillWhiteBackground: boolean = false
+ fillWhiteBackground: boolean = false,
+ tileGrid?: SparseTileGrid
): HTMLCanvasElement {
const exportCanvas = document.createElement('canvas');
exportCanvas.width = dimensions.width;
@@ -70,14 +95,22 @@ export function compositeCanvas(
const renderOrder = layers.slice().reverse();
const groups = groupLayersForCompositing(renderOrder);
- const getMaskedLayerCanvas = (layer: LayerItem, srcCanvas: HTMLCanvasElement): HTMLCanvasElement => {
- if (!layer.maskCanvas || layer.maskEnabled === false) return srcCanvas;
+ const getMaskedLayerCanvas = (
+ layer: LayerItem,
+ srcCanvas: HTMLCanvasElement
+ ): { canvas: HTMLCanvasElement; isTemporary: boolean } => {
+ if (!layer.maskCanvas || layer.maskEnabled === false) {
+ return { canvas: srcCanvas, isTemporary: false };
+ }
const masked = document.createElement('canvas');
masked.width = dimensions.width;
masked.height = dimensions.height;
const mCtx = masked.getContext('2d');
const maskCtx = layer.maskCanvas.getContext('2d', { willReadFrequently: true });
- if (!mCtx || !maskCtx) return srcCanvas;
+ if (!mCtx || !maskCtx) {
+ releaseTemporaryCanvas(masked);
+ return { canvas: srcCanvas, isTemporary: false };
+ }
mCtx.drawImage(srcCanvas, 0, 0);
const imgData = mCtx.getImageData(0, 0, dimensions.width, dimensions.height);
const maskData = maskCtx.getImageData(0, 0, dimensions.width, dimensions.height).data;
@@ -88,7 +121,7 @@ export function compositeCanvas(
d[i + 3] = Math.round(d[i + 3] * maskLum);
}
mCtx.putImageData(imgData, 0, 0);
- return masked;
+ return { canvas: masked, isTemporary: true };
};
for (const group of groups) {
@@ -107,9 +140,9 @@ export function compositeCanvas(
continue;
}
- const rawBaseCanvas = layerCanvasesMap.get(baseLayer.id);
- if (!rawBaseCanvas) continue;
- const baseCanvas = getMaskedLayerCanvas(baseLayer, rawBaseCanvas);
+ const baseAcq = acquireLayerExportCanvas(baseLayer.id, dimensions, layerCanvasesMap, tileGrid);
+ if (!baseAcq.canvas) continue;
+ const maskedBase = getMaskedLayerCanvas(baseLayer, baseAcq.canvas);
const activeClipped = group.clippedLayers.filter(
(cl) => cl.type !== 'folder' && cl.type !== 'adjustment' && isLayerEffectivelyVisible(cl)
@@ -119,7 +152,7 @@ export function compositeCanvas(
ctx.save();
ctx.globalAlpha = getEffectiveOpacity(baseLayer);
ctx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- ctx.drawImage(baseCanvas, 0, 0);
+ ctx.drawImage(maskedBase.canvas, 0, 0);
ctx.restore();
} else {
// Group isolated offscreen canvas for base + clipped layers
@@ -127,31 +160,38 @@ export function compositeCanvas(
groupCanvas.width = dimensions.width;
groupCanvas.height = dimensions.height;
const gCtx = groupCanvas.getContext('2d');
- if (!gCtx) continue;
+ if (gCtx) {
+ gCtx.save();
+ gCtx.globalAlpha = getEffectiveOpacity(baseLayer);
+ gCtx.drawImage(maskedBase.canvas, 0, 0);
+ gCtx.restore();
- gCtx.save();
- gCtx.globalAlpha = getEffectiveOpacity(baseLayer);
- gCtx.drawImage(baseCanvas, 0, 0);
- gCtx.restore();
+ for (const clipped of activeClipped) {
+ const clipAcq = acquireLayerExportCanvas(clipped.id, dimensions, layerCanvasesMap, tileGrid);
+ if (!clipAcq.canvas) continue;
+ const maskedClip = getMaskedLayerCanvas(clipped, clipAcq.canvas);
- for (const clipped of activeClipped) {
- const rawClippedCanvas = layerCanvasesMap.get(clipped.id);
- if (!rawClippedCanvas) continue;
- const cCanvas = getMaskedLayerCanvas(clipped, rawClippedCanvas);
+ gCtx.save();
+ gCtx.globalAlpha = getEffectiveOpacity(clipped);
+ gCtx.globalCompositeOperation = 'source-atop';
+ gCtx.drawImage(maskedClip.canvas, 0, 0);
+ gCtx.restore();
- gCtx.save();
- gCtx.globalAlpha = getEffectiveOpacity(clipped);
- gCtx.globalCompositeOperation = 'source-atop';
- gCtx.drawImage(cCanvas, 0, 0);
- gCtx.restore();
- }
+ if (maskedClip.isTemporary) releaseTemporaryCanvas(maskedClip.canvas);
+ if (clipAcq.isTemporary) releaseTemporaryCanvas(clipAcq.canvas);
+ }
- ctx.save();
- ctx.globalAlpha = 1.0;
- ctx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
- ctx.drawImage(groupCanvas, 0, 0);
- ctx.restore();
+ ctx.save();
+ ctx.globalAlpha = 1.0;
+ ctx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ ctx.drawImage(groupCanvas, 0, 0);
+ ctx.restore();
+ }
+ releaseTemporaryCanvas(groupCanvas);
}
+
+ if (maskedBase.isTemporary) releaseTemporaryCanvas(maskedBase.canvas);
+ if (baseAcq.isTemporary) releaseTemporaryCanvas(baseAcq.canvas);
}
return exportCanvas;
@@ -185,46 +225,55 @@ export async function serializeDocument(
extension: string
): Promise<{ data: Blob | ArrayBuffer; mimeType: string }> {
const ext = extension.toLowerCase();
+ const tileGrid = data.tileGrid ?? (data.tabId ? documentStore.getSession(data.tabId)?.tileGrid : documentStore.getActiveTileGrid());
// 1. PSD format with layers (ag-psd expects bottom-to-top order and opacity 0..255)
if (ext === '.psd' || ext === '.psb') {
- const children = data.layers
- .slice()
- .reverse()
- .filter((l) => l.type === 'raster' || l.type === 'vector' || l.type === 'frame')
- .map((layer) => {
- const c = data.layerCanvasesMap.get(layer.id);
- return {
- name: layer.name,
- hidden: !layer.visible,
- opacity: Math.round(Math.max(0, Math.min(1, layer.opacity ?? 1)) * 255),
- blendMode: toAgPsdBlendMode(layer.blendMode),
- canvas: c || undefined,
- };
- });
-
- const dpi = data.dimensions.dpi || 300;
- const { writePsd } = await import('ag-psd');
- const psdBuffer = writePsd({
- width: data.dimensions.width,
- height: data.dimensions.height,
- children,
- imageResources: {
- resolutionInfo: {
- horizontalResolution: dpi,
- horizontalResolutionUnit: 'PPI',
- widthUnit: 'Inches',
- verticalResolution: dpi,
- verticalResolutionUnit: 'PPI',
- heightUnit: 'Inches',
+ const tempCanvases: HTMLCanvasElement[] = [];
+ try {
+ const children = data.layers
+ .slice()
+ .reverse()
+ .filter((l) => l.type === 'raster' || l.type === 'vector' || l.type === 'frame')
+ .map((layer) => {
+ const acq = acquireLayerExportCanvas(layer.id, data.dimensions, data.layerCanvasesMap, tileGrid);
+ if (acq.isTemporary && acq.canvas) tempCanvases.push(acq.canvas);
+ return {
+ name: layer.name,
+ hidden: !layer.visible,
+ opacity: Math.round(Math.max(0, Math.min(1, layer.opacity ?? 1)) * 255),
+ blendMode: toAgPsdBlendMode(layer.blendMode),
+ canvas: acq.canvas || undefined,
+ };
+ });
+
+ const dpi = data.dimensions.dpi || 300;
+ const { writePsd } = await import('ag-psd');
+ const psdBuffer = writePsd({
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ children,
+ imageResources: {
+ resolutionInfo: {
+ horizontalResolution: dpi,
+ horizontalResolutionUnit: 'PPI',
+ widthUnit: 'Inches',
+ verticalResolution: dpi,
+ verticalResolutionUnit: 'PPI',
+ heightUnit: 'Inches',
+ },
},
- },
- });
+ });
- return {
- data: psdBuffer,
- mimeType: 'image/vnd.adobe.photoshop',
- };
+ return {
+ data: psdBuffer,
+ mimeType: 'image/vnd.adobe.photoshop',
+ };
+ } finally {
+ for (const temp of tempCanvases) {
+ releaseTemporaryCanvas(temp);
+ }
+ }
}
// 2. Native Ink Studio Project (.ink, .sora) format
@@ -233,9 +282,10 @@ export async function serializeDocument(
const maskImages: Record<string, string> = {};
const serializableLayers = data.layers.map((l) => {
if (l.type === 'raster' || l.type === 'vector' || l.type === 'frame') {
- const c = data.layerCanvasesMap.get(l.id);
- if (c) {
- layerImages[l.id] = c.toDataURL('image/png');
+ const acq = acquireLayerExportCanvas(l.id, data.dimensions, data.layerCanvasesMap, tileGrid);
+ if (acq.canvas) {
+ layerImages[l.id] = acq.canvas.toDataURL('image/png');
+ if (acq.isTemporary) releaseTemporaryCanvas(acq.canvas);
}
}
if (l.maskCanvas && typeof l.maskCanvas.toDataURL === 'function') {
@@ -271,10 +321,15 @@ export async function serializeDocument(
data.layerCanvasesMap,
data.getEffectiveOpacity,
data.isLayerEffectivelyVisible,
- true // white background for JPEG
+ true, // white background for JPEG
+ tileGrid
);
- const blob = await canvasToBlob(compCanvas, 'image/jpeg', 0.92);
- return { data: blob, mimeType: 'image/jpeg' };
+ try {
+ const blob = await canvasToBlob(compCanvas, 'image/jpeg', 0.92);
+ return { data: blob, mimeType: 'image/jpeg' };
+ } finally {
+ releaseTemporaryCanvas(compCanvas);
+ }
}
// 4. WebP format
@@ -285,10 +340,15 @@ export async function serializeDocument(
data.layerCanvasesMap,
data.getEffectiveOpacity,
data.isLayerEffectivelyVisible,
- false
+ false,
+ tileGrid
);
- const blob = await canvasToBlob(compCanvas, 'image/webp', 0.92);
- return { data: blob, mimeType: 'image/webp' };
+ try {
+ const blob = await canvasToBlob(compCanvas, 'image/webp', 0.92);
+ return { data: blob, mimeType: 'image/webp' };
+ } finally {
+ releaseTemporaryCanvas(compCanvas);
+ }
}
// 5. Default: PNG format
@@ -298,10 +358,15 @@ export async function serializeDocument(
data.layerCanvasesMap,
data.getEffectiveOpacity,
data.isLayerEffectivelyVisible,
- false
+ false,
+ tileGrid
);
- const blob = await canvasToBlob(compCanvas, 'image/png');
- return { data: blob, mimeType: 'image/png' };
+ try {
+ const blob = await canvasToBlob(compCanvas, 'image/png');
+ return { data: blob, mimeType: 'image/png' };
+ } finally {
+ releaseTemporaryCanvas(compCanvas);
+ }
}
/**
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index f14b90e..b95d903 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -620,8 +620,8 @@ export class TauriScratchDiskDriver implements IScratchDiskDriver {
export class InMemoryScratchDiskDriver implements IScratchDiskDriver {
private storage: Map<string, Uint8Array> = new Map();
- public async init(_sessionId: string): Promise<void> {
- this.storage.clear();
+ public async init(sessionId: string): Promise<void> {
+ await this.clear(sessionId);
}
public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
@@ -666,6 +666,7 @@ export interface TileMemoryManagerOptions {
budgetMb?: number;
driver?: IScratchDiskDriver;
sessionId?: string;
+ onMemoryChanged?: () => void;
}
export class TileMemoryManager {
@@ -680,6 +681,7 @@ export class TileMemoryManager {
private inFlightPageIns: Map<string, Promise<Uint8Array>> = new Map();
private evictionPromise: Promise<void> | null = null;
private needsAnotherEvictionPass: boolean = false;
+ private onMemoryChanged?: () => void;
constructor(grid: SparseTileGrid, options?: TileMemoryManagerOptions) {
this.grid = grid;
@@ -687,6 +689,7 @@ export class TileMemoryManager {
this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
this.sessionId = options?.sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
this.driver = options?.driver || createDefaultScratchDiskDriver();
+ this.onMemoryChanged = options?.onMemoryChanged;
void this.driver.init(this.sessionId);
}
@@ -731,14 +734,18 @@ export class TileMemoryManager {
this.activeBytes += tile.data.byteLength;
tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
if (tile.lod === 0) {
- void this.checkBudgetAndEvict();
+ if (this.onMemoryChanged) {
+ this.onMemoryChanged();
+ } else {
+ void this.checkBudgetAndEvict();
+ }
}
}
}
public notifyTileFreed(tile: TileBuffer): void {
if (tile.data !== null) {
- this.activeBytes -= tile.data.byteLength;
+ this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
}
}
@@ -939,7 +946,7 @@ export class TileMemoryManager {
await this.driver.writeTiles(this.sessionId, payloads);
for (const tile of validTiles) {
if (tile.data) {
- this.activeBytes -= tile.data.byteLength;
+ this.activeBytes = Math.max(0, this.activeBytes - tile.data.byteLength);
tile.data = null;
tile.isPagedToDisk = true;
tile.dirty = false;
@@ -948,6 +955,57 @@ export class TileMemoryManager {
}
}
+ /**
+ * Drops all cached LOD > 0 tiles and evicts up to `bytesToFree` of LOD 0 tiles to scratch disk.
+ * Used by DocumentStore to cooperatively reclaim RAM from inactive document tabs.
+ */
+ public async evictBytesToDisk(bytesToFree: number): Promise<number> {
+ if (bytesToFree <= 0 || this.activeBytes <= 0) return 0;
+ let freed = 0;
+
+ // 1. Drop regenerable LOD > 0 tiles first (zero disk I/O)
+ for (const tile of this.grid.getAllTiles()) {
+ if (tile.lod > 0 && tile.data !== null) {
+ const sz = tile.data.byteLength;
+ this.activeBytes = Math.max(0, this.activeBytes - sz);
+ freed += sz;
+ tile.data = null;
+ tile.dirty = true;
+ }
+ }
+
+ if (freed >= bytesToFree) return freed;
+
+ // 2. Evict LOD 0 tiles oldest-first to scratch disk
+ const lod0: TileBuffer[] = [];
+ for (const tile of this.grid.getAllTiles()) {
+ if (tile.lod === 0 && tile.data !== null) {
+ lod0.push(tile);
+ }
+ }
+ lod0.sort((a, b) => a.lastAccessTimestamp - b.lastAccessTimestamp);
+
+ const toEvict: TileBuffer[] = [];
+ for (const tile of lod0) {
+ if (freed >= bytesToFree) break;
+ toEvict.push(tile);
+ freed += tile.data?.byteLength || 0;
+ }
+
+ if (toEvict.length > 0) {
+ await this.evictTiles(toEvict);
+ }
+
+ return freed;
+ }
+
+ /**
+ * Offloads all in-memory tiles of this document to scratch disk.
+ */
+ public async evictAllToDisk(): Promise<number> {
+ return this.evictBytesToDisk(this.activeBytes);
+ }
+
public async clear(): Promise<void> {
this.inFlightPageIns.clear();
this.activeBytes = 0;
@@ -955,6 +1013,21 @@ export class TileMemoryManager {
}
}
+let nextSparseTileGridId = 1;
+
+/**
+ * Releases an HTMLCanvasElement's backing store immediately so Chromium/WebView2 reclaims RAM.
+ */
+export function releaseTemporaryCanvas(canvas: HTMLCanvasElement | null | undefined): void {
+ if (!canvas) return;
+ try {
+ canvas.width = 0;
+ canvas.height = 0;
+ } catch {
+ // Ignore read-only or detached mock canvases in tests
+ }
+}
+
// ============================================================================
// SparseTileGrid
// ============================================================================
@@ -966,6 +1039,7 @@ export class TileMemoryManager {
* Completely deprecates multi-gigabyte full-sized DOM layer canvases.
*/
export class SparseTileGrid {
+ private readonly gridId: number = nextSparseTileGridId++;
private tiles: Map<string, TileBuffer> = new Map();
private layerFormats: Map<string, TileFormat> = new Map();
private ingestedLayers: Set<string> = new Set();
@@ -983,6 +1057,19 @@ export class SparseTileGrid {
this.memoryManager = new TileMemoryManager(this, memoryManagerOptions);
}
+ public getGridId(): number {
+ return this.gridId;
+ }
+
+ public hasLayerTiles(layerId: string): boolean {
+ for (const tile of this.tiles.values()) {
+ if (tile.layerId === layerId && (tile.lod ?? 0) === 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
public getLayerVersion(layerId: string): number {
return this.layerVersions.get(layerId) ?? 0;
}
@@ -1416,14 +1503,93 @@ export class SparseTileGrid {
}
/**
- * Generates a layer thumbnail directly from the sparse tile grid or LOD mipmaps.
- * Completely bypasses full-size canvas allocation.
+ * Allocates a temporary HTMLCanvasElement strictly sized to `rect` and populates it from tiles.
+ * Caller must release it via `releaseTemporaryCanvas(canvas)` when finished.
+ */
+ public createRegionCanvas(
+ layerId: string,
+ rect: { x: number; y: number; width: number; height: number }
+ ): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || rect.width <= 0 || rect.height <= 0) return null;
+ const w = Math.max(1, Math.ceil(rect.width));
+ const h = Math.max(1, Math.ceil(rect.height));
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return canvas;
+
+ if (this.hasLayerTiles(layerId)) {
+ const region = this.readImageData(layerId, Math.floor(rect.x), Math.floor(rect.y), w, h);
+ if (typeof ImageData !== 'undefined') {
+ const imgData = new ImageData(new Uint8ClampedArray(region.data.buffer as ArrayBuffer, region.data.byteOffset, region.data.byteLength), w, h);
+ ctx.putImageData(imgData, 0, 0);
+ }
+ }
+ return canvas;
+ }
+
+ /**
+ * Materializes a full-layer temporary HTMLCanvasElement from tiles (for export/filters).
+ * Caller MUST release it immediately after use via `releaseTemporaryCanvas(canvas)`.
+ */
+ public exportLayerToCanvas(layerId: string, width: number, height: number): HTMLCanvasElement | null {
+ if (typeof document === 'undefined' || width <= 0 || height <= 0) return null;
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ if (this.hasLayerTiles(layerId)) {
+ this.renderLayerToCanvas(layerId, canvas);
+ }
+ return canvas;
+ }
+
+ /**
+ * Ensures LOD 3 mipmap tiles exist and are up-to-date for all populated regions of `layerId`.
+ */
+ public getOrBuildLod3Tiles(layerId: string): TileBuffer[] {
+ const lod3Coords = new Map<string, { tx: number; ty: number }>();
+
+ for (const tile of this.tiles.values()) {
+ if (tile.layerId !== layerId) continue;
+ if ((tile.lod ?? 0) === 0) {
+ const l3x = tile.tileX >> 3;
+ const l3y = tile.tileY >> 3;
+ const k = `${l3x}:${l3y}`;
+ if (!lod3Coords.has(k)) {
+ lod3Coords.set(k, { tx: l3x, ty: l3y });
+ }
+ } else if (tile.lod === 3) {
+ const k = `${tile.tileX}:${tile.tileY}`;
+ if (!lod3Coords.has(k)) {
+ lod3Coords.set(k, { tx: tile.tileX, ty: tile.tileY });
+ }
+ }
+ }
+
+ const result: TileBuffer[] = [];
+ for (const { tx, ty } of lod3Coords.values()) {
+ let tile = this.getTile(layerId, tx, ty, 3);
+ if (!tile || tile.data === null || this.isLodTileDirty(layerId, tx, ty, 3)) {
+ tile = this.generateLodTile(layerId, tx, ty, 3);
+ }
+ if (tile && tile.data !== null) {
+ result.push(tile);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Generates a layer thumbnail directly from LOD 3 mipmap tiles (1/8 resolution: 2048px per tile).
+ * Completely bypasses full-size canvas allocation and full-resolution pixel reads.
*/
public generateThumbnail(
layerId: string,
thumbWidth: number,
thumbHeight: number,
- docDimensions: { width: number; height: number }
+ docDimensions: { width: number; height: number },
+ preserveAlpha: boolean = true
): string {
if (typeof document === 'undefined') return '';
if (!this.thumbCanvas) {
@@ -1435,26 +1601,28 @@ export class SparseTileGrid {
const ctx = canvas.getContext('2d');
if (!ctx) return '';
- ctx.clearRect(0, 0, thumbWidth, thumbHeight);
-
const docW = Math.max(1, docDimensions.width);
const docH = Math.max(1, docDimensions.height);
- // Sample directly from LOD 0 tiles without flushing full mipmap pyramids
- let renderLod = 0;
- let tiles = this.getLayerTiles(layerId, 0);
- if (tiles.length === 0) {
- renderLod = 3;
- tiles = this.getLayerTiles(layerId, 3);
- }
+ const tiles = this.getOrBuildLod3Tiles(layerId);
if (tiles.length === 0) {
- return canvas.toDataURL('image/png');
+ if (preserveAlpha) {
+ ctx.clearRect(0, 0, thumbWidth, thumbHeight);
+ return canvas.toDataURL('image/png');
+ }
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, thumbWidth, thumbHeight);
+ return canvas.toDataURL('image/jpeg', 0.65);
}
- const lodDocSize = TILE_SIZE << renderLod;
+ const renderLod = 3;
+ const lodDocSize = TILE_SIZE << renderLod; // 2048 document pixels per LOD 3 tile
const thumbImg = ctx.createImageData(thumbWidth, thumbHeight);
const outData = thumbImg.data;
+ if (!preserveAlpha) {
+ outData.fill(255);
+ }
const scaleX = docW / thumbWidth;
const scaleY = docH / thumbHeight;
@@ -1490,19 +1658,29 @@ export class SparseTileGrid {
else if (rgba[alt3 + 3] > 0) srcIdx = alt3;
}
- if (rgba[srcIdx + 3] > 0) {
+ const sa = rgba[srcIdx + 3];
+ if (sa > 0) {
const dstIdx = (py * thumbWidth + px) * 4;
- outData[dstIdx] = rgba[srcIdx];
- outData[dstIdx + 1] = rgba[srcIdx + 1];
- outData[dstIdx + 2] = rgba[srcIdx + 2];
- outData[dstIdx + 3] = rgba[srcIdx + 3];
+ if (preserveAlpha || sa === 255) {
+ outData[dstIdx] = rgba[srcIdx];
+ outData[dstIdx + 1] = rgba[srcIdx + 1];
+ outData[dstIdx + 2] = rgba[srcIdx + 2];
+ outData[dstIdx + 3] = sa;
+ } else {
+ const a = sa / 255;
+ const inv = 1 - a;
+ outData[dstIdx] = Math.round(rgba[srcIdx] * a + 255 * inv);
+ outData[dstIdx + 1] = Math.round(rgba[srcIdx + 1] * a + 255 * inv);
+ outData[dstIdx + 2] = Math.round(rgba[srcIdx + 2] * a + 255 * inv);
+ outData[dstIdx + 3] = 255;
+ }
}
}
}
}
ctx.putImageData(thumbImg, 0, 0);
- return canvas.toDataURL('image/png');
+ return preserveAlpha ? canvas.toDataURL('image/png') : canvas.toDataURL('image/jpeg', 0.65);
}
// ==========================================================================
@@ -1647,6 +1825,113 @@ export class SparseTileGrid {
}
}
+ public fillLayerSolidColor(
+ layerId: string,
+ width: number,
+ height: number,
+ colorCss: string,
+ format?: TileFormat
+ ): void {
+ const lower = (colorCss || '').trim().toLowerCase();
+ if (!lower || lower === 'transparent') {
+ this.clearLayer(layerId);
+ this.ingestedLayers.add(layerId);
+ if (format) this.setLayerFormat(layerId, format);
+ return;
+ }
+ if (lower === '#ffffff' || lower === '#fff' || lower === 'white') {
+ this.fillLayerSolidWhite(layerId, width, height, format);
+ return;
+ }
+
+ let r = 255, g = 255, b = 255, a = 255;
+ if (lower.startsWith('#')) {
+ const hex = lower.slice(1);
+ if (hex.length === 3) {
+ r = parseInt(hex[0] + hex[0], 16) || 0;
+ g = parseInt(hex[1] + hex[1], 16) || 0;
+ b = parseInt(hex[2] + hex[2], 16) || 0;
+ } else if (hex.length >= 6) {
+ r = parseInt(hex.slice(0, 2), 16) || 0;
+ g = parseInt(hex.slice(2, 4), 16) || 0;
+ b = parseInt(hex.slice(4, 6), 16) || 0;
+ if (hex.length === 8) {
+ a = parseInt(hex.slice(6, 8), 16) || 255;
+ }
+ }
+ } else if (lower === 'black') {
+ r = 0; g = 0; b = 0;
+ }
+
+ this.clearLayer(layerId);
+ this.ingestedLayers.add(layerId);
+ if (format) this.setLayerFormat(layerId, format);
+ if (width <= 0 || height <= 0) return;
+
+ const targetFormat = format || this.getLayerFormat(layerId);
+ const pixelU32 = isLittleEndian
+ ? ((a << 24) | (b << 16) | (g << 8) | r) >>> 0
+ : ((r << 24) | (g << 16) | (b << 8) | a) >>> 0;
+ const grayVal = Math.round((r * 299 + g * 587 + b * 114) / 1000);
+ const isInk1Bit = a >= 24 && grayVal < 128;
+
+ if (targetFormat === 'monochrome-1bit' && !isInk1Bit) {
+ this.notifyChange();
+ return;
+ }
+
+ const maxTileX = pixelToTileCoord(width - 1, 0);
+ const maxTileY = pixelToTileCoord(height - 1, 0);
+
+ for (let ty = 0; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const validH = Math.min(TILE_SIZE, height - tileDocY);
+ for (let tx = 0; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, width - tileDocX);
+ const tile = this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ if (!tile.data) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ this.memoryManager?.notifyTileAllocated(tile);
+ }
+ if (tile.format === 'color-32bit') {
+ const dst32 = new Uint32Array(tile.data.buffer, tile.data.byteOffset, TILE_PIXELS);
+ if (validW === TILE_SIZE && validH === TILE_SIZE) {
+ dst32.fill(pixelU32);
+ } else {
+ dst32.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ dst32.fill(pixelU32, rowStart, rowStart + validW);
+ }
+ }
+ } else if (tile.format === 'grayscale-8bit') {
+ if (validW === TILE_SIZE && validH === TILE_SIZE) {
+ tile.data.fill(grayVal);
+ } else {
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ tile.data.fill(grayVal, rowStart, rowStart + validW);
+ }
+ }
+ } else {
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ for (let x = 0; x < validW; x++) {
+ setPixel1Bit(tile.data, x, y, true);
+ }
+ }
+ }
+ tile.dirty = true;
+ tile.version++;
+ this.markLodAncestorsDirty(layerId, tx, ty);
+ }
+ }
+ this.bumpLayerVersion(layerId);
+ this.notifyChange();
+ }
+
public fillLayerSolidWhite(layerId: string, width: number, height: number, format?: TileFormat): void {
this.clearLayer(layerId);
this.ingestedLayers.add(layerId);
@@ -1839,6 +2124,23 @@ export class SparseTileGrid {
};
}
+ public snapshotLayerTiles(
+ layerId: string
+ ): Map<string, { format: TileFormat; data: Uint8Array | null }> {
+ const snapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
+ for (const tile of this.getLayerTiles(layerId, 0)) {
+ const key = getTileKey(layerId, tile.tileX, tile.tileY, 0);
+ if (tile.data) {
+ const copy = new Uint8Array(tile.data.length);
+ copy.set(tile.data);
+ snapshot.set(key, { format: tile.format, data: copy });
+ } else {
+ snapshot.set(key, { format: tile.format, data: null });
+ }
+ }
+ return snapshot;
+ }
+
public snapshotTilesInRect(
layerId: string,
bounds: { x: number; y: number; width: number; height: number }
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
index a1a5eb1..586e7f4 100644
--- a/src/utils/undoCache.ts
+++ b/src/utils/undoCache.ts
@@ -61,6 +61,26 @@ export class UndoCacheManager {
return this.sessionId;
}
+ public getDocumentId(): string {
+ return this.sessionId;
+ }
+
+ public getRamStepCount(): number {
+ return this.ramItems.size;
+ }
+
+ public getDiskCachedCount(): number {
+ return this.diskCachedIds.size;
+ }
+
+ public getCompressedRamCount(): number {
+ return this.compressedRamCache.size;
+ }
+
+ public isOffloaded(itemId: string): boolean {
+ return this.diskCachedIds.has(itemId) || this.compressedRamCache.has(itemId);
+ }
+
/**
* Prunes orphaned history IDs evicted by redo branching or the 50-step cap.
*/
@@ -83,23 +103,45 @@ export class UndoCacheManager {
/**
* Register a history item and enforce the in-memory LRU budget.
*/
- public async registerStep(item: HistoryItem, allHistory: HistoryItem[]): Promise<void> {
+ public async registerStep(
+ item: HistoryItem,
+ allHistory: HistoryItem[],
+ maxRamSteps: number = MAX_RAM_UNDO_STEPS
+ ): Promise<void> {
this.pruneOrphanedIds(allHistory);
if (!item.tileDeltas || item.tileDeltas.length === 0) return;
this.ramItems.add(item.id);
- if (this.ramItems.size > MAX_RAM_UNDO_STEPS) {
+ if (this.ramItems.size > maxRamSteps) {
for (const oldItem of allHistory) {
if (oldItem.id !== item.id && this.ramItems.has(oldItem.id) && oldItem.tileDeltas) {
await this.offloadToDisk(oldItem);
this.ramItems.delete(oldItem.id);
- if (this.ramItems.size <= MAX_RAM_UNDO_STEPS) break;
+ if (this.ramItems.size <= maxRamSteps) break;
}
}
}
}
+ /**
+ * Offloads all in-RAM tile deltas for this document to scratch disk (or compressed cache).
+ * Used when switching away from a document tab or when reclaiming shared RAM budget.
+ */
+ public async offloadAllToDisk(allHistory: HistoryItem[], maxCount?: number): Promise<number> {
+ this.pruneOrphanedIds(allHistory);
+ let offloaded = 0;
+ 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++;
+ }
+ }
+ return offloaded;
+ }
+
/**
* Offload a single history item's tile deltas to disk via Tauri IPC (with fast zlib compression),
* or to a compact zlib-compressed RAM buffer when running in a browser environment.
@@ -118,6 +160,7 @@ export class UndoCacheManager {
data: compressed,
});
this.diskCachedIds.add(item.id);
+ this.ramItems.delete(item.id);
item.tileDeltas = undefined;
return;
} catch (err) {
@@ -126,6 +169,7 @@ export class UndoCacheManager {
}
this.compressedRamCache.set(item.id, compressed);
+ this.ramItems.delete(item.id);
item.tileDeltas = undefined;
}