Skip to content

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

44.0 KB
Raw Blame
import React, { useState, useRef, useCallback, useEffect } from 'react';
import {
  CanvasColorMode,
  CanvasDimensions,
  CanvasSelection,
  ComicFrame,
  FrameDivideMode,
  LayerItem,
  LayerTreeDelta,
  ShapeDragPreview,
  SpeechBalloon,
  TextLayerData,
  TextSettings,
  TileDelta,
} from '../../types/editor';
import { documentStore } from '../../utils/documentStore';
import { computeShapeGeometry, resolveShapeFillColor } from '../../utils/shapeEngine';
import {
  nativeClearToolPreview,
  nativeEncloseFillDoc,
  nativeFloodFillDoc,
  nativeLassoFillDoc,
  nativeLiquifyBegin,
  nativeLiquifyCancel,
  nativeLiquifyCommit,
  nativeLiquifyStepGpu,
  nativePaintUnfilledDoc,
  nativePickColor,
  nativeShapeCommit,
  nativeShapePreview,
  type NativeFillReferMode,
  type NativeShapeParams,
} from '../../utils/nativeEngineBridge';
import { createDefaultSpeechBalloon } from '../../utils/balloonEngine';
import {
  createRectFrame,
  doesCutSegmentCrossFrame,
  MANGA_GUTTER_HORIZONTAL_MM,
  MANGA_GUTTER_VERTICAL_MM,
  mmToPixels,
  Point2D,
} from '../../utils/frameEngine';
import { hitTestEditableVectorLayer } from '../../utils/vectorLayerRenderer';
import { extractPersistableTextStyle, normalizeTextSettings } from '../../utils/textSettings';
import { useToolStore, toolStoreActions } from '../../stores';
import { t } from '../../i18n';
import { PushHistoryStepFn } from './types';

export interface TextPlacementSession {
  x: number;
  y: number;
  settings: TextSettings;
  editingLayerId?: string | null;
}

export interface TextDragPreview {
  start: Point2D;
  end: Point2D;
}

export interface FrameDragPreview {
  mode: 'create' | 'divide';
  start: Point2D;
  end: Point2D;
}

export interface LassoFillPreview {
  points: Point2D[];
  color: string;
  opacity: number;
  isTransparentInk: boolean;
  mode?: 'lasso' | 'enclose-and-fill' | 'paint-unfilled';
  brushSize?: number;
}

export interface UseShapeAndFillToolsParams {
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  layers: LayerItem[];
  activeLayer: LayerItem | undefined;
  activeLayerId: string;
  selectedLayerIds?: string[];
  selection: CanvasSelection | null;
  onCommitFloatingSelection?: () => void;
  flushPendingHistoryTasks?: () => void;
  isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
  getEffectiveOpacity: (layer: LayerItem) => number;
  getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => { x: number; y: number };
  setActiveLayerId: (id: string) => void;
  upsertTextLayer: (textData: TextLayerData, editingLayerId?: string | null) => LayerItem;
  upsertBalloonLayer: (balloonData: SpeechBalloon, editingLayerId?: string | null) => LayerItem;
  createFrameFolder: (
    frames: ComicFrame[],
    customName?: string,
    addInitialChildLayer?: boolean
  ) => { folder: LayerItem; childLayer: LayerItem | null; layerTreeDelta: LayerTreeDelta };
  divideFrameFolder: (
    folderId: string,
    cutStart: Point2D,
    cutEnd: Point2D,
    dpi?: number,
    mode?: FrameDivideMode
  ) => { divided: boolean; layerTreeDelta?: LayerTreeDelta; tileDeltas?: TileDelta[] };
  deleteLayer?: (id: string) => void;
  updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
  pushHistoryStep: PushHistoryStepFn;
  showToast?: (msg: string) => void;
}

export interface UseShapeAndFillToolsResult {
  textSession: TextPlacementSession | null;
  setTextSession: React.Dispatch<React.SetStateAction<TextPlacementSession | null>>;
  textDragPreview: TextDragPreview | null;
  activeBalloon: SpeechBalloon | null;
  setActiveBalloon: React.Dispatch<React.SetStateAction<SpeechBalloon | null>>;
  frameDragPreview: FrameDragPreview | null;
  shapeDragPreview: ShapeDragPreview | null;
  lassoFillPreview: LassoFillPreview | null;
  openLayerForEditing: (layer: LayerItem) => boolean;
  isPipetteSamplingRef: React.MutableRefObject<boolean>;
  handleSampleColor: (pt: { x: number; y: number }, commit?: boolean) => void;
  handleConfirmText: () => void;
  handleCancelText: () => void;
  handleDeleteText: () => void;
  handleConfirmBalloon: () => void;
  handleDeleteBalloon: () => void;
  handleShapeFillPointerDown: (
    e: React.PointerEvent<HTMLElement>,
    pt: { x: number; y: number }
  ) => boolean;
  handleShapeFillPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;
  handleShapeFillPointerUp: (
    e: React.PointerEvent<HTMLElement>,
    pt: { x: number; y: number }
  ) => boolean;
}

function buildNativeShapeParams(
  preview: ShapeDragPreview,
  strokeColor: string,
  fillColor: string,
  layerId: string
): NativeShapeParams {
  const geom = computeShapeGeometry(
    preview.start,
    preview.end,
    preview.settings,
    preview.shiftKey,
    preview.altKey
  );
  const s = preview.settings;
  const startPt: [number, number] =
    s.shape === 'line' || s.shape === 'arrow' ? [geom.x1, geom.y1] : [geom.x, geom.y];
  const endPt: [number, number] =
    s.shape === 'line' || s.shape === 'arrow'
      ? [geom.x2, geom.y2]
      : [geom.x + geom.width, geom.y + geom.height];
  return {
    kind: s.shape,
    start: startPt,
    end: endPt,
    mode: s.mode,
    strokeColor,
    fillColor,
    strokeWidth: Math.max(1, s.strokeWidth),
    opacity: Math.max(0.01, Math.min(1, s.opacity)),
    dashed: s.dashed,
    dashLength: s.dashLength,
    dashGap: s.dashGap,
    cornerRadius: s.cornerRadius,
    polygonSides: s.polygonSides,
    starInnerRatio: s.starInnerRatio,
    antiAlias: s.antiAlias,
    layerId,
  };
}

function mapFillReferMode(mode: string | undefined): NativeFillReferMode {
  if (mode === 'refer-reference') return 'refer-reference';
  if (mode === 'active' || mode === 'refer-active') return 'refer-active';
  return 'refer-all';
}

export function useShapeAndFillTools({
  dimensions,
  colorMode,
  layers,
  activeLayer,
  activeLayerId,
  selectedLayerIds = [],
  selection,
  onCommitFloatingSelection,
  flushPendingHistoryTasks,
  isLayerEffectivelyVisible,
  getCanvasCoords,
  setActiveLayerId,
  upsertTextLayer,
  upsertBalloonLayer,
  createFrameFolder,
  divideFrameFolder,
  deleteLayer,
  updateLayerThumbnail,
  pushHistoryStep,
  showToast,
}: UseShapeAndFillToolsParams): UseShapeAndFillToolsResult {
  const [textSession, setTextSession] = useState<TextPlacementSession | null>(null);
  const [textDragPreview, setTextDragPreview] = useState<TextDragPreview | null>(null);
  const [activeBalloon, setActiveBalloon] = useState<SpeechBalloon | null>(null);
  const [editingBalloonLayerId, setEditingBalloonLayerId] = useState<string | null>(null);
  const [frameDragPreview, setFrameDragPreview] = useState<FrameDragPreview | null>(null);
  const [shapeDragPreview, setShapeDragPreview] = useState<ShapeDragPreview | null>(null);
  const [lassoFillPreview, setLassoFillPreview] = useState<LassoFillPreview | null>(null);

  const textSessionRef = useRef<TextPlacementSession | null>(null);
  textSessionRef.current = textSession;
  const upsertTextLayerRef = useRef(upsertTextLayer);
  upsertTextLayerRef.current = upsertTextLayer;
  const textDragRef = useRef<{ start: { x: number; y: number }; end: { x: number; y: number } } | null>(null);

  const isPipetteSamplingRef = useRef<boolean>(false);
  const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);
  const activeSmartFillModeRef = useRef<'lasso' | 'enclose-and-fill' | 'paint-unfilled' | null>(null);
  const frameStartRef = useRef<{ x: number; y: number } | null>(null);
  const shapeDragRef = useRef<{
    start: { x: number; y: number };
    end: { x: number; y: number };
    shiftKey: boolean;
    altKey: boolean;
    spaceHeld: boolean;
  } | null>(null);
  const shapePreviewInFlightRef = useRef<boolean>(false);

  // GPU Liquify session refs (120+ FPS native DX12 displacement field)
  const isLiquifyingRef = useRef<boolean>(false);
  const prevLiquifyPointRef = useRef<{ x: number; y: number } | null>(null);
  const liquifyLastPointerPosRef = useRef<{ pt: { x: number; y: number }; pressure: number } | null>(
    null
  );
  const liquifyRafIdRef = useRef<number | null>(null);
  const liquifyChainRef = useRef<Promise<unknown>>(Promise.resolve());

  const pushLiveShapePreview = useCallback(
    (preview: ShapeDragPreview) => {
      if (shapePreviewInFlightRef.current || !activeLayerId) return;
      const { primaryColor, secondaryColor } = useToolStore.getState();
      const fillColor = resolveShapeFillColor(preview.settings, primaryColor, secondaryColor);
      const docId = documentStore.getActiveDocumentId();
      shapePreviewInFlightRef.current = true;
      void nativeShapePreview(
        buildNativeShapeParams(preview, primaryColor, fillColor, activeLayerId),
        docId
      )
        .catch(() => {})
        .finally(() => {
          shapePreviewInFlightRef.current = false;
        });
    },
    [activeLayerId]
  );

  useEffect(() => {
    if (!shapeDragPreview) return;
    const handleKeyDown = (ev: KeyboardEvent) => {
      if (!shapeDragRef.current) return;
      if (ev.key === 'Escape') {
        ev.preventDefault();
        shapeDragRef.current = null;
        setShapeDragPreview(null);
        void nativeClearToolPreview();
        return;
      }
      if (ev.key === ' ' || ev.code === 'Space') {
        shapeDragRef.current.spaceHeld = true;
      }
      if (ev.key === 'Shift' || ev.key === 'Alt') {
        shapeDragRef.current.shiftKey = ev.shiftKey;
        shapeDragRef.current.altKey = ev.altKey;
        const next: ShapeDragPreview = {
          start: { ...shapeDragRef.current.start },
          end: { ...shapeDragRef.current.end },
          shiftKey: ev.shiftKey,
          altKey: ev.altKey,
          settings: useToolStore.getState().shapeSettings,
        };
        setShapeDragPreview(next);
        pushLiveShapePreview(next);
      }
    };
    const handleKeyUp = (ev: KeyboardEvent) => {
      if (!shapeDragRef.current) return;
      if (ev.key === ' ' || ev.code === 'Space') {
        shapeDragRef.current.spaceHeld = false;
      }
      if (ev.key === 'Shift' || ev.key === 'Alt') {
        shapeDragRef.current.shiftKey = ev.shiftKey;
        shapeDragRef.current.altKey = ev.altKey;
        const next: ShapeDragPreview = {
          start: { ...shapeDragRef.current.start },
          end: { ...shapeDragRef.current.end },
          shiftKey: ev.shiftKey,
          altKey: ev.altKey,
          settings: useToolStore.getState().shapeSettings,
        };
        setShapeDragPreview(next);
        pushLiveShapePreview(next);
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, [shapeDragPreview, pushLiveShapePreview]);

  useEffect(() => {
    const cancelLassoFill = () => {
      if (lassoFillPointsRef.current.length > 0 || activeSmartFillModeRef.current !== null) {
        lassoFillPointsRef.current = [];
        activeSmartFillModeRef.current = null;
        setLassoFillPreview(null);
      }
    };
    const cancelFrameDrag = () => {
      if (frameStartRef.current !== null) {
        frameStartRef.current = null;
        setFrameDragPreview(null);
      }
    };
    const unsub = useToolStore.subscribe(() => {
      const s = useToolStore.getState();
      const activeMode = activeSmartFillModeRef.current;
      if (
        s.tool !== 'fill' ||
        (activeMode !== null && s.fillSettings.method !== activeMode) ||
        (s.fillSettings.method !== 'lasso' &&
          s.fillSettings.method !== 'enclose-and-fill' &&
          s.fillSettings.method !== 'paint-unfilled')
      ) {
        cancelLassoFill();
      }
      if (s.tool !== 'frame') {
        cancelFrameDrag();
      }
    });
    const onKeyDown = (ev: KeyboardEvent) => {
      if (ev.key === 'Escape') {
        if (lassoFillPointsRef.current.length > 0) {
          ev.preventDefault();
          cancelLassoFill();
        }
        if (frameStartRef.current !== null) {
          ev.preventDefault();
          cancelFrameDrag();
        }
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => {
      unsub();
      window.removeEventListener('keydown', onKeyDown);
    };
  }, []);

  const openLayerForEditing = useCallback(
    (layer: LayerItem): boolean => {
      if (layer.locked) {
        showToast?.(t('Layer is locked'));
        return false;
      }
      if (layer.type === 'text' && layer.textData) {
        setActiveLayerId(layer.id);
        setActiveBalloon(null);
        setEditingBalloonLayerId(null);
        const td = layer.textData;
        const normalized = normalizeTextSettings(td);
        toolStoreActions.updateTextSettings(extractPersistableTextStyle(normalized));
        setTextSession({
          x: td.x,
          y: td.y,
          editingLayerId: layer.id,
          settings: normalized,
        });
        return true;
      }
      if (layer.type === 'balloon' && layer.balloonData) {
        setActiveLayerId(layer.id);
        setTextSession(null);
        setEditingBalloonLayerId(layer.id);
        setActiveBalloon(JSON.parse(JSON.stringify(layer.balloonData)));
        return true;
      }
      return false;
    },
    [setActiveLayerId, showToast]
  );

  const commitTextSession = useCallback((session: TextPlacementSession | null) => {
    if (!session) return;
    const persistable = extractPersistableTextStyle(session.settings);
    toolStoreActions.updateTextSettings(persistable);
    if (!session.settings.text.trim()) return;
    const normalized = normalizeTextSettings(session.settings);
    const textData: TextLayerData = {
      ...normalized,
      x: Math.round(session.x),
      y: Math.round(session.y),
    };
    upsertTextLayerRef.current(textData, session.editingLayerId);
  }, []);

  useEffect(() => {
    let prevTool = useToolStore.getState().tool;
    let prevTextSettings = useToolStore.getState().textSettings;
    const unsub = useToolStore.subscribe(() => {
      const state = useToolStore.getState();
      const curTool = state.tool;
      if (prevTool === 'liquify' && curTool !== 'liquify' && isLiquifyingRef.current) {
        isLiquifyingRef.current = false;
        if (liquifyRafIdRef.current) {
          cancelAnimationFrame(liquifyRafIdRef.current);
          liquifyRafIdRef.current = null;
        }
        liquifyChainRef.current = liquifyChainRef.current
          .then(() => nativeLiquifyCancel())
          .catch(() => {});
      }
      if (prevTool !== curTool && curTool !== 'text' && curTool !== 'object') {
        if (textDragRef.current) {
          textDragRef.current = null;
          setTextDragPreview(null);
        }
        if (textSessionRef.current) {
          commitTextSession(textSessionRef.current);
          setTextSession(null);
        }
      }
      prevTool = curTool;

      if (state.textSettings !== prevTextSettings) {
        prevTextSettings = state.textSettings;
        if (textSessionRef.current) {
          const syncedStyle = extractPersistableTextStyle(state.textSettings);
          setTextSession((prev) => {
            if (!prev) return null;
            const cur = prev.settings;
            let changed = false;
            for (const key of Object.keys(syncedStyle) as Array<keyof TextSettings>) {
              if (cur[key] !== syncedStyle[key]) {
                changed = true;
                break;
              }
            }
            return changed ? { ...prev, settings: { ...cur, ...syncedStyle } } : prev;
          });
        }
      }
    });
    return () => {
      unsub();
      if (liquifyRafIdRef.current) {
        cancelAnimationFrame(liquifyRafIdRef.current);
        liquifyRafIdRef.current = null;
      }
      if (isLiquifyingRef.current) {
        isLiquifyingRef.current = false;
        liquifyChainRef.current = liquifyChainRef.current
          .then(() => nativeLiquifyCancel())
          .catch(() => {});
      }
    };
  }, [commitTextSession]);

  // Instant <0.1 ms native Rust Eyedropper / Pipette directly on sparse tile grid
  const handleSampleColor = useCallback(
    (pt: { x: number; y: number }, commit = true) => {
      const docId = documentStore.getActiveDocumentId();
      void nativePickColor({
        x: Math.floor(pt.x),
        y: Math.floor(pt.y),
        sampleAllLayers: true,
        docId,
      })
        .then((picked) => {
          if (picked?.hex) {
            toolStoreActions.setPrimaryColor(picked.hex, commit, colorMode);
          }
        })
        .catch(() => {});
    },
    [colorMode]
  );

  const handleConfirmText = useCallback(() => {
    commitTextSession(textSessionRef.current);
    setTextSession(null);
  }, [commitTextSession]);

  const handleCancelText = useCallback(() => {
    setTextSession(null);
  }, []);

  const handleDeleteText = useCallback(() => {
    const editingId = textSessionRef.current?.editingLayerId;
    if (editingId && deleteLayer) {
      deleteLayer(editingId);
    }
    setTextSession(null);
  }, [deleteLayer]);

  const handleConfirmBalloon = useCallback(() => {
    if (!activeBalloon) return;
    upsertBalloonLayer(activeBalloon, editingBalloonLayerId);
    setActiveBalloon(null);
    setEditingBalloonLayerId(null);
  }, [activeBalloon, editingBalloonLayerId, upsertBalloonLayer]);

  const handleDeleteBalloon = useCallback(() => {
    if (editingBalloonLayerId && deleteLayer) {
      deleteLayer(editingBalloonLayerId);
    }
    setActiveBalloon(null);
    setEditingBalloonLayerId(null);
  }, [editingBalloonLayerId, deleteLayer]);

  const queueLiquifyStep = useCallback(
    (from: { x: number; y: number }, to: { x: number; y: number }, pressure: number) => {
      const ls = useToolStore.getState().liquifySettings;
      liquifyChainRef.current = liquifyChainRef.current
        .then(() =>
          nativeLiquifyStepGpu({
            fromX: from.x,
            fromY: from.y,
            toX: to.x,
            toY: to.y,
            pressure: Math.max(0.05, Math.min(1, pressure || 1.0)),
            settings: {
              mode: ls.mode,
              size: ls.size,
              strength: Math.max(0.01, Math.min(1, ls.strength / 100)),
              hardness: Math.max(0, Math.min(1, ls.hardness / 100)),
              usePressure: Boolean(ls.usePressure),
              multiLayer: Boolean(ls.multiLayer),
            },
          })
        )
        .catch((err) => console.warn('[Liquify] nativeLiquifyStepGpu failed:', err));
    },
    []
  );

  const startLiquifyLoop = useCallback(() => {
    if (liquifyRafIdRef.current) cancelAnimationFrame(liquifyRafIdRef.current);
    const tick = () => {
      if (!isLiquifyingRef.current || !liquifyLastPointerPosRef.current) {
        liquifyRafIdRef.current = null;
        return;
      }
      const { pt, pressure } = liquifyLastPointerPosRef.current;
      queueLiquifyStep(pt, pt, pressure);
      liquifyRafIdRef.current = requestAnimationFrame(tick);
    };
    liquifyRafIdRef.current = requestAnimationFrame(tick);
  }, [queueLiquifyStep]);

  const handleShapeFillPointerDown = useCallback(
    (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
      const {
        tool,
        primaryColor,
        fillSettings,
        balloonSettings,
        liquifySettings,
        shapeSettings,
      } = useToolStore.getState();

      if (tool === 'pipette') {
        e.preventDefault();
        try {
          (e.target as HTMLElement).setPointerCapture(e.pointerId);
        } catch {
          // Ignore
        }
        isPipetteSamplingRef.current = true;
        handleSampleColor(pt, false);
        return true;
      }

      if (tool === 'shape') {
        e.preventDefault();
        if (
          !activeLayer ||
          activeLayer.type !== 'raster' ||
          activeLayer.locked ||
          !isLayerEffectivelyVisible(activeLayer)
        ) {
          showToast?.(t('Select an unlocked, visible raster layer to draw shapes'));
          return true;
        }
        try {
          (e.target as HTMLElement).setPointerCapture(e.pointerId);
        } catch {
          // Ignore
        }
        shapeDragRef.current = {
          start: pt,
          end: pt,
          shiftKey: e.shiftKey,
          altKey: e.altKey,
          spaceHeld: false,
        };
        setShapeDragPreview({
          start: pt,
          end: pt,
          shiftKey: e.shiftKey,
          altKey: e.altKey,
          settings: shapeSettings,
        });
        return true;
      }

      if (tool === 'liquify') {
        e.preventDefault();
        const isMulti = Boolean(liquifySettings.multiLayer);
        if (
          !isMulti &&
          (!activeLayer ||
            activeLayer.type !== 'raster' ||
            activeLayer.locked ||
            !isLayerEffectivelyVisible(activeLayer))
        ) {
          showToast?.(t('Select an unlocked, visible raster layer to use Liquify'));
          return true;
        }
        flushPendingHistoryTasks?.();
        const targetIds = isMulti
          ? selectedLayerIds.length > 1
            ? selectedLayerIds
            : null
          : activeLayerId
            ? [activeLayerId]
            : null;

        isLiquifyingRef.current = true;
        prevLiquifyPointRef.current = pt;
        liquifyLastPointerPosRef.current = { pt, pressure: e.pressure || 1.0 };

        try {
          (e.target as HTMLElement).setPointerCapture(e.pointerId);
        } catch {
          // Ignore
        }

        liquifyChainRef.current = liquifyChainRef.current
          .then(() => nativeLiquifyBegin(isMulti, targetIds))
          .catch(() => {});

        const mode = liquifySettings.mode;
        if (
          mode === 'expand' ||
          mode === 'pinch' ||
          mode === 'twirl-cw' ||
          mode === 'twirl-ccw' ||
          mode === 'reconstruct'
        ) {
          queueLiquifyStep(pt, pt, e.pressure || 1.0);
          startLiquifyLoop();
        }
        return true;
      }

      if (tool === 'fill') {
        e.preventDefault();
        if (selection?.floating) {
          onCommitFloatingSelection?.();
        }
        if (!activeLayerId || !activeLayer) {
          showToast?.(t('Select a raster layer to use the Fill tool'));
          return true;
        }
        if (activeLayer.type === 'frame-folder') {
          showToast?.(t('Select a child layer inside the Frame Border Folder to fill'));
          return true;
        }
        if (activeLayer.type !== 'raster') {
          showToast?.(t('Select a raster layer to use the Fill tool'));
          return true;
        }
        if (activeLayer.locked) {
          showToast?.(t('Active layer is locked'));
          return true;
        }
        if (!isLayerEffectivelyVisible(activeLayer)) {
          showToast?.(t('Active layer is hidden'));
          return true;
        }

        if (
          fillSettings.method === 'lasso' ||
          fillSettings.method === 'enclose-and-fill' ||
          fillSettings.method === 'paint-unfilled'
        ) {
          const isTransparentInk = useToolStore.getState().isTransparentColor;
          const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
          if (fillSettings.method === 'paint-unfilled' && isTransparentInk && !isBg) {
            showToast?.(t('Switch off Transparent Ink (C) to paint unfilled areas'));
            return true;
          }
          try {
            (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);
          } catch {
            // Ignore
          }
          activeSmartFillModeRef.current = fillSettings.method;
          lassoFillPointsRef.current = [pt];
          setLassoFillPreview({
            points: [pt],
            color: primaryColor,
            opacity: Math.max(0, Math.min(1, fillSettings.opacity ?? 1)),
            isTransparentInk,
            mode: fillSettings.method,
            brushSize:
              fillSettings.method === 'paint-unfilled'
                ? Math.max(2, Math.min(300, fillSettings.brushSize ?? 24))
                : undefined,
          });
          return true;
        }

        const px = Math.floor(pt.x);
        const py = Math.floor(pt.y);
        if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return true;

        flushPendingHistoryTasks?.();
        const docId = documentStore.getActiveDocumentId();
        const isTransparentInk = useToolStore.getState().isTransparentColor;
        const targetLayerId = activeLayerId;

        void nativeFloodFillDoc(
          {
            x: px,
            y: py,
            color: isTransparentInk ? '#00000000' : primaryColor,
            tolerance: fillSettings.tolerance ?? 32,
            closeGap: fillSettings.closeGap ?? 0,
            areaScale: fillSettings.areaScale ?? 0,
            antiAlias: fillSettings.antiAlias ?? true,
            opacity: Math.max(0, Math.min(1, fillSettings.opacity ?? 1)),
            referMode: mapFillReferMode(fillSettings.method),
            layerId: targetLayerId,
          },
          docId
        )
          .then((fillRes) => {
            if (fillRes?.modified) {
              updateLayerThumbnail(targetLayerId, true);
            }
          })
          .catch((err) => {
            console.warn('Native flood fill failed:', err);
            showToast?.(t('Fill failed'));
          });
        return true;
      }

      if (tool === 'frame') {
        e.preventDefault();
        try {
          (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);
        } catch {
          // Ignore
        }
        const mode = useToolStore.getState().frameSettings.mode ?? 'create';
        frameStartRef.current = pt;
        setFrameDragPreview({ mode, start: pt, end: pt });
        return true;
      }

      if (tool === 'object') {
        e.preventDefault();
        const hit = hitTestEditableVectorLayer(layers, pt, isLayerEffectivelyVisible);
        if (hit) {
          openLayerForEditing(hit);
        } else {
          showToast?.(t('Click a Text or Speech Balloon layer to edit'));
        }
        return true;
      }

      if (tool === 'text') {
        e.preventDefault();
        const existingSession = textSessionRef.current;
        const hitText = hitTestEditableVectorLayer(layers, pt, isLayerEffectivelyVisible, 'text');
        if (existingSession) {
          const hadText = Boolean(existingSession.settings.text.trim());
          commitTextSession(existingSession);
          setTextSession(null);
          if (hitText && hitText.id !== existingSession.editingLayerId && openLayerForEditing(hitText)) {
            return true;
          }
          if (hadText) return true;
        } else if (hitText && openLayerForEditing(hitText)) {
          return true;
        }

        setActiveBalloon(null);
        setEditingBalloonLayerId(null);
        try {
          (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);
        } catch {
          // Ignore
        }
        textDragRef.current = { start: pt, end: pt };
        setTextDragPreview(null);
        return true;
      }

      if (tool === 'balloon') {
        e.preventDefault();
        const hitBalloon = hitTestEditableVectorLayer(
          layers,
          pt,
          isLayerEffectivelyVisible,
          'balloon'
        );
        if (hitBalloon && openLayerForEditing(hitBalloon)) {
          return true;
        }
        setTextSession(null);
        const newBalloon = createDefaultSpeechBalloon(
          Math.round(pt.x - 100),
          Math.round(pt.y - 70),
          200,
          140,
          balloonSettings.shape
        );
        newBalloon.strokeWidth = balloonSettings.strokeWidth;
        newBalloon.strokeColor = primaryColor || '#000000';
        newBalloon.fillColor = balloonSettings.fillColor || '#ffffff';
        newBalloon.vertical = balloonSettings.vertical;
        setEditingBalloonLayerId(null);
        setActiveBalloon(newBalloon);
        return true;
      }

      return false;
    },
    [
      handleSampleColor,
      activeLayer,
      activeLayerId,
      selectedLayerIds,
      isLayerEffectivelyVisible,
      flushPendingHistoryTasks,
      selection,
      onCommitFloatingSelection,
      dimensions,
      queueLiquifyStep,
      startLiquifyLoop,
      layers,
      updateLayerThumbnail,
      openLayerForEditing,
      commitTextSession,
      showToast,
    ]
  );

  const handleShapeFillPointerMove = useCallback(
    (e: React.PointerEvent<HTMLElement>): boolean => {
      const { tool, fillSettings, shapeSettings } = useToolStore.getState();

      if (tool === 'pipette') {
        if (isPipetteSamplingRef.current) {
          handleSampleColor(getCanvasCoords(e), false);
        }
        return true;
      }

      if (tool === 'shape') {
        if (!shapeDragRef.current) return true;
        const pt = getCanvasCoords(e);
        if (shapeDragRef.current.spaceHeld) {
          const dx = pt.x - shapeDragRef.current.end.x;
          const dy = pt.y - shapeDragRef.current.end.y;
          shapeDragRef.current.start = {
            x: shapeDragRef.current.start.x + dx,
            y: shapeDragRef.current.start.y + dy,
          };
        }
        shapeDragRef.current.end = pt;
        shapeDragRef.current.shiftKey = e.shiftKey;
        shapeDragRef.current.altKey = e.altKey;
        const preview: ShapeDragPreview = {
          start: { ...shapeDragRef.current.start },
          end: { ...pt },
          shiftKey: e.shiftKey,
          altKey: e.altKey,
          settings: shapeSettings,
        };
        setShapeDragPreview(preview);
        pushLiveShapePreview(preview);
        return true;
      }

      if (tool === 'liquify') {
        if (!isLiquifyingRef.current) return true;
        const pt = getCanvasCoords(e);
        const pressure = e.pressure || 1.0;
        liquifyLastPointerPosRef.current = { pt, pressure };
        const prev = prevLiquifyPointRef.current || pt;
        prevLiquifyPointRef.current = pt;
        queueLiquifyStep(prev, pt, pressure);
        return true;
      }

      if (tool === 'frame' && frameStartRef.current) {
        const mode = useToolStore.getState().frameSettings.mode ?? 'create';
        setFrameDragPreview({ mode, start: frameStartRef.current, end: getCanvasCoords(e) });
        return true;
      }

      if (tool === 'text' && textDragRef.current) {
        const pt = getCanvasCoords(e);
        textDragRef.current.end = pt;
        const dist = Math.hypot(
          pt.x - textDragRef.current.start.x,
          pt.y - textDragRef.current.start.y
        );
        if (dist >= 12) {
          setTextDragPreview({ start: { ...textDragRef.current.start }, end: { ...pt } });
        }
        return true;
      }

      if (
        tool === 'fill' &&
        (fillSettings.method === 'lasso' ||
          fillSettings.method === 'enclose-and-fill' ||
          fillSettings.method === 'paint-unfilled') &&
        lassoFillPointsRef.current.length > 0
      ) {
        const pt = getCanvasCoords(e);
        const pts = lassoFillPointsRef.current;
        const last = pts[pts.length - 1];
        const minSpacing = fillSettings.method === 'paint-unfilled' ? 1.0 : 1.5;
        if (!last || Math.hypot(pt.x - last.x, pt.y - last.y) >= minSpacing) {
          pts.push(pt);
          const ts = useToolStore.getState();
          setLassoFillPreview({
            points: [...pts],
            color: ts.primaryColor,
            opacity: Math.max(0, Math.min(1, ts.fillSettings.opacity ?? 1)),
            isTransparentInk: ts.isTransparentColor,
            mode: fillSettings.method,
            brushSize:
              fillSettings.method === 'paint-unfilled'
                ? Math.max(2, Math.min(300, ts.fillSettings.brushSize ?? 24))
                : undefined,
          });
        }
        return true;
      }

      return false;
    },
    [getCanvasCoords, handleSampleColor, pushLiveShapePreview, queueLiquifyStep]
  );

  const handleShapeFillPointerUp = useCallback(
    (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
      const {
        tool,
        primaryColor,
        secondaryColor,
        fillSettings,
        frameSettings,
        shapeSettings,
      } = useToolStore.getState();

      if (tool === 'pipette') {
        try {
          (e.target as HTMLElement).releasePointerCapture(e.pointerId);
        } catch {
          // Ignore
        }
        if (isPipetteSamplingRef.current) {
          isPipetteSamplingRef.current = false;
          handleSampleColor(pt, true);
        }
        return true;
      }

      if (tool === 'shape') {
        try {
          (e.target as HTMLElement).releasePointerCapture(e.pointerId);
        } catch {
          // Ignore
        }
        const drag = shapeDragRef.current;
        shapeDragRef.current = null;
        setShapeDragPreview(null);
        if (!drag) {
          void nativeClearToolPreview();
          return true;
        }
        if (
          !activeLayer ||
          activeLayer.type !== 'raster' ||
          activeLayer.locked ||
          !isLayerEffectivelyVisible(activeLayer)
        ) {
          void nativeClearToolPreview();
          return true;
        }

        flushPendingHistoryTasks?.();
        const fillColor = resolveShapeFillColor(shapeSettings, primaryColor, secondaryColor);
        const finalPreview: ShapeDragPreview = {
          start: drag.start,
          end: pt,
          shiftKey: e.shiftKey || drag.shiftKey,
          altKey: e.altKey || drag.altKey,
          settings: shapeSettings,
        };
        const docId = documentStore.getActiveDocumentId();
        const targetLayerId = activeLayerId;

        void nativeShapeCommit(
          buildNativeShapeParams(finalPreview, primaryColor, fillColor, targetLayerId),
          docId
        )
          .then((res) => {
            if (res?.modified) {
              updateLayerThumbnail(targetLayerId, true);
            }
          })
          .catch(() => {
            void nativeClearToolPreview();
          });
        return true;
      }

      if (tool === 'liquify') {
        try {
          (e.target as HTMLElement).releasePointerCapture(e.pointerId);
        } catch {
          // Ignore
        }
        if (liquifyRafIdRef.current) {
          cancelAnimationFrame(liquifyRafIdRef.current);
          liquifyRafIdRef.current = null;
        }
        if (isLiquifyingRef.current) {
          isLiquifyingRef.current = false;
          prevLiquifyPointRef.current = null;
          liquifyLastPointerPosRef.current = null;
          const docId = documentStore.getActiveDocumentId();
          liquifyChainRef.current = liquifyChainRef.current
            .then(() => nativeLiquifyCommit(docId))
            .then((res) => {
              if (res?.layerIds?.length) {
                for (const lid of res.layerIds) {
                  updateLayerThumbnail(lid, true);
                }
              }
            })
            .catch(() => {});
        }
        return true;
      }

      if (
        tool === 'fill' &&
        (fillSettings.method === 'lasso' ||
          fillSettings.method === 'enclose-and-fill' ||
          fillSettings.method === 'paint-unfilled') &&
        lassoFillPointsRef.current.length > 0
      ) {
        try {
          (e.currentTarget as HTMLElement)?.releasePointerCapture?.(e.pointerId);
        } catch {
          // Ignore
        }
        const activeMethod = activeSmartFillModeRef.current ?? fillSettings.method;
        const pts: [number, number][] = lassoFillPointsRef.current.map((p) => [p.x, p.y]);
        lassoFillPointsRef.current = [];
        activeSmartFillModeRef.current = null;
        setLassoFillPreview(null);
        if (activeMethod !== 'paint-unfilled' && pts.length < 3) {
          return true;
        }
        flushPendingHistoryTasks?.();
        if (
          !activeLayerId ||
          !activeLayer ||
          activeLayer.type !== 'raster' ||
          activeLayer.locked ||
          !isLayerEffectivelyVisible(activeLayer)
        ) {
          return true;
        }

        const docId = documentStore.getActiveDocumentId();
        const isTransparentInk = useToolStore.getState().isTransparentColor;
        const fillColor = isTransparentInk ? '#00000000' : primaryColor;
        const fillOpacity = Math.max(0, Math.min(1, fillSettings.opacity ?? 1));
        const targetLayerId = activeLayerId;

        const opPromise =
          activeMethod === 'enclose-and-fill'
            ? nativeEncloseFillDoc(
                {
                  points: pts,
                  color: fillColor,
                  tolerance: fillSettings.tolerance ?? 32,
                  closeGap: fillSettings.smartCloseGap ?? 10,
                  areaScale: fillSettings.smartAreaScale ?? 1,
                  antiAlias: fillSettings.antiAlias ?? true,
                  opacity: fillOpacity,
                  referMode: mapFillReferMode(fillSettings.smartReferMode ?? 'refer-reference'),
                  encloseTarget: fillSettings.encloseTarget ?? 'all-enclosed',
                  layerId: targetLayerId,
                },
                docId
              )
            : activeMethod === 'paint-unfilled'
              ? nativePaintUnfilledDoc(
                  {
                    points: pts,
                    brushRadius: Math.max(1, Math.min(150, (fillSettings.brushSize ?? 24) * 0.5)),
                    color: fillColor,
                    tolerance: fillSettings.tolerance ?? 32,
                    closeGap: fillSettings.smartCloseGap ?? 10,
                    areaScale: fillSettings.smartAreaScale ?? 1,
                    antiAlias: fillSettings.antiAlias ?? true,
                    opacity: fillOpacity,
                    referMode: mapFillReferMode(fillSettings.smartReferMode ?? 'refer-reference'),
                    layerId: targetLayerId,
                  },
                  docId
                )
              : nativeLassoFillDoc(
                  {
                    points: pts,
                    color: fillColor,
                    opacity: fillOpacity,
                    antiAlias: fillSettings.antiAlias ?? true,
                    layerId: targetLayerId,
                  },
                  docId
                );

        void opPromise
          .then((res) => {
            if (res?.modified) {
              updateLayerThumbnail(targetLayerId, true);
            } else if (activeMethod === 'enclose-and-fill') {
              showToast?.(
                t('No closed outline found — try increasing Close Gap or check Reference Layer')
              );
            }
          })
          .catch(() => {});
        return true;
      }

      if (tool === 'frame' && frameStartRef.current) {
        try {
          if ((e.currentTarget as HTMLElement)?.hasPointerCapture?.(e.pointerId)) {
            (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
          }
        } catch {
          // Ignore
        }
        const s = frameStartRef.current;
        frameStartRef.current = null;
        setFrameDragPreview(null);
        const mode = frameSettings.mode ?? 'create';
        const dpi = dimensions.dpi ?? 600;

        if (mode === 'divide') {
          if (Math.hypot(pt.x - s.x, pt.y - s.y) < 8) return true;
          let targetFolder: LayerItem | undefined;
          if (activeLayer?.type === 'frame-folder') {
            targetFolder = activeLayer;
          } else if (activeLayer?.parentId) {
            const parent = layers.find((l) => l.id === activeLayer.parentId);
            if (parent?.type === 'frame-folder') targetFolder = parent;
          }
          if (!targetFolder) {
            targetFolder = layers.find(
              (l) =>
                l.type === 'frame-folder' &&
                isLayerEffectivelyVisible(l) &&
                (l.comicFrames || []).some((f) => doesCutSegmentCrossFrame(f, s, pt))
            );
          }
          if (!targetFolder) {
            showToast?.(t('No Frame Border Folder intersected by cut line'));
            return true;
          }
          const divideMode = frameSettings.divideMode ?? 'same-folder';
          flushPendingHistoryTasks?.();
          const res = divideFrameFolder(targetFolder.id, s, pt, dpi, divideMode);
          if (res.divided) {
            pushHistoryStep(
              'frame',
              divideMode === 'split-folders' ? t('Divide Frame Folder') : t('Divide Frame Border'),
              null,
              null,
              targetFolder.id,
              undefined,
              res.tileDeltas,
              undefined,
              undefined,
              undefined,
              undefined,
              res.layerTreeDelta
            );
            showToast?.(
              divideMode === 'split-folders'
                ? t('Frame split into 2 Frame Folders')
                : t('Frame divided with manga gutter')
            );
          } else {
            showToast?.(t('Cut line must cross completely through a frame border'));
          }
          return true;
        }

        const minX = Math.floor(Math.min(s.x, pt.x));
        const minY = Math.floor(Math.min(s.y, pt.y));
        const maxX = Math.ceil(Math.max(s.x, pt.x));
        const maxY = Math.ceil(Math.max(s.y, pt.y));
        const w = maxX - minX;
        const h = maxY - minY;
        const overlapsCanvas =
          maxX > 0 && maxY > 0 && minX < dimensions.width && minY < dimensions.height;

        if (w >= 8 && h >= 8 && overlapsCanvas) {
          flushPendingHistoryTasks?.();
          const rectFrame = createRectFrame('', minX, minY, w, h, {
            dpi,
            borderWidth: frameSettings.thickness || 4,
            gutterVerticalPx: mmToPixels(
              frameSettings.gutterVerticalMm ?? MANGA_GUTTER_VERTICAL_MM,
              dpi
            ),
            gutterHorizontalPx: mmToPixels(
              frameSettings.gutterHorizontalMm ?? MANGA_GUTTER_HORIZONTAL_MM,
              dpi
            ),
            fillBackground: frameSettings.fillBackground,
            fillColor: frameSettings.fillColor || '#ffffff',
            strokeColor: frameSettings.strokeColor || primaryColor || '#000000',
          });
          const { folder, layerTreeDelta } = createFrameFolder([rectFrame], undefined, true);
          pushHistoryStep(
            'frame',
            t('Create Frame Folder'),
            null,
            null,
            folder.id,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            layerTreeDelta
          );
          showToast?.(t('Created Frame Border Folder (child layers auto-clip)'));
        }
        return true;
      }

      if (tool === 'text' && textDragRef.current) {
        try {
          if ((e.currentTarget as HTMLElement)?.hasPointerCapture?.(e.pointerId)) {
            (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
          }
        } catch {
          // Ignore
        }
        const drag = textDragRef.current;
        textDragRef.current = null;
        setTextDragPreview(null);

        const latestTextSettings = useToolStore.getState().textSettings;
        const dragW = Math.abs(pt.x - drag.start.x);
        const dragH = Math.abs(pt.y - drag.start.y);
        const isBoxDrag = dragW >= 36 && Math.hypot(dragW, dragH) >= 36;
        const originX = isBoxDrag ? Math.min(drag.start.x, pt.x) : drag.start.x;
        const originY = isBoxDrag ? Math.min(drag.start.y, pt.y) : drag.start.y;
        const maxWidth = isBoxDrag ? Math.round(dragW) : null;

        setTextSession({
          x: Math.round(originX),
          y: Math.round(originY),
          editingLayerId: null,
          settings: normalizeTextSettings({
            ...latestTextSettings,
            text: '',
            maxWidth,
          }),
        });
        return true;
      }

      return false;
    },
    [
      handleSampleColor,
      activeLayerId,
      activeLayer,
      layers,
      isLayerEffectivelyVisible,
      pushHistoryStep,
      updateLayerThumbnail,
      flushPendingHistoryTasks,
      dimensions,
      createFrameFolder,
      divideFrameFolder,
      showToast,
    ]
  );

  return {
    textSession,
    setTextSession,
    textDragPreview,
    activeBalloon,
    setActiveBalloon,
    frameDragPreview,
    shapeDragPreview,
    lassoFillPreview,
    openLayerForEditing,
    isPipetteSamplingRef,
    handleSampleColor,
    handleConfirmText,
    handleCancelText,
    handleDeleteText,
    handleConfirmBalloon,
    handleDeleteBalloon,
    handleShapeFillPointerDown,
    handleShapeFillPointerMove,
    handleShapeFillPointerUp,
  };
}