Skip to content

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

24.0 KB
Raw Blame
import React, { useEffect, useRef, useState } from 'react';
import { BrushSettings, FillSettings, LiquifySettings, RetouchSettings, ToolType } from '../../types/editor';
import { ModifierAction } from '../../types/settings';
import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utils/brushOutline';
import { computeTipStampDimensions, isNaturalPaintBrush } from '../../utils/brushMath';
import { preloadTipImage } from '../../utils/brushStorage';
import { isNativeStrokeTool, setNativeCursor } from '../../utils/nativeEngineBridge';
import { useUiStore } from '../../stores';
import {
  computeEffectiveCursorAngleDeg,
  computeNextDynamicCursorAngleDeg,
  CursorConfig,
  formatCursorRingTransform,
  normalizeAngleDeg,
  resolveBrushCursorRotationSpec,
} from './types';

export interface UseCanvasEffectsParams {
  viewportRef: React.RefObject<HTMLDivElement | null>;
  brushSettings: BrushSettings;
  onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;
  fillSettings?: FillSettings;
  onUpdateFillSettings?: (newSettings: Partial<FillSettings>) => void;
  liquifySettings?: LiquifySettings;
  onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
  retouchSettings?: RetouchSettings;
  onUpdateRetouchSettings?: (newSettings: Partial<RetouchSettings>) => void;
  tool: ToolType;
  liveZoom: number;
  liveRotation: number;
  liveFlipX: boolean;
  liveFlipY: boolean;
  isSpaceDown: boolean;
  isPanning: boolean;
  isRotating: boolean;
  isZoomDragging: boolean;
  isRotateModifier: boolean;
  hasOpenDocument: boolean;
  showCursorCoordinates: boolean;
  showPressureInStatusBar: boolean;
  heldModifierAction: ModifierAction;
  isResizingBrush: boolean;
  setIsResizingBrush: React.Dispatch<React.SetStateAction<boolean>>;
  quickPalettePos: { x: number; y: number } | null;
  setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;
  resizeOriginRef: React.MutableRefObject<{ clientX: number; clientY: number }>;
  resizeStartSettingsRef: React.MutableRefObject<{ size: number; hardness: number }>;
  nativeCanvasActive?: boolean;
}

export function useCanvasEffects({
  viewportRef,
  brushSettings,
  onUpdateBrushSettings,
  fillSettings,
  onUpdateFillSettings,
  liquifySettings,
  onUpdateLiquifySettings,
  retouchSettings,
  onUpdateRetouchSettings,
  tool,
  liveZoom,
  liveRotation,
  liveFlipX,
  liveFlipY,
  isSpaceDown,
  isPanning,
  isRotating,
  isZoomDragging,
  isRotateModifier,
  hasOpenDocument,
  showCursorCoordinates,
  showPressureInStatusBar,
  heldModifierAction,
  isResizingBrush,
  setIsResizingBrush,
  quickPalettePos,
  setQuickPalettePos,
  resizeOriginRef,
  resizeStartSettingsRef,
  nativeCanvasActive = false,
}: UseCanvasEffectsParams) {
  // Resolve tip image and extract vector outline silhouette
  const activeTipImage = resolveBrushTipImage(brushSettings);
  const [tipOutline, setTipOutline] = useState<TipOutline | null>(() => {
    return activeTipImage ? getBrushTipOutline(activeTipImage) : null;
  });

  useEffect(() => {
    let isCancelled = false;

    if (activeTipImage) {
      if (activeTipImage.complete && activeTipImage.naturalWidth > 0) {
        setTipOutline(getBrushTipOutline(activeTipImage));
      } else {
        const handleLoad = () => {
          if (!isCancelled) {
            setTipOutline(getBrushTipOutline(activeTipImage));
          }
        };
        activeTipImage.addEventListener('load', handleLoad, { once: true });
      }
      return () => {
        isCancelled = true;
      };
    }

    if (brushSettings.customTipDataUrl) {
      preloadTipImage(brushSettings.customTipDataUrl)
        .then((img) => {
          if (!isCancelled) {
            setTipOutline(getBrushTipOutline(img));
          }
        })
        .catch(() => {
          if (!isCancelled) {
            setTipOutline(null);
          }
        });
      return () => {
        isCancelled = true;
      };
    }

    setTipOutline(null);
  }, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);

  const [liveResizePreview, setLiveResizePreview] = useState<{
    size: number;
    hardness: number;
  } | null>(null);

  const isBrushOrEraser = tool === 'brush' || tool === 'decoration' || tool === 'eraser';
  const isPaintUnfilled = tool === 'fill' && fillSettings?.method === 'paint-unfilled';
  const isCustomTip = Boolean(
    tipOutline && !brushSettings.isRibbon && isBrushOrEraser
  );
  const isSquare = isBrushOrEraser && brushSettings.preset === 'square-digital' && !tipOutline;

  const baseActiveToolSize =
    tool === 'liquify' && liquifySettings
      ? liquifySettings.size
      : tool === 'retouch' && retouchSettings
        ? retouchSettings.size
        : isPaintUnfilled
          ? Math.max(2, Math.min(300, fillSettings?.brushSize ?? 24))
          : brushSettings.size;
  const activeToolSize =
    isResizingBrush && liveResizePreview ? liveResizePreview.size : baseActiveToolSize;
  const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);
  const thicknessRatio = isBrushOrEraser ? (brushSettings.thickness ?? 1.0) : 1.0;
  const thicknessVertical = Boolean(brushSettings.thicknessVertical && isBrushOrEraser);
  const tipAngleDeg = isBrushOrEraser ? (brushSettings.customTipAngle ?? 0) : 0;
  const cursorRotationSpec = resolveBrushCursorRotationSpec(brushSettings, tool);
  const followDirection = cursorRotationSpec.enabled;
  const naturalPaintMode = isBrushOrEraser && isNaturalPaintBrush(brushSettings);

  const tipAspect =
    isCustomTip && tipOutline ? tipOutline.height / Math.max(1, tipOutline.width) : 1;
  const tipCursorDims = computeTipStampDimensions(
    cursorBaseWidth,
    thicknessRatio,
    thicknessVertical,
    isCustomTip && tipOutline ? tipOutline.width : 1,
    isCustomTip && tipOutline ? tipOutline.height : 1
  );
  const cursorWidth = Math.max(2, tipCursorDims.width);
  const cursorHeight = Math.max(2, tipCursorDims.height);

  const dynamicDirDegRef = useRef<number>(0);
  const hasDynamicDirRef = useRef<boolean>(false);
  const twistDegRef = useRef<number>(0);
  const lastDirAnchorRef = useRef<{ x: number; y: number } | null>(null);
  const cursorConfigRef = useRef<CursorConfig>({
    activeToolSize,
    tipAspect,
    thicknessRatio,
    thicknessVertical,
    tipAngleDeg,
    orientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,
    followDirection,
    rotationSource: cursorRotationSpec.source,
    naturalPaintMode,
    dynamicDirDeg: 0,
    twistDeg: 0,
    rotation: liveRotation,
    flipX: liveFlipX,
    flipY: liveFlipY,
  });
  cursorConfigRef.current = {
    activeToolSize,
    tipAspect,
    thicknessRatio,
    thicknessVertical,
    tipAngleDeg,
    orientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,
    followDirection,
    rotationSource: cursorRotationSpec.source,
    naturalPaintMode,
    dynamicDirDeg: dynamicDirDegRef.current,
    twistDeg: twistDegRef.current,
    rotation: liveRotation,
    flipX: liveFlipX,
    flipY: liveFlipY,
  };
  // Brush tip rotation: effective tip angle relative to canvas + viewport canvas rotation
  const totalAngleDeg = computeEffectiveCursorAngleDeg(cursorConfigRef.current) + liveRotation;
  const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);

  // Zero-latency direct DOM cursor preview element & pointer stat readout
  const cursorRingRef = useRef<HTMLDivElement | null>(null);
  const pointerStatRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!showCursorCoordinates && !showPressureInStatusBar) return;
    let rafId = 0;
    const handlePointerStat = (e: Event) => {
      const detail = (e as CustomEvent).detail;
      cancelAnimationFrame(rafId);
      rafId = requestAnimationFrame(() => {
        const el = pointerStatRef.current;
        if (!el || !detail) return;
        const parts: string[] = [];
        if (showCursorCoordinates && detail.x !== null && detail.x !== undefined) {
          parts.push(`${detail.x}, ${detail.y}`);
        }
        if (showPressureInStatusBar && detail.pressure > 0) {
          parts.push(`${Math.round(detail.pressure * 100)}%`);
        }
        el.textContent = parts.join('  ·  ');
      });
    };
    window.addEventListener('canvas-pointer-stat', handlePointerStat);
    return () => {
      window.removeEventListener('canvas-pointer-stat', handlePointerStat);
      cancelAnimationFrame(rafId);
    };
  }, [showCursorCoordinates, showPressureInStatusBar]);

  // Reset transient direction tracking when rotation mode changes (e.g. toggling "This brush rotates" or switching brush)
  useEffect(() => {
    hasDynamicDirRef.current = false;
    lastDirAnchorRef.current = null;
    twistDegRef.current = 0;
    if (!cursorRotationSpec.enabled) {
      dynamicDirDegRef.current = 0;
    }
    cursorConfigRef.current.dynamicDirDeg = dynamicDirDegRef.current;
    cursorConfigRef.current.twistDeg = 0;
  }, [cursorRotationSpec.enabled, cursorRotationSpec.source, brushSettings.preset]);

  // Update cursor rotation/flip in-place when viewport rotates/flips or brush tip angle/rotation settings change while hovering
  useEffect(() => {
    const ring = cursorRingRef.current;
    const pos = lastPointerPosRef.current;
    if (ring && pos && ring.style.display !== 'none') {
      const cfg = cursorConfigRef.current;
      ring.style.transform = formatCursorRingTransform(
        pos.x,
        pos.y,
        cfg.rotation,
        cfg.flipX,
        cfg.flipY,
        computeEffectiveCursorAngleDeg(cfg)
      );
    }
  }, [
    tipAngleDeg,
    cursorRotationSpec.enabled,
    cursorRotationSpec.source,
    cursorRotationSpec.orientationOffsetDeg,
    liveRotation,
    liveFlipX,
    liveFlipY,
    brushSettings.preset,
  ]);

  const isResizeCanvasModalOpen = useUiStore((s) => s.isResizeCanvasModalOpen);

  const shouldHideCursorRing =
    Boolean(nativeCanvasActive && isNativeStrokeTool(tool)) ||
    isResizeCanvasModalOpen ||
    isSpaceDown ||
    isPanning ||
    isRotating ||
    isZoomDragging ||
    isRotateModifier ||
    isResizingBrush ||
    heldModifierAction === 'brush-size' ||
    heldModifierAction === 'pan' ||
    heldModifierAction === 'rotate' ||
    heldModifierAction === 'zoom-drag' ||
    (tool !== 'brush' &&
      tool !== 'decoration' &&
      tool !== 'eraser' &&
      tool !== 'liquify' &&
      tool !== 'retouch' &&
      tool !== 'select-pen' &&
      tool !== 'select-eraser' &&
      !isPaintUnfilled);
  const shouldHideCursorRingRef = useRef(shouldHideCursorRing);
  shouldHideCursorRingRef.current = shouldHideCursorRing;
  const nativeCanvasActiveRef = useRef(nativeCanvasActive);
  nativeCanvasActiveRef.current = nativeCanvasActive;
  const cursorToolRef = useRef(tool);
  cursorToolRef.current = tool;

  const showRingAtLocalPosRef = useRef<
    ((x: number, y: number, tiltX?: number, tiltY?: number, twist?: number) => void) | null
  >(null);

  // Lightweight visibility toggle when Space/Shift/Alt/pan/rotate/tool/nativeCanvasActive changes
  // (hides DOM cursor ring ONCE on transition instead of mutating style.display on every pointermove)
  useEffect(() => {
    const ring = cursorRingRef.current;
    if (!ring) return;
    if (shouldHideCursorRing) {
      if (ring.style.display !== 'none') {
        ring.style.display = 'none';
      }
    } else if (lastPointerPosRef.current && showRingAtLocalPosRef.current) {
      showRingAtLocalPosRef.current(lastPointerPosRef.current.x, lastPointerPosRef.current.y);
    }
  }, [shouldHideCursorRing, cursorRingRef, lastPointerPosRef]);

  useEffect(() => {
    const viewport = viewportRef.current;
    if (!viewport) return;

    let cachedRect: DOMRect | null = nativeCanvasActiveRef.current
      ? null
      : viewport.getBoundingClientRect();
    const updateRect = () => {
      if (viewport && !nativeCanvasActiveRef.current) {
        cachedRect = viewport.getBoundingClientRect();
      } else {
        cachedRect = null;
      }
    };

    let ringRafId: number | null = null;
    let pendingRingX = 0;
    let pendingRingY = 0;
    let pendingTiltX: number | undefined;
    let pendingTiltY: number | undefined;
    let pendingTwist: number | undefined;

    const showRingAtLocalPos = (
      x: number,
      y: number,
      tiltX?: number,
      tiltY?: number,
      twist?: number
    ) => {
      const ring = cursorRingRef.current;
      if (!ring) return;
      const cfg = cursorConfigRef.current;
      if (cfg.followDirection) {
        const anchor = lastDirAnchorRef.current;
        const sdx = anchor ? x - anchor.x : 0;
        const sdy = anchor ? y - anchor.y : 0;
        if (!anchor) {
          lastDirAnchorRef.current = { x, y };
        }
        const next = computeNextDynamicCursorAngleDeg({
          source: cfg.rotationSource,
          currentDeg: dynamicDirDegRef.current,
          hasCurrent: hasDynamicDirRef.current,
          sdx,
          sdy,
          canvasRotationDeg: cfg.rotation,
          flipX: cfg.flipX,
          flipY: cfg.flipY,
          tiltX,
          tiltY,
          twist,
        });
        if (next.updated) {
          dynamicDirDegRef.current = next.angleDeg;
          hasDynamicDirRef.current = true;
          cfg.dynamicDirDeg = next.angleDeg;
          if (cfg.rotationSource === 'direction') {
            lastDirAnchorRef.current = { x, y };
          }
        }
        if (
          cfg.naturalPaintMode &&
          cfg.rotationSource === 'direction' &&
          twist !== undefined &&
          Number.isFinite(twist)
        ) {
          twistDegRef.current = normalizeAngleDeg(twist);
          cfg.twistDeg = twistDegRef.current;
        }
      }
      ring.style.transform = formatCursorRingTransform(
        x,
        y,
        cfg.rotation,
        cfg.flipX,
        cfg.flipY,
        computeEffectiveCursorAngleDeg(cfg)
      );
      if (ring.style.display !== 'block') {
        ring.style.display = 'block';
      }
    };
    showRingAtLocalPosRef.current = showRingAtLocalPos;

    const scheduleShowRing = (
      x: number,
      y: number,
      tiltX?: number,
      tiltY?: number,
      twist?: number
    ) => {
      pendingRingX = x;
      pendingRingY = y;
      pendingTiltX = tiltX;
      pendingTiltY = tiltY;
      pendingTwist = twist;
      if (ringRafId === null) {
        if (typeof requestAnimationFrame === 'function') {
          ringRafId = requestAnimationFrame(() => {
            ringRafId = null;
            if (shouldHideCursorRingRef.current) return;
            showRingAtLocalPos(
              pendingRingX,
              pendingRingY,
              pendingTiltX,
              pendingTiltY,
              pendingTwist
            );
          });
        } else {
          showRingAtLocalPos(x, y, tiltX, tiltY, twist);
        }
      }
    };

    window.addEventListener('resize', updateRect);
    window.addEventListener('scroll', updateRect, true);
    const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;
    ro?.observe(viewport);

    const updateCursorRingCoords = (
      clientX: number,
      clientY: number,
      forceRefreshRect: boolean = false,
      tiltX?: number,
      tiltY?: number,
      twist?: number,
      immediate: boolean = false
    ) => {
      // When native DX12 canvas owns the cursor & stroke, skip all DOM layout reads & style writes.
      if (nativeCanvasActiveRef.current && isNativeStrokeTool(cursorToolRef.current)) {
        return;
      }
      const ring = cursorRingRef.current;
      if (!ring) return;

      if (shouldHideCursorRingRef.current) {
        if (ring.style.display !== 'none') {
          ring.style.display = 'none';
        }
        return;
      }

      if (forceRefreshRect || !cachedRect) {
        cachedRect = viewport.getBoundingClientRect();
      }
      if (!cachedRect) return;

      const x = clientX - cachedRect.left;
      const y = clientY - cachedRect.top;

      if (x < 0 || x > cachedRect.width || y < 0 || y > cachedRect.height) {
        lastPointerPosRef.current = null;
        lastDirAnchorRef.current = null;
        hasDynamicDirRef.current = false;
        if (ring.style.display !== 'none') {
          ring.style.display = 'none';
        }
        return;
      }

      lastPointerPosRef.current = { x, y };

      if (immediate) {
        showRingAtLocalPos(x, y, tiltX, tiltY, twist);
      } else {
        scheduleShowRing(x, y, tiltX, tiltY, twist);
      }
    };

    const handleWindowPointerMove = (e: PointerEvent) => {
      if (nativeCanvasActiveRef.current && isNativeStrokeTool(cursorToolRef.current)) {
        return;
      }
      updateCursorRingCoords(e.clientX, e.clientY, false, e.tiltX, e.tiltY, e.twist, false);
    };

    const handleViewportPointerEnterOrDown = (e: PointerEvent) => {
      if (nativeCanvasActiveRef.current && isNativeStrokeTool(cursorToolRef.current)) {
        return;
      }
      updateCursorRingCoords(e.clientX, e.clientY, true, e.tiltX, e.tiltY, e.twist, true);
    };

    const handlePointerLeave = () => {
      if (ringRafId !== null && typeof cancelAnimationFrame === 'function') {
        cancelAnimationFrame(ringRafId);
        ringRafId = null;
      }
      lastPointerPosRef.current = null;
      lastDirAnchorRef.current = null;
      hasDynamicDirRef.current = false;
      if (cursorRingRef.current && cursorRingRef.current.style.display !== 'none') {
        cursorRingRef.current.style.display = 'none';
      }
    };

    viewport.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
    viewport.addEventListener('pointerdown', handleViewportPointerEnterOrDown, { passive: true });
    viewport.addEventListener('pointerenter', handleViewportPointerEnterOrDown, { passive: true });
    viewport.addEventListener('pointerleave', handlePointerLeave, { passive: true });

    return () => {
      showRingAtLocalPosRef.current = null;
      if (ringRafId !== null && typeof cancelAnimationFrame === 'function') {
        cancelAnimationFrame(ringRafId);
      }
      window.removeEventListener('resize', updateRect);
      window.removeEventListener('scroll', updateRect, true);
      ro?.disconnect();
      viewport.removeEventListener('pointermove', handleWindowPointerMove);
      viewport.removeEventListener('pointerdown', handleViewportPointerEnterOrDown);
      viewport.removeEventListener('pointerenter', handleViewportPointerEnterOrDown);
      viewport.removeEventListener('pointerleave', handlePointerLeave);
    };
  }, [viewportRef, hasOpenDocument]);

  // Dismiss quick palette on Escape and reset transient UI state on window blur / tab hide
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && quickPalettePos) {
        setQuickPalettePos(null);
      }
    };

    const handleBlur = () => {
      setIsResizingBrush(false);
      setQuickPalettePos(null);
    };

    const handleVisibilityChange = () => {
      if (document.hidden) {
        handleBlur();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('blur', handleBlur);
    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('blur', handleBlur);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [quickPalettePos, setIsResizingBrush, setQuickPalettePos]);

  // Handle active brush resizing window drag listeners.
  // During Ctrl+Alt+Drag, update ONLY the lightweight local on-canvas preview (and native GPU
  // cursor size) at 60 Hz — committing to the global tool store & full 90-field native brush
  // config ONCE on pointer-up so BrushPreview & RightSidebar never thrash mid-drag.
  useEffect(() => {
    if (!isResizingBrush) {
      setLiveResizePreview(null);
      return;
    }

    let rafId: number | null = null;
    let pendingSize = resizeStartSettingsRef.current.size;
    let pendingHardness = resizeStartSettingsRef.current.hardness;
    let hasChanged = false;
    setLiveResizePreview({ size: pendingSize, hardness: pendingHardness });

    const flushPreview = () => {
      rafId = null;
      setLiveResizePreview({ size: pendingSize, hardness: pendingHardness });
      if (nativeCanvasActiveRef.current && isNativeStrokeTool(tool)) {
        const cfg = cursorConfigRef.current;
        void setNativeCursor({
          size: Math.max(0.5, pendingSize),
          thicknessRatio: Math.max(0.05, Math.min(1.0, cfg.thicknessRatio || 1.0)),
          thicknessVertical: cfg.thicknessVertical,
          tipAngleDeg: cfg.tipAngleDeg,
          isSquare: isSquare,
          visible: false,
        });
      }
    };

    const commitFinalSettings = () => {
      if (!hasChanged) return;
      if (tool === 'liquify' && onUpdateLiquifySettings) {
        onUpdateLiquifySettings({ size: Math.round(pendingSize) });
      } else if (tool === 'retouch' && onUpdateRetouchSettings) {
        onUpdateRetouchSettings({
          size: Math.max(2, Math.min(300, Math.round(pendingSize))),
          hardness: Math.round(pendingHardness * 100),
        });
      } else if (isPaintUnfilled && onUpdateFillSettings) {
        onUpdateFillSettings({
          brushSize: Math.max(2, Math.min(300, Math.round(pendingSize))),
        });
      } else {
        onUpdateBrushSettings({ size: pendingSize, hardness: pendingHardness });
      }
    };

    const finishResize = () => {
      if (rafId !== null) {
        cancelAnimationFrame(rafId);
        rafId = null;
      }
      commitFinalSettings();
      setLiveResizePreview(null);
      setIsResizingBrush(false);
    };

    const handleWindowPointerMove = (e: PointerEvent) => {
      if (typeof e.buttons === 'number' && e.buttons === 0) {
        finishResize();
        return;
      }
      const dx = e.clientX - resizeOriginRef.current.clientX;
      const dy = resizeOriginRef.current.clientY - e.clientY;

      // Exponential + linear hybrid sensitivity for 0.5px..1000px precision (CSP-style)
      const baseSize = Math.max(0.5, resizeStartSettingsRef.current.size);
      const rawSize = baseSize * Math.exp(dx * 0.006) + dx * 0.15;
      const clampedSize = Math.max(0.5, Math.min(1000, rawSize));
      const nextSize =
        clampedSize < 10 ? Math.round(clampedSize * 10) / 10 : Math.round(clampedSize);

      const nextHardness = Math.max(
        0.05,
        Math.min(
          1.0,
          Math.round((resizeStartSettingsRef.current.hardness + dy * 0.004) * 100) / 100
        )
      );

      if (nextSize === pendingSize && nextHardness === pendingHardness) return;
      pendingSize = nextSize;
      pendingHardness = nextHardness;
      hasChanged = true;

      if (rafId === null) {
        rafId = requestAnimationFrame(flushPreview);
      }
    };

    const handleWindowMouseUp = (e: MouseEvent) => {
      if (typeof e.buttons !== 'number' || e.buttons === 0) {
        finishResize();
      }
    };

    window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
    window.addEventListener('pointerup', finishResize, true);
    window.addEventListener('pointercancel', finishResize, true);
    window.addEventListener('mouseup', handleWindowMouseUp, true);

    document.body.style.cursor = 'ew-resize';
    document.body.style.userSelect = 'none';

    return () => {
      if (rafId !== null) cancelAnimationFrame(rafId);
      window.removeEventListener('pointermove', handleWindowPointerMove);
      window.removeEventListener('pointerup', finishResize, true);
      window.removeEventListener('pointercancel', finishResize, true);
      window.removeEventListener('mouseup', handleWindowMouseUp, true);
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    };
  }, [
    isResizingBrush,
    isPaintUnfilled,
    isSquare,
    onUpdateBrushSettings,
    onUpdateFillSettings,
    onUpdateLiquifySettings,
    onUpdateRetouchSettings,
    tool,
    setIsResizingBrush,
  ]);

  return {
    tipOutline,
    isCustomTip,
    isSquare,
    isCursorRotating: cursorRotationSpec.enabled,
    cursorOrientationOffsetDeg: cursorRotationSpec.orientationOffsetDeg,
    thicknessRatio,
    thicknessVertical,
    tipAngleDeg,
    cursorWidth,
    cursorHeight,
    totalAngleDeg,
    liveResizePreview,
    cursorConfigRef,
    lastPointerPosRef,
    cursorRingRef,
    pointerStatRef,
  };
}