Skip to content

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

21.0 KB
Raw Blame
import React, { useCallback } from 'react';
import {
  AdjustmentLayerData,
  CanvasColorMode,
  CanvasDimensions,
  CanvasSelection,
  ExpressionColor,
  FilterType,
  LayerItem,
  LayerStyles,
  LayerTreeDelta,
  TileDelta,
} from '../types/editor';
import { documentStore } from '../utils/documentStore';
import { releaseTemporaryCanvas } from '../utils/tauriEnv';
import {
  FilmGrainParams,
  GaussianBlurParams,
  MotionBlurParams,
  UnsharpMaskParams,
  TonalCorrectionType,
  BrightnessContrastParams,
  BinarizationParams,
  HueSaturationParams,
  PosterizationParams,
  LevelCorrectionParams,
  toNativeFilterSpec,
  toNativeTonalSpec,
} from '../utils/toolConfigs';
import {
  ingestNativeDirtyRect,
  nativeClearToolPreview,
  nativeImageOpApply,
  nativeImageOpPreview,
  nativeLayerHistogram,
} from '../utils/nativeEngineBridge';
import { HalftoneDotShape } from '../utils/screentoneEngine';
import { get2DContext } from '../utils/canvasUtils';
import {
  renderSaturatedLines,
  renderStreamLines,
  SaturatedLinesOptions,
  StreamLinesOptions,
} from '../utils/mangaEffectsEngine';
import { SimpleToneSettings } from '../components/SimpleToneModal';
import { useUiStore, uiStoreActions } from '../stores';
import { t, tc } from '../i18n';
import { PushHistoryStepFn } from './drawing';

export type AnyFilterParams =
  | GaussianBlurParams
  | MotionBlurParams
  | UnsharpMaskParams
  | FilmGrainParams;

export type AnyTonalParams =
  | BrightnessContrastParams
  | BinarizationParams
  | HueSaturationParams
  | PosterizationParams
  | LevelCorrectionParams
  | Record<string, never>;

export interface UseTonalAndFilterActionsParams {
  hasOpenDocument: boolean;
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  layers: LayerItem[];
  activeLayer: LayerItem | undefined;
  activeLayerId: string;
  selection: CanvasSelection | null;
  setActiveLayerId: (id: string) => void;
  updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
  handleCommitFloatingSelection: () => void;
  pushHistoryStepRef: React.MutableRefObject<PushHistoryStepFn | null>;
  addLayer: (
    type?: 'raster' | 'folder' | 'vector',
    parentId?: string | null,
    customName?: string,
    customId?: string
  ) => LayerItem;
  pasteLayerFromCanvas: (
    canvas: HTMLCanvasElement,
    name?: string,
    blendMode?: LayerItem['blendMode'],
    opacity?: number,
    customId?: string,
    extraProps?: Partial<LayerItem>
  ) => void;
  addAdjustmentLayer: (
    type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',
    data: AdjustmentLayerData
  ) => void;
  updateAdjustmentData: (layerId: string, data: AdjustmentLayerData) => void;
  updateLayerStyles: (layerId: string, styles: LayerStyles) => void;
  fillScreentoneSelection: (
    selection: CanvasSelection | null,
    density: number,
    frequency: number,
    angle: number,
    dotShape: HalftoneDotShape,
    densityType: 'specified' | 'image'
  ) => { id: string; tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta };
  applyExpressionColorOfPreview: (
    layerId: string
  ) => { tileDeltas: TileDelta[] } | null | undefined;
  applyLayerColorPermanently: (
    layerId: string
  ) => { tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta } | null | undefined;
  convertLayer: (
    layerId: string,
    targetMode: ExpressionColor,
    options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
  ) => { tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta } | null | undefined;
  showToast: (msg: string) => void;
}

export function useTonalAndFilterActions({
  hasOpenDocument,
  dimensions,
  activeLayer,
  activeLayerId,
  selection,
  updateLayerThumbnail,
  handleCommitFloatingSelection,
  pushHistoryStepRef,
  addLayer,
  pasteLayerFromCanvas,
  addAdjustmentLayer,
  updateAdjustmentData,
  updateLayerStyles,
  fillScreentoneSelection,
  applyExpressionColorOfPreview,
  applyLayerColorPermanently,
  convertLayer,
  showToast,
}: UseTonalAndFilterActionsParams) {
  const handleOpenAdjustmentModal = useCallback(
    (
      layerId?: string,
      initialType: 'curves' | 'gradient-map' | 'levels' | 'color-balance' = 'curves'
    ) => {
      uiStoreActions.setAdjustmentModalState({
        isOpen: true,
        layerId: layerId || undefined,
        initialType,
      });
    },
    []
  );

  const handleApplyAdjustment = useCallback(
    (type: 'curves' | 'gradient-map' | 'levels' | 'color-balance', data: AdjustmentLayerData) => {
      const targetId = useUiStore.getState().adjustmentModalState.layerId;
      const adjTypeLabel = tc('adjustmentType', data.type);
      if (targetId) {
        updateAdjustmentData(targetId, data);
        showToast(t('Updated {type} adjustment layer', { type: adjTypeLabel }));
      } else {
        addAdjustmentLayer(type, data);
        showToast(t('Created new {type} adjustment layer', { type: adjTypeLabel }));
      }
      uiStoreActions.setAdjustmentModalState({ isOpen: false });
    },
    [updateAdjustmentData, addAdjustmentLayer, showToast]
  );

  const handleOpenLayerStylesModal = useCallback(
    (layerId?: string) => {
      const targetId = layerId || activeLayerId;
      if (targetId) {
        uiStoreActions.setLayerStylesModalState({
          isOpen: true,
          layerId: targetId,
        });
      }
    },
    [activeLayerId]
  );

  const handleApplyLayerStyles = useCallback(
    (styles: LayerStyles) => {
      const targetId = useUiStore.getState().layerStylesModalState.layerId;
      if (targetId) {
        updateLayerStyles(targetId, styles);
        showToast(t('Updated Layer Styles'));
      }
      uiStoreActions.setLayerStylesModalState({ isOpen: false });
    },
    [updateLayerStyles, showToast]
  );

  const handleApplyFilter = useCallback(
    (type: FilterType, params?: AnyFilterParams) => {
      if (
        !hasOpenDocument ||
        !activeLayer ||
        activeLayer.type !== 'raster' ||
        activeLayer.locked
      ) {
        showToast(t('Select an unlocked raster layer to apply filter'));
        return;
      }
      if (dimensions.width <= 0 || dimensions.height <= 0) return;

      const targetLayerId = activeLayerId;
      const docId = documentStore.getActiveDocumentId();
      const spec = toNativeFilterSpec(type, (params ?? {}) as Record<string, unknown>);
      const filterName = tc('filterName', type.replace('-', ' '));

      void nativeImageOpApply({ category: 'filter', filter: spec }, targetLayerId, docId)
        .then((res) => {
          if (res?.modified) {
            updateLayerThumbnail(targetLayerId, true);
          }
          showToast(t('Filter applied: {name}', { name: filterName }));
        })
        .catch((err) => {
          console.error('[NativeFilter] apply failed:', err);
          showToast(t('Failed to apply filter'));
        });
    },
    [hasOpenDocument, activeLayer, activeLayerId, dimensions, updateLayerThumbnail, showToast]
  );

  const getTonalLabel = useCallback((type: TonalCorrectionType) => {
    switch (type) {
      case 'brightness-contrast':
        return t('Brightness/Contrast');
      case 'binarization':
        return t('Binarization');
      case 'hue-saturation':
        return t('Hue/Saturation/Luminosity');
      case 'posterization':
        return t('Posterization');
      case 'level-correction':
        return t('Level Correction');
      case 'reverse-gradient':
        return t('Reverse Gradient');
      default:
        return t('Tonal Correction');
    }
  }, []);

  const handleOpenTonalModal = useCallback(
    (type: TonalCorrectionType) => {
      if (
        !hasOpenDocument ||
        !activeLayer ||
        activeLayer.locked ||
        activeLayer.type !== 'raster'
      ) {
        return;
      }
      if (selection?.floating) {
        handleCommitFloatingSelection();
      }

      const targetLayerId = activeLayerId;
      const docId = documentStore.getActiveDocumentId();
      const bounds = selection
        ? {
            x0: Math.max(0, Math.floor(selection.bounds.x)),
            y0: Math.max(0, Math.floor(selection.bounds.y)),
            x1: Math.min(dimensions.width, Math.ceil(selection.bounds.x + selection.bounds.width)),
            y1: Math.min(dimensions.height, Math.ceil(selection.bounds.y + selection.bounds.height)),
          }
        : { x0: 0, y0: 0, x1: dimensions.width, y1: dimensions.height };

      uiStoreActions.setTonalModalState({
        isOpen: true,
        type,
        targetLayerId,
        beforeTileSnapshot: null,
        histograms: null,
        selectionMask: null,
        bounds,
      });

      if (type === 'level-correction') {
        void nativeLayerHistogram(targetLayerId, docId)
          .then((h) => {
            if (!h) return;
            const current = useUiStore.getState().tonalModalState;
            if (!current.isOpen || current.targetLayerId !== targetLayerId) return;
            uiStoreActions.setTonalModalState({
              ...current,
              histograms: {
                rgb: new Uint32Array(h.rgb ?? h.luminance),
                r: new Uint32Array(h.r),
                g: new Uint32Array(h.g),
                b: new Uint32Array(h.b),
              },
            });
          })
          .catch(() => {});
      }
    },
    [
      hasOpenDocument,
      activeLayer,
      activeLayerId,
      dimensions,
      selection,
      handleCommitFloatingSelection,
    ]
  );

  const handleTonalPreviewChange = useCallback(
    (type: TonalCorrectionType, params: AnyTonalParams, enabled: boolean) => {
      const state = useUiStore.getState().tonalModalState;
      if (!state.isOpen || !state.targetLayerId) return;
      if (!enabled) {
        void nativeClearToolPreview();
        return;
      }
      const docId = documentStore.getActiveDocumentId();
      const tonal = toNativeTonalSpec(type, (params ?? {}) as Record<string, unknown>);
      void nativeImageOpPreview({ category: 'tonal', tonal }, state.targetLayerId, docId).catch(
        () => {}
      );
    },
    []
  );

  const handleTonalApply = useCallback(
    (type: TonalCorrectionType, params: AnyTonalParams) => {
      const state = useUiStore.getState().tonalModalState;
      if (!state.isOpen || !state.targetLayerId) return;
      const targetLayerId = state.targetLayerId;
      const docId = documentStore.getActiveDocumentId();
      const tonal = toNativeTonalSpec(type, (params ?? {}) as Record<string, unknown>);
      const label = getTonalLabel(type);

      uiStoreActions.setTonalModalState({
        isOpen: false,
        type,
        targetLayerId: '',
        beforeTileSnapshot: null,
        histograms: null,
        selectionMask: null,
        bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
      });

      void nativeImageOpApply({ category: 'tonal', tonal }, targetLayerId, docId)
        .then((res) => {
          if (res?.modified) {
            updateLayerThumbnail(targetLayerId, true);
          }
          showToast(t('Applied {label}', { label }));
        })
        .catch((err) => {
          console.error('[NativeTonal] apply failed:', err);
          void nativeClearToolPreview();
        });
    },
    [updateLayerThumbnail, getTonalLabel, showToast]
  );

  const handleTonalCancel = useCallback(() => {
    const state = useUiStore.getState().tonalModalState;
    if (!state.isOpen) return;
    void nativeClearToolPreview();
    uiStoreActions.setTonalModalState({
      isOpen: false,
      type: state.type,
      targetLayerId: '',
      beforeTileSnapshot: null,
      histograms: null,
      selectionMask: null,
      bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
    });
  }, []);

  const handleApplyReverseGradient = useCallback(() => {
    if (
      !hasOpenDocument ||
      !activeLayer ||
      activeLayer.locked ||
      activeLayer.type !== 'raster'
    ) {
      return;
    }
    if (selection?.floating) {
      handleCommitFloatingSelection();
    }
    const targetLayerId = activeLayerId;
    const docId = documentStore.getActiveDocumentId();
    void nativeImageOpApply(
      { category: 'tonal', tonal: { kind: 'reverse-gradient' } },
      targetLayerId,
      docId
    )
      .then((res) => {
        if (res?.modified) {
          updateLayerThumbnail(targetLayerId, true);
        }
        showToast(t('Inverted colors (Reverse Gradient)'));
      })
      .catch(() => {});
  }, [
    hasOpenDocument,
    activeLayer,
    activeLayerId,
    selection,
    handleCommitFloatingSelection,
    updateLayerThumbnail,
    showToast,
  ]);

  const handleApplyMangaEffects = useCallback(
    (type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => {
      if (!activeLayerId || !activeLayer || dimensions.width <= 0 || dimensions.height <= 0) {
        return;
      }
      if (activeLayer.type !== 'raster' || activeLayer.locked) {
        showToast(t('Select an unlocked raster layer to apply manga effects.'));
        return;
      }
      const docId = documentStore.getActiveDocumentId();
      if (!docId) return;

      // Render in bounded 512x512 DOM canvas chunks (never allocates a full-doc DOM canvas).
      // For documents up to 16 MP (e.g. 4096x4096), assemble into one atomic RGBA buffer so Undo/Redo
      // covers the entire canvas in a single history step instead of only the first 512x512 chunk.
      const CHUNK = 512;
      const totalPixels = dimensions.width * dimensions.height;
      const useSingleAtomicIngest = totalPixels <= 16_777_216;
      const fullRgba = useSingleAtomicIngest ? new Uint8Array(totalPixels * 4) : null;

      const chunkCanvas = document.createElement('canvas');
      chunkCanvas.width = Math.min(CHUNK, dimensions.width);
      chunkCanvas.height = Math.min(CHUNK, dimensions.height);
      const cCtx = get2DContext(chunkCanvas);
      if (!cCtx) {
        releaseTemporaryCanvas(chunkCanvas);
        return;
      }

      const tasks: Array<() => Promise<unknown>> = [];
      const effectTypeLabel = tc('mangaEffect', type);
      const targetLayerId = activeLayerId;
      try {
        for (let cy = 0; cy < dimensions.height; cy += CHUNK) {
          const ch = Math.min(CHUNK, dimensions.height - cy);
          for (let cx = 0; cx < dimensions.width; cx += CHUNK) {
            const cw = Math.min(CHUNK, dimensions.width - cx);
            if (chunkCanvas.width !== cw) chunkCanvas.width = cw;
            if (chunkCanvas.height !== ch) chunkCanvas.height = ch;

            cCtx.setTransform(1, 0, 0, 1, 0, 0);
            cCtx.clearRect(0, 0, cw, ch);
            cCtx.save();
            cCtx.translate(-cx, -cy);
            if (type === 'saturated') {
              renderSaturatedLines(
                cCtx,
                dimensions.width,
                dimensions.height,
                options as SaturatedLinesOptions
              );
            } else {
              renderStreamLines(
                cCtx,
                dimensions.width,
                dimensions.height,
                options as StreamLinesOptions
              );
            }
            cCtx.restore();

            const img = cCtx.getImageData(0, 0, cw, ch);
            if (fullRgba) {
              const rowBytes = cw * 4;
              for (let row = 0; row < ch; row++) {
                const srcOff = row * rowBytes;
                const dstOff = ((cy + row) * dimensions.width + cx) * 4;
                fullRgba.set(img.data.subarray(srcOff, srcOff + rowBytes), dstOff);
              }
            } else {
              const bytes = new Uint8Array(img.data.buffer.slice(0));
              const isFirst = tasks.length === 0;
              tasks.push(() =>
                ingestNativeDirtyRect({
                  docId,
                  layerId: targetLayerId,
                  x: cx,
                  y: cy,
                  width: cw,
                  height: ch,
                  bytes,
                  recordHistory: isFirst,
                  actionType: 'brush',
                  label: t('Manga Effect ({type})', { type: effectTypeLabel }),
                })
              );
            }
          }
        }
      } finally {
        releaseTemporaryCanvas(chunkCanvas);
      }

      if (fullRgba) {
        tasks.push(() =>
          ingestNativeDirtyRect({
            docId,
            layerId: targetLayerId,
            x: 0,
            y: 0,
            width: dimensions.width,
            height: dimensions.height,
            bytes: fullRgba,
            recordHistory: true,
            actionType: 'brush',
            label: t('Manga Effect ({type})', { type: effectTypeLabel }),
          })
        );
      }

      void (async () => {
        try {
          for (const run of tasks) {
            await run();
          }
          updateLayerThumbnail(targetLayerId, true);
          showToast(t('Applied manga {type} lines', { type: effectTypeLabel }));
        } catch (err) {
          console.error('[MangaEffects] Failed to apply manga effects:', err);
          showToast(t('Failed to apply manga effects.'));
        }
      })();
    },
    [activeLayerId, activeLayer, dimensions.width, dimensions.height, updateLayerThumbnail, showToast]
  );

  const handleInsert3DRasterLayer = useCallback(
    (layer: LayerItem, canvas: HTMLCanvasElement) => {
      if (layer.type === 'folder') {
        addLayer('folder', layer.parentId, layer.name, layer.id);
      } else {
        pasteLayerFromCanvas(canvas, layer.name, layer.blendMode, layer.opacity, layer.id, layer);
      }
      showToast(t('Added 3D layer "{name}".', { name: layer.name }));
    },
    [addLayer, pasteLayerFromCanvas, showToast]
  );

  const handleFillScreentone = useCallback(() => {
    uiStoreActions.setToneModalOpen(true);
  }, []);

  const handleConfirmTone = useCallback(
    (settings: SimpleToneSettings) => {
      uiStoreActions.setToneModalOpen(false);
      if (selection?.floating) {
        handleCommitFloatingSelection();
      }
      const { id, tileDeltas, layerTreeDelta } = fillScreentoneSelection(
        selection,
        settings.density,
        settings.frequency,
        settings.angle,
        settings.dotShape,
        settings.densityType
      );
      if (tileDeltas.length > 0 || layerTreeDelta) {
        pushHistoryStepRef.current?.(
          'screentone',
          t('Screentone ({density}%)', { density: settings.density }),
          null,
          null,
          id,
          selection?.bounds,
          tileDeltas,
          undefined,
          undefined,
          undefined,
          false,
          layerTreeDelta
        );
      }
      showToast(t('Created Screentone Layer ({density}%)', { density: settings.density }));
    },
    [selection, handleCommitFloatingSelection, fillScreentoneSelection, pushHistoryStepRef, showToast]
  );

  const handleApplyExpressionColor = useCallback(
    (layerId: string) => {
      const result = applyExpressionColorOfPreview(layerId);
      if (result) {
        if (result.tileDeltas.length > 0) {
          pushHistoryStepRef.current?.(
            'expression-color',
            t('Apply Expression Color'),
            null,
            null,
            layerId,
            undefined,
            result.tileDeltas
          );
        }
        showToast(t('Applied expression color to layer'));
      }
    },
    [applyExpressionColorOfPreview, pushHistoryStepRef, showToast]
  );

  const handleApplyLayerColor = useCallback(
    (layerId: string) => {
      const result = applyLayerColorPermanently(layerId);
      if (result && (result.tileDeltas.length > 0 || result.layerTreeDelta)) {
        pushHistoryStepRef.current?.(
          'layer-color',
          t('Apply Layer Color Tint'),
          null,
          null,
          layerId,
          undefined,
          result.tileDeltas,
          undefined,
          undefined,
          undefined,
          false,
          result.layerTreeDelta
        );
        showToast(t('Applied tint to layer permanently'));
      }
    },
    [applyLayerColorPermanently, pushHistoryStepRef, showToast]
  );

  const handleConvertLayer = useCallback(
    (
      layerId: string,
      targetMode: ExpressionColor,
      options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
    ) => {
      const result = convertLayer(layerId, targetMode, options);
      if (result && (result.tileDeltas.length > 0 || result.layerTreeDelta)) {
        pushHistoryStepRef.current?.(
          'layer-convert',
          t('Convert to {mode}', { mode: tc('expressionColorUpper', targetMode.toUpperCase()) }),
          null,
          null,
          layerId,
          undefined,
          result.tileDeltas,
          undefined,
          undefined,
          undefined,
          false,
          result.layerTreeDelta
        );
        showToast(t('Converted layer to {mode}', { mode: tc('expressionColor', targetMode) }));
      }
    },
    [convertLayer, pushHistoryStepRef, showToast]
  );

  return {
    handleOpenAdjustmentModal,
    handleApplyAdjustment,
    handleOpenLayerStylesModal,
    handleApplyLayerStyles,
    handleApplyFilter,
    handleOpenTonalModal,
    handleTonalPreviewChange,
    handleTonalApply,
    handleTonalCancel,
    handleApplyReverseGradient,
    handleApplyMangaEffects,
    handleInsert3DRasterLayer,
    handleFillScreentone,
    handleConfirmTone,
    handleApplyExpressionColor,
    handleApplyLayerColor,
    handleConvertLayer,
  };
}