Skip to content

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

5.5 KB
Raw Blame
/**
 * Optimized Time-lapse Capture Area Renderers (Phase 6 Native DX12 Pipeline)
 *
 * Supports three capture areas with zero legacy JS tile grids:
 * 1. `artwork`     – Direct Rust `captureNativeTimelapseFrame` (zero JS pixel transfer)
 * 2. `canvas-view` – Downscaled DX12 flattened artboard composed under viewport camera transform
 * 3. `app-window`  – Native off-main-thread Windows GDI PrintWindow (`PW_RENDERFULLCONTENT`)
 */

import { CanvasDimensions } from '../types/editor';
import { ViewportTransform } from './layerTree';
import { flattenNativeDocument } from './nativeEngineBridge';
import { invokeTauri, isTauriRuntime, toArrayBuffer } from './timelapseStorage';

export interface TimelapseLiveCaptureContext {
  viewportElement?: HTMLElement | null;
  camera?: ViewportTransform | null;
  showCheckerboard?: boolean;
  valueCheckEnabled?: boolean;
  matteColor?: string;
  isDrawingActive?: () => boolean;
  documentName?: string;
}

function resolveCanvasMatteColor(explicit?: string): string {
  if (explicit) return explicit;
  if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    try {
      const val = getComputedStyle(document.documentElement)
        .getPropertyValue('--ui-canvas-matte')
        .trim();
      if (val) return val;
    } catch {
      // fallback below
    }
  }
  return '#161616';
}

export function computeCanvasViewDimensions(
  viewportW: number,
  viewportH: number,
  maxCaptureDim: number
): { width: number; height: number } {
  const safeW = Math.max(64, viewportW);
  const safeH = Math.max(64, viewportH);
  const scale = Math.min(1, maxCaptureDim / Math.max(safeW, safeH));
  return {
    width: Math.max(2, Math.round((safeW * scale) / 2) * 2),
    height: Math.max(2, Math.round((safeH * scale) / 2) * 2),
  };
}

/**
 * Renders the current viewport camera view (`canvas-view` timelapse mode) by compositing a
 * bounded downscaled DX12 artboard snapshot under the active pan/zoom/rotation/flip transform.
 */
export async function renderNativeCanvasViewToCanvas(
  targetCanvas: HTMLCanvasElement,
  docId: string,
  dimensions: CanvasDimensions,
  viewportW: number,
  viewportH: number,
  camera: ViewportTransform,
  maxCaptureDim: number,
  options?: {
    showCheckerboard?: boolean;
    valueCheckEnabled?: boolean;
    matteColor?: string;
  }
): Promise<boolean> {
  if (typeof document === 'undefined') return false;
  const ctx = targetCanvas.getContext('2d');
  if (!ctx) return false;

  const flat = await flattenNativeDocument(docId, {
    maxDim: Math.min(1920, maxCaptureDim),
    showCheckerboard: Boolean(options?.showCheckerboard),
    fillWhiteBackground: !options?.showCheckerboard,
    applyValueCheck: Boolean(options?.valueCheckEnabled),
  });
  if (!flat) return false;

  const outW = Math.max(2, Math.floor(targetCanvas.width));
  const outH = Math.max(2, Math.floor(targetCanvas.height));
  const safeVpW = Math.max(1, viewportW);
  const safeVpH = Math.max(1, viewportH);
  const docW = Math.max(1, dimensions.width);
  const docH = Math.max(1, dimensions.height);

  const scaleX = outW / safeVpW;
  const scaleY = outH / safeVpH;
  const matteColor = resolveCanvasMatteColor(options?.matteColor);

  const artCanvas = document.createElement('canvas');
  artCanvas.width = flat.width;
  artCanvas.height = flat.height;
  const artCtx = artCanvas.getContext('2d');
  if (!artCtx) return false;
  artCtx.putImageData(new ImageData(flat.rgba, flat.width, flat.height), 0, 0);

  try {
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = 'source-over';
    ctx.fillStyle = matteColor;
    ctx.fillRect(0, 0, outW, outH);

    ctx.scale(scaleX, scaleY);
    ctx.translate(camera.pan.x, camera.pan.y);
    ctx.rotate((camera.rotation * Math.PI) / 180);
    ctx.scale((camera.flipX ? -1 : 1) * camera.zoom, (camera.flipY ? -1 : 1) * camera.zoom);
    ctx.translate(-docW / 2, -docH / 2);

    ctx.drawImage(artCanvas, 0, 0, docW, docH);
    ctx.restore();
    return true;
  } finally {
    artCanvas.width = 0;
    artCanvas.height = 0;
  }
}

/**
 * Captures the live native desktop InkStudio app window off the main JS thread using Rust's
 * Win32 `PrintWindow(PW_CLIENTONLY | PW_RENDERFULLCONTENT)`.
 */
export async function captureNativeAppWindowToCanvas(
  targetCanvas: HTMLCanvasElement,
  maxCaptureDim: number
): Promise<{ width: number; height: number } | null> {
  if (!isTauriRuntime() || typeof document === 'undefined') return null;
  try {
    const raw = await invokeTauri<ArrayBuffer | Uint8Array | number[]>(
      'timelapse_capture_app_window',
      { maxDim: Math.max(320, Math.min(3840, Math.round(maxCaptureDim))) }
    );
    const buf = toArrayBuffer(raw);
    if (buf.byteLength < 12) return null;

    const view = new DataView(buf);
    const width = view.getUint32(0, true);
    const height = view.getUint32(4, true);
    if (width < 2 || height < 2 || width > 4096 || height > 4096) return null;

    const expectedBytes = width * height * 4;
    if (buf.byteLength < 8 + expectedBytes) return null;

    targetCanvas.width = width;
    targetCanvas.height = height;
    const ctx = targetCanvas.getContext('2d');
    if (!ctx) return null;

    const rgba = new Uint8ClampedArray(buf, 8, expectedBytes);
    const imgData =
      typeof ImageData !== 'undefined'
        ? new ImageData(rgba, width, height)
        : (() => {
            const d = ctx.createImageData(width, height);
            d.data.set(rgba);
            return d;
          })();
    ctx.putImageData(imgData, 0, 0);
    return { width, height };
  } catch {
    return null;
  }
}