Skip to content

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

10.0 KB
Raw Blame
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type {
  CanvasColorMode,
  CanvasDimensions,
  CanvasSelection,
  LayerItem,
  Point2D,
} from '../../types/editor';
import { documentStore } from '../../utils/documentStore';
import {
  nativeRetouchCancel,
  nativeRetouchCommit,
  nativeRetouchStep,
} from '../../utils/nativeEngineBridge';
import { toolStoreActions, useToolStore } from '../../stores';
import { t } from '../../i18n';
import type { PushHistoryStepFn } from './types';

export interface CloneSourceIndicator {
  anchor: Point2D;
  liveSamplePos: Point2D | null;
  isPicking: boolean;
}

export interface UseRetouchToolParams {
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  layers: LayerItem[];
  activeLayer: LayerItem | undefined;
  activeLayerId: string;
  selection: CanvasSelection | null;
  flushPendingHistoryTasks?: () => void;
  isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
  getEffectiveOpacity: (layer: LayerItem) => number;
  getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => Point2D;
  updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
  pushHistoryStep: PushHistoryStepFn;
  showToast?: (msg: string) => void;
}

export interface UseRetouchToolResult {
  cloneSourceIndicator: CloneSourceIndicator | null;
  isPickingCloneSource: boolean;
  setIsPickingCloneSource: React.Dispatch<React.SetStateAction<boolean>>;
  handleRetouchPointerDown: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;
  handleRetouchPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;
  handleRetouchPointerUp: (e: React.PointerEvent<HTMLElement>) => boolean;
}

export function useRetouchTool({
  activeLayer,
  activeLayerId,
  flushPendingHistoryTasks,
  isLayerEffectivelyVisible,
  getCanvasCoords,
  updateLayerThumbnail,
  showToast,
}: UseRetouchToolParams): UseRetouchToolResult {
  const cloneAnchor = useToolStore((s) => s.cloneSourceAnchor);
  const isPickingCloneSource = useToolStore((s) => s.isPickingCloneSource);
  const [liveSamplePos, setLiveSamplePos] = useState<Point2D | null>(null);

  const setCloneAnchor = useCallback((anchor: Point2D | null) => {
    toolStoreActions.setCloneSourceAnchor(anchor);
  }, []);
  const setIsPickingCloneSource: React.Dispatch<React.SetStateAction<boolean>> = useCallback(
    (next) => {
      const val =
        typeof next === 'function' ? next(useToolStore.getState().isPickingCloneSource) : next;
      toolStoreActions.setIsPickingCloneSource(val);
    },
    []
  );

  const isActiveRef = useRef<boolean>(false);
  const lastPtRef = useRef<Point2D | null>(null);
  const alignedOffsetRef = useRef<Point2D | null>(null);
  const activeOffsetRef = useRef<Point2D | null>(null);
  const cloneAnchorRef = useRef<Point2D | null>(null);
  cloneAnchorRef.current = cloneAnchor;
  const isPickingRef = useRef<boolean>(false);
  isPickingRef.current = isPickingCloneSource;
  const stepChainRef = useRef<Promise<unknown>>(Promise.resolve());

  useEffect(() => {
    let prevTool = useToolStore.getState().tool;
    const unsub = useToolStore.subscribe(() => {
      const curTool = useToolStore.getState().tool;
      if (prevTool === 'retouch' && curTool !== 'retouch') {
        if (isActiveRef.current) {
          isActiveRef.current = false;
          const docId = documentStore.getActiveDocumentId();
          stepChainRef.current = stepChainRef.current
            .then(() => nativeRetouchCancel(docId))
            .catch(() => {});
        }
        setIsPickingCloneSource(false);
        setLiveSamplePos(null);
      }
      prevTool = curTool;
    });
    return () => {
      unsub();
      if (isActiveRef.current) {
        isActiveRef.current = false;
        const docId = documentStore.getActiveDocumentId();
        stepChainRef.current = stepChainRef.current
          .then(() => nativeRetouchCancel(docId))
          .catch(() => {});
      }
    };
  }, [setIsPickingCloneSource]);

  const queueNativeStep = useCallback(
    (_from: Point2D, to: Point2D, pressure: number, sourceOrigin: [number, number] | null) => {
      const { retouchSettings, primaryColor } = useToolStore.getState();
      const docId = documentStore.getActiveDocumentId();
      const params = {
        x: to.x,
        y: to.y,
        pressure: Math.max(0.05, Math.min(1, pressure || 1.0)),
        cloneSource: sourceOrigin,
        settings: {
          kind: retouchSettings.mode,
          size: retouchSettings.size,
          hardness: Math.max(0, Math.min(1, retouchSettings.hardness / 100)),
          strength: Math.max(0.01, Math.min(1, retouchSettings.strength / 100)),
          usePressure: retouchSettings.usePressure,
          smudgeFingerPainting: retouchSettings.smudgeFingerPainting,
          fgColor: primaryColor || '#000000',
          pigmentBlending: retouchSettings.pigmentBlending,
          pigmentStrength: Math.max(0, Math.min(1, (retouchSettings.pigmentStrength ?? 100) / 100)),
          tonalRange: retouchSettings.tonalRange,
          protectTones: retouchSettings.protectTones,
          spongeMode: retouchSettings.spongeMode ?? 'saturate',
          cloneAligned: retouchSettings.cloneAligned,
          cloneSampleMode: retouchSettings.cloneSampleMode,
        },
      };
      stepChainRef.current = stepChainRef.current
        .then(() => nativeRetouchStep(params, docId))
        .catch((err) => console.warn('[Retouch] nativeRetouchStep failed:', err));
    },
    []
  );

  const handleRetouchPointerDown = useCallback(
    (e: React.PointerEvent<HTMLElement>, pt: Point2D): boolean => {
      const { tool, retouchSettings } = useToolStore.getState();
      if (tool !== 'retouch') return false;
      e.preventDefault();

      const needsCloneSource =
        retouchSettings.mode === 'clone-stamp' || retouchSettings.mode === 'heal';
      if (needsCloneSource && (e.altKey || isPickingRef.current)) {
        setCloneAnchor({ x: pt.x, y: pt.y });
        setLiveSamplePos(null);
        alignedOffsetRef.current = null;
        setIsPickingCloneSource(false);
        showToast?.(t('Clone source set ({x}, {y})', { x: Math.round(pt.x), y: Math.round(pt.y) }));
        return true;
      }

      if (
        !activeLayer ||
        activeLayer.type !== 'raster' ||
        activeLayer.locked ||
        !isLayerEffectivelyVisible(activeLayer)
      ) {
        showToast?.(t('Select an unlocked, visible raster layer to use Retouch tools'));
        return true;
      }

      let sourceOrigin: [number, number] | null = null;
      activeOffsetRef.current = null;
      if (needsCloneSource) {
        const anchor = cloneAnchorRef.current;
        if (!anchor) {
          showToast?.(t('Alt+Click on canvas (or click Pick Source) to set Clone Stamp origin'));
          return true;
        }
        const offset =
          retouchSettings.cloneAligned && alignedOffsetRef.current
            ? { ...alignedOffsetRef.current }
            : { x: anchor.x - pt.x, y: anchor.y - pt.y };
        if (retouchSettings.cloneAligned && !alignedOffsetRef.current) {
          alignedOffsetRef.current = { ...offset };
        }
        activeOffsetRef.current = offset;
        sourceOrigin = [pt.x + offset.x, pt.y + offset.y];
        setLiveSamplePos({ x: sourceOrigin[0], y: sourceOrigin[1] });
      }

      flushPendingHistoryTasks?.();
      isActiveRef.current = true;
      lastPtRef.current = pt;

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

      queueNativeStep(pt, pt, e.pressure || 1.0, sourceOrigin);
      return true;
    },
    [
      activeLayer,
      flushPendingHistoryTasks,
      isLayerEffectivelyVisible,
      queueNativeStep,
      setCloneAnchor,
      setIsPickingCloneSource,
      showToast,
    ]
  );

  const handleRetouchPointerMove = useCallback(
    (e: React.PointerEvent<HTMLElement>): boolean => {
      const { tool } = useToolStore.getState();
      if (tool !== 'retouch') return false;
      if (!isActiveRef.current || !lastPtRef.current) return true;

      const pt = getCanvasCoords(e);
      const prev = lastPtRef.current;
      lastPtRef.current = pt;

      let sourceOrigin: [number, number] | null = null;
      if (activeOffsetRef.current) {
        const sx = pt.x + activeOffsetRef.current.x;
        const sy = pt.y + activeOffsetRef.current.y;
        sourceOrigin = [sx, sy];
        setLiveSamplePos({ x: sx, y: sy });
      }

      queueNativeStep(prev, pt, e.pressure || 1.0, sourceOrigin);
      return true;
    },
    [getCanvasCoords, queueNativeStep]
  );

  const handleRetouchPointerUp = useCallback(
    (e: React.PointerEvent<HTMLElement>): boolean => {
      const { tool } = useToolStore.getState();
      if (tool !== 'retouch' && !isActiveRef.current) return false;
      if (!isActiveRef.current) return tool === 'retouch';

      try {
        if ((e.target as HTMLElement).hasPointerCapture?.(e.pointerId)) {
          (e.target as HTMLElement).releasePointerCapture(e.pointerId);
        }
      } catch {
        // Ignore
      }

      isActiveRef.current = false;
      lastPtRef.current = null;
      activeOffsetRef.current = null;
      setLiveSamplePos(null);

      const docId = documentStore.getActiveDocumentId();
      const layerId = activeLayerId;
      stepChainRef.current = stepChainRef.current
        .then(() => nativeRetouchCommit(docId))
        .then((res) => {
          if (res?.modified) {
            updateLayerThumbnail(res.layerId || layerId, true);
          }
        })
        .catch(() => {});
      return true;
    },
    [activeLayerId, updateLayerThumbnail]
  );

  const cloneSourceIndicator: CloneSourceIndicator | null = cloneAnchor
    ? {
        anchor: cloneAnchor,
        liveSamplePos,
        isPicking: isPickingCloneSource,
      }
    : isPickingCloneSource
      ? {
          anchor: { x: -9999, y: -9999 },
          liveSamplePos: null,
          isPicking: true,
        }
      : null;

  return {
    cloneSourceIndicator,
    isPickingCloneSource,
    setIsPickingCloneSource,
    handleRetouchPointerDown,
    handleRetouchPointerMove,
    handleRetouchPointerUp,
  };
}