Skip to content

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

3.4 KB
Raw Blame
/**
 * Webtoon Chapter Slicer & ZIP Exporter Engine (Phase 6 Zero-Canvas Rust Pipeline)
 *
 * Cuts tall Webtoon canvases (e.g. 800x30000px) into sequential vertical tiles (e.g. 800x1280px)
 * directly on the Rust DX12 compositor + WIC JPEG / Rust PNG encoder without allocating any
 * full-document or full-slice DOM `<canvas>` backing stores.
 */

import { zipSync } from 'fflate';
import { saveFileWithDialog, SaveFileDialogResult } from './fileSaveDialog';
import { exportNativeDocumentImage } from './nativeEngineBridge';
import { t } from '../i18n';

export interface WebtoonSliceOptions {
  sliceWidth?: number;
  sliceHeight?: number;
  format?: 'jpg' | 'png';
  quality?: number;
  filePrefix?: string;
  onProgress?: (progress: { current: number; total: number; percent: number }) => void;
}

/**
 * Zero-canvas native Rust Webtoon slicer: renders and encodes each vertical slice directly via
 * `exportNativeDocumentImage` on DX12 + WIC and packages them into a ZIP archive.
 */
export async function exportNativeWebtoonChapterZip(
  docId: string | null | undefined,
  totalWidth: number,
  totalHeight: number,
  options: WebtoonSliceOptions = {}
): Promise<Uint8Array> {
  const safeTotalWidth = Math.max(1, Math.round(totalWidth) || 1);
  const safeTotalHeight = Math.max(1, Math.round(totalHeight) || 1);
  const sliceHeight = Math.max(1, Math.round(options.sliceHeight || 1280));
  const format = options.format || 'jpg';
  const quality = options.quality ?? 0.92;
  const filePrefix = options.filePrefix || 'slice_';
  const ext = format === 'jpg' ? 'jpg' : 'png';
  const totalSlices = Math.max(1, Math.ceil(safeTotalHeight / sliceHeight));

  const zipFiles: Record<string, Uint8Array> = {};

  for (let i = 0; i < totalSlices; i++) {
    const srcY = i * sliceHeight;
    const currentSliceH = Math.max(1, Math.min(sliceHeight, safeTotalHeight - srcY));

    const bytes = await exportNativeDocumentImage({
      docId: docId ?? null,
      format,
      quality,
      options: {
        region: {
          x: 0,
          y: srcY,
          width: safeTotalWidth,
          height: currentSliceH,
        },
        fillWhiteBackground: format === 'jpg',
      },
    });
    if (!bytes) {
      throw new Error(t('Native Webtoon export requires the Windows desktop Rust engine.'));
    }

    const fileName = `${filePrefix}${String(i + 1).padStart(3, '0')}.${ext}`;
    zipFiles[fileName] = bytes;

    options.onProgress?.({
      current: i + 1,
      total: totalSlices,
      percent: Math.round(((i + 1) / totalSlices) * 100),
    });

    await new Promise((r) => setTimeout(r, 0));
  }

  return zipSync(zipFiles, { level: 6 });
}

export async function saveWebtoonZipWithDialog(
  zipBytes: Uint8Array,
  filename = 'webtoon_chapter.zip'
): Promise<SaveFileDialogResult> {
  return saveFileWithDialog({
    data: zipBytes,
    suggestedName: filename,
    mimeType: 'application/zip',
    description: t('Webtoon Slices Archive'),
    extensions: ['.zip'],
    category: 'webtoon',
    title: t('Save Webtoon Slices As'),
  });
}

export function downloadWebtoonZip(
  zipBytes: Uint8Array,
  filename = 'webtoon_chapter.zip'
): void {
  const blob = new Blob([zipBytes as BlobPart], { type: 'application/zip' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}