Skip to content

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

30.4 KB
Raw Blame
import React, { useState, useRef, useCallback, useEffect } from 'react';
import {
  BlendMode,
  CanvasColorMode,
  CanvasDimensions,
  CanvasSelection,
  LayerItem,
  LayerTreeDelta,
  Point2D,
  TileDelta,
  TransformMode,
  TransformSession,
} from '../../types/editor';
import { documentStore } from '../../utils/documentStore';
import type { TileFormat } from '../../utils/tauriEnv';
import {
  computePolygonBounds,
  isPointInSelection,
  selectionMetaToCanvasSelection,
  SelectionTileSnapshot,
} from '../../utils/selectionUtils';
import {
  fromNativeLayerNodeMeta,
  isNativeCanvasActive,
  nativeDeselect,
  nativeSelectAll,
  nativeSelectLasso,
  nativeSelectMagicWand,
  nativeSelectRect,
  nativeSelectionClearOutside,
  nativeSelectionClearPixels,
  nativeSelectionCommitFloating,
  nativeSelectionCopy,
  nativeSelectionCut,
  nativeSelectionExpand,
  nativeSelectionFeather,
  nativeSelectionFillColor,
  nativeSelectionGetState,
  nativeSelectionInvert,
  nativeSelectionLiftFloating,
  nativeSelectionMoveFloating,
  nativeSelectionMoveToNewLayer,
  nativeSelectionPaste,
  nativeTransformBegin,
  nativeTransformCancel,
  nativeTransformCommit,
  subscribeNativeSelectionChanged,
  type NativeSelectionCombineMode,
  type NativeTransformSessionSnapshot,
  type NativeWandReferMode,
} from '../../utils/nativeEngineBridge';
import { useDocumentStore, useToolStore } from '../../stores';
import { t } from '../../i18n';
import { PushHistoryStepFn } from './types';

export function nativeTransformSnapshotToSession(
  snap: NativeTransformSessionSnapshot,
  fallbackLayerId: string,
  isSelection: boolean
): TransformSession {
  const srcBounds = snap.sourceBounds ?? { x: 0, y: 0, width: 1, height: 1 };
  const safeW = Math.max(1, srcBounds.width || 1);
  const safeH = Math.max(1, srcBounds.height || 1);

  // Rust MeshState stores cell counts (cols, rows) with (rows + 1) * (cols + 1) control points,
  // while TS TransformSession stores vertex grid counts (meshCols, meshRows).
  const cellCols = Math.max(1, snap.mesh?.cols || 3);
  const cellRows = Math.max(1, snap.mesh?.rows || 3);
  const vCols = cellCols + 1;
  const vRows = cellRows + 1;
  const rawMeshPoints = Array.isArray(snap.mesh?.points) ? snap.mesh.points : [];
  const meshPoints: Point2D[][] = [];
  for (let r = 0; r < vRows; r++) {
    const row: Point2D[] = [];
    for (let c = 0; c < vCols; c++) {
      const pt = rawMeshPoints[r * vCols + c] ?? {
        x: srcBounds.x + (c / Math.max(1, cellCols)) * safeW,
        y: srcBounds.y + (r / Math.max(1, cellRows)) * safeH,
      };
      row.push({ x: pt.x, y: pt.y });
    }
    meshPoints.push(row);
  }

  const aff = snap.affine ?? {
    x: srcBounds.x,
    y: srcBounds.y,
    width: safeW,
    height: safeH,
    rotation: 0,
    skewX: 0,
    skewY: 0,
    flipX: false,
    flipY: false,
  };
  const targetLayerIds =
    Array.isArray(snap.targetLayerIds) && snap.targetLayerIds.length > 0
      ? [...snap.targetLayerIds]
      : [fallbackLayerId];
  const rawCorners = Array.isArray(snap.corners) && snap.corners.length === 4 ? snap.corners : null;
  const rawPins = Array.isArray(snap.puppet?.pins) ? snap.puppet.pins : [];
  const rawCagePoints = Array.isArray(snap.cage?.points) ? snap.cage.points : [];
  const rawCageRest = Array.isArray(snap.cage?.restPoints) ? snap.cage.restPoints : [];
  const cageClosed = Boolean(snap.cage?.closed);

  return {
    active: snap.active,
    nativeGpuActive: true,
    layerId: targetLayerIds[0] || fallbackLayerId,
    layerIds: targetLayerIds,
    bounds: {
      x: srcBounds.x,
      y: srcBounds.y,
      width: safeW,
      height: safeH,
    },
    x: Number.isFinite(aff.x) ? aff.x : srcBounds.x,
    y: Number.isFinite(aff.y) ? aff.y : srcBounds.y,
    width: Math.max(1, Number.isFinite(aff.width) ? aff.width : safeW),
    height: Math.max(1, Number.isFinite(aff.height) ? aff.height : safeH),
    rotation: ((Number.isFinite(aff.rotation) ? aff.rotation : 0) * 180) / Math.PI,
    flipH: Boolean(aff.flipX),
    flipV: Boolean(aff.flipY),
    isSelection,
    mode: snap.mode ?? 'affine',
    perspectiveQuad: rawCorners
      ? [
          { x: rawCorners[0].x, y: rawCorners[0].y },
          { x: rawCorners[1].x, y: rawCorners[1].y },
          { x: rawCorners[2].x, y: rawCorners[2].y },
          { x: rawCorners[3].x, y: rawCorners[3].y },
        ]
      : [
          { x: srcBounds.x, y: srcBounds.y },
          { x: srcBounds.x + safeW, y: srcBounds.y },
          { x: srcBounds.x + safeW, y: srcBounds.y + safeH },
          { x: srcBounds.x, y: srcBounds.y + safeH },
        ],
    meshCols: vCols,
    meshRows: vRows,
    meshPoints,
    puppet: {
      pins: rawPins.map((p) => ({
        id: p.id,
        restX: p.restX,
        restY: p.restY,
        x: p.x,
        y: p.y,
        rotation: p.rotation,
        depth: p.depth,
      })),
      selectedPinId: rawPins[0]?.id ?? null,
      rigidity: 'normal',
      density: 'normal',
      expansion: 6,
      showMesh: snap.showMesh !== false,
    },
    cage: {
      phase: cageClosed ? 'deform' : 'define',
      closed: cageClosed,
      points: rawCagePoints.map((v, idx) => ({
        id: `cage-${idx}`,
        restX: rawCageRest[idx]?.x ?? v.x,
        restY: rawCageRest[idx]?.y ?? v.y,
        x: v.x,
        y: v.y,
      })),
      selectedPointId: null,
      showCage: true,
    },
  };
}

export interface UseSelectionToolsParams {
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  layers: LayerItem[];
  activeLayer: LayerItem | undefined;
  activeLayerId: string;
  selectedLayerIds: string[];
  flushPendingHistoryTasks?: () => void;
  updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
  pushHistoryStep: PushHistoryStepFn;
  showToast: (msg: string) => void;
  onSyncNativeLayers?: (layers: LayerItem[], activeLayerId?: string) => void;
  copySelectionToClipboard?: (
    selection: CanvasSelection,
    targetId?: string
  ) => { copied: boolean; empty?: boolean; layerName?: string; snapshot?: SelectionTileSnapshot };
  createLayerFromTileSnapshot?: (
    tileSnapshot: {
      format: TileFormat;
      tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;
    },
    layerName: string,
    blendMode?: BlendMode,
    opacity?: number,
    layerOverrides?: Partial<LayerItem>
  ) => { id: string; name: string; tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta };
}

export interface UseSelectionToolsResult {
  selection: CanvasSelection | null;
  setSelection: React.Dispatch<React.SetStateAction<CanvasSelection | null>>;
  transformSession: TransformSession | null;
  setTransformSession: React.Dispatch<React.SetStateAction<TransformSession | null>>;
  isSelectionPenDrawingRef: React.MutableRefObject<boolean>;
  restoreSelectionFromHistory: (sel: CanvasSelection | null) => void;
  handleCommitFloatingSelection: () => void;
  handleDeselect: (recordHistory?: boolean | unknown) => void;
  handleClearSelection: () => void;
  handleDeleteOutsideSelection: () => void;
  handleCopySelection: () => void;
  handleCutSelection: () => void;
  handleMoveSelectionToNewLayer: () => void;
  handleCopySelectionToNewLayer: () => void;
  handleFillSelectionColor: () => void;
  handleExpandSelection: (pixels?: number) => void;
  handleContractSelection: (pixels?: number) => void;
  handleFeatherSelection: (radius?: number) => void;
  handleInvertSelection: () => void;
  handleSelectAll: () => void;
  handleStartTransform: (initialMode?: TransformMode) => void;
  handleApplyTransform: () => void;
  handleCancelTransform: () => void;
  handleSelectionPointerDown: (
    e: React.PointerEvent<HTMLElement>,
    pt: { x: number; y: number }
  ) => boolean;
  handleSelectionPointerMove: (pt: { x: number; y: number }) => boolean;
  handleSelectionPointerUp: (
    pt: { x: number; y: number },
    e?: React.PointerEvent<HTMLElement>
  ) => boolean;
}

function getCombineMode(e?: React.PointerEvent<HTMLElement>): NativeSelectionCombineMode {
  if (!e) return 'replace';
  if (e.shiftKey && e.altKey) return 'intersect';
  if (e.shiftKey) return 'add';
  if (e.altKey) return 'subtract';
  return 'replace';
}

export function useSelectionTools({
  dimensions,
  layers,
  activeLayer,
  activeLayerId,
  selectedLayerIds,
  flushPendingHistoryTasks,
  updateLayerThumbnail,
  onSyncNativeLayers,
  showToast,
}: UseSelectionToolsParams): UseSelectionToolsResult {
  const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
  const [selection, setSelection] = useState<CanvasSelection | null>(null);
  const [transformSession, setTransformSession] = useState<TransformSession | null>(null);

  const isSelectionPenDrawingRef = useRef<boolean>(false);
  const selectionDragRef = useRef<{
    isDragging: boolean;
    startX: number;
    startY: number;
    origX: number;
    origY: number;
  } | null>(null);
  const selectRectStartRef = useRef<{ x: number; y: number; mode: NativeSelectionCombineMode } | null>(
    null
  );
  const lassoPointsRef = useRef<Array<{ x: number; y: number }>>([]);
  const lassoModeRef = useRef<NativeSelectionCombineMode>('replace');

  const isMountedRef = useRef<boolean>(true);

  // Keep React selection action-bar metadata synchronized with native Rust SparseSelectionMask
  // (including SelectPen / SelectEraser strokes painted directly in DX12 and document tab switches!)
  useEffect(() => {
    isMountedRef.current = true;
    const unsub = subscribeNativeSelectionChanged((ev) => {
      if (!isMountedRef.current) return;
      const curDocId = documentStore.getActiveDocumentId();
      if (curDocId && ev.docId && ev.docId !== curDocId) return;
      setSelection(selectionMetaToCanvasSelection(ev.selection));
    });
    return () => {
      isMountedRef.current = false;
      unsub();
    };
  }, []);

  useEffect(() => {
    selectRectStartRef.current = null;
    lassoPointsRef.current = [];
    selectionDragRef.current = null;
    if (!activeDocumentId) {
      setSelection(null);
      return;
    }
    if (!isNativeCanvasActive()) {
      setSelection(null);
      return;
    }
    let cancelled = false;
    void nativeSelectionGetState(activeDocumentId)
      .then((meta) => {
        if (!cancelled && isMountedRef.current && documentStore.getActiveDocumentId() === activeDocumentId) {
          setSelection(selectionMetaToCanvasSelection(meta));
        }
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, [activeDocumentId]);

  const restoreSelectionFromHistory = useCallback((sel: CanvasSelection | null) => {
    selectRectStartRef.current = null;
    lassoPointsRef.current = [];
    selectionDragRef.current = null;
    isSelectionPenDrawingRef.current = false;
    setSelection(sel);
  }, []);

  const handleCommitFloatingSelection = useCallback(() => {
    if (!selection?.floating) return;
    const docId = documentStore.getActiveDocumentId();
    const lid = selection.floating.layerId || activeLayerId;
    void nativeSelectionCommitFloating(docId)
      .then((meta) => {
        setSelection(selectionMetaToCanvasSelection(meta));
        if (lid) updateLayerThumbnail(lid, true);
      })
      .catch(() => {});
  }, [selection, activeLayerId, updateLayerThumbnail]);

  const handleDeselect = useCallback((_recordHistory?: boolean | unknown) => {
    selectRectStartRef.current = null;
    lassoPointsRef.current = [];
    selectionDragRef.current = null;
    setSelection(null);
    void nativeDeselect(documentStore.getActiveDocumentId()).catch(() => {});
  }, []);

  const handleClearSelection = useCallback(() => {
    if (!selection) return;
    if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
      showToast(t('Select an unlocked raster layer'));
      return;
    }
    flushPendingHistoryTasks?.();
    const docId = documentStore.getActiveDocumentId();
    const lid = activeLayerId;
    void nativeSelectionClearPixels(lid, docId)
      .then((res) => {
        if (res?.modified) updateLayerThumbnail(lid, true);
      })
      .catch(() => {});
  }, [selection, activeLayer, activeLayerId, flushPendingHistoryTasks, updateLayerThumbnail, showToast]);

  const handleDeleteOutsideSelection = useCallback(() => {
    if (!selection) return;
    if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
      showToast(t('Select an unlocked raster layer'));
      return;
    }
    flushPendingHistoryTasks?.();
    const docId = documentStore.getActiveDocumentId();
    const lid = activeLayerId;
    void nativeSelectionClearOutside(lid, docId)
      .then((res) => {
        if (res?.modified) updateLayerThumbnail(lid, true);
      })
      .catch(() => {});
  }, [selection, activeLayer, activeLayerId, flushPendingHistoryTasks, updateLayerThumbnail, showToast]);

  const handleCopySelection = useCallback(() => {
    if (!activeLayer || activeLayer.type !== 'raster') {
      showToast(t('Select a raster layer to copy'));
      return;
    }
    const docId = documentStore.getActiveDocumentId();
    void nativeSelectionCopy(activeLayerId, docId)
      .then((ok) => {
        showToast(ok ? t('Copied selection to clipboard') : t('Selection is empty'));
      })
      .catch(() => {});
  }, [activeLayer, activeLayerId, showToast]);

  const handleCutSelection = useCallback(() => {
    if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
      showToast(t('Select an unlocked raster layer to cut'));
      return;
    }
    flushPendingHistoryTasks?.();
    const docId = documentStore.getActiveDocumentId();
    const lid = activeLayerId;
    void nativeSelectionCut(lid, docId)
      .then((ok) => {
        if (ok) {
          updateLayerThumbnail(lid, true);
          showToast(t('Cut selection to clipboard'));
        } else {
          showToast(t('Selection is empty'));
        }
      })
      .catch(() => {});
  }, [activeLayer, activeLayerId, flushPendingHistoryTasks, updateLayerThumbnail, showToast]);

  const handleMoveSelectionToNewLayer = useCallback(() => {
    if (!selection) return;
    if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
      showToast(t('Select an unlocked raster layer'));
      return;
    }
    flushPendingHistoryTasks?.();
    const docId = documentStore.getActiveDocumentId();
    const newId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
    void nativeSelectionMoveToNewLayer(newId, activeLayerId, docId)
      .then((snap) => {
        if (snap) {
          if (Array.isArray(snap.layers) && snap.layers.length > 0) {
            onSyncNativeLayers?.(
              snap.layers.map(fromNativeLayerNodeMeta),
              snap.activeLayerId ?? newId
            );
          }
          updateLayerThumbnail(activeLayerId, true);
          updateLayerThumbnail(newId, true);
          showToast(t('Moved selection to new layer'));
        }
      })
      .catch(() => {});
  }, [
    selection,
    activeLayer,
    activeLayerId,
    flushPendingHistoryTasks,
    onSyncNativeLayers,
    updateLayerThumbnail,
    showToast,
  ]);

  const handleCopySelectionToNewLayer = useCallback(() => {
    if (!selection) return;
    if (!activeLayer || activeLayer.type !== 'raster') return;
    flushPendingHistoryTasks?.();
    const docId = documentStore.getActiveDocumentId();
    const newId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
    void nativeSelectionCopy(activeLayerId, docId)
      .then((ok) => (ok ? nativeSelectionPaste(newId, docId) : null))
      .then((snap) => {
        if (snap) {
          if (Array.isArray(snap.layers) && snap.layers.length > 0) {
            onSyncNativeLayers?.(
              snap.layers.map(fromNativeLayerNodeMeta),
              snap.activeLayerId ?? newId
            );
          }
          updateLayerThumbnail(newId, true);
          showToast(t('Copied selection to new layer'));
        }
      })
      .catch(() => {});
  }, [
    selection,
    activeLayer,
    activeLayerId,
    flushPendingHistoryTasks,
    onSyncNativeLayers,
    updateLayerThumbnail,
    showToast,
  ]);

  const handleFillSelectionColor = useCallback(() => {
    if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
      showToast(t('Select an unlocked raster layer'));
      return;
    }
    flushPendingHistoryTasks?.();
    const { primaryColor } = useToolStore.getState();
    const docId = documentStore.getActiveDocumentId();
    const lid = activeLayerId;
    void nativeSelectionFillColor({
      color: primaryColor || '#000000',
      opacity: 1.0,
      layerId: lid,
      docId,
    })
      .then((res) => {
        if (res?.modified) updateLayerThumbnail(lid, true);
      })
      .catch(() => {});
  }, [activeLayer, activeLayerId, flushPendingHistoryTasks, updateLayerThumbnail, showToast]);

  const handleExpandSelection = useCallback((pixels = 5) => {
    void nativeSelectionExpand(Math.abs(pixels), documentStore.getActiveDocumentId())
      .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
      .catch(() => {});
  }, []);

  const handleContractSelection = useCallback((pixels = 5) => {
    void nativeSelectionExpand(-Math.abs(pixels), documentStore.getActiveDocumentId())
      .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
      .catch(() => {});
  }, []);

  const handleFeatherSelection = useCallback((radius = 5) => {
    void nativeSelectionFeather(Math.max(1, radius), documentStore.getActiveDocumentId())
      .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
      .catch(() => {});
  }, []);

  const handleInvertSelection = useCallback(() => {
    void nativeSelectionInvert(documentStore.getActiveDocumentId())
      .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
      .catch(() => {});
  }, []);

  const handleSelectAll = useCallback(() => {
    void nativeSelectAll(documentStore.getActiveDocumentId())
      .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
      .catch(() => {});
  }, []);

  // --- Interactive 5-Mode DX12 GPU Transform & Warp ---

  const handleStartTransform = useCallback(
    (initialMode: TransformMode = 'affine') => {
      if (!activeLayer) {
        showToast(t('Select a layer to transform'));
        return;
      }
      if (activeLayer.locked) {
        showToast(t('Layer is locked'));
        return;
      }
      flushPendingHistoryTasks?.();
      const targets =
        selectedLayerIds.length > 1
          ? selectedLayerIds
          : activeLayer.type === 'folder'
            ? [activeLayer.id]
            : [activeLayerId];
      const hasSel = Boolean(selection);
      const fallbackId = activeLayerId;

      void nativeTransformBegin(initialMode, targets)
        .then((snap) => {
          if (!snap || !snap.active) {
            showToast(t('Nothing to transform on selected layer'));
            return;
          }
          setTransformSession(nativeTransformSnapshotToSession(snap, fallbackId, hasSel));
        })
        .catch((err) => {
          console.warn('[NativeTransform] begin failed:', err);
          showToast(t('Nothing to transform on selected layer'));
        });
    },
    [activeLayer, activeLayerId, selectedLayerIds, selection, flushPendingHistoryTasks, showToast]
  );

  const handleApplyTransform = useCallback(() => {
    if (!transformSession) return;
    const docId = documentStore.getActiveDocumentId();
    const fallbackIds = transformSession.layerIds ?? [transformSession.layerId];
    setTransformSession(null);

    void nativeTransformCommit(docId)
      .then((res) => {
        const dirtyIds = res?.layerIds?.length ? res.layerIds : fallbackIds;
        for (const lid of dirtyIds) {
          updateLayerThumbnail(lid, true);
        }
      })
      .catch((err) => {
        console.warn('[NativeTransform] commit failed:', err);
      });
  }, [transformSession, updateLayerThumbnail]);

  const handleCancelTransform = useCallback(() => {
    if (!transformSession) return;
    setTransformSession(null);
    void nativeTransformCancel();
  }, [transformSession]);

  // --- Pointer Interactions for Selection Tools ---

  const handleSelectionPointerDown = useCallback(
    (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
      const { tool, wandSettings } = useToolStore.getState();
      if (
        tool !== 'select-rect' &&
        tool !== 'select-lasso' &&
        tool !== 'select-wand' &&
        tool !== 'select-pen' &&
        tool !== 'select-eraser'
      ) {
        return false;
      }

      // SelectPen & SelectEraser strokes run natively on the zero-IPC Rust DX12 stroke path!
      if (tool === 'select-pen' || tool === 'select-eraser') {
        return true;
      }

      e.preventDefault();
      const combineMode = getCombineMode(e);
      const docId = documentStore.getActiveDocumentId();

      // Drag inside existing selection (with no modifier keys) lifts floating selection on GPU
      if (
        combineMode === 'replace' &&
        selection &&
        !selection.isDraftPreview &&
        isPointInSelection(pt.x, pt.y, selection) &&
        tool !== 'select-wand'
      ) {
        if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
          return true;
        }
        try {
          (e.target as HTMLElement).setPointerCapture(e.pointerId);
        } catch {
          // Ignore
        }
        const origX = selection.floating ? selection.floating.x : selection.bounds.x;
        const origY = selection.floating ? selection.floating.y : selection.bounds.y;
        selectionDragRef.current = {
          isDragging: true,
          startX: pt.x,
          startY: pt.y,
          origX,
          origY,
        };
        if (!selection.floating) {
          void nativeSelectionLiftFloating(activeLayerId, docId)
            .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
            .catch(() => {});
        }
        return true;
      }

      // Commit floating pixels before creating a brand-new selection
      if (selection?.floating) {
        handleCommitFloatingSelection();
      }

      if (tool === 'select-wand') {
        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;
        const referMode: NativeWandReferMode =
          wandSettings.referMode === 'all'
            ? 'all'
            : wandSettings.referMode === 'reference'
              ? 'reference'
              : 'active';
        void nativeSelectMagicWand({
          docId,
          x: px,
          y: py,
          tolerance: wandSettings.tolerance ?? 32,
          contiguous: wandSettings.contiguous ?? true,
          antiAlias: wandSettings.antiAlias ?? true,
          referMode,
          mode: combineMode,
        })
          .then((meta) => setSelection(selectionMetaToCanvasSelection(meta)))
          .catch(() => {});
        return true;
      }

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

      if (tool === 'select-rect') {
        selectRectStartRef.current = { x: pt.x, y: pt.y, mode: combineMode };
        setSelection({
          type: 'rect',
          bounds: { x: Math.floor(pt.x), y: Math.floor(pt.y), width: 0, height: 0 },
          isDraftPreview: true,
        });
        return true;
      }

      if (tool === 'select-lasso') {
        lassoModeRef.current = combineMode;
        lassoPointsRef.current = [pt];
        setSelection({
          type: 'lasso',
          bounds: { x: Math.floor(pt.x), y: Math.floor(pt.y), width: 0, height: 0 },
          polygon: [pt],
          isDraftPreview: true,
        });
        return true;
      }

      return false;
    },
    [
      selection,
      activeLayer,
      activeLayerId,
      dimensions.width,
      dimensions.height,
      handleCommitFloatingSelection,
    ]
  );

  const handleSelectionPointerMove = useCallback(
    (pt: { x: number; y: number }): boolean => {
      const { tool } = useToolStore.getState();

      if (selectionDragRef.current?.isDragging) {
        const d = selectionDragRef.current;
        const newX = Math.round(d.origX + (pt.x - d.startX));
        const newY = Math.round(d.origY + (pt.y - d.startY));
        void nativeSelectionMoveFloating(newX, newY, documentStore.getActiveDocumentId()).catch(
          () => {}
        );
        setSelection((prev) =>
          prev
            ? {
                ...prev,
                bounds: { ...prev.bounds, x: newX, y: newY },
                floating: prev.floating ? { ...prev.floating, x: newX, y: newY } : prev.floating,
              }
            : null
        );
        return true;
      }

      if (selectRectStartRef.current) {
        if (tool !== 'select-rect') {
          selectRectStartRef.current = null;
          return false;
        }
        const s = selectRectStartRef.current;
        const x0 = Math.max(0, Math.min(dimensions.width, Math.floor(Math.min(s.x, pt.x))));
        const y0 = Math.max(0, Math.min(dimensions.height, Math.floor(Math.min(s.y, pt.y))));
        const x1 = Math.max(0, Math.min(dimensions.width, Math.ceil(Math.max(s.x, pt.x))));
        const y1 = Math.max(0, Math.min(dimensions.height, Math.ceil(Math.max(s.y, pt.y))));
        setSelection({
          type: 'rect',
          bounds: { x: x0, y: y0, width: Math.max(0, x1 - x0), height: Math.max(0, y1 - y0) },
          isDraftPreview: true,
        });
        return true;
      }

      if (lassoPointsRef.current.length > 0) {
        if (tool !== 'select-lasso') {
          lassoPointsRef.current = [];
          return false;
        }
        const pts = lassoPointsRef.current;
        const last = pts[pts.length - 1];
        if (!last || Math.hypot(pt.x - last.x, pt.y - last.y) >= 2) {
          pts.push(pt);
          setSelection({
            type: 'lasso',
            bounds: computePolygonBounds(pts),
            polygon: [...pts],
            isDraftPreview: true,
          });
        }
        return true;
      }

      return false;
    },
    [dimensions.height, dimensions.width]
  );

  const handleSelectionPointerUp = useCallback(
    (pt: { x: number; y: number }, e?: React.PointerEvent<HTMLElement>): boolean => {
      if (e) {
        try {
          if ((e.target as HTMLElement).hasPointerCapture?.(e.pointerId)) {
            (e.target as HTMLElement).releasePointerCapture(e.pointerId);
          }
        } catch {
          // Ignore
        }
      }

      const docId = documentStore.getActiveDocumentId();

      if (selectionDragRef.current?.isDragging) {
        selectionDragRef.current = null;
        return true;
      }

      if (selectRectStartRef.current) {
        const s = selectRectStartRef.current;
        selectRectStartRef.current = null;
        const x0 = Math.max(0, Math.min(dimensions.width, Math.floor(Math.min(s.x, pt.x))));
        const y0 = Math.max(0, Math.min(dimensions.height, Math.floor(Math.min(s.y, pt.y))));
        const x1 = Math.max(0, Math.min(dimensions.width, Math.ceil(Math.max(s.x, pt.x))));
        const y1 = Math.max(0, Math.min(dimensions.height, Math.ceil(Math.max(s.y, pt.y))));
        const w = x1 - x0;
        const h = y1 - y0;
        if (w < 2 || h < 2) {
          if (s.mode === 'replace') {
            handleDeselect();
          } else if (isNativeCanvasActive()) {
            void nativeSelectionGetState(docId)
              .then((meta) => {
                if (isMountedRef.current) setSelection(selectionMetaToCanvasSelection(meta));
              })
              .catch(() => {});
          }
          return true;
        }
        if (isNativeCanvasActive()) {
          void nativeSelectRect({ docId, x: x0, y: y0, width: w, height: h, mode: s.mode })
            .then((meta) => {
              if (isMountedRef.current) setSelection(selectionMetaToCanvasSelection(meta));
            })
            .catch(() => {});
        } else {
          setSelection({
            type: 'rect',
            bounds: { x: x0, y: y0, width: w, height: h },
          });
        }
        return true;
      }

      if (lassoPointsRef.current.length > 0) {
        const rawPts = lassoPointsRef.current;
        const pts = rawPts.map((p): [number, number] => [p.x, p.y]);
        const mode = lassoModeRef.current;
        lassoPointsRef.current = [];
        if (pts.length < 3) {
          if (mode === 'replace') {
            handleDeselect();
          } else if (isNativeCanvasActive()) {
            void nativeSelectionGetState(docId)
              .then((meta) => {
                if (isMountedRef.current) setSelection(selectionMetaToCanvasSelection(meta));
              })
              .catch(() => {});
          }
          return true;
        }
        if (isNativeCanvasActive()) {
          void nativeSelectLasso({ docId, points: pts, antiAlias: true, mode })
            .then((meta) => {
              if (isMountedRef.current) setSelection(selectionMetaToCanvasSelection(meta));
            })
            .catch(() => {});
        } else {
          const polyBounds = computePolygonBounds(rawPts);
          const x0 = Math.max(0, Math.min(dimensions.width, Math.floor(polyBounds.x)));
          const y0 = Math.max(0, Math.min(dimensions.height, Math.floor(polyBounds.y)));
          const x1 = Math.max(
            0,
            Math.min(dimensions.width, Math.ceil(polyBounds.x + polyBounds.width))
          );
          const y1 = Math.max(
            0,
            Math.min(dimensions.height, Math.ceil(polyBounds.y + polyBounds.height))
          );
          if (x1 - x0 < 2 || y1 - y0 < 2) {
            if (mode === 'replace') handleDeselect();
          } else {
            setSelection({
              type: 'lasso',
              bounds: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 },
              polygon: rawPts,
            });
          }
        }
        return true;
      }

      return false;
    },
    [dimensions.height, dimensions.width, handleDeselect]
  );

  // Unused layers reference kept in signature for caller compatibility
  void layers;

  return {
    selection,
    setSelection,
    transformSession,
    setTransformSession,
    isSelectionPenDrawingRef,
    restoreSelectionFromHistory,
    handleCommitFloatingSelection,
    handleDeselect,
    handleClearSelection,
    handleDeleteOutsideSelection,
    handleCopySelection,
    handleCutSelection,
    handleMoveSelectionToNewLayer,
    handleCopySelectionToNewLayer,
    handleFillSelectionColor,
    handleExpandSelection,
    handleContractSelection,
    handleFeatherSelection,
    handleInvertSelection,
    handleSelectAll,
    handleStartTransform,
    handleApplyTransform,
    handleCancelTransform,
    handleSelectionPointerDown,
    handleSelectionPointerMove,
    handleSelectionPointerUp,
  };
}