A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import { buildLayerTree } from '../layerTree';
import { recoveryService } from '../../services/recoveryService';
import { buildInkStudioXmpMetadata, sanitizeWorkTimeMs } from '../artworkTimeTracker';
import {
exportNativeDocumentImage,
saveNativeInkDocument,
syncNativeDocumentMeta,
} from '../nativeEngineBridge';
import {
ExportImageOptions,
ExportImageResult,
PRIMARY_PROJECT_EXTENSION,
SaveDocumentData,
SavedFileInfo,
} from './types';
import { buildPsdLayerTree } from './psdExport';
import {
getRememberedSaveDir,
rememberSaveDir,
} from '../fileSaveDialog';
import {
buildCleanFileName,
getParentDirectory,
normalizeExtension,
normalizeSavedFileName,
sanitizeDocumentStem,
} from './fileNameUtils';
import { t } from '../../i18n';
interface NativePickSavePathResponse {
canceled: boolean;
fileName?: string | null;
path?: string | null;
directory?: string | null;
extension?: string | null;
filterIndex?: number;
}
interface SaveFilterSpec {
name: string;
extensions: string[];
}
function isTauriDesktopEnv(): boolean {
return (
typeof window !== 'undefined' &&
Boolean((window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__)
);
}
async function toRawBytes(serialized: {
data: Blob | ArrayBuffer;
rawBytes?: Uint8Array;
}): Promise<Uint8Array> {
if (serialized.rawBytes) return serialized.rawBytes;
if (serialized.data instanceof Blob) {
return new Uint8Array(await serialized.data.arrayBuffer());
}
return new Uint8Array(serialized.data);
}
const PROJECT_SAVE_FILTERS: SaveFilterSpec[] = [
{ name: 'Ink Studio Project', extensions: ['ink'] },
{ name: 'Photoshop Document with Layers', extensions: ['psd'] },
{ name: 'PNG Image', extensions: ['png'] },
{ name: 'JPEG Image', extensions: ['jpg', 'jpeg'] },
{ name: 'WebP Image', extensions: ['webp'] },
];
const IMAGE_EXPORT_FILTERS: SaveFilterSpec[] = [
{ name: 'PNG Image', extensions: ['png'] },
{ name: 'JPEG Image', extensions: ['jpg', 'jpeg'] },
{ name: 'WebP Image', extensions: ['webp'] },
];
function findFilterIndexForExt(filters: SaveFilterSpec[], ext: string): number {
const bare = ext.replace(/^\./, '').toLowerCase();
const idx = filters.findIndex((f) => f.extensions.includes(bare));
return idx >= 0 ? idx : 0;
}
/**
* Native zero-canvas GPU image exporter (PNG / JPEG / WebP) powered directly by
* `crates/ink-engine` DX12 compositor + pure-Rust PNG/WebP & Windows WIC JPEG encoders.
*/
export async function exportImage(
data: SaveDocumentData,
options: ExportImageOptions = {}
): Promise<ExportImageResult> {
const format = options.format ?? 'png';
const isJpeg = format === 'jpg' || format === 'jpeg';
const isWebp = format === 'webp';
const mimeType = isJpeg ? 'image/jpeg' : isWebp ? 'image/webp' : 'image/png';
const quality = options.quality ?? 0.92;
const fillWhite = options.fillWhiteBackground ?? isJpeg;
const onProgress = options.onProgress ?? data.onProgress;
onProgress?.({
phase: 'compositing',
current: 1,
total: 2,
percent: 40,
message: t('Encoding {format}...', { format: format.toUpperCase() }),
});
const encodedBytes = await exportNativeDocumentImage({
docId: data.tabId ?? null,
format,
quality,
options: { fillWhiteBackground: fillWhite },
});
if (!encodedBytes) {
throw new Error(t('Native image export requires the Windows desktop Rust engine.'));
}
onProgress?.({
phase: 'done',
current: 2,
total: 2,
percent: 100,
message: t('Export complete'),
});
return {
blob: new Blob([encodedBytes as BlobPart], { type: mimeType }),
mimeType,
width: data.dimensions.width,
height: data.dimensions.height,
usedGpu: true,
};
}
/**
* Serializes the document according to the requested file extension with ZERO DOM `<canvas>` backing stores.
*/
export async function serializeDocument(
data: SaveDocumentData,
extension: string
): Promise<{
data: Blob | ArrayBuffer;
rawBytes?: Uint8Array;
mimeType: string;
previewDataUrl?: string;
}> {
const ext = extension.toLowerCase();
// 1. PSD/PSB format with full folder hierarchy, blend modes, clipping, alphaLock, and masks (zero-canvas)
if (ext === '.psd' || ext === '.psb') {
const tree = buildLayerTree(data.layers);
const children = await buildPsdLayerTree(tree, data.tabId ?? null);
const dpi = data.dimensions.dpi || 300;
const workTimeMs = sanitizeWorkTimeMs(data.workTimeMs);
const { writePsd } = await import('ag-psd');
const psdBuffer = writePsd(
{
width: data.dimensions.width,
height: data.dimensions.height,
children,
imageResources: {
resolutionInfo: {
horizontalResolution: dpi,
horizontalResolutionUnit: 'PPI',
widthUnit: 'Inches',
verticalResolution: dpi,
verticalResolutionUnit: 'PPI',
heightUnit: 'Inches',
},
...(workTimeMs > 0 ? { xmpMetadata: buildInkStudioXmpMetadata(workTimeMs) } : {}),
},
},
{
psb: ext === '.psb',
noBackground: true,
}
);
return {
data: psdBuffer,
rawBytes: new Uint8Array(psdBuffer),
mimeType: 'image/vnd.adobe.photoshop',
};
}
// 2. Native Ink Studio Project (.ink)
if (ext === '.sora') {
throw new Error(t('Legacy .sora format is read-only. Save as .ink instead.'));
}
if (ext === PRIMARY_PROJECT_EXTENSION) {
throw new Error(t('Use native Rust saveNativeInkDocument to save .ink project files.'));
}
// 3. JPEG format (native DX12 + WIC with white background)
if (ext === '.jpg' || ext === '.jpeg') {
const exported = await exportImage(data, {
format: 'jpg',
quality: 0.92,
fillWhiteBackground: true,
});
const rawBytes = new Uint8Array(await exported.blob.arrayBuffer());
return { data: exported.blob, rawBytes, mimeType: exported.mimeType };
}
// 4. WebP format (native DX12 + RFC-9649 lossless WebP with transparency)
if (ext === '.webp') {
const exported = await exportImage(data, {
format: 'webp',
quality: 0.92,
fillWhiteBackground: false,
});
const rawBytes = new Uint8Array(await exported.blob.arrayBuffer());
return { data: exported.blob, rawBytes, mimeType: exported.mimeType };
}
// 5. Default: PNG format (native DX12 + Rust PNG with transparency)
const exported = await exportImage(data, {
format: 'png',
fillWhiteBackground: false,
});
const rawBytes = new Uint8Array(await exported.blob.arrayBuffer());
return { data: exported.blob, rawBytes, mimeType: exported.mimeType };
}
/**
* Triggers fallback download using standard anchor element.
*/
export function downloadFile(
content: Blob | ArrayBuffer,
fileName: string,
mimeType: string
) {
const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 200);
}
function getSerializedByteSize(content: Blob | ArrayBuffer): number {
return content instanceof Blob ? content.size : content.byteLength;
}
/**
* Prompts user to select save location and format via native OS dialog (Tauri Desktop).
* Always picks the target path & format FIRST before serializing so Cancel does zero work.
*/
export async function promptSaveAs(
data: SaveDocumentData,
defaultExtension: string = PRIMARY_PROJECT_EXTENSION,
fallbackToDownload: boolean = true,
options?: { initialDir?: string }
): Promise<SavedFileInfo> {
const resolvedDefaultExt = normalizeExtension(
defaultExtension.toLowerCase() === '.sora' ? PRIMARY_PROJECT_EXTENSION : defaultExtension,
PRIMARY_PROJECT_EXTENSION
);
const cleanStem = sanitizeDocumentStem(data.name, 'Untitled');
const suggestedName = buildCleanFileName(cleanStem, resolvedDefaultExt, 'Untitled');
if (isTauriDesktopEnv()) {
try {
const { invoke } = await import('@tauri-apps/api/core');
const initialDir = options?.initialDir || getRememberedSaveDir('project') || undefined;
const defaultFilterIndex = findFilterIndexForExt(PROJECT_SAVE_FILTERS, resolvedDefaultExt);
const picked = await invoke<NativePickSavePathResponse>('native_pick_save_path', {
suggestedName: cleanStem,
filters: PROJECT_SAVE_FILTERS.map((f) => ({ ...f, name: t(f.name) })),
defaultFilterIndex,
title: t('Save As'),
initialDir: initialDir ?? null,
});
if (picked?.canceled) {
throw new Error('Save canceled');
}
if (picked?.path) {
const chosenPath = picked.path;
const normalized = normalizeSavedFileName(
picked.fileName || suggestedName,
picked.extension || resolvedDefaultExt
);
let bytesWritten = 0;
let previewDataUrl: string | undefined;
if (normalized.extension === PRIMARY_PROJECT_EXTENSION && data.tabId) {
await syncNativeDocumentMeta(data.tabId, {
name: normalized.stem,
perspectiveRuler: data.perspectiveRuler ?? null,
straightRuler: data.straightRuler ?? null,
animationTimeline: data.animationTimeline ?? null,
timelapse: data.timelapse ?? null,
workTimeMs: data.workTimeMs,
}).catch((err) => console.warn('[SaveManager] Failed to sync doc meta before save:', err));
const nativeSave = await saveNativeInkDocument(data.tabId, chosenPath);
bytesWritten = nativeSave.bytesWritten;
previewDataUrl = nativeSave.previewDataUrl ?? undefined;
} else {
const serialized = await serializeDocument(
{ ...data, name: normalized.stem },
normalized.extension
);
const rawBytes = await toRawBytes(serialized);
bytesWritten = rawBytes.byteLength;
previewDataUrl = serialized.previewDataUrl;
await invoke<number>('write_allowed_file_binary', rawBytes, {
headers: {
'x-path': encodeURIComponent(chosenPath),
},
});
}
const dir = picked.directory || getParentDirectory(chosenPath);
if (dir) {
rememberSaveDir('project', dir);
}
if (data.tabId) {
recoveryService.markCleanSaved(data.tabId).catch(console.warn);
}
return {
name: normalized.fileName,
path: chosenPath,
extension: normalized.extension,
size: bytesWritten,
previewDataUrl,
};
}
} catch (err: unknown) {
if (err instanceof Error && err.message === 'Save canceled') {
throw err;
}
throw err;
}
}
if (fallbackToDownload) {
const serialized = await serializeDocument(
{ ...data, name: cleanStem },
resolvedDefaultExt
);
downloadFile(serialized.data, suggestedName, serialized.mimeType);
if (data.tabId) {
recoveryService.markCleanSaved(data.tabId).catch(console.warn);
}
return {
name: suggestedName,
extension: resolvedDefaultExt,
size: getSerializedByteSize(serialized.data),
previewDataUrl: serialized.previewDataUrl,
};
}
throw new Error(t('Save dialog was not available'));
}
/**
* Writes directly to an authorized Tauri disk path without prompting.
*/
export async function saveToExistingHandle(
data: SaveDocumentData,
fileInfo: SavedFileInfo
): Promise<{ size: number; previewDataUrl?: string }> {
const hasNativePath = Boolean(
isTauriDesktopEnv() && fileInfo.path && fileInfo.path.trim().length > 0
);
if (!hasNativePath) {
throw new Error(t('No valid file handle or disk path to save to'));
}
const cleanStem = sanitizeDocumentStem(fileInfo.name || data.name, 'Untitled');
const targetExt = normalizeExtension(fileInfo.extension, PRIMARY_PROJECT_EXTENSION);
if (targetExt === PRIMARY_PROJECT_EXTENSION && data.tabId) {
await syncNativeDocumentMeta(data.tabId, {
name: cleanStem,
perspectiveRuler: data.perspectiveRuler ?? null,
straightRuler: data.straightRuler ?? null,
animationTimeline: data.animationTimeline ?? null,
timelapse: data.timelapse ?? null,
workTimeMs: data.workTimeMs,
}).catch((err) => console.warn('[SaveManager] Failed to sync doc meta before save:', err));
const nativeSave = await saveNativeInkDocument(data.tabId, fileInfo.path!);
recoveryService.markCleanSaved(data.tabId).catch(console.warn);
return {
size: nativeSave.bytesWritten,
previewDataUrl: nativeSave.previewDataUrl ?? undefined,
};
}
const serialized = await serializeDocument({ ...data, name: cleanStem }, targetExt);
const { invoke } = await import('@tauri-apps/api/core');
const bytes = await toRawBytes(serialized);
await invoke<number>('write_allowed_file_binary', bytes, {
headers: {
'x-path': encodeURIComponent(fileInfo.path!),
},
});
if (data.tabId) {
recoveryService.markCleanSaved(data.tabId).catch(console.warn);
}
return {
size: bytes.byteLength,
previewDataUrl: serialized.previewDataUrl,
};
}
/**
* Prompts user to choose a save path specifically for an exported flattened image (PNG / JPG / WebP).
*/
export async function promptExportPngImage(
data: SaveDocumentData,
defaultName?: string,
options?: { initialDir?: string }
): Promise<string> {
const cleanStem = sanitizeDocumentStem(defaultName || data.name, 'artwork');
const suggestedName = buildCleanFileName(cleanStem, '.png', 'artwork');
if (isTauriDesktopEnv()) {
const { invoke } = await import('@tauri-apps/api/core');
const initialDir = options?.initialDir || getRememberedSaveDir('project') || undefined;
const picked = await invoke<NativePickSavePathResponse>('native_pick_save_path', {
suggestedName: cleanStem,
filters: IMAGE_EXPORT_FILTERS.map((f) => ({ ...f, name: t(f.name) })),
defaultFilterIndex: 0,
title: t('Export Image As'),
initialDir: initialDir ?? null,
});
if (picked?.canceled) {
throw new Error('Export canceled');
}
if (picked?.path) {
const chosenPath = picked.path;
const normalized = normalizeSavedFileName(
picked.fileName || suggestedName,
picked.extension || '.png'
);
const exportExt =
normalized.extension === '.jpg' ||
normalized.extension === '.jpeg' ||
normalized.extension === '.webp'
? normalized.extension
: '.png';
const serialized = await serializeDocument({ ...data, name: normalized.stem }, exportExt);
const rawBytes = await toRawBytes(serialized);
await invoke<number>('write_allowed_file_binary', rawBytes, {
headers: {
'x-path': encodeURIComponent(chosenPath),
},
});
const dir = picked.directory || getParentDirectory(chosenPath);
if (dir) {
rememberSaveDir('project', dir);
}
return normalized.fileName;
}
}
const serialized = await serializeDocument({ ...data, name: cleanStem }, '.png');
downloadFile(serialized.data, suggestedName, 'image/png');
return suggestedName;
}