A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { BrushSettings, CanvasDimensions, LayerItem, ToolType } from '../types/editor';
import { isBackgroundLayerId } from './drawing/types';
import { CanvasNavigationHandle } from './useCanvasNavigation';
import {
selectIsAnyModalOpen,
useDocumentStore,
useToolStore,
useUiStore,
useUpdaterStore,
useWorkspaceStore,
} from '../stores';
import {
DEFAULT_INTERFACE_SCALE,
INTERFACE_SCALE_APPLIED_EVENT,
} from '../utils/interfaceScale';
import {
canNativeEngineHandleBrush,
classifyNativeTool,
clearNativeCanvas,
initNativeEngineBridge,
isNativeCanvasActive,
isNativeStrokeTool,
NativeUiRect,
NativeWheelNavMode,
parseCssColorToRgba,
setNativeAppearance,
setNativeCamera,
setNativeCursor,
setNativeDocument,
setNativeMaskMode,
setNativeOccludedRects,
setNativePolicy,
setNativePressureCurve,
setNativeRulers,
setNativeViewport,
subscribeNativeCamera,
subscribeNativeCanvasActive,
subscribeNativePointerStat,
subscribeNativeViewportInvalidated,
syncNativeFullBrushConfig,
} from '../utils/nativeEngineBridge';
import { recoveryService } from '../services/recoveryService';
export interface UseNativeEngineViewportParams {
viewportRef: React.RefObject<HTMLDivElement | null>;
navigation?: CanvasNavigationHandle;
dimensions: CanvasDimensions;
showCheckerboard: boolean;
hasOpenDocument: boolean;
tool: ToolType;
brushSettings: BrushSettings;
primaryColor: string;
activeLayer?: LayerItem | null;
isMaskMode?: boolean;
isSquare: boolean;
thicknessRatio: number;
thicknessVertical: boolean;
tipAngleDeg: number;
isResizingBrush: boolean;
isSpaceDown: boolean;
isPanning: boolean;
isRotating: boolean;
isZoomDragging: boolean;
isRotateModifier: boolean;
pan: { x: number; y: number };
zoom: number;
rotation: number;
flipX: boolean;
flipY: boolean;
}
const OCCLUDER_SELECTOR = [
'[data-native-occluder="true"]',
'[role="dialog"]',
'[aria-modal="true"]',
'[role="menu"]',
'[role="listbox"]',
'[data-chrome-floating="true"]',
'[data-testid="floating-brush-pill"]',
'[data-testid="quick-brush-panel"]',
'[data-testid="collab-room-overlay"]',
'[data-testid="collab-follow-banner"]',
'[data-testid^="focus-hud"]',
'[data-testid*="popover"]',
'[data-testid*="modal"]',
'[data-testid*="context-menu"]',
'[data-testid*="dropdown"]',
'.shadow-ui-popover',
].join(',');
const OCCLUDER_MUTATION_THROTTLE_MS = 80;
const MODAL_SELECTOR = '[role="dialog"],[aria-modal="true"],[data-testid*="modal"]';
const IGNORED_MUTATION_ANCESTOR_SELECTOR = [
'[data-testid="status-bar"]',
'[data-chrome-bar="status"]',
'[data-testid="native-gpu-perf-hud"]',
'[data-testid="canvas-interaction-surface"]',
'[data-testid="brush-cursor-ring"]',
'[data-testid="canvas-artboard"]',
].join(',');
function isElementNode(node: Node | null | undefined): node is Element {
return Boolean(node && node.nodeType === 1);
}
function getAttrSafe(el: Element, name: string): string | null {
return typeof el.getAttribute === 'function' ? el.getAttribute(name) : null;
}
function isIgnoredMutationTarget(node: Node | null | undefined): boolean {
if (!isElementNode(node)) return false;
if (typeof node.closest === 'function') {
return Boolean(node.closest(IGNORED_MUTATION_ANCESTOR_SELECTOR));
}
let cur: Node | null = node;
while (isElementNode(cur)) {
const tid = getAttrSafe(cur, 'data-testid');
if (
tid === 'status-bar' ||
tid === 'native-gpu-perf-hud' ||
tid === 'canvas-interaction-surface' ||
tid === 'brush-cursor-ring' ||
tid === 'canvas-artboard' ||
getAttrSafe(cur, 'data-chrome-bar') === 'status'
) {
return true;
}
cur = cur.parentNode;
}
return false;
}
function matchesModalElement(el: Element): boolean {
if (typeof el.matches === 'function') {
try {
if (el.matches(MODAL_SELECTOR)) return true;
} catch {
// Fall through to attribute check
}
}
const role = getAttrSafe(el, 'role');
const ariaModal = getAttrSafe(el, 'aria-modal');
const tid = getAttrSafe(el, 'data-testid') || '';
return role === 'dialog' || ariaModal === 'true' || tid.includes('modal');
}
function matchesOccluderElement(el: Element): boolean {
if (typeof el.matches === 'function') {
try {
if (el.matches(OCCLUDER_SELECTOR)) return true;
} catch {
// Fall through to attribute check
}
}
if (
getAttrSafe(el, 'data-native-occluder') === 'true' ||
getAttrSafe(el, 'data-chrome-floating') === 'true' ||
getAttrSafe(el, 'aria-modal') === 'true'
) {
return true;
}
const role = getAttrSafe(el, 'role');
if (role === 'dialog' || role === 'menu' || role === 'listbox') return true;
const tid = getAttrSafe(el, 'data-testid') || '';
if (
tid === 'floating-brush-pill' ||
tid === 'quick-brush-panel' ||
tid === 'collab-room-overlay' ||
tid === 'collab-follow-banner' ||
tid.startsWith('focus-hud') ||
tid.includes('popover') ||
tid.includes('modal') ||
tid.includes('context-menu') ||
tid.includes('dropdown')
) {
return true;
}
return false;
}
function hasOccluderAncestor(el: Element): boolean {
if (typeof el.closest === 'function') {
try {
return Boolean(el.closest(OCCLUDER_SELECTOR));
} catch {
// Fall through
}
}
let cur: Node | null = el;
while (isElementNode(cur)) {
if (matchesOccluderElement(cur)) return true;
cur = cur.parentNode;
}
return false;
}
function nodeContainsOccluder(node: Node): { occluder: boolean; modal: boolean } {
if (!isElementNode(node)) return { occluder: false, modal: false };
const directModal = matchesModalElement(node);
if (directModal) return { occluder: true, modal: true };
const directOccluder = matchesOccluderElement(node);
if (typeof node.querySelector === 'function') {
try {
if (node.querySelector(MODAL_SELECTOR)) return { occluder: true, modal: true };
if (directOccluder || node.querySelector(OCCLUDER_SELECTOR)) {
return { occluder: true, modal: false };
}
} catch {
// Fall through
}
}
return { occluder: directOccluder, modal: false };
}
/**
* Filters `document.body` MutationRecords so high-frequency DOM writes (StatusBar 30 Hz
* pressure bar, cursor ring, artboard transforms, perf HUD) NEVER trigger `querySelectorAll`
* + `getComputedStyle` + `getBoundingClientRect` forced reflows.
*/
export function classifyOccluderMutations(
records?: ReadonlyArray<MutationRecord>
): { shouldScan: boolean; isModalEvent: boolean } {
if (!records || records.length === 0) {
return { shouldScan: true, isModalEvent: false };
}
let shouldScan = false;
let isModalEvent = false;
for (let i = 0; i < records.length; i++) {
const rec = records[i];
if (!rec) continue;
if (rec.type === 'attributes') {
if (rec.attributeName === 'style') continue;
if (isIgnoredMutationTarget(rec.target)) continue;
if (rec.attributeName === 'aria-modal') {
shouldScan = true;
isModalEvent = true;
break;
}
if (
rec.attributeName === 'data-native-occluder' ||
rec.attributeName === 'data-chrome-floating'
) {
shouldScan = true;
continue;
}
if (isElementNode(rec.target) && hasOccluderAncestor(rec.target)) {
shouldScan = true;
if (matchesModalElement(rec.target)) {
isModalEvent = true;
break;
}
}
} else if (rec.type === 'childList') {
if (isIgnoredMutationTarget(rec.target)) continue;
const checkList = (nodes: NodeList | undefined) => {
if (!nodes) return;
for (let j = 0; j < nodes.length; j++) {
const res = nodeContainsOccluder(nodes[j]);
if (res.occluder) shouldScan = true;
if (res.modal) {
isModalEvent = true;
return;
}
}
};
checkList(rec.addedNodes);
if (isModalEvent) break;
checkList(rec.removedNodes);
if (isModalEvent) break;
if (!shouldScan && isElementNode(rec.target) && hasOccluderAncestor(rec.target)) {
shouldScan = true;
}
}
}
return { shouldScan, isModalEvent };
}
const PHYS_EDGE_EPS = 1e-3;
/**
* Converts a CSS DOMRect into integer physical pixel bounds with outward epsilon-guarded
* floor/ceil rounding so fractional DPR (`1.25`, `1.5`) and WebView zoom (`0.85..1.25`)
* never leave 1px transparent cutout border seams while preserving exact integer bounds.
*/
export function computePhysicalPixelRect(
rect: { left: number; top: number; right: number; bottom: number },
dpr: number
): { xPx: number; yPx: number; widthPx: number; heightPx: number } {
const safeDpr = Number.isFinite(dpr) && dpr > 0.05 ? dpr : 1;
const xPx = Math.max(0, Math.floor(rect.left * safeDpr + PHYS_EDGE_EPS));
const yPx = Math.max(0, Math.floor(rect.top * safeDpr + PHYS_EDGE_EPS));
const rightPx = Math.max(xPx, Math.ceil(rect.right * safeDpr - PHYS_EDGE_EPS));
const bottomPx = Math.max(yPx, Math.ceil(rect.bottom * safeDpr - PHYS_EDGE_EPS));
return {
xPx,
yPx,
widthPx: Math.max(0, rightPx - xPx),
heightPx: Math.max(0, bottomPx - yPx),
};
}
function isEditableElement(el: Element | null): boolean {
if (!el) return false;
const tag = el.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
return Boolean((el as HTMLElement).isContentEditable);
}
export function useNativeEngineViewport({
viewportRef,
navigation,
dimensions,
showCheckerboard,
hasOpenDocument,
tool,
brushSettings,
primaryColor,
activeLayer,
isMaskMode = false,
isSquare,
thicknessRatio,
thicknessVertical,
tipAngleDeg,
isResizingBrush,
isSpaceDown,
isPanning,
isRotating,
isZoomDragging,
isRotateModifier,
pan,
zoom,
rotation,
flipX,
flipY,
}: UseNativeEngineViewportParams) {
const [nativeActive, setNativeActive] = useState<boolean>(() => isNativeCanvasActive());
const [textInputFocused, setTextInputFocused] = useState<boolean>(false);
const [workspaceInteracting, setWorkspaceInteracting] = useState<boolean>(false);
const [hasDomModal, setHasDomModal] = useState<boolean>(false);
const appView = useUiStore((s) => s.appView);
const interfaceScale = useUiStore(
(s) => s.appSettings.interfaceScale ?? DEFAULT_INTERFACE_SCALE
);
const themePreset = useUiStore((s) => s.appSettings.themePreset);
const appearance = useUiStore((s) => s.appSettings.appearance);
const wheelModeRaw = useUiStore((s) => s.appSettings.modifierKeys?.mouseWheel ?? 'zoom');
const globalPressureCurve = useUiStore((s) => s.appSettings.pressureCurve);
const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);
const isUpdaterModalOpen = useUpdaterStore((s) => s.isModalOpen);
const isUiModalOpen = useUiStore(
(s) =>
selectIsAnyModalOpen(s) ||
s.isBrushStudioModalOpen ||
s.isAppearanceStudioOpen ||
s.is3DLayerOpen
);
const isModalOpen = isUiModalOpen || isUpdaterModalOpen || hasDomModal;
const isWorkspaceVisible = hasOpenDocument && appView === 'workspace';
const secondaryColor = useToolStore((s) => s.secondaryColor);
const straightRuler = useDocumentStore((s) => s.straightRuler);
const perspectiveRuler = useDocumentStore((s) => s.perspectiveRuler);
const openPopover = useWorkspaceStore((s) => s.openPopover);
const floatingPanelsCount = useWorkspaceStore((s) => s.layout.floatingPanels?.length ?? 0);
const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
const nativeActiveRef = useRef(nativeActive);
nativeActiveRef.current = nativeActive;
const applyingNativeCameraRef = useRef(false);
const lastViewportSigRef = useRef<string>('');
const lastOccludedSigRef = useRef<string>('');
const lastBrushSyncSigRef = useRef<string>('');
const lastRulerSyncSigRef = useRef<string>('');
const lastPressureCurveSigRef = useRef<string>('');
const nativeStrokeOwned =
nativeActive &&
isWorkspaceVisible &&
canNativeEngineHandleBrush(tool, brushSettings, activeLayer, isMaskMode);
// Detect native Windows DX12 DirectComposition engine once on desktop
useEffect(() => {
let mounted = true;
const unsub = subscribeNativeCanvasActive((active) => {
if (mounted) setNativeActive(active);
});
void initNativeEngineBridge().then((active) => {
if (mounted) {
setNativeActive(active);
}
});
return () => {
mounted = false;
unsub();
};
}, []);
// Toggle transparent WebView2 cutout attribute on :root strictly while workspace document is visible
useEffect(() => {
if (typeof document === 'undefined' || !document.documentElement) return;
const root = document.documentElement;
if (nativeActive && isWorkspaceVisible) {
if (typeof root.setAttribute === 'function') {
root.setAttribute('data-native-canvas', 'true');
} else if (root.dataset) {
root.dataset.nativeCanvas = 'true';
}
} else if (typeof root.removeAttribute === 'function') {
root.removeAttribute('data-native-canvas');
} else if (root.dataset) {
delete root.dataset.nativeCanvas;
}
return () => {
if (typeof document !== 'undefined' && document.documentElement) {
const el = document.documentElement;
if (typeof el.removeAttribute === 'function') {
el.removeAttribute('data-native-canvas');
} else if (el.dataset) {
delete el.dataset.nativeCanvas;
}
}
};
}, [nativeActive, isWorkspaceVisible]);
// Hide DirectComposition visual whenever appView !== 'workspace' or !hasOpenDocument
useEffect(() => {
if (!nativeActive || isWorkspaceVisible) return;
lastViewportSigRef.current = '';
lastOccludedSigRef.current = '';
void setNativeViewport({
xPx: 0,
yPx: 0,
widthPx: 0,
heightPx: 0,
dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
visible: false,
});
}, [nativeActive, isWorkspaceVisible]);
// Always hide DirectComposition visual when CanvasArea unmounts (e.g. switching to WelcomeScreen)
useEffect(() => {
return () => {
if (!nativeActiveRef.current) return;
lastViewportSigRef.current = '';
lastOccludedSigRef.current = '';
void setNativeViewport({
xPx: 0,
yPx: 0,
widthPx: 0,
heightPx: 0,
dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
visible: false,
});
};
}, []);
// Track text-input focus and workspace splitter/drag guard on document
useEffect(() => {
if (!nativeActive || typeof document === 'undefined') return;
const syncFocus = () => setTextInputFocused(isEditableElement(document.activeElement));
syncFocus();
document.addEventListener('focusin', syncFocus, true);
document.addEventListener('focusout', syncFocus, true);
const root = document.documentElement;
const syncWorkspace = () => {
setWorkspaceInteracting(root.getAttribute('data-workspace-interacting') === 'true');
};
syncWorkspace();
const attrObserver = new MutationObserver(syncWorkspace);
attrObserver.observe(root, {
attributes: true,
attributeFilter: ['data-workspace-interacting'],
});
return () => {
document.removeEventListener('focusin', syncFocus, true);
document.removeEventListener('focusout', syncFocus, true);
attrObserver.disconnect();
};
}, [nativeActive]);
// Observe canvas viewport physical bounds (ResizeObserver + DPR + interfaceScale + WM_DPICHANGED + layout)
// AND occluded UI rects (modals, popovers, dropdowns, context menus, FloatingBrushPill, floating docks)
useEffect(() => {
if (!nativeActive || !isWorkspaceVisible) {
setHasDomModal(false);
return;
}
const viewport = viewportRef.current;
if (!viewport || typeof window === 'undefined') return;
let rafId: number | null = null;
let throttleTimer: ReturnType<typeof setTimeout> | null = null;
let lastOccluderScanMs = 0;
let deferredAfterDrawing = false;
let dprMql: MediaQueryList | null = null;
let scaleTimer: ReturnType<typeof setTimeout> | null = null;
let settleTimer: ReturnType<typeof setTimeout> | null = null;
const pushViewportAndOccluders = () => {
rafId = null;
lastOccluderScanMs = typeof performance !== 'undefined' ? performance.now() : Date.now();
const vp = viewportRef.current;
if (!vp) return;
const dpr = window.devicePixelRatio || 1;
const rect = vp.getBoundingClientRect();
const { xPx: leftPx, yPx: topPx, widthPx, heightPx } = computePhysicalPixelRect(rect, dpr);
const visible = widthPx > 0 && heightPx > 0;
const vpSig = `${leftPx},${topPx},${widthPx},${heightPx},${dpr.toFixed(4)},${visible ? 1 : 0}`;
if (vpSig !== lastViewportSigRef.current) {
lastViewportSigRef.current = vpSig;
void setNativeViewport({
xPx: leftPx,
yPx: topPx,
widthPx,
heightPx,
dpr,
visible,
});
}
// Compute physical-pixel UI occlusion rects overlapping the canvas viewport
const occluded: NativeUiRect[] = [];
let occSig = '';
let detectedDomModal = false;
if (visible) {
const nodes = document.querySelectorAll(OCCLUDER_SELECTOR);
for (let i = 0; i < nodes.length; i++) {
const el = nodes[i] as HTMLElement;
if (!el || el === vp) continue;
const style = window.getComputedStyle(el);
if (
style.display === 'none' ||
style.visibility === 'hidden' ||
style.pointerEvents === 'none' ||
parseFloat(style.opacity || '1') <= 0.01
) {
continue;
}
const r = el.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) continue;
if (el.getAttribute('aria-modal') === 'true') {
detectedDomModal = true;
}
// Only include elements that overlap the viewport bounds
if (
r.right <= rect.left ||
r.left >= rect.right ||
r.bottom <= rect.top ||
r.top >= rect.bottom
) {
continue;
}
const { xPx: x, yPx: y, widthPx: w, heightPx: h } = computePhysicalPixelRect(r, dpr);
if (w > 0 && h > 0) {
occluded.push({ x, y, width: w, height: h });
occSig += `${x},${y},${w},${h};`;
}
}
}
setHasDomModal((prev) => (prev === detectedDomModal ? prev : detectedDomModal));
if (occSig !== lastOccludedSigRef.current) {
lastOccludedSigRef.current = occSig;
void setNativeOccludedRects(occluded);
}
};
const scheduleSync = () => {
if (rafId !== null) return;
rafId = requestAnimationFrame(pushViewportAndOccluders);
};
const scheduleThrottledOccluderSync = (isModalEvent: boolean) => {
// Skip routine occluder rescans during active strokes unless a modal opens
if (recoveryService.getIsDrawingActive() && !isModalEvent) {
deferredAfterDrawing = true;
return;
}
if (isModalEvent) {
if (throttleTimer !== null) {
clearTimeout(throttleTimer);
throttleTimer = null;
}
scheduleSync();
return;
}
const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
const elapsed = now - lastOccluderScanMs;
if (elapsed >= OCCLUDER_MUTATION_THROTTLE_MS) {
if (throttleTimer !== null) {
clearTimeout(throttleTimer);
throttleTimer = null;
}
scheduleSync();
return;
}
if (throttleTimer === null) {
throttleTimer = setTimeout(() => {
throttleTimer = null;
if (recoveryService.getIsDrawingActive()) {
deferredAfterDrawing = true;
return;
}
scheduleSync();
}, Math.max(16, OCCLUDER_MUTATION_THROTTLE_MS - elapsed));
}
};
const forceResyncWithSettle = () => {
lastViewportSigRef.current = '';
lastOccludedSigRef.current = '';
scheduleSync();
if (settleTimer !== null) clearTimeout(settleTimer);
settleTimer = setTimeout(() => {
settleTimer = null;
lastViewportSigRef.current = '';
scheduleSync();
}, 60);
};
const handleDprChange = () => {
forceResyncWithSettle();
attachDprListener();
};
const attachDprListener = () => {
if (dprMql) {
dprMql.removeEventListener?.('change', handleDprChange);
dprMql = null;
}
if (typeof window.matchMedia === 'function') {
const cur = window.devicePixelRatio || 1;
dprMql = window.matchMedia(`(resolution: ${cur}dppx)`);
dprMql.addEventListener?.('change', handleDprChange);
}
};
pushViewportAndOccluders();
attachDprListener();
// Re-sync after async Tauri setZoom() settles when interfaceScale changes
scaleTimer = setTimeout(forceResyncWithSettle, 80);
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(scheduleSync) : null;
ro?.observe(viewport);
if (document.body) {
ro?.observe(document.body);
}
const mo = new MutationObserver((records) => {
const { shouldScan, isModalEvent } = classifyOccluderMutations(records);
if (!shouldScan) return;
scheduleThrottledOccluderSync(isModalEvent);
});
// Do NOT observe `style` mutations across `document.body` — StatusBar 30 Hz pressure bars,
// cursor rings, and artboard pan/zoom transforms would otherwise cause 30–60 Hz forced reflows!
mo.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: [
'class',
'role',
'aria-modal',
'data-native-occluder',
'data-chrome-floating',
],
});
const unsubDrawing = recoveryService.subscribeDrawingActive((active) => {
if (!active && deferredAfterDrawing) {
deferredAfterDrawing = false;
scheduleSync();
}
});
const unsubInvalidated = subscribeNativeViewportInvalidated(forceResyncWithSettle);
window.addEventListener('resize', scheduleSync);
window.addEventListener(INTERFACE_SCALE_APPLIED_EVENT, forceResyncWithSettle);
window.visualViewport?.addEventListener('resize', scheduleSync);
return () => {
if (rafId !== null) cancelAnimationFrame(rafId);
if (throttleTimer !== null) clearTimeout(throttleTimer);
if (scaleTimer !== null) clearTimeout(scaleTimer);
if (settleTimer !== null) clearTimeout(settleTimer);
dprMql?.removeEventListener?.('change', handleDprChange);
ro?.disconnect();
mo.disconnect();
unsubDrawing();
unsubInvalidated();
window.removeEventListener('resize', scheduleSync);
window.removeEventListener(INTERFACE_SCALE_APPLIED_EVENT, forceResyncWithSettle);
window.visualViewport?.removeEventListener('resize', scheduleSync);
};
}, [
nativeActive,
isWorkspaceVisible,
viewportRef,
interfaceScale,
palettesHidden,
floatingPanelsCount,
openPopover,
isUiModalOpen,
isUpdaterModalOpen,
workspaceInteracting,
]);
// Sync document size
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
void setNativeDocument(dimensions.width, dimensions.height, showCheckerboard);
}, [nativeActive, hasOpenDocument, dimensions.width, dimensions.height, showCheckerboard]);
// Sync canvas matte color & checkerboard setting from CSS theme tokens
useEffect(() => {
if (!nativeActive || !hasOpenDocument || typeof window === 'undefined') return;
const syncAppearance = () => {
const matteCss = getComputedStyle(document.documentElement).getPropertyValue(
'--ui-canvas-matte'
);
const rgba = parseCssColorToRgba(matteCss, [0.086, 0.086, 0.086, 1.0]);
void setNativeAppearance(rgba, showCheckerboard);
};
const raf = requestAnimationFrame(syncAppearance);
return () => cancelAnimationFrame(raf);
}, [nativeActive, hasOpenDocument, themePreset, appearance, showCheckerboard]);
// Sync full Phase 4 CSP BrushSettings, FG/BG colors & content-hashed tip/paper textures ONLY on change.
// Skip during interactive Ctrl+Alt+Drag brush resize so 60 Hz size/hardness preview never runs
// a 90-field JSON.stringify + full NativeBrushConfig IPC; final config syncs once on pointer-up.
useEffect(() => {
if (!nativeActive || !hasOpenDocument || isResizingBrush) return;
let sig = '';
try {
sig = JSON.stringify([
tool,
primaryColor,
secondaryColor,
brushSettings.size,
brushSettings.minSizeFactor,
brushSettings.opacity,
brushSettings.flow,
brushSettings.brushDensity,
brushSettings.adjustDensityByGap,
brushSettings.hardness,
brushSettings.antiAlias,
brushSettings.spacing,
brushSettings.stabilization,
brushSettings.sharpCorners,
brushSettings.postCorrection,
brushSettings.smoothing,
brushSettings.usePressure,
brushSettings.useTilt,
brushSettings.tiltScale,
brushSettings.pressureCurveGamma,
brushSettings.pressureCurve,
brushSettings.isTransparentInk,
isBackgroundLayerId(activeLayer?.id ?? ''),
brushSettings.customTipDataUrl?.length ?? 0,
brushSettings.customTipDataUrl?.slice(0, 64) ?? '',
brushSettings.subTips?.map((t) => `${t.width}x${t.height}:${t.dataUrl?.length ?? 0}`),
brushSettings.subTipOrder,
brushSettings.isColorTip,
brushSettings.isDualToneTip,
brushSettings.thickness,
brushSettings.thicknessVertical,
brushSettings.customTipAngle,
brushSettings.customTipAngleDynamics,
brushSettings.customTipRotationRandomScale,
brushSettings.flipH,
brushSettings.flipV,
brushSettings.blendTipsMode,
brushSettings.brushCombineMode,
brushSettings.paperTexture?.length ?? 0,
brushSettings.paperTexture?.slice(0, 64) ?? '',
brushSettings.surfaceTextureId,
brushSettings.grain,
brushSettings.textureDensity,
brushSettings.paperTextureMode,
brushSettings.grainMappingMode,
brushSettings.paperTextureScale,
brushSettings.paperTextureRotate,
brushSettings.paperTextureOffsetX,
brushSettings.paperTextureOffsetY,
brushSettings.paperTextureBrightness,
brushSettings.paperTextureContrast,
brushSettings.paperTextureInverted,
brushSettings.paperTextureApplyEachPlot,
brushSettings.paperTextureEmphasizeDensity,
brushSettings.wetEdge,
brushSettings.wetEdgeRadius,
brushSettings.wetEdgeAlphaPower,
brushSettings.wetEdgeValuePower,
brushSettings.sizeSensor,
brushSettings.opacitySensor,
brushSettings.densitySensor,
brushSettings.thicknessSensor,
brushSettings.intervalSensor,
brushSettings.textureDensitySensor,
brushSettings.dynamics,
brushSettings.spray,
brushSettings.taper,
brushSettings.dualBrush,
brushSettings.dualBrushConfig?.enabled,
brushSettings.dualBrushConfig?.compositeMode,
brushSettings.dualBrushConfig?.size,
brushSettings.dualBrushConfig?.sizeRatio,
brushSettings.dualBrushConfig?.linkSizeWithMain,
brushSettings.dualBrushConfig?.spacing,
brushSettings.dualBrushConfig?.scatter,
brushSettings.dualBrushConfig?.thickness,
brushSettings.dualBrushConfig?.angle,
brushSettings.dualBrushConfig?.angleDynamics,
brushSettings.dualBrushConfig?.hardness,
brushSettings.dualBrushConfig?.density,
brushSettings.dualBrushConfig?.tipDataUrl?.length ?? 0,
brushSettings.dualBrushConfig?.subTips?.length ?? 0,
brushSettings.dualBrushConfig?.isRibbon,
brushSettings.dualScale,
brushSettings.dualTipDataUrl?.length ?? 0,
// Phase 5: Natural Paint, Pigment Mixing, Bristle Ribbon, Continuous Ribbon & Impasto
brushSettings.preset,
brushSettings.brushName,
brushSettings.renderMode,
brushSettings.isRibbon,
brushSettings.ribbonRepeatMode,
brushSettings.colorMixing,
brushSettings.perceptualMixing,
brushSettings.amountOfPaint,
brushSettings.densityOfPaint,
brushSettings.colorStretch,
brushSettings.mixGroundColor,
brushSettings.useBlur,
brushSettings.blurStrength,
brushSettings.mixingMode,
brushSettings.amountOfPaintSensor,
brushSettings.densityOfPaintSensor,
brushSettings.colorStretchSensor,
brushSettings.bristleSplaySensor,
brushSettings.paintLoadSensor,
brushSettings.grainPenetrationSensor,
brushSettings.dualSurfaceTextureId,
brushSettings.dualGrainDepth,
brushSettings.bristle,
brushSettings.naturalPaint,
brushSettings.impasto,
]);
} catch {
sig = `${Date.now()}`;
}
if (sig === lastBrushSyncSigRef.current) return;
lastBrushSyncSigRef.current = sig;
const isBgEraser =
(tool === 'eraser' || Boolean(brushSettings.isTransparentInk)) &&
isBackgroundLayerId(activeLayer?.id ?? '');
void syncNativeFullBrushConfig(tool, brushSettings, primaryColor, secondaryColor, isBgEraser);
}, [
nativeActive,
hasOpenDocument,
isResizingBrush,
tool,
primaryColor,
secondaryColor,
brushSettings,
activeLayer?.id,
]);
// Sync non-destructive layer mask painting mode into native Rust engine
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
void setNativeMaskMode(Boolean(isMaskMode));
}, [nativeActive, hasOpenDocument, isMaskMode]);
// Sync global pressure curve ONLY when changed
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
const sig = JSON.stringify(globalPressureCurve ?? null);
if (sig === lastPressureCurveSigRef.current) return;
lastPressureCurveSigRef.current = sig;
void setNativePressureCurve(globalPressureCurve);
}, [nativeActive, hasOpenDocument, globalPressureCurve]);
// Sync straight ruler & perspective ruler ONLY when changed
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
const sig = JSON.stringify([straightRuler ?? null, perspectiveRuler ?? null]);
if (sig === lastRulerSyncSigRef.current) return;
lastRulerSyncSigRef.current = sig;
void setNativeRulers(straightRuler, perspectiveRuler);
}, [nativeActive, hasOpenDocument, straightRuler, perspectiveRuler]);
// Sync GPU brush cursor config
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
const hideCursor =
isModalOpen ||
isSpaceDown ||
isPanning ||
isRotating ||
isZoomDragging ||
isRotateModifier ||
isResizingBrush ||
!isNativeStrokeTool(tool);
void setNativeCursor({
size: Math.max(0.5, brushSettings.size || 12),
thicknessRatio: Math.max(0.05, Math.min(1.0, thicknessRatio || 1.0)),
thicknessVertical,
tipAngleDeg,
isSquare,
visible: !hideCursor,
});
}, [
nativeActive,
hasOpenDocument,
tool,
brushSettings.size,
thicknessRatio,
thicknessVertical,
tipAngleDeg,
isSquare,
isModalOpen,
isSpaceDown,
isPanning,
isRotating,
isZoomDragging,
isRotateModifier,
isResizingBrush,
]);
// Sync interaction policy (tool classification, wheel mode, focus & modal guards)
useEffect(() => {
if (!nativeActive || !isWorkspaceVisible) return;
const wheelMode: NativeWheelNavMode =
wheelModeRaw === 'scroll'
? 'scroll'
: wheelModeRaw === 'brush-size'
? 'brush-size'
: 'zoom';
void setNativePolicy({
activeTool: classifyNativeTool(tool),
nativeStrokeEnabled: nativeStrokeOwned && !isResizingBrush,
wheelMode,
isWebtoonMode,
textInputFocused,
workspaceInteracting,
modalOpen: isModalOpen || Boolean(openPopover),
});
}, [
nativeActive,
isWorkspaceVisible,
tool,
nativeStrokeOwned,
isResizingBrush,
wheelModeRaw,
isWebtoonMode,
textInputFocused,
workspaceInteracting,
isModalOpen,
openPopover,
]);
// Bidirectional camera sync between Rust 120–240Hz navigator and React useCanvasNavigation
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
// Push initial camera snapshot into Rust
const initial = navigation
? navigation.getCameraState()
: { pan, zoom, rotation, flipX, flipY };
void setNativeCamera({
panX: initial.pan.x,
panY: initial.pan.y,
zoom: initial.zoom,
rotation: initial.rotation,
flipX: initial.flipX,
flipY: initial.flipY,
});
const unsubReactCam = navigation
? navigation.subscribeCamera((cam, meta) => {
// Never echo native Rust camera events back over IPC (their rAF broadcast fires
// asynchronously after `applyingNativeCameraRef` resets, which would otherwise
// overwrite Rust's live gesture camera with 16-32ms stale coordinates -> ghosting/lag).
if (applyingNativeCameraRef.current || meta?.source === 'native') return;
void setNativeCamera({
panX: cam.pan.x,
panY: cam.pan.y,
zoom: cam.zoom,
rotation: cam.rotation,
flipX: cam.flipX,
flipY: cam.flipY,
});
})
: () => {};
const unsubNativeCam = subscribeNativeCamera((ev) => {
if (!navigation?.setCameraLive) return;
applyingNativeCameraRef.current = true;
try {
navigation.setCameraLive(
{
pan: { x: ev.panX, y: ev.panY },
zoom: ev.zoom,
rotation: ev.rotation,
flipX: ev.flipX,
flipY: ev.flipY,
},
ev.commit,
'native'
);
} finally {
applyingNativeCameraRef.current = false;
}
});
return () => {
unsubReactCam();
unsubNativeCam();
};
}, [nativeActive, hasOpenDocument, navigation]);
// Subscribe to throttled pointer stats (~30Hz) from Rust and forward active-pressure
// transitions into `recoveryService` so native strokes pause checkpoints, timelapse & disk walks.
// (4 Hz GPU diagnostics are consumed solely by the isolated `NativeGpuPerfHud` leaf store.)
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
let wasPressureDown = false;
const unsubStat = subscribeNativePointerStat((stat) => {
const pressureDown = typeof stat.pressure === 'number' && stat.pressure > 0.001;
if (pressureDown) {
wasPressureDown = true;
recoveryService.notifyNativeStrokeStart();
} else if (wasPressureDown) {
wasPressureDown = false;
recoveryService.notifyNativeStrokeEnd();
}
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent('canvas-pointer-stat', {
detail: {
x: stat.docX,
y: stat.docY,
pressure: stat.pressure,
},
})
);
}
});
return () => {
if (wasPressureDown) {
wasPressureDown = false;
recoveryService.notifyNativeStrokeEnd();
}
unsubStat();
};
}, [nativeActive, hasOpenDocument]);
const handleClearNativeCanvas = useCallback(() => {
void clearNativeCanvas();
}, []);
return {
nativeActive: nativeActive && isWorkspaceVisible,
nativeStrokeOwned,
onClearNativeCanvas: handleClearNativeCanvas,
};
}