Skip to content

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

10.4 KB
Raw Blame
import React, { useRef, useCallback } from 'react';
import {
  BrushSettings,
  CanvasColorMode,
  CanvasDimensions,
  LayerItem,
  Point,
  VectorKnot,
  VectorStroke,
} from '../../types/editor';
import { documentStore } from '../../utils/documentStore';
import {
  nativeRasterizeVectorLayer,
  type NativeVectorStrokePath,
} from '../../utils/nativeEngineBridge';
import { multiplayerService } from '../../services/multiplayerService';
import {
  applyVectorEraser,
  computeStrokeBounds,
  modifyStrokeWidth,
  pinchVectorStroke,
  simplifyPathPoints,
  simplifyVectorStroke,
} from '../../utils/vectorEngine';
import { useToolStore } from '../../stores';
import { t, tc, td } from '../../i18n';
import { PushHistoryStepFn } from './types';

export function toNativeVectorStrokes(strokes: VectorStroke[]): NativeVectorStrokePath[] {
  return strokes
    .filter((s) => !s.deleted && s.knots.length > 0)
    .map((s) => ({
      id: s.id,
      points: s.knots.map((k) => ({
        x: k.x,
        y: k.y,
        pressure: k.pressure ?? 1.0,
        width: k.width,
      })),
      color: s.color === 'none' ? '#000000' : s.color,
      size: s.baseWidth || 4,
      opacity: s.opacity ?? 1.0,
      hardness: 0.92,
      closed: Boolean(s.closed),
    }));
}

export interface CommitVectorStrokeArgs {
  activeLayer: LayerItem;
  currentLayerId: string;
  allPoints: Point[];
  bs: BrushSettings;
  isEraser: boolean;
  isPencil: boolean;
  isMonochrome: boolean;
  strokeColor: string;
  dims: CanvasDimensions;
  mergedDirty: { minX: number; minY: number; maxX: number; maxY: number } | null;
  strokeId: string | null;
  labelOverride?: string;
  pushHistoryStep: PushHistoryStepFn;
}

export function commitVectorStrokeOrErase({
  activeLayer,
  currentLayerId,
  allPoints,
  bs,
  isEraser,
  isPencil,
  strokeColor,
  dims,
  mergedDirty,
  strokeId,
  labelOverride,
  pushHistoryStep,
}: CommitVectorStrokeArgs): VectorStroke | undefined {
  const knots: VectorKnot[] = allPoints.map((pt, idx) => ({
    x: pt.x,
    y: pt.y,
    pressure: pt.pressure,
    width: pt.width || Math.max(0.5, (bs.size || 10) * pt.pressure),
    timestamp: Date.now() + idx,
  }));
  const prevStrokes = [...(activeLayer.vectorStrokes || [])];
  const docId = documentStore.getActiveDocumentId();

  if (isEraser) {
    const eraserRadius = Math.max(1, (bs.size || 10) * 0.5);
    const eraserPath = allPoints.map((p) => ({ x: p.x, y: p.y }));
    const eraserResult = applyVectorEraser(eraserPath, eraserRadius, prevStrokes, 'intersection');
    const updatedStrokes = eraserResult.updatedStrokes;
    activeLayer.vectorStrokes = updatedStrokes;

    void nativeRasterizeVectorLayer(
      currentLayerId,
      toNativeVectorStrokes(updatedStrokes),
      true,
      docId
    ).catch(() => {});

    pushHistoryStep(
      'eraser',
      t('Vector Eraser'),
      null,
      null,
      currentLayerId,
      mergedDirty
        ? {
            x: Math.max(0, Math.floor(mergedDirty.minX)),
            y: Math.max(0, Math.floor(mergedDirty.minY)),
            width: Math.max(1, Math.ceil(mergedDirty.maxX - mergedDirty.minX)),
            height: Math.max(1, Math.ceil(mergedDirty.maxY - mergedDirty.minY)),
          }
        : { x: 0, y: 0, width: dims.width, height: dims.height },
      undefined,
      { before: prevStrokes, after: updatedStrokes },
      undefined,
      strokeId || undefined
    );
    if (multiplayerService.isConnected()) {
      multiplayerService.sendLayerUpdate(currentLayerId, { vectorStrokes: updatedStrokes });
    }
    return undefined;
  }

  const simplifiedKnots = simplifyPathPoints(knots, 0.5);
  const strokeKnots = simplifiedKnots.length >= 2 ? simplifiedKnots : knots;
  const bounds = computeStrokeBounds(strokeKnots);
  const newStroke: VectorStroke = {
    id: strokeId || `vec-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
    layerId: currentLayerId,
    tool: isPencil ? 'pencil' : 'brush',
    knots: strokeKnots,
    color: strokeColor,
    baseWidth: bs.size || 10,
    opacity: bs.opacity ?? 1.0,
    bounds,
  };

  const updatedStrokes = [...prevStrokes, newStroke];
  activeLayer.vectorStrokes = updatedStrokes;

  void nativeRasterizeVectorLayer(
    currentLayerId,
    toNativeVectorStrokes(updatedStrokes),
    true,
    docId
  ).catch(() => {});

  const vPad = Math.ceil(Math.max(16, bs.size || 10));
  const vx = Math.max(0, Math.floor(bounds.minX - vPad));
  const vy = Math.max(0, Math.floor(bounds.minY - vPad));
  const vw = Math.max(0, Math.min(dims.width, Math.ceil(bounds.maxX + vPad)) - vx);
  const vh = Math.max(0, Math.min(dims.height, Math.ceil(bounds.maxY + vPad)) - vy);

  pushHistoryStep(
    isPencil ? 'pencil' : 'brush',
    labelOverride || (bs.brushName ? td(bs.brushName) : isPencil ? t('Vector Pencil') : t('Vector Pen')),
    null,
    null,
    currentLayerId,
    vw > 0 && vh > 0
      ? { x: vx, y: vy, width: vw, height: vh }
      : { x: 0, y: 0, width: dims.width, height: dims.height },
    undefined,
    { before: prevStrokes, after: updatedStrokes },
    undefined,
    newStroke.id
  );

  return newStroke;
}

export interface UseVectorDrawingParams {
  activeLayer: LayerItem | undefined;
  activeLayerId: string;
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => { x: number; y: number };
  updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
  pushHistoryStep: PushHistoryStepFn;
  showToast: (msg: string) => void;
}

export interface UseVectorDrawingResult {
  commitVectorStrokeOrErase: typeof commitVectorStrokeOrErase;
  handleVectorEditPointerDown: (
    e: React.PointerEvent<HTMLElement>,
    pt: { x: number; y: number }
  ) => boolean;
  handleVectorEditPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;
  handleVectorEditPointerUp: () => boolean;
}

export function useVectorDrawing({
  activeLayer,
  activeLayerId,
  getCanvasCoords,
  updateLayerThumbnail,
  pushHistoryStep,
  showToast,
}: UseVectorDrawingParams): UseVectorDrawingResult {
  const isVectorEditingRef = useRef<boolean>(false);
  const lastVectorEditPtRef = useRef<{ x: number; y: number } | null>(null);
  const vectorEditBeforeStrokesRef = useRef<VectorStroke[] | null>(null);
  const rasterInFlightRef = useRef<boolean>(false);

  const flushVectorEditRaster = useCallback(
    (recordHistory: boolean = false) => {
      if (!activeLayer?.vectorStrokes) return;
      if (!recordHistory && rasterInFlightRef.current) return;
      const docId = documentStore.getActiveDocumentId();
      rasterInFlightRef.current = true;
      void nativeRasterizeVectorLayer(
        activeLayerId,
        toNativeVectorStrokes(activeLayer.vectorStrokes),
        recordHistory,
        docId
      )
        .catch(() => {})
        .finally(() => {
          rasterInFlightRef.current = false;
        });
    },
    [activeLayer, activeLayerId]
  );

  const handleVectorEditPointerDown = useCallback(
    (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
      e.preventDefault();
      if (!activeLayer || activeLayer.type !== 'vector' || !activeLayer.vectorStrokes) {
        showToast(t('Select a Vector Layer to use Correct Line tools'));
        return true;
      }
      isVectorEditingRef.current = true;
      lastVectorEditPtRef.current = pt;
      vectorEditBeforeStrokesRef.current = activeLayer.vectorStrokes.map((st) => ({
        ...st,
        knots: st.knots.map((k) => ({ ...k })),
        bounds: st.bounds ? { ...st.bounds } : st.bounds,
      }));
      return true;
    },
    [activeLayer, showToast]
  );

  const handleVectorEditPointerMove = useCallback(
    (e: React.PointerEvent<HTMLElement>): boolean => {
      if (!isVectorEditingRef.current || !activeLayer?.vectorStrokes) return true;
      const pt = getCanvasCoords(e);
      const lastPt = lastVectorEditPtRef.current || pt;
      const delta = { x: pt.x - lastPt.x, y: pt.y - lastPt.y };
      lastVectorEditPtRef.current = pt;

      const vectorEditSettings = useToolStore.getState().vectorEditSettings;
      const radius = vectorEditSettings.radius || 35;
      let updated = false;

      const newStrokes = activeLayer.vectorStrokes.map((stroke) => {
        if (stroke.deleted) return stroke;
        if (
          pt.x < stroke.bounds.minX - radius ||
          pt.x > stroke.bounds.maxX + radius ||
          pt.y < stroke.bounds.minY - radius ||
          pt.y > stroke.bounds.maxY + radius
        ) {
          return stroke;
        }
        if (vectorEditSettings.mode === 'pinch') {
          if (Math.hypot(delta.x, delta.y) > 0.05) {
            updated = true;
            return pinchVectorStroke(stroke, pt, radius, delta);
          }
        } else if (vectorEditSettings.mode === 'width') {
          updated = true;
          return modifyStrokeWidth(stroke, pt, radius, vectorEditSettings.widthFactor);
        } else if (vectorEditSettings.mode === 'simplify') {
          updated = true;
          return simplifyVectorStroke(stroke, vectorEditSettings.simplifyTolerance);
        }
        return stroke;
      });

      if (updated) {
        activeLayer.vectorStrokes = newStrokes;
        flushVectorEditRaster(false);
      }
      return true;
    },
    [activeLayer, flushVectorEditRaster, getCanvasCoords]
  );

  const handleVectorEditPointerUp = useCallback((): boolean => {
    if (!isVectorEditingRef.current) return false;
    isVectorEditingRef.current = false;
    flushVectorEditRaster(true);
    const vectorEditSettings = useToolStore.getState().vectorEditSettings;
    if (activeLayer?.vectorStrokes && vectorEditBeforeStrokesRef.current) {
      const updatedStrokes = [...activeLayer.vectorStrokes];
      pushHistoryStep(
        'brush',
        t('Correct Line ({mode})', { mode: tc('vectorEditMode', vectorEditSettings.mode) }),
        null,
        null,
        activeLayerId,
        undefined,
        undefined,
        {
          before: vectorEditBeforeStrokesRef.current,
          after: updatedStrokes,
        }
      );
      if (multiplayerService.isConnected()) {
        multiplayerService.sendLayerUpdate(activeLayerId, { vectorStrokes: updatedStrokes });
      }
      updateLayerThumbnail(activeLayerId);
    }
    vectorEditBeforeStrokesRef.current = null;
    return true;
  }, [activeLayer, activeLayerId, flushVectorEditRaster, pushHistoryStep, updateLayerThumbnail]);

  return {
    commitVectorStrokeOrErase,
    handleVectorEditPointerDown,
    handleVectorEditPointerMove,
    handleVectorEditPointerUp,
  };
}