Skip to content

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

10.6 KB
Raw Blame
import { describe, it, expect } from 'vitest';
import {
  buildNativeBrushConfigPayload,
  getHistorySnapshotEntries,
  type NativeHistoryStateSnapshot,
  type NativeTransformSessionSnapshot,
} from '../nativeEngineBridge';
import { nativeTransformSnapshotToSession } from '../../hooks/drawing/useSelectionTools';
import {
  createDefaultGradientMesh,
  DEFAULT_GRADIENT_SETTINGS,
  toNativeFilterSpec,
  toNativeGradientParams,
  toNativeTonalSpec,
} from '../toolConfigs';
import {
  computeBatchDeleteLayers,
  computeMergeFolderLayers,
} from '../../hooks/layerManager/layerTreeOps';
import { importAutoActionSetsJson } from '../autoActionEngine';
import { parseLegacySoraV1Json } from '../legacySoraMigrator';
import type { BrushSettings, LayerItem } from '../../types/editor';

describe('IPC contracts and bug-audit regression suite', () => {
  describe('HistoryStateSnapshot entries vs items contract (App.tsx crash fix)', () => {
    it('extracts Rust-serialized entries without throwing', () => {
      const rustSnap: NativeHistoryStateSnapshot = {
        entries: [
          {
            id: 'h-0',
            type: 'initial',
            label: 'New Canvas',
            timestamp: 1700000000000,
            timeFormatted: '12:00:00',
            thumbnailUrl: '',
          },
          {
            id: 'h-1',
            type: 'brush',
            label: 'Brush Stroke',
            timestamp: 1700000005000,
            timeFormatted: '12:00:05',
            thumbnailUrl: '',
          },
        ],
        index: 1,
        canUndo: true,
        canRedo: false,
      };
      const entries = getHistorySnapshotEntries(rustSnap);
      expect(entries).toHaveLength(2);
      expect(entries[0]?.label).toBe('New Canvas');
      expect(entries[1]?.id).toBe('h-1');
    });

    it('falls back to legacy items or empty array safely on malformed snapshots', () => {
      const legacy = {
        items: [
          {
            id: 'h-legacy',
            type: 'brush',
            label: 'Legacy Step',
            timestamp: 1,
            timeFormatted: '00:00:01',
            thumbnailUrl: '',
          },
        ],
        index: 0,
        canUndo: false,
        canRedo: false,
      } as unknown as NativeHistoryStateSnapshot;
      expect(getHistorySnapshotEntries(legacy)).toHaveLength(1);
      expect(getHistorySnapshotEntries(null)).toEqual([]);
      expect(getHistorySnapshotEntries(undefined)).toEqual([]);
      expect(getHistorySnapshotEntries({} as NativeHistoryStateSnapshot)).toEqual([]);
    });
  });

  describe('TransformSessionSnapshot Rust <-> TS schema alignment', () => {
    it('hydrates exact Rust TransformSessionSnapshot JSON including cell-to-vertex mesh stride and cage state', () => {
      // Exact wire shape emitted by crates/ink-engine/src/tools/transform.rs
      const rustSnap: NativeTransformSessionSnapshot = {
        active: true,
        docId: 'doc-1',
        mode: 'mesh',
        showMesh: true,
        targetLayerIds: ['layer-1', 'layer-2'],
        sourceBounds: { x: 100, y: 50, width: 200, height: 100 },
        affine: {
          x: 110,
          y: 60,
          width: 240,
          height: 120,
          rotation: 0.25,
          skewX: 0.1,
          skewY: -0.05,
          flipX: true,
          flipY: false,
        },
        corners: [
          { x: 100, y: 50 },
          { x: 300, y: 50 },
          { x: 300, y: 150 },
          { x: 100, y: 150 },
        ],
        mesh: {
          // 2x2 cells => 3x3 = 9 vertices
          cols: 2,
          rows: 2,
          points: [
            { x: 100, y: 50 },
            { x: 200, y: 50 },
            { x: 300, y: 50 },
            { x: 100, y: 100 },
            { x: 215, y: 105 },
            { x: 300, y: 100 },
            { x: 100, y: 150 },
            { x: 200, y: 150 },
            { x: 300, y: 150 },
          ],
        },
        puppet: {
          pins: [
            { id: 'p1', restX: 120, restY: 80, x: 140, y: 90, rotation: 0, depth: 0 },
          ],
          meshVertices: [],
          meshTriangles: [],
        },
        cage: {
          points: [
            { x: 100, y: 50 },
            { x: 300, y: 50 },
            { x: 200, y: 150 },
          ],
          restPoints: [
            { x: 100, y: 50 },
            { x: 300, y: 50 },
            { x: 200, y: 150 },
          ],
          closed: true,
        },
      };

      const session = nativeTransformSnapshotToSession(rustSnap, 'fallback', false);
      expect(session.active).toBe(true);
      expect(session.layerId).toBe('layer-1');
      expect(session.layerIds).toEqual(['layer-1', 'layer-2']);
      expect(session.bounds).toEqual({ x: 100, y: 50, width: 200, height: 100 });
      expect(session.x).toBe(110);
      expect(session.y).toBe(60);
      expect(session.width).toBe(240);
      expect(session.height).toBe(120);
      expect(session.flipH).toBe(true);
      expect(session.flipV).toBe(false);
      // 2 cells -> 3 vertices per axis
      expect(session.meshCols).toBe(3);
      expect(session.meshRows).toBe(3);
      expect(session.meshPoints).toHaveLength(3);
      expect(session.meshPoints?.[1]?.[1]).toEqual({ x: 215, y: 105 });
      expect(session.cage?.phase).toBe('deform');
      expect(session.cage?.points).toHaveLength(3);
      expect(session.puppet?.pins).toHaveLength(1);
    });
  });

  describe('Gradient mesh cell count & dragged node UV mapping', () => {
    it('emits cell counts (cols-1, rows-1) and non-uniform UVs for dragged nodes', () => {
      const bounds = { x: 0, y: 0, width: 400, height: 200 };
      const mesh = createDefaultGradientMesh(bounds, 3, 3, '#ff0000', '#0000ff');
      // Drag center node (index 4) to (300, 150) => u = 0.75, v = 0.75
      mesh.nodes[4] = { ...mesh.nodes[4], x: 300, y: 150 };

      const params = toNativeGradientParams({
        settings: { ...DEFAULT_GRADIENT_SETTINGS, type: 'mesh' },
        start: { x: 0, y: 0 },
        end: { x: 400, y: 200 },
        primaryColor: '#ff0000',
        secondaryColor: '#0000ff',
        mesh,
      });

      expect(params.mesh).toBeDefined();
      expect(params.mesh?.cols).toBe(2);
      expect(params.mesh?.rows).toBe(2);
      expect(params.mesh?.nodes).toHaveLength(9);
      expect(params.mesh?.nodes[4]?.u).toBeCloseTo(0.75, 4);
      expect(params.mesh?.nodes[4]?.v).toBeCloseTo(0.75, 4);
    });
  });

  describe('Filter & Tonal spec sanitization', () => {
    it('clamps binarization threshold to u8 and film-grain seed to u32', () => {
      const tonal = toNativeTonalSpec('binarization', { threshold: 999 });
      expect(tonal).toEqual({ kind: 'binarization', threshold: 255 });

      const tonalNeg = toNativeTonalSpec('binarization', { threshold: -50 });
      expect(tonalNeg).toEqual({ kind: 'binarization', threshold: 0 });

      const level = toNativeTonalSpec('level-correction', {
        inputMin: 12,
        inputMax: 240,
        gamma: 1.25,
        outputMin: 5,
        outputMax: 250,
      });
      expect(level).toEqual({
        kind: 'level-correction',
        inBlack: 12,
        inWhite: 240,
        gamma: 1.25,
        outBlack: 5,
        outWhite: 250,
      });

      const filter = toNativeFilterSpec('film-grain', {
        intensity: 25,
        size: 1.5,
        monochromatic: true,
        seed: -42,
      });
      expect(filter.kind).toBe('film-grain');
      if (filter.kind === 'film-grain') {
        expect(filter.seed).toBeGreaterThanOrEqual(0);
        expect(Number.isInteger(filter.seed)).toBe(true);
      }
    });
  });

  describe('Brush config naturalPaint.penetrationCurve sanitization', () => {
    it('converts array penetrationCurve into a finite scalar for Rust f32 deserialization', async () => {
      const brushSettings = {
        size: 20,
        opacity: 1,
        flow: 1,
        hardness: 0.9,
        spacing: 0.1,
        naturalPaint: {
          enabled: true,
          penetrationCurve: [0, 0.25, 0.5, 0.75, 1] as unknown as number,
        },
      } as unknown as BrushSettings;

      const payload = await buildNativeBrushConfigPayload(
        'brush',
        brushSettings,
        '#112233',
        '#ffffff'
      );
      const np = payload.naturalPaint as Record<string, unknown>;
      expect(typeof np.penetrationCurve).toBe('number');
      expect(Number.isFinite(np.penetrationCurve)).toBe(true);
    });
  });

  describe('Layer tree ops: mask metadata preservation & batch delete reparenting', () => {
    it('preserves hasMask on merged folder raster layer even without maskCanvas', () => {
      const layers: LayerItem[] = [
        {
          id: 'folder-1',
          name: 'Group',
          type: 'folder',
          visible: true,
          opacity: 0.8,
          blendMode: 'pass-through',
          locked: false,
          collapsed: false,
          parentId: null,
          hasMask: true,
          maskEnabled: true,
          maskLinked: true,
        },
        {
          id: 'child-1',
          name: 'Ink',
          type: 'raster',
          visible: true,
          opacity: 1,
          blendMode: 'normal',
          locked: false,
          collapsed: false,
          parentId: 'folder-1',
        },
      ];

      const merged = computeMergeFolderLayers(layers, 'folder-1', 'merged-1');
      expect(merged).not.toBeNull();
      const mergedLayer = merged!.nextLayers.find((l) => l.id === 'merged-1');
      expect(mergedLayer?.hasMask).toBe(true);
      expect(mergedLayer?.blendMode).toBe('normal');
    });

    it('reparents preserved raster child to null when its parent folder is deleted in batch delete', () => {
      const layers: LayerItem[] = [
        {
          id: 'folder-1',
          name: 'Folder',
          type: 'folder',
          visible: true,
          opacity: 1,
          blendMode: 'pass-through',
          locked: false,
          collapsed: false,
          parentId: null,
        },
        {
          id: 'raster-only',
          name: 'Only Raster',
          type: 'raster',
          visible: true,
          opacity: 1,
          blendMode: 'normal',
          locked: false,
          collapsed: false,
          parentId: 'folder-1',
        },
      ];

      const res = computeBatchDeleteLayers(layers, ['folder-1', 'raster-only'], 'raster-only');
      expect(res.nextLayers).toHaveLength(1);
      expect(res.nextLayers[0]?.id).toBe('raster-only');
      expect(res.nextLayers[0]?.parentId).toBeNull();
    });
  });

  describe('Malformed JSON safety in importers', () => {
    it('throws descriptive errors instead of raw SyntaxError on corrupt JSON', () => {
      expect(() => importAutoActionSetsJson('{corrupt')).toThrow('Invalid Auto Actions JSON format');
      expect(() => parseLegacySoraV1Json('{corrupt')).toThrow(
        'Invalid legacy .sora project payload: malformed JSON'
      );
    });
  });
});