Skip to content

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

17.2 KB
Raw Blame
import React, { useRef, useCallback, useEffect } from 'react';
import {
  ToolType,
  BrushSettings,
  Point,
  CanvasDimensions,
  CanvasSelection,
  CanvasColorMode,
  DirtyRect,
  LayerItem,
  VectorStroke,
} from '../../types/editor';
import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../types/perspective';
import { QuickShapePreviewState } from '../../utils/quickShapeEngine';
import { useToolStore, uiStoreActions } from '../../stores';
import { multiplayerService } from '../../services/multiplayerService';
import { recoveryService } from '../../services/recoveryService';
import { artworkTimeTracker } from '../../utils/artworkTimeTracker';
import { screenToCanvas } from '../../utils/canvasUtils';
import { enforceColorMode } from '../../utils/colorUtils';
import { subscribeNativeStrokeCommitted } from '../../utils/nativeEngineBridge';
import { commitVectorStrokeOrErase } from './useVectorDrawing';
import { LastStrokeEndState, PushHistoryStepFn } from './types';

export interface UseBrushStrokeSessionParams {
  disabled: boolean;
  activeSessionId?: string | null;
  viewportRef: React.RefObject<HTMLDivElement | null>;
  interactionRef: React.MutableRefObject<HTMLDivElement | null>;
  isDrawingRef: React.MutableRefObject<boolean>;
  lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;
  panRef: React.MutableRefObject<{ x: number; y: number }>;
  zoomRef: React.MutableRefObject<number>;
  rotationRef: React.MutableRefObject<number>;
  flipXRef: React.MutableRefObject<boolean>;
  flipYRef: React.MutableRefObject<boolean>;
  toolOverrideRef: React.MutableRefObject<ToolType | undefined>;
  brushSettingsOverrideRef: React.MutableRefObject<BrushSettings | undefined>;
  colorModeRef: React.MutableRefObject<CanvasColorMode>;
  activeLayerIdRef: React.MutableRefObject<string>;
  activeLayerLockedRef: React.MutableRefObject<boolean>;
  activeLayerVisibleRef: React.MutableRefObject<boolean>;
  dimensionsRef: React.MutableRefObject<CanvasDimensions>;
  selectionRef: React.MutableRefObject<CanvasSelection | null>;
  isMaskModeRef: React.MutableRefObject<boolean>;
  layersRef: React.MutableRefObject<LayerItem[] | undefined>;
  rulerRef: React.MutableRefObject<PerspectiveRuler | null | undefined>;
  straightRulerRef?: React.MutableRefObject<StraightRuler | null | undefined>;
  onActiveConstraintAxisChangeRef: React.MutableRefObject<
    ((axis: ConstraintAxis | null) => void) | undefined
  >;
  onQuickShapePreviewChangeRef?: React.MutableRefObject<
    ((preview: QuickShapePreviewState | null) => void) | undefined
  >;
  onUpdateLayerThumbnail: (layerId: string) => void;
  onUpdateMaskThumbnailRef: React.MutableRefObject<
    ((layerId: string, immediate?: boolean, skipVersionBump?: boolean) => void) | undefined
  >;
  onCollabStrokeStartRef: React.MutableRefObject<
    | ((
        strokeId: string,
        layerId: string,
        brushSettings: BrushSettings,
        tool: ToolType,
        startPoint: Point
      ) => void)
    | undefined
  >;
  onCollabStrokeChunkRef: React.MutableRefObject<
    ((strokeId: string, points: Point[]) => void) | undefined
  >;
  onCollabStrokeFinishRef: React.MutableRefObject<
    | ((
        strokeId: string,
        layerId: string,
        endPoint: Point,
        dirtyRect?: DirtyRect,
        vectorStroke?: VectorStroke
      ) => void)
    | undefined
  >;
  onCollabCursorMoveRef: React.MutableRefObject<
    ((x: number, y: number, isDrawing: boolean, tool: ToolType) => void) | undefined
  >;
  pushHistoryStep: PushHistoryStepFn;
  flushPendingHistoryTasks: () => void;
  enqueueHistoryTask: (task: () => void) => void;
}

export interface UseBrushStrokeSessionResult {
  abortActiveStroke: () => void;
  handlePointerDown: (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => void;
  handlePointerMove: (
    e: React.PointerEvent<HTMLElement>,
    coalescedEvents?: PointerEvent[],
    predictedEvents?: PointerEvent[]
  ) => void;
  handlePointerUp: (e: React.PointerEvent<HTMLElement>) => void;
  handlePointerEnter: () => void;
  handlePointerLeave: () => void;
}

/**
 * Phase 5 Stroke Session Coordinator:
 * - 100% of raster & layer-mask brush strokes execute natively in Rust + wgpu (`crates/ink-engine`).
 * - This hook bridges native Rust stroke commits (`native-engine://stroke-committed`) into
 *   artwork time tracking, Shift+click anchor memory, and collaborative multiplayer sync.
 * - Handles lightweight DOM pointer capture strictly for Vector layers (`layer.type === 'vector'`).
 */
export function useBrushStrokeSession(
  params: UseBrushStrokeSessionParams
): UseBrushStrokeSessionResult {
  const {
    disabled,
    activeSessionId,
    viewportRef,
    interactionRef,
    isDrawingRef,
    panRef,
    zoomRef,
    rotationRef,
    flipXRef,
    flipYRef,
    toolOverrideRef,
    brushSettingsOverrideRef,
    dimensionsRef,
    onActiveConstraintAxisChangeRef,
    onQuickShapePreviewChangeRef,
  } = params;

  const paramsRef = useRef<UseBrushStrokeSessionParams>(params);
  paramsRef.current = params;

  const vectorStateRef = useRef<{
    activePointerId: number | null;
    strokeId: string | null;
    points: Point[];
    minX: number;
    minY: number;
    maxX: number;
    maxY: number;
    cachedRect: DOMRect | null;
    statRaf: number | null;
    pendingStat: { x: number | null; y: number | null; pressure: number } | null;
  }>({
    activePointerId: null,
    strokeId: null,
    points: [],
    minX: Infinity,
    minY: Infinity,
    maxX: -Infinity,
    maxY: -Infinity,
    cachedRect: null,
    statRaf: null,
    pendingStat: null,
  });

  const getTool = useCallback(
    (): ToolType => toolOverrideRef.current ?? useToolStore.getState().tool,
    [toolOverrideRef]
  );

  const getBrushSettings = useCallback(
    (): BrushSettings =>
      brushSettingsOverrideRef.current ?? useToolStore.getState().brushSettings,
    [brushSettingsOverrideRef]
  );

  const dispatchPointerStat = useCallback(
    (x: number | null, y: number | null, pressure: number) => {
      const s = vectorStateRef.current;
      s.pendingStat = { x, y, pressure };
      if (s.statRaf !== null) return;
      if (typeof requestAnimationFrame === 'function') {
        s.statRaf = requestAnimationFrame(() => {
          s.statRaf = null;
          const detail = s.pendingStat;
          if (detail && typeof window !== 'undefined') {
            window.dispatchEvent(new CustomEvent('canvas-pointer-stat', { detail }));
          }
        });
      }
    },
    []
  );

  const getCanvasPoint = useCallback(
    (e: React.PointerEvent<HTMLElement> | PointerEvent): Point => {
      const s = vectorStateRef.current;
      const vp = viewportRef.current;
      const rect = s.cachedRect ?? vp?.getBoundingClientRect() ?? null;
      const dims = dimensionsRef.current;
      const pos = rect
        ? screenToCanvas(
            e.clientX,
            e.clientY,
            rect,
            panRef.current,
            zoomRef.current,
            rotationRef.current,
            dims,
            flipXRef.current,
            flipYRef.current
          )
        : { x: e.clientX, y: e.clientY };
      const bs = getBrushSettings();
      const pressure =
        e.pointerType === 'mouse' ? 0.8 : Math.max(0.02, Math.min(1, e.pressure || 0.5));
      const minF = bs.minSizeFactor ?? 0.1;
      const width =
        bs.usePressure !== false
          ? Math.max(0.5, (bs.size || 10) * (minF + (1 - minF) * pressure))
          : Math.max(0.5, bs.size || 10);
      return {
        x: pos.x,
        y: pos.y,
        pressure,
        width,
        tiltX: e.tiltX ?? 0,
        tiltY: e.tiltY ?? 0,
        twist: e.twist ?? 0,
        timestamp: e.timeStamp || performance.now(),
      };
    },
    [dimensionsRef, flipXRef, flipYRef, getBrushSettings, panRef, rotationRef, viewportRef, zoomRef]
  );

  const abortActiveStroke = useCallback(() => {
    const s = vectorStateRef.current;
    if (
      s.activePointerId !== null &&
      interactionRef.current?.hasPointerCapture?.(s.activePointerId)
    ) {
      try {
        interactionRef.current.releasePointerCapture(s.activePointerId);
      } catch {
        // Ignore release errors
      }
    }
    s.activePointerId = null;
    s.strokeId = null;
    s.points = [];
    s.minX = Infinity;
    s.minY = Infinity;
    s.maxX = -Infinity;
    s.maxY = -Infinity;
    isDrawingRef.current = false;
    onActiveConstraintAxisChangeRef.current?.(null);
    onQuickShapePreviewChangeRef?.current?.(null);
    recoveryService.setDrawingActive(false);
    uiStoreActions.setIsDrawing(false);
  }, [
    interactionRef,
    isDrawingRef,
    onActiveConstraintAxisChangeRef,
    onQuickShapePreviewChangeRef,
  ]);

  useEffect(() => {
    if (disabled) {
      abortActiveStroke();
    }
  }, [disabled, abortActiveStroke]);

  useEffect(() => {
    const handleResize = () => {
      vectorStateRef.current.cachedRect = null;
    };
    window.addEventListener('resize', handleResize);
    window.addEventListener('scroll', handleResize, true);
    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('scroll', handleResize, true);
    };
  }, []);

  useEffect(() => {
    return () => {
      abortActiveStroke();
      const s = vectorStateRef.current;
      if (s.statRaf !== null) {
        cancelAnimationFrame(s.statRaf);
        s.statRaf = null;
      }
      recoveryService.setDrawingActive(false);
      uiStoreActions.setIsDrawing(false);
    };
  }, [activeSessionId, abortActiveStroke]);

  useEffect(() => {
    const handleFocusLoss = () => {
      if (isDrawingRef.current) {
        abortActiveStroke();
      }
      if (recoveryService.getIsDrawingActive()) {
        recoveryService.notifyNativeStrokeEnd();
      }
    };
    window.addEventListener('blur', handleFocusLoss);
    return () => {
      window.removeEventListener('blur', handleFocusLoss);
    };
  }, [abortActiveStroke, isDrawingRef]);

  // Subscribe to committed native Rust DX12 strokes for artwork stats, Shift+click anchor & collab sync
  useEffect(() => {
    const unsubCommitted = subscribeNativeStrokeCommitted((ev) => {
      const curDocId = paramsRef.current.activeSessionId;
      if (curDocId && ev.docId && ev.docId !== curDocId) return;
      artworkTimeTracker.recordArtworkAction();
      const rawPts = ev.points;
      if (rawPts && rawPts.length > 0) {
        const rawLast = rawPts[rawPts.length - 1];
        paramsRef.current.lastStrokeEndRef.current = {
          x: rawLast.x,
          y: rawLast.y,
          pressure: rawLast.pressure,
          width: rawLast.width,
          layerId: ev.layerId,
        };
      }
      // Avoid allocating/mapping point arrays when not in a multiplayer session
      if (!multiplayerService.isConnected()) return;
      if (!rawPts || rawPts.length === 0) return;

      const onStart = paramsRef.current.onCollabStrokeStartRef.current;
      const onChunk = paramsRef.current.onCollabStrokeChunkRef.current;
      const onFinish = paramsRef.current.onCollabStrokeFinishRef.current;
      if (!onStart || !onFinish) return;

      const pts: Point[] = rawPts.map((p) => ({
        x: p.x,
        y: p.y,
        pressure: p.pressure,
        width: p.width,
        tiltX: p.tiltX,
        tiltY: p.tiltY,
        twist: p.twist,
        timestamp: p.timestampMs,
        isCorner: p.isCorner,
      }));
      const last = pts[pts.length - 1];
      const strokeId = ev.entryId || `native-${Date.now()}`;
      const bs = getBrushSettings();
      const tool = getTool();
      onStart(strokeId, ev.layerId, bs, tool, pts[0]);
      if (pts.length > 2 && onChunk) {
        onChunk(strokeId, pts.slice(1, -1));
      }
      onFinish(strokeId, ev.layerId, last, ev.dirtyRect);
      multiplayerService.streamNativeDirtyRectTiles(ev.layerId, ev.dirtyRect, {
        strokeId,
      });
    });
    return () => {
      unsubCommitted();
    };
  }, [getBrushSettings, getTool]);

  const handlePointerDown = useCallback(
    (e: React.PointerEvent<HTMLElement>) => {
      const p = paramsRef.current;
      if (p.disabled || e.button !== 0) return;
      const tool = getTool();
      if (tool !== 'brush' && tool !== 'decoration' && tool !== 'eraser') return;
      if (p.activeLayerLockedRef.current || !p.activeLayerVisibleRef.current) return;

      const activeLayer = p.layersRef.current?.find((l) => l.id === p.activeLayerIdRef.current);
      // Raster & mask-mode strokes are owned 100% by native Rust DX12 `ink-engine`.
      // DOM pointer capture here handles ONLY vector layers.
      if (!activeLayer || activeLayer.type !== 'vector') return;

      e.preventDefault();
      const s = vectorStateRef.current;
      s.cachedRect = viewportRef.current?.getBoundingClientRect() ?? null;
      const pt = getCanvasPoint(e);
      s.activePointerId = e.pointerId;
      s.strokeId = `vec-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      s.points = [pt];
      s.minX = pt.x - pt.width;
      s.minY = pt.y - pt.width;
      s.maxX = pt.x + pt.width;
      s.maxY = pt.y + pt.width;
      isDrawingRef.current = true;
      recoveryService.setDrawingActive(true);
      uiStoreActions.setIsDrawing(true);

      try {
        interactionRef.current?.setPointerCapture?.(e.pointerId);
      } catch {
        // Ignore pointer capture errors
      }
    },
    [getCanvasPoint, getTool, interactionRef, isDrawingRef, viewportRef]
  );

  const handlePointerMove = useCallback(
    (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
      const p = paramsRef.current;
      const s = vectorStateRef.current;
      const pt = getCanvasPoint(e);
      dispatchPointerStat(pt.x, pt.y, pt.pressure);
      p.onCollabCursorMoveRef.current?.(pt.x, pt.y, isDrawingRef.current, getTool());

      if (!isDrawingRef.current || e.pointerId !== s.activePointerId) return;
      const samples =
        coalescedEvents && coalescedEvents.length > 0
          ? coalescedEvents.map((ce) => getCanvasPoint(ce))
          : [pt];

      for (const sample of samples) {
        s.points.push(sample);
        s.minX = Math.min(s.minX, sample.x - sample.width);
        s.minY = Math.min(s.minY, sample.y - sample.width);
        s.maxX = Math.max(s.maxX, sample.x + sample.width);
        s.maxY = Math.max(s.maxY, sample.y + sample.width);
      }
    },
    [dispatchPointerStat, getCanvasPoint, getTool, isDrawingRef]
  );

  const handlePointerUp = useCallback(
    (e: React.PointerEvent<HTMLElement>) => {
      const p = paramsRef.current;
      const s = vectorStateRef.current;
      if (!isDrawingRef.current || e.pointerId !== s.activePointerId) return;

      e.preventDefault();
      if (interactionRef.current?.hasPointerCapture?.(e.pointerId)) {
        try {
          interactionRef.current.releasePointerCapture(e.pointerId);
        } catch {
          // Ignore release errors
        }
      }

      const activeLayer = p.layersRef.current?.find((l) => l.id === p.activeLayerIdRef.current);
      const bs = getBrushSettings();
      const tool = getTool();
      const isEraser = tool === 'eraser';
      const isMonochrome =
        p.colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
      const strokeColor = enforceColorMode(
        bs.color,
        isMonochrome ? 'monochrome' : p.colorModeRef.current
      );

      try {
        if (activeLayer && activeLayer.type === 'vector' && s.points.length > 0) {
          const vecStroke = commitVectorStrokeOrErase({
            activeLayer,
            currentLayerId: p.activeLayerIdRef.current,
            allPoints: s.points,
            bs,
            isEraser,
            isPencil: Boolean(!isEraser && bs.preset?.startsWith('pencil')),
            isMonochrome,
            strokeColor,
            dims: p.dimensionsRef.current,
            mergedDirty: {
              minX: s.minX,
              minY: s.minY,
              maxX: s.maxX,
              maxY: s.maxY,
            },
            strokeId: s.strokeId,
            pushHistoryStep: p.pushHistoryStep,
          });
          artworkTimeTracker.recordArtworkAction();
          p.onUpdateLayerThumbnail(p.activeLayerIdRef.current);
          const last = s.points[s.points.length - 1];
          p.lastStrokeEndRef.current = {
            x: last.x,
            y: last.y,
            pressure: last.pressure,
            width: last.width,
            layerId: p.activeLayerIdRef.current,
          };
          p.onCollabStrokeFinishRef.current?.(
            s.strokeId || `vec-${Date.now()}`,
            p.activeLayerIdRef.current,
            last,
            undefined,
            vecStroke
          );
        }
      } finally {
        s.activePointerId = null;
        s.strokeId = null;
        s.points = [];
        isDrawingRef.current = false;
        recoveryService.setDrawingActive(false);
        uiStoreActions.setIsDrawing(false);
      }
    },
    [getBrushSettings, getTool, interactionRef, isDrawingRef]
  );

  const handlePointerEnter = useCallback(() => {
    vectorStateRef.current.cachedRect = viewportRef.current?.getBoundingClientRect() ?? null;
  }, [viewportRef]);

  const handlePointerLeave = useCallback(() => {
    if (!isDrawingRef.current) {
      dispatchPointerStat(null, null, 0);
    }
  }, [dispatchPointerStat, isDrawingRef]);

  return {
    abortActiveStroke,
    handlePointerDown,
    handlePointerMove,
    handlePointerUp,
    handlePointerEnter,
    handlePointerLeave,
  };
}