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 { DocumentTab } from '../types/editor';
import {
extractFilenameFromPath,
getMimeTypeForFilename,
readTauriFileBytes,
} from './fileDropImport';
export const OPEN_FILES_EVENT = 'inkstudio://open-files';
interface TauriWindow extends Window {
__TAURI_INTERNALS__?: unknown;
}
export function isTauriDesktop(): boolean {
return typeof window !== 'undefined' && Boolean((window as TauriWindow).__TAURI_INTERNALS__);
}
/**
* Strips Windows verbatim prefixes (`\\?\` / `\\?\UNC\`) and normalizes path separators
* and casing (case-insensitive for Windows drive/UNC paths) for reliable tab deduplication.
*/
export function normalizePathForComparison(rawPath: string | null | undefined): string {
if (!rawPath || typeof rawPath !== 'string') return '';
let p = rawPath.trim();
if (!p) return '';
if (p.startsWith('\\\\?\\UNC\\') || p.startsWith('//?/UNC/')) {
p = '\\\\' + p.slice(8);
} else if (p.startsWith('\\\\?\\') || p.startsWith('//?/')) {
p = p.slice(4);
}
const normalizedSlashes = p.replace(/\\/g, '/').replace(/\/+$/, '');
const isWindowsPath =
/^[a-zA-Z]:\//.test(normalizedSlashes) || normalizedSlashes.startsWith('//');
return isWindowsPath ? normalizedSlashes.toLowerCase() : normalizedSlashes;
}
/**
* Finds an already-open DocumentTab matching the given OS filesystem path so re-opening
* the same `.ink` file focuses the existing tab instead of creating a duplicate.
*/
export function findOpenDocumentBySourcePath(
documents: readonly DocumentTab[],
filePath: string
): DocumentTab | undefined {
const target = normalizePathForComparison(filePath);
if (!target) return undefined;
return documents.find((doc) => {
const tabPath = doc.sourcePath ?? doc.savedFileInfo?.path ?? null;
if (!tabPath) return false;
return normalizePathForComparison(tabPath) === target;
});
}
/**
* Reads an OS-authorized local file from Tauri's backend and wraps it as a standard Web `File`.
*/
export async function readTauriPathAsFile(filePath: string): Promise<File> {
const bytes = await readTauriFileBytes(filePath);
if (bytes.byteLength === 0) {
throw new Error('File is empty');
}
const filename = extractFilenameFromPath(filePath);
const mime = getMimeTypeForFilename(filename);
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
return new File([copy.buffer], filename, { type: mime });
}
/**
* Atomically marks the frontend ready in the Tauri backend and drains any OS launch file paths
* (e.g. from double-clicking a `.ink` file on cold startup).
*/
export async function takePendingOpenFiles(): Promise<string[]> {
if (!isTauriDesktop()) return [];
try {
const { invoke } = await import('@tauri-apps/api/core');
const paths = await invoke<string[]>('take_pending_open_files');
return Array.isArray(paths)
? paths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0)
: [];
} catch (err) {
console.warn('[osFileOpen] Failed to query pending launch files:', err);
return [];
}
}
/**
* Subscribes to warm OS file-open events forwarded by the Tauri single-instance plugin
* (and macOS `RunEvent::Opened`) so files opened while Ink Studio is running open inside
* the existing app window.
*/
export async function listenForOpenFiles(
onPaths: (paths: string[]) => void
): Promise<() => void> {
if (!isTauriDesktop()) return () => {};
try {
const { listen } = await import('@tauri-apps/api/event');
return await listen<string[]>(OPEN_FILES_EVENT, (event) => {
const payload = event.payload;
if (!Array.isArray(payload) || payload.length === 0) return;
const valid = payload.filter(
(p): p is string => typeof p === 'string' && p.trim().length > 0
);
if (valid.length > 0) {
onPaths(valid);
}
});
} catch (err) {
console.warn('[osFileOpen] Failed to attach open-files listener:', err);
return () => {};
}
}