Skip to content

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

16.1 KB
Raw Blame
import React, { useEffect, useRef } from 'react';
import {
  BrushSettings,
  CanvasDimensions,
  FillSettings,
  LiquifySettings,
  RetouchSettings,
  ToolType,
} from '../../types/editor';
import { ModifierAction } from '../../types/settings';
import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
import { screenToCanvas } from '../../utils/canvasUtils';
import { resolvePointerModifierAction } from '../../utils/shortcutManager';
import { isNativeStrokeTool } from '../../utils/nativeEngineBridge';
import { isWorkspaceInteractionActive } from '../../utils/workspacePointerGuard';
import { artworkTimeTracker } from '../../utils/artworkTimeTracker';
import { recoveryService } from '../../services/recoveryService';
import { toolStoreActions, uiStoreActions, useToolStore, useUiStore } from '../../stores';
import { extractCoalescedEvents, extractPredictedEvents } from './types';

export interface UseCanvasPointerHandlersParams {
  viewportRef: React.RefObject<HTMLDivElement | null>;
  dimensions: CanvasDimensions;
  brushSettings: BrushSettings;
  fillSettings?: FillSettings;
  liquifySettings?: LiquifySettings;
  retouchSettings?: RetouchSettings;
  tool: ToolType;
  navigation?: CanvasNavigationHandle;
  pan: { x: number; y: number };
  zoom: number;
  rotation: number;
  flipX: boolean;
  flipY: boolean;
  isSpaceDown: boolean;
  quickPalettePos: { x: number; y: number } | null;
  setQuickPalettePos: React.Dispatch<React.SetStateAction<{ x: number; y: number } | null>>;
  setIsResizingBrush: React.Dispatch<React.SetStateAction<boolean>>;
  resizeOriginRef: React.MutableRefObject<{ clientX: number; clientY: number }>;
  resizeStartSettingsRef: React.MutableRefObject<{ size: number; hardness: number }>;
  onStartPan: (e: React.PointerEvent) => void;
  onStartRotate: (e: React.PointerEvent) => void;
  onStartZoomDrag?: (e: React.PointerEvent) => void;
  onSampleColor?: (pt: { x: number; y: number }, commit?: boolean) => void;
  onUndo?: () => void;
  onSwapColors?: () => void;
  onPointerDown: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[]) => void;
  onPointerMove: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[], predicted?: PointerEvent[]) => void;
  onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
  nativeCanvasActive?: boolean;
  nativeStrokeOwned?: boolean;
}

export function useCanvasPointerHandlers({
  viewportRef,
  dimensions,
  brushSettings,
  fillSettings,
  liquifySettings,
  retouchSettings,
  tool,
  navigation,
  pan,
  zoom,
  rotation,
  flipX,
  flipY,
  isSpaceDown,
  quickPalettePos,
  setQuickPalettePos,
  setIsResizingBrush,
  resizeOriginRef,
  resizeStartSettingsRef,
  onStartPan,
  onStartRotate,
  onStartZoomDrag,
  onSampleColor,
  onUndo,
  onSwapColors,
  onPointerDown,
  onPointerMove,
  onPointerUp,
  nativeCanvasActive = false,
  nativeStrokeOwned,
}: UseCanvasPointerHandlersParams) {
  const tempEraserPrevToolRef = useRef<ToolType | null>(null);
  const activeDomPointerIdRef = useRef<number | null>(null);

  const releaseExternalFocus = () => {
    const active = document.activeElement as HTMLElement | null;
    if (!active || active === document.body) return;
    if (viewportRef.current?.contains(active)) return;
    const tag = active.tagName;
    if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || tag === 'BUTTON') {
      active.blur();
    }
  };

  // Start brush resizing drag
  const startBrushResize = (e: React.PointerEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsResizingBrush(true);
    resizeOriginRef.current = { clientX: e.clientX, clientY: e.clientY };
    resizeStartSettingsRef.current = {
      size:
        tool === 'liquify' && liquifySettings
          ? liquifySettings.size
          : tool === 'retouch' && retouchSettings
            ? retouchSettings.size
            : tool === 'fill' && fillSettings?.method === 'paint-unfilled'
              ? Math.max(2, Math.min(300, fillSettings.brushSize ?? 24))
              : brushSettings.size,
      hardness:
        tool === 'retouch' && retouchSettings
          ? retouchSettings.hardness / 100
          : (brushSettings.hardness ?? 1.0),
    };
  };

  const modifierEyedropperCleanupRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    return () => {
      modifierEyedropperCleanupRef.current?.();
      modifierEyedropperCleanupRef.current = null;
    };
  }, []);

  // Start continuous eyedropper sampling for modifier buttons (e.g. Right Click / Barrel Button)
  const startModifierEyedropper = (e: React.PointerEvent) => {
    if (!onSampleColor || !viewportRef.current) return;
    e.preventDefault();
    e.stopPropagation();

    modifierEyedropperCleanupRef.current?.();

    let lastClientX = e.clientX;
    let lastClientY = e.clientY;

    const sampleAtClient = (clientX: number, clientY: number, commit: boolean) => {
      const vp = viewportRef.current;
      if (!vp) return;
      const rect = vp.getBoundingClientRect();
      const cam = navigation
        ? navigation.getCameraState()
        : { pan, zoom, rotation, flipX, flipY };
      const pt = screenToCanvas(
        clientX,
        clientY,
        rect,
        cam.pan,
        cam.zoom,
        cam.rotation,
        dimensions,
        cam.flipX,
        cam.flipY
      );
      onSampleColor(pt, commit);
    };

    sampleAtClient(lastClientX, lastClientY, false);

    const handleMove = (ev: PointerEvent) => {
      lastClientX = ev.clientX;
      lastClientY = ev.clientY;
      sampleAtClient(lastClientX, lastClientY, false);
    };
    const cleanup = () => {
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
      window.removeEventListener('pointercancel', handleCancel);
      window.removeEventListener('blur', handleCancel);
      if (modifierEyedropperCleanupRef.current === cleanup) {
        modifierEyedropperCleanupRef.current = null;
      }
    };
    const handleUp = (ev: PointerEvent) => {
      lastClientX = ev.clientX;
      lastClientY = ev.clientY;
      sampleAtClient(lastClientX, lastClientY, true);
      cleanup();
    };
    const handleCancel = () => {
      cleanup();
    };
    modifierEyedropperCleanupRef.current = cleanup;
    window.addEventListener('pointermove', handleMove, { passive: true });
    window.addEventListener('pointerup', handleUp);
    window.addEventListener('pointercancel', handleCancel);
    window.addEventListener('blur', handleCancel);
  };

  // Open floating Quick Palette near cursor when mapped to 'quick-palette'
  const openQuickPaletteAt = (e: React.PointerEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const vp = viewportRef.current;
    if (!vp) return;
    const rect = vp.getBoundingClientRect();
    const x = Math.max(12, Math.min(rect.width - 210, e.clientX - rect.left));
    const y = Math.max(12, Math.min(rect.height - 150, e.clientY - rect.top));
    setQuickPalettePos({ x, y });
  };

  // Dispatch a resolved ModifierAction; returns true if the event was consumed
  const dispatchModifierAction = (
    action: ModifierAction,
    e: React.PointerEvent<HTMLElement>,
    allowDrawingPassThrough: boolean
  ): boolean => {
    switch (action) {
      case 'pan':
        e.stopPropagation();
        onStartPan(e);
        return true;
      case 'rotate':
        e.stopPropagation();
        onStartRotate(e);
        return true;
      case 'zoom-drag':
        if (onStartZoomDrag) {
          e.stopPropagation();
          onStartZoomDrag(e);
          return true;
        }
        return false;
      case 'brush-size':
        startBrushResize(e);
        return true;
      case 'eyedropper':
        if (
          allowDrawingPassThrough &&
          e.button === 0 &&
          e.altKey &&
          (tool === 'transform' ||
            (tool === 'retouch' && retouchSettings?.mode === 'clone-stamp') ||
            tool === 'pen' ||
            tool === '3d')
        ) {
          return false;
        }
        if (e.button !== 0 || !allowDrawingPassThrough) {
          startModifierEyedropper(e);
          return true;
        }
        // When button 0 + Alt is held, GlobalShortcutListener already switched tool to pipette,
        // or if not, sample directly via startModifierEyedropper
        if (tool !== 'pipette') {
          startModifierEyedropper(e);
          return true;
        }
        return false;
      case 'temp-eraser': {
        if (!allowDrawingPassThrough) return false;
        const cur = useToolStore.getState().tool;
        if (cur !== 'eraser') {
          tempEraserPrevToolRef.current = cur;
          toolStoreActions.selectTool('eraser');
        }
        return false; // let stroke begin on eraser
      }
      case 'undo':
        e.preventDefault();
        e.stopPropagation();
        onUndo?.();
        return true;
      case 'swap-colors':
        e.preventDefault();
        e.stopPropagation();
        onSwapColors?.();
        return true;
      case 'quick-palette':
        openQuickPaletteAt(e);
        return true;
      case 'straight-line':
      case 'none':
      default:
        return false;
    }
  };

  // Native DX12 engine owns Space+drag (pan/rotate/zoom-drag) directly at 120–240 Hz for
  // both mouse (WH_MOUSE_LL) and stylus (WinTab/Windows Ink). Skip duplicate JS drag loops
  // so WebView2 never fights Rust over camera coordinates.
  const isNativeOwnedSpaceNav = (
    resolved: { slot: string; action: ModifierAction },
    e: React.PointerEvent<HTMLElement>
  ): boolean => {
    if (!nativeCanvasActive || e.pointerType === 'touch') return false;
    if (
      resolved.slot !== 'space' &&
      resolved.slot !== 'shiftSpace' &&
      resolved.slot !== 'ctrlSpace'
    ) {
      return false;
    }
    return (
      resolved.action === 'pan' ||
      resolved.action === 'rotate' ||
      resolved.action === 'zoom-drag'
    );
  };

  // Viewport background pointer down (fallback if an unstopped event bubbles past interaction surface)
  const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.defaultPrevented || isWorkspaceInteractionActive()) return;
    releaseExternalFocus();
    if (quickPalettePos) setQuickPalettePos(null);

    const modSettings = useUiStore.getState().appSettings.modifierKeys;
    const resolved = resolvePointerModifierAction(
      {
        button: e.button,
        pointerType: e.pointerType,
        ctrlKey: e.ctrlKey,
        metaKey: e.metaKey,
        shiftKey: e.shiftKey,
        altKey: e.altKey,
        isSpaceDown,
      },
      modSettings
    );
    if (resolved) {
      if (useUiStore.getState().isResizeCanvasModalOpen) {
        if (
          resolved.action === 'pan' ||
          resolved.action === 'rotate' ||
          resolved.action === 'zoom-drag'
        ) {
          dispatchModifierAction(resolved.action, e, false);
        }
        return;
      }
      if (isNativeOwnedSpaceNav(resolved, e)) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      if (dispatchModifierAction(resolved.action, e, false)) {
        return;
      }
    }
  };

  // Canvas pointer down: resolve Modifier Key Settings first, otherwise dispatch drawing/tool stroke
  // Works uniformly across both the paper area and the surrounding viewport pasteboard (CSP-style).
  const handleCanvasPointerDown = (e: React.PointerEvent<HTMLElement>) => {
    if (isWorkspaceInteractionActive()) return;
    releaseExternalFocus();
    if (quickPalettePos) setQuickPalettePos(null);

    const modSettings = useUiStore.getState().appSettings.modifierKeys;
    const resolved = resolvePointerModifierAction(
      {
        button: e.button,
        pointerType: e.pointerType,
        ctrlKey: e.ctrlKey,
        metaKey: e.metaKey,
        shiftKey: e.shiftKey,
        altKey: e.altKey,
        isSpaceDown,
      },
      modSettings
    );

    if (resolved) {
      if (useUiStore.getState().isResizeCanvasModalOpen) {
        if (
          resolved.action === 'pan' ||
          resolved.action === 'rotate' ||
          resolved.action === 'zoom-drag'
        ) {
          if (dispatchModifierAction(resolved.action, e, false)) {
            return;
          }
        }
        return;
      }
      if (isNativeOwnedSpaceNav(resolved, e)) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
      if (dispatchModifierAction(resolved.action, e, true)) {
        return;
      }
    }

    if (useUiStore.getState().isResizeCanvasModalOpen) {
      return;
    }

    if (e.button === 0) {
      e.preventDefault();
      e.stopPropagation();
    } else {
      return;
    }

    // When native DX12 `ink-engine` owns Brush/Decoration/Eraser strokes directly via lock-free SPSC
    // rings (WinTab/Windows Ink/native mouse), notify recoveryService of active native drawing so
    // checkpoints, timelapse readbacks & scratch-disk walks pause, then skip JS stroke dispatch.
    const isNativeOwned = nativeStrokeOwned ?? (nativeCanvasActive && isNativeStrokeTool(tool));
    if (isNativeOwned) {
      recoveryService.notifyNativeStrokeStart();
      return;
    }

    // Capture pointer uniformly on the full-viewport interaction surface so dragging past any
    // canvas edge (or even outside the window) never cuts off frames, strokes, selections, or shapes.
    try {
      (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);
    } catch {
      // Ignore synthetic pointer capture errors
    }

    const coalesced = extractCoalescedEvents(e);
    (e as any).coalescedEvents = coalesced;
    if (e.nativeEvent) {
      (e.nativeEvent as any).coalescedEvents = coalesced;
    }
    artworkTimeTracker.recordArtworkAction();
    activeDomPointerIdRef.current = e.pointerId;
    uiStoreActions.setIsDrawing(true);
    onPointerDown(e, coalesced);
  };

  const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {
    if (isWorkspaceInteractionActive() || useUiStore.getState().isResizeCanvasModalOpen) return;
    const isNativeOwned = nativeStrokeOwned ?? (nativeCanvasActive && isNativeStrokeTool(tool));
    if (isNativeOwned && activeDomPointerIdRef.current !== e.pointerId) {
      return;
    }
    const coalesced = extractCoalescedEvents(e);
    const predicted = extractPredictedEvents(e);
    (e as any).coalescedEvents = coalesced;
    (e as any).predictedEvents = predicted;
    if (e.nativeEvent) {
      (e.nativeEvent as any).coalescedEvents = coalesced;
      (e.nativeEvent as any).predictedEvents = predicted;
    }
    onPointerMove(e, coalesced, predicted);
  };

  const handleCanvasPointerUp = (e: React.PointerEvent<HTMLElement>) => {
    const isTrackedDomStroke = activeDomPointerIdRef.current === e.pointerId;
    if (isTrackedDomStroke) {
      activeDomPointerIdRef.current = null;
    }
    if (nativeCanvasActive && isNativeStrokeTool(tool) && !isTrackedDomStroke) {
      recoveryService.notifyNativeStrokeEnd();
      if (tempEraserPrevToolRef.current !== null) {
        const prev = tempEraserPrevToolRef.current;
        tempEraserPrevToolRef.current = null;
        toolStoreActions.selectTool(prev);
      }
      return;
    }
    onPointerUp(e);
    uiStoreActions.setIsDrawing(false);
    try {
      const target = e.currentTarget as HTMLElement | null;
      if (target?.hasPointerCapture?.(e.pointerId)) {
        target.releasePointerCapture(e.pointerId);
      }
    } catch {
      // Ignore synthetic capture release errors
    }
    if (tempEraserPrevToolRef.current !== null) {
      const prev = tempEraserPrevToolRef.current;
      tempEraserPrevToolRef.current = null;
      toolStoreActions.selectTool(prev);
    }
  };

  const handleCanvasPointerCancel = (e: React.PointerEvent<HTMLElement>) => {
    handleCanvasPointerUp(e);
  };

  const handleContextMenu = (e: React.MouseEvent<HTMLElement>) => {
    const modSettings = useUiStore.getState().appSettings.modifierKeys;
    if (modSettings.rightClick !== 'none' || modSettings.stylusButton1 !== 'none') {
      e.preventDefault();
    }
  };

  return {
    releaseExternalFocus,
    startBrushResize,
    startModifierEyedropper,
    openQuickPaletteAt,
    dispatchModifierAction,
    handleViewportPointerDown,
    handleCanvasPointerDown,
    handleCanvasPointerMove,
    handleCanvasPointerUp,
    handleCanvasPointerCancel,
    handleContextMenu,
  };
}