Skip to content

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

23.1 KB
Raw Blame
import React, { useRef, useState, useCallback, useEffect } from 'react';
import { Eraser, Droplets, Sun, Moon, Square, Radio, Spline } from 'lucide-react';
import type { BrushSettings } from '../../types/editor';
import { IconButton, SegmentedControl } from '../ui';
import {
  cleanNativeDirtyBrush,
  isNativeCanvasActive,
  renderNativeScratchpadPreview,
} from '../../utils/nativeEngineBridge';
import {
  buildDefaultSampleStroke,
  RecordedScratchpadStroke,
  renderScratchpadStrokes2D,
  renderSingleScratchpadStroke2D,
  ScratchpadSamplePoint,
  toNativeScratchpadStrokes,
} from '../../utils/scratchpadRenderer';
import { useI18n } from '../../i18n';

type ScratchpadBg = 'dark' | 'gray' | 'white';

const SCRATCHPAD_W = 560;
const SCRATCHPAD_H = 440;
const MAX_RECORDED_STROKES = 24;

const BG_COLORS: Record<ScratchpadBg, string> = {
  dark: '#18181b',
  gray: '#525252',
  white: '#f6f4ef',
};

const BG_LABELS: Record<ScratchpadBg, string> = {
  dark: 'Dark',
  gray: 'Mid-Grey',
  white: 'Paper White',
};

const QUICK_SWATCHES = [
  { label: 'Sumi Ink', hex: '#18181b' },
  { label: 'Prussian Blue', hex: '#1d4ed8' },
  { label: 'Vermilion Red', hex: '#dc2626' },
  { label: 'Cadmium Yellow', hex: '#facc15' },
  { label: 'Ultramarine Violet', hex: '#6d28d9' },
];

export interface BrushStudioScratchpadProps {
  brushSettings: BrushSettings;
  onPatchSettings?: (patch: Partial<BrushSettings>) => void;
}

export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
  brushSettings,
  onPatchSettings,
}) => {
  const { t, tc } = useI18n();
  const baseCanvasRef = useRef<HTMLCanvasElement | null>(null);
  const draftCanvasRef = useRef<HTMLCanvasElement | null>(null);
  const [bgMode, setBgMode] = useState<ScratchpadBg>('white');
  const [testColor, setTestColor] = useState<string>(brushSettings.color || '#1d4ed8');
  const [useActiveColor, setUseActiveColor] = useState<boolean>(true);
  const [livePreview, setLivePreview] = useState<boolean>(true);
  const [showSampleStroke, setShowSampleStroke] = useState<boolean>(true);
  const [strokeCount, setStrokeCount] = useState<number>(0);
  const [renderRevision, setRenderRevision] = useState<number>(0);

  const activeColor = useActiveColor ? brushSettings.color || '#1d4ed8' : testColor;

  const strokesRef = useRef<RecordedScratchpadStroke[]>([]);
  const showSampleStrokeRef = useRef<boolean>(true);
  const nextStrokeIdRef = useRef<number>(1);
  const renderTokenRef = useRef<number>(0);
  const gpuInFlightRef = useRef<boolean>(false);
  const gpuPendingRef = useRef<{
    token: number;
    bs: BrushSettings;
    color: string;
    strokes: RecordedScratchpadStroke[];
  } | null>(null);

  const sessionRef = useRef<{
    drawing: boolean;
    pointerId: number;
    activeStroke: RecordedScratchpadStroke | null;
    clearedSampleOnDown: boolean;
  }>({
    drawing: false,
    pointerId: -1,
    activeStroke: null,
    clearedSampleOnDown: false,
  });

  const paintRgbaToBase = useCallback((rgba: Uint8ClampedArray<ArrayBuffer>, w: number, h: number) => {
    const base = baseCanvasRef.current;
    if (!base) return;
    const bCtx = base.getContext('2d');
    if (!bCtx) return;
    if (typeof ImageData !== 'undefined') {
      const imgData = new ImageData(rgba, w, h);
      if (w === base.width && h === base.height) {
        bCtx.clearRect(0, 0, base.width, base.height);
        bCtx.putImageData(imgData, 0, 0);
      } else {
        const tmp = document.createElement('canvas');
        tmp.width = w;
        tmp.height = h;
        tmp.getContext('2d')?.putImageData(imgData, 0, 0);
        bCtx.clearRect(0, 0, base.width, base.height);
        bCtx.drawImage(tmp, 0, 0, base.width, base.height);
      }
    }
  }, []);

  const clearDraftIfIdle = useCallback(() => {
    if (sessionRef.current.drawing) return;
    const draft = draftCanvasRef.current;
    draft?.getContext('2d')?.clearRect(0, 0, draft.width, draft.height);
  }, []);

  const dispatchGpuRender = useCallback(
    (
      token: number,
      bs: BrushSettings,
      color: string,
      strokes: RecordedScratchpadStroke[]
    ) => {
      if (gpuInFlightRef.current) {
        gpuPendingRef.current = { token, bs, color, strokes };
        return;
      }
      gpuInFlightRef.current = true;
      const nativeStrokes = toNativeScratchpadStrokes(strokes, color);
      void renderNativeScratchpadPreview(
        'brush',
        bs,
        color,
        bs.secondaryColor || '#ffffff',
        nativeStrokes,
        SCRATCHPAD_W,
        SCRATCHPAD_H
      )
        .then((img) => {
          const isCleared = strokesRef.current.length === 0 && !showSampleStrokeRef.current;
          if (isCleared) return;
          if (img) {
            // Paint the latest finished frame if it hasn't been superseded by a newer clear/reset
            if (token >= renderTokenRef.current - 1) {
              paintRgbaToBase(img.rgba, img.width, img.height);
              clearDraftIfIdle();
            }
          } else {
            // Native renderer unavailable — fall back cleanly to 2D canvas replay
            const base = baseCanvasRef.current;
            const bCtx = base?.getContext('2d');
            if (base && bCtx) {
              renderScratchpadStrokes2D(bCtx, base.width, base.height, strokes, bs, color);
              clearDraftIfIdle();
            }
          }
        })
        .finally(() => {
          gpuInFlightRef.current = false;
          const pending = gpuPendingRef.current;
          if (pending) {
            gpuPendingRef.current = null;
            dispatchGpuRender(pending.token, pending.bs, pending.color, pending.strokes);
          }
        });
    },
    [clearDraftIfIdle, paintRgbaToBase]
  );

  // Re-render once custom tip image finishes async browser decode
  useEffect(() => {
    const img = brushSettings.customTipImage;
    if (!img || (img.complete && (img.naturalWidth || img.width) > 0)) return;
    const onLoad = () => setRenderRevision((r) => r + 1);
    if (typeof img.addEventListener === 'function') {
      img.addEventListener('load', onLoad, { once: true });
      return () => img.removeEventListener('load', onLoad);
    }
    return undefined;
  }, [brushSettings.customTipImage]);

  // Live re-render whenever brushSettings, activeColor, recorded strokes, or sample state changes
  useEffect(() => {
    const base = baseCanvasRef.current;
    if (!base) return;
    const bCtx = base.getContext('2d');
    if (!bCtx) return;

    const userStrokes = strokesRef.current;
    const strokesToRender =
      userStrokes.length > 0
        ? userStrokes
        : showSampleStroke
          ? [buildDefaultSampleStroke(base.width, base.height, activeColor)]
          : [];

    if (strokesToRender.length === 0) {
      renderTokenRef.current += 1;
      gpuPendingRef.current = null;
      bCtx.clearRect(0, 0, base.width, base.height);
      return;
    }

    // When Live preview is toggled OFF, only re-render on explicit stroke additions / sample toggle,
    // leaving existing strokes frozen for side-by-side comparison.
    if (!livePreview && userStrokes.length > 0) {
      return;
    }

    const token = ++renderTokenRef.current;
    if (isNativeCanvasActive()) {
      dispatchGpuRender(token, brushSettings, activeColor, strokesToRender);
    } else {
      renderScratchpadStrokes2D(bCtx, base.width, base.height, strokesToRender, brushSettings, activeColor);
      clearDraftIfIdle();
    }
  }, [
    brushSettings,
    activeColor,
    livePreview,
    showSampleStroke,
    strokeCount,
    renderRevision,
    dispatchGpuRender,
    clearDraftIfIdle,
  ]);

  const clearScratchpad = useCallback(() => {
    renderTokenRef.current += 1;
    gpuPendingRef.current = null;
    strokesRef.current = [];
    showSampleStrokeRef.current = false;
    setStrokeCount(0);
    setShowSampleStroke(false);
    const base = baseCanvasRef.current;
    const draft = draftCanvasRef.current;
    base?.getContext('2d')?.clearRect(0, 0, base.width, base.height);
    draft?.getContext('2d')?.clearRect(0, 0, draft.width, draft.height);
  }, []);

  const restoreSampleStroke = useCallback(() => {
    renderTokenRef.current += 1;
    gpuPendingRef.current = null;
    strokesRef.current = [];
    showSampleStrokeRef.current = true;
    setStrokeCount(0);
    setShowSampleStroke(true);
    setRenderRevision((r) => r + 1);
  }, []);

  const extractSamplePoint = (
    e: PointerEvent | React.PointerEvent<HTMLCanvasElement>
  ): ScratchpadSamplePoint => {
    const canvas = draftCanvasRef.current!;
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / Math.max(1, rect.width);
    const scaleY = canvas.height / Math.max(1, rect.height);
    const x = (e.clientX - rect.left) * scaleX;
    const y = (e.clientY - rect.top) * scaleY;
    const pressure =
      e.pointerType === 'mouse' ? 0.72 : Math.max(0.05, Math.min(1, e.pressure || 0.5));
    return {
      x,
      y,
      pressure,
      tiltX: e.tiltX ?? 0,
      tiltY: e.tiltY ?? 0,
      twist: e.twist ?? 0,
      timestampMs: e.timeStamp || performance.now(),
    };
  };

  const repaintActiveDraft = (stroke: RecordedScratchpadStroke) => {
    const draft = draftCanvasRef.current;
    const dCtx = draft?.getContext('2d');
    if (!draft || !dCtx) return;
    dCtx.clearRect(0, 0, draft.width, draft.height);
    renderSingleScratchpadStroke2D(dCtx, stroke, brushSettings, activeColor);
  };

  const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
    if (e.button !== 0) return;
    e.preventDefault();
    const draft = draftCanvasRef.current;
    if (!draft) return;
    const dCtx = draft.getContext('2d');
    if (!dCtx) return;

    try {
      draft.setPointerCapture(e.pointerId);
    } catch {
      // Ignore synthetic pointer capture errors in tests
    }

    // Clear the starter sample stroke from base canvas the moment the user starts drawing
    let clearedSample = false;
    if (strokesRef.current.length === 0 && showSampleStrokeRef.current) {
      clearedSample = true;
      showSampleStrokeRef.current = false;
      setShowSampleStroke(false);
      const base = baseCanvasRef.current;
      base?.getContext('2d')?.clearRect(0, 0, base.width, base.height);
    }

    const pt = extractSamplePoint(e);
    const id = nextStrokeIdRef.current++;
    const stroke: RecordedScratchpadStroke = {
      id,
      points: [pt],
      color: activeColor,
      followActiveColor: useActiveColor,
      seed: ((id * 2654435761) ^ 0x2468ace1) >>> 0,
    };

    sessionRef.current = {
      drawing: true,
      pointerId: e.pointerId,
      activeStroke: stroke,
      clearedSampleOnDown: clearedSample,
    };

    repaintActiveDraft(stroke);
  };

  const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
    const s = sessionRef.current;
    if (!s.drawing || e.pointerId !== s.pointerId || !s.activeStroke) return;

    const nativeEv = e.nativeEvent as PointerEvent | undefined;
    const coalesced =
      typeof nativeEv?.getCoalescedEvents === 'function' ? nativeEv.getCoalescedEvents() : null;

    if (coalesced && coalesced.length > 0) {
      for (const ce of coalesced) {
        s.activeStroke.points.push(extractSamplePoint(ce));
      }
    } else {
      s.activeStroke.points.push(extractSamplePoint(e));
    }

    repaintActiveDraft(s.activeStroke);
  };

  const finishStroke = (e: React.PointerEvent<HTMLCanvasElement>) => {
    const s = sessionRef.current;
    if (!s.drawing || e.pointerId !== s.pointerId) return;
    const finished = s.activeStroke;
    s.drawing = false;
    s.pointerId = -1;
    s.activeStroke = null;
    s.clearedSampleOnDown = false;

    const base = baseCanvasRef.current;
    const draft = draftCanvasRef.current;
    if (draft?.hasPointerCapture?.(e.pointerId)) {
      try {
        draft.releasePointerCapture(e.pointerId);
      } catch {
        // Ignore release errors
      }
    }

    if (!finished || finished.points.length === 0) {
      draft?.getContext('2d')?.clearRect(0, 0, draft.width, draft.height);
      return;
    }

    if (!livePreview) {
      // Frozen comparison mode: bake stroke straight onto base canvas
      if (base && draft) {
        const bCtx = base.getContext('2d');
        const dCtx = draft.getContext('2d');
        if (bCtx && dCtx) {
          bCtx.save();
          bCtx.globalAlpha = Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0));
          bCtx.drawImage(draft, 0, 0);
          bCtx.restore();
          dCtx.clearRect(0, 0, draft.width, draft.height);
        }
      }
      strokesRef.current = [...strokesRef.current, finished].slice(-MAX_RECORDED_STROKES);
      setStrokeCount(strokesRef.current.length);
      return;
    }

    // Live Preview mode: record stroke and trigger real-time replay (DX12 GPU or 2D)
    strokesRef.current = [...strokesRef.current, finished].slice(-MAX_RECORDED_STROKES);
    setStrokeCount(strokesRef.current.length);
    setRenderRevision((r) => r + 1);
  };

  return (
    <div
      data-testid="brush-studio-scratchpad"
      className="flex flex-col h-full bg-ui-void"
    >
      {/* Compact Top Scratchpad Toolbar: Ink Swatches | Surface | Live & Sample | Clear */}
      <div className="px-2.5 py-1.5 border-b border-ui-subtle flex items-center justify-between gap-2 bg-ui-header shrink-0">
        <div className="flex items-center gap-1.5 min-w-0">
          <button
            type="button"
            onClick={() => setUseActiveColor(true)}
            title={t('Active foreground ink ({color})', {
              color: brushSettings.color || '#1d4ed8',
            })}
            aria-label={t('Use active foreground color')}
            aria-pressed={useActiveColor}
            className={`w-4 h-4 rounded-full border cursor-pointer transition-transform shrink-0 ${
              useActiveColor
                ? 'border-ui-strong scale-110 ring-1 ring-ui-accent ring-offset-1 ring-offset-ui-header'
                : 'border-ui-default hover:scale-105'
            }`}
            style={{ backgroundColor: brushSettings.color || '#1d4ed8' }}
          />
          <div className="w-px h-3.5 bg-ui-default mx-0.5 shrink-0" />
          {QUICK_SWATCHES.map((sw) => {
            const selected = !useActiveColor && testColor === sw.hex;
            const swLabel = t(sw.label);
            return (
              <button
                key={sw.hex}
                type="button"
                onClick={() => {
                  setUseActiveColor(false);
                  setTestColor(sw.hex);
                }}
                title={t('Test ink: {label}', { label: swLabel })}
                aria-label={t('Test ink: {label}', { label: swLabel })}
                aria-pressed={selected}
                className={`w-3.5 h-3.5 rounded-full border cursor-pointer transition-transform shrink-0 ${
                  selected
                    ? 'border-ui-strong scale-110 ring-1 ring-ui-accent ring-offset-1 ring-offset-ui-header'
                    : 'border-ui-default hover:scale-105'
                }`}
                style={{ backgroundColor: sw.hex }}
              />
            );
          })}
        </div>

        <div className="flex items-center gap-1.5 shrink-0">
          <button
            type="button"
            data-testid="scratchpad-live-toggle"
            aria-pressed={livePreview}
            onClick={() => setLivePreview((v) => !v)}
            title={
              livePreview
                ? t('Live Preview ON — edits update drawn strokes in real time')
                : t('Live Preview OFF — strokes stay frozen for comparison')
            }
            className={`h-6 px-2 rounded-ui-xs border text-[10px] font-medium flex items-center gap-1 cursor-pointer transition-colors ${
              livePreview
                ? 'bg-ui-accent-subtle border-ui-accent-border/50 text-ui-primary'
                : 'bg-ui-control border-ui-subtle text-ui-muted hover:text-ui-secondary'
            }`}
          >
            <Radio className={`w-2.5 h-2.5 ${livePreview ? 'text-ui-accent' : 'text-ui-muted'}`} />
            <span>{t('Live')}</span>
          </button>

          {strokeCount === 0 && !showSampleStroke && (
            <IconButton
              size="xs"
              variant="subtle"
              data-testid="scratchpad-sample-btn"
              onClick={restoreSampleStroke}
              title={t('Show Sample S-Curve Stroke')}
              icon={<Spline className="w-3 h-3" />}
              label={t('Sample')}
            />
          )}

          <SegmentedControl<ScratchpadBg>
            size="xs"
            aria-label={t('Scratchpad Surface')}
            data-testid="scratchpad-bg-switcher"
            value={bgMode}
            onChange={setBgMode}
            options={[
              {
                value: 'dark',
                label: tc('theme', 'Dark'),
                icon: <Moon className="w-2.5 h-2.5" />,
                title: t('Dark Studio Surface'),
              },
              {
                value: 'gray',
                label: t('Grey'),
                icon: <Square className="w-2.5 h-2.5" />,
                title: t('Mid-Grey Surface'),
              },
              {
                value: 'white',
                label: t('Paper'),
                icon: <Sun className="w-2.5 h-2.5" />,
                title: t('Paper White Surface'),
              },
            ]}
          />

          {brushSettings.naturalPaint?.autoClean === false && (
            <IconButton
              size="xs"
              variant="subtle"
              onClick={() => void cleanNativeDirtyBrush(brushSettings.preset)}
              title={t('Wash dirty pigment off bristles')}
              icon={<Droplets className="w-3 h-3 text-ui-accent" />}
              label={t('Clean')}
            />
          )}

          <IconButton
            size="xs"
            variant="subtle"
            onClick={clearScratchpad}
            title={t('Clear Scratchpad')}
            icon={<Eraser className="w-3 h-3" />}
            label={t('Clear')}
          />
        </div>
      </div>

      {/* Framed Interactive Dual-Canvas Live Painting Surface */}
      <div className="flex-1 min-h-0 p-2.5 bg-ui-void flex">
        <div
          className="relative flex-1 rounded-ui-md border border-ui-default overflow-hidden select-none touch-none"
          style={{ backgroundColor: BG_COLORS[bgMode] }}
        >
          <canvas
            ref={baseCanvasRef}
            data-testid="scratchpad-base-canvas"
            width={SCRATCHPAD_W}
            height={SCRATCHPAD_H}
            className="absolute inset-0 w-full h-full pointer-events-none"
          />
          <canvas
            ref={draftCanvasRef}
            data-testid="scratchpad-draft-canvas"
            width={SCRATCHPAD_W}
            height={SCRATCHPAD_H}
            onPointerDown={handlePointerDown}
            onPointerMove={handlePointerMove}
            onPointerUp={finishStroke}
            onPointerCancel={finishStroke}
            style={{ opacity: Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0)) }}
            className="absolute inset-0 w-full h-full cursor-crosshair"
          />
        </div>
      </div>

      {/* Live Quick-Tune Bar (Size, Opacity, Flow) for instant visual feedback from any tab */}
      {onPatchSettings && (
        <div
          data-testid="scratchpad-quick-controls"
          className="px-3 py-1.5 bg-ui-panel border-t border-ui-subtle flex items-center gap-3 shrink-0 text-[10px]"
        >
          <label className="flex-1 flex items-center gap-2 min-w-0">
            <span className="text-ui-muted shrink-0">{t('Size')}</span>
            <input
              type="range"
              data-testid="scratchpad-size-slider"
              aria-label={t('Brush Size')}
              min={1}
              max={200}
              step={1}
              value={Math.round(Math.max(1, Math.min(200, brushSettings.size ?? 14)))}
              onChange={(e) => onPatchSettings({ size: Number(e.target.value) })}
              className="flex-1 min-w-0 accent-[var(--ui-accent)] h-1 cursor-pointer"
            />
            <span className="font-ui-mono tabular-nums text-ui-secondary w-9 text-right shrink-0">
              {Math.round(brushSettings.size ?? 14)}px
            </span>
          </label>
          <div className="w-px h-3.5 bg-ui-subtle shrink-0" />
          <label className="w-28 flex items-center gap-1.5 shrink-0">
            <span className="text-ui-muted shrink-0">{t('Opacity')}</span>
            <input
              type="range"
              data-testid="scratchpad-opacity-slider"
              aria-label={t('Opacity')}
              min={1}
              max={100}
              step={1}
              value={Math.round(Math.max(1, Math.min(100, (brushSettings.opacity ?? 1) * 100)))}
              onChange={(e) => onPatchSettings({ opacity: Number(e.target.value) / 100 })}
              className="flex-1 min-w-0 accent-[var(--ui-accent)] h-1 cursor-pointer"
            />
            <span className="font-ui-mono tabular-nums text-ui-secondary w-7 text-right shrink-0">
              {Math.round((brushSettings.opacity ?? 1) * 100)}%
            </span>
          </label>
          <div className="w-px h-3.5 bg-ui-subtle shrink-0" />
          <label className="w-24 flex items-center gap-1.5 shrink-0">
            <span className="text-ui-muted shrink-0">{t('Flow')}</span>
            <input
              type="range"
              data-testid="scratchpad-flow-slider"
              aria-label={t('Flow')}
              min={5}
              max={100}
              step={1}
              value={Math.round(Math.max(5, Math.min(100, (brushSettings.flow ?? 1) * 100)))}
              onChange={(e) => onPatchSettings({ flow: Number(e.target.value) / 100 })}
              className="flex-1 min-w-0 accent-[var(--ui-accent)] h-1 cursor-pointer"
            />
            <span className="font-ui-mono tabular-nums text-ui-secondary w-7 text-right shrink-0">
              {Math.round((brushSettings.flow ?? 1) * 100)}%
            </span>
          </label>
        </div>
      )}

      {/* Clean Bottom Micro-Status Readout */}
      <div className="h-6 px-3 bg-ui-header border-t border-ui-subtle flex items-center justify-between gap-2 shrink-0 text-[10px]">
        <div className="flex items-center gap-1.5 min-w-0 text-ui-muted">
          <span
            aria-hidden="true"
            className="w-2 h-2 rounded-full border border-ui-strong shrink-0"
            style={{ backgroundColor: activeColor }}
          />
          <span className="font-ui-mono uppercase text-ui-secondary shrink-0">
            {activeColor}
          </span>
          <span className="text-ui-disabled">·</span>
          <span className="truncate">
            {t('{surface} — Draw & overlap strokes', { surface: t(BG_LABELS[bgMode]) })}
          </span>
        </div>

        <div className="flex items-center gap-2 font-ui-mono tabular-nums text-ui-secondary shrink-0">
          <span title={t('Brush Size')}>{Math.round(brushSettings.size ?? 14)}px</span>
          <span className="text-ui-disabled">·</span>
          <span title={t('Opacity')}>{Math.round((brushSettings.opacity ?? 1) * 100)}%</span>
          <span className="text-ui-disabled">·</span>
          <span title={t('Spacing')}>
            {t('{pct}% spc', { pct: Math.round((brushSettings.spacing ?? 0.06) * 100) })}
          </span>
        </div>
      </div>
    </div>
  );
};