Skip to content

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

77.4 KB
Raw Blame
pub mod clip_parser;
mod dcomp_host;
mod doc_wire;
mod file_open;
mod native_docs;
mod native_engine;
mod native_tools;
mod os_hotkeys;
mod psd_parser;
mod raster_journal;
mod raster_ops;
mod recovery;
mod save_dialog;
mod scratch_disk;
mod server;
mod system_perf;
mod tablet_input;
mod timelapse;
mod wic_codec;

use server::{
    download_cloudflared as server_download_cloudflared, get_local_ip, get_server_status,
    is_cloudflared_installed as server_is_cloudflared_installed, start_embedded_server,
    stop_embedded_server, ServerInfo,
};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, RwLock};
use tauri::{Emitter, Manager};

static ALLOWED_PATHS: LazyLock<RwLock<HashSet<PathBuf>>> =
    LazyLock::new(|| RwLock::new(HashSet::new()));

/// Paths explicitly selected by the user in a native OS Save dialog (may not exist on disk yet).
/// Stored as `canonical_parent.join(file_name)` so path traversal is impossible.
static AUTHORIZED_WRITE_PATHS: LazyLock<RwLock<HashSet<PathBuf>>> =
    LazyLock::new(|| RwLock::new(HashSet::new()));

#[tauri::command]
async fn start_collab_server(
    port: Option<u16>,
    room_name: Option<String>,
    enable_tunnel: Option<bool>,
) -> Result<ServerInfo, String> {
    let p = port.unwrap_or(30303);
    let name = room_name.unwrap_or_else(|| "Ink Studio Session".to_string());
    let tunnel = enable_tunnel.unwrap_or(true);
    start_embedded_server(p, name, tunnel).await
}

#[tauri::command]
async fn stop_collab_server() -> Result<(), String> {
    stop_embedded_server().await
}

#[tauri::command]
async fn get_collab_server_status() -> ServerInfo {
    get_server_status().await
}

#[tauri::command]
async fn download_cloudflared() -> Result<String, String> {
    server_download_cloudflared().await
}

#[tauri::command]
async fn is_cloudflared_installed() -> bool {
    server_is_cloudflared_installed().await
}

#[tauri::command]
fn get_os_username() -> String {
    let raw = std::env::var("USERNAME")
        .or_else(|_| std::env::var("USER"))
        .or_else(|_| std::env::var("LOGNAME"))
        .unwrap_or_default();
    let cleaned: String = raw
        .trim()
        .chars()
        .filter(|c| !c.is_control())
        .take(40)
        .collect();
    if cleaned.is_empty() {
        "Artist".to_string()
    } else {
        cleaned
    }
}

#[tauri::command]
fn get_local_lan_ip() -> String {
    get_local_ip()
}

fn sanitize_id(raw: &str) -> String {
    let s: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if s.is_empty() {
        "default".to_string()
    } else {
        s
    }
}

const ALLOWED_DOCUMENT_EXTS: &[&str] = &[
    "ink", "inkb", "psd", "psb", "clip", "csp", "lip", "sut", "png", "jpg", "jpeg", "webp", "bmp",
    "gif", "svg", "avif", "ico", "glb", "gltf", "obj", "cls", "json", "sora", // .sora: read-only legacy migrator
];

const DIRECT_SAVE_ALLOWED_EXTS: &[&str] = &["ink", "psd", "psb", "png", "jpg", "jpeg", "webp"];

const DELETE_ALLOWED_EXTS: &[&str] = &[
    "ink", "psd", "psb", "clip", "csp", "png", "jpg", "jpeg", "webp", "bmp", "gif", "svg",
];

const MAX_READ_FILE_BYTES: u64 = 512 * 1024 * 1024; // 512 MB ceiling

fn percent_decode(input: &str) -> Result<String, String> {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err("Malformed percent-encoded header".to_string());
            }
            let hi = (bytes[i + 1] as char)
                .to_digit(16)
                .ok_or_else(|| "Invalid hex in header".to_string())?;
            let lo = (bytes[i + 2] as char)
                .to_digit(16)
                .ok_or_else(|| "Invalid hex in header".to_string())?;
            out.push(((hi << 4) | lo) as u8);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| "Header is not valid UTF-8".to_string())
}

fn header_str(request: &tauri::ipc::Request<'_>, name: &str) -> Result<String, String> {
    let raw = request
        .headers()
        .get(name)
        .ok_or_else(|| format!("Missing required IPC header: {}", name))?
        .to_str()
        .map_err(|_| format!("Invalid ASCII in IPC header: {}", name))?;
    let decoded = percent_decode(raw)?;
    if decoded.is_empty() || decoded.contains('\0') {
        return Err(format!("Invalid IPC header value: {}", name));
    }
    Ok(decoded)
}

fn header_parse<T: std::str::FromStr>(
    request: &tauri::ipc::Request<'_>,
    name: &str,
) -> Result<T, String> {
    let raw = request
        .headers()
        .get(name)
        .ok_or_else(|| format!("Missing required IPC header: {}", name))?
        .to_str()
        .map_err(|_| format!("Invalid ASCII in IPC header: {}", name))?;
    raw.parse::<T>()
        .map_err(|_| format!("Failed to parse IPC header: {}", name))
}

fn header_opt_str(request: &tauri::ipc::Request<'_>, name: &str) -> Option<String> {
    let raw = request.headers().get(name)?.to_str().ok()?;
    let decoded = percent_decode(raw).ok()?;
    if decoded.is_empty() || decoded.contains('\0') {
        return None;
    }
    Some(decoded)
}

fn header_opt_parse<T: std::str::FromStr>(
    request: &tauri::ipc::Request<'_>,
    name: &str,
) -> Option<T> {
    let raw = request.headers().get(name)?.to_str().ok()?;
    raw.parse::<T>().ok()
}

fn raw_body<'a>(request: &'a tauri::ipc::Request<'_>) -> Result<&'a [u8], String> {
    match request.body() {
        tauri::ipc::InvokeBody::Raw(bytes) => Ok(bytes.as_slice()),
        tauri::ipc::InvokeBody::Json(_) => Err("Expected raw binary IPC request body".to_string()),
    }
}

fn has_allowed_extension(p: &Path, allowed: &[&str]) -> bool {
    p.extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
        .map(|ext| allowed.contains(&ext.as_str()))
        .unwrap_or(false)
}

/// Register a trusted OS-provided file path (e.g. from native drag-drop or CLI launch)
/// into the thread-safe in-memory allowlist after symlink and extension checks.
fn register_allowed_path(path: &Path) {
    if !has_allowed_extension(path, ALLOWED_DOCUMENT_EXTS) {
        return;
    }
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return;
    };
    if meta.file_type().is_symlink() || !meta.is_file() {
        return;
    }
    let Ok(canonical) = std::fs::canonicalize(path) else {
        return;
    };
    if !has_allowed_extension(&canonical, ALLOWED_DOCUMENT_EXTS) {
        return;
    }
    if let Ok(mut guard) = ALLOWED_PATHS.write() {
        guard.insert(canonical);
    }
}

fn unregister_allowed_path(canonical: &Path) {
    if let Ok(mut guard) = ALLOWED_PATHS.write() {
        guard.remove(canonical);
    }
    if let Ok(mut guard) = AUTHORIZED_WRITE_PATHS.write() {
        guard.remove(canonical);
    }
}

/// Resolves a target save path (which may not exist yet) to `canonical_parent.join(file_name)`
/// after checking extension, rejecting symlinks/directories, and verifying parent exists.
fn resolve_canonical_target_path(path: &Path, allowed_exts: &[&str]) -> Result<PathBuf, String> {
    if !has_allowed_extension(path, allowed_exts) {
        return Err("Refusing to write file with unsupported save extension".to_string());
    }
    let file_name = path
        .file_name()
        .filter(|n| !n.is_empty())
        .ok_or_else(|| "Invalid target filename".to_string())?;
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .ok_or_else(|| "Target file must include a parent directory".to_string())?;
    let canonical_parent = std::fs::canonicalize(parent)
        .map_err(|_| "Target parent directory does not exist".to_string())?;
    let target = canonical_parent.join(file_name);
    if !has_allowed_extension(&target, allowed_exts) {
        return Err("Refusing to write file with unsupported save extension".to_string());
    }
    if let Ok(meta) = std::fs::symlink_metadata(&target) {
        if meta.file_type().is_symlink() {
            return Err("Refusing to overwrite symbolic link".to_string());
        }
        if !meta.is_file() {
            return Err("Target path is not a regular file".to_string());
        }
    }
    Ok(target)
}

fn register_allowed_write_path(path: &Path) {
    if let Ok(resolved) = resolve_canonical_target_path(path, DIRECT_SAVE_ALLOWED_EXTS) {
        if let Ok(mut guard) = AUTHORIZED_WRITE_PATHS.write() {
            guard.insert(resolved);
        }
    }
}

async fn validate_write_path(
    raw_path: &str,
    allowed_dirs: &[PathBuf],
) -> Result<PathBuf, String> {
    if raw_path.is_empty() || raw_path.contains('\0') {
        return Err("Invalid file path".to_string());
    }
    let p = Path::new(raw_path);
    let resolved = resolve_canonical_target_path(p, DIRECT_SAVE_ALLOWED_EXTS)?;

    let in_write_allowlist = AUTHORIZED_WRITE_PATHS
        .read()
        .map(|g| g.contains(&resolved))
        .unwrap_or(false);
    let in_read_allowlist = if resolved.exists() {
        std::fs::canonicalize(&resolved)
            .map(|canon| is_path_authorized(&canon, allowed_dirs))
            .unwrap_or(false)
    } else {
        resolved
            .parent()
            .map(|parent| allowed_dirs.iter().any(|dir| parent.starts_with(dir)))
            .unwrap_or(false)
    };

    if !in_write_allowlist && !in_read_allowlist {
        return Err("Access denied: file is outside authorized InkStudio save paths".to_string());
    }

    Ok(resolved)
}

fn get_allowed_base_dirs(app: &tauri::AppHandle) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    let candidates = [
        app.path().document_dir().ok().map(|d| d.join("InkStudio")),
        app.path().app_local_data_dir().ok(),
        app.path().app_data_dir().ok(),
    ];
    for candidate in candidates.into_iter().flatten() {
        if let Ok(canonical) = std::fs::canonicalize(&candidate) {
            dirs.push(canonical);
        }
    }
    dirs
}

fn is_path_authorized(canonical: &Path, allowed_dirs: &[PathBuf]) -> bool {
    if let Ok(guard) = ALLOWED_PATHS.read() {
        if guard.contains(canonical) {
            return true;
        }
    }
    allowed_dirs.iter().any(|dir| canonical.starts_with(dir))
}

async fn validate_read_path(
    raw_path: &str,
    allowed_dirs: &[PathBuf],
) -> Result<(PathBuf, u64), String> {
    if raw_path.is_empty() || raw_path.contains('\0') {
        return Err("Invalid file path".to_string());
    }
    let p = Path::new(raw_path);
    if !has_allowed_extension(p, ALLOWED_DOCUMENT_EXTS) {
        return Err("Refusing to read file with unsupported extension".to_string());
    }
    let meta = tokio::fs::symlink_metadata(p)
        .await
        .map_err(|_| "File does not exist or is inaccessible".to_string())?;
    if meta.file_type().is_symlink() {
        return Err("Refusing to read symbolic link".to_string());
    }
    if !meta.is_file() {
        return Err("Path is not a regular file".to_string());
    }
    let canonical = tokio::fs::canonicalize(p)
        .await
        .map_err(|_| "Failed to resolve canonical file path".to_string())?;
    if !has_allowed_extension(&canonical, ALLOWED_DOCUMENT_EXTS) {
        return Err("Refusing to read file with unsupported extension".to_string());
    }
    if !is_path_authorized(&canonical, allowed_dirs) {
        return Err("Access denied: file is outside allowed InkStudio paths".to_string());
    }
    if meta.len() > MAX_READ_FILE_BYTES {
        return Err("File exceeds 512 MB safety limit".to_string());
    }
    Ok((canonical, meta.len()))
}

async fn validate_delete_path(
    raw_path: &str,
    allowed_dirs: &[PathBuf],
) -> Result<Option<PathBuf>, String> {
    if raw_path.is_empty() || raw_path.contains('\0') {
        return Err("Invalid file path".to_string());
    }
    let p = Path::new(raw_path);
    if !has_allowed_extension(p, DELETE_ALLOWED_EXTS) {
        return Err("Refusing to delete file with unsupported extension".to_string());
    }
    let meta = match tokio::fs::symlink_metadata(p).await {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // Verify parent directory is authorized before reporting NotFound
            // so arbitrary disk paths cannot be probed for existence.
            let parent_authorized = if let Some(parent) = p.parent() {
                tokio::fs::canonicalize(parent)
                    .await
                    .map(|canon_parent| {
                        allowed_dirs.iter().any(|dir| canon_parent.starts_with(dir))
                    })
                    .unwrap_or(false)
            } else {
                false
            };
            if !parent_authorized {
                return Err("Access denied: file is outside allowed InkStudio paths".to_string());
            }
            return Ok(None);
        }
        Err(_) => return Err("File is inaccessible".to_string()),
    };
    if meta.file_type().is_symlink() {
        return Err("Refusing to delete symbolic link".to_string());
    }
    if !meta.is_file() {
        return Err("Path is not a regular file".to_string());
    }
    let canonical = tokio::fs::canonicalize(p)
        .await
        .map_err(|_| "Failed to resolve canonical file path".to_string())?;
    if !has_allowed_extension(&canonical, DELETE_ALLOWED_EXTS) {
        return Err("Refusing to delete file with unsupported extension".to_string());
    }
    if !is_path_authorized(&canonical, allowed_dirs) {
        return Err("Access denied: file is outside allowed InkStudio paths".to_string());
    }
    Ok(Some(canonical))
}

#[tauri::command]
async fn delete_file_from_disk(app: tauri::AppHandle, path: String) -> Result<bool, String> {
    let allowed_dirs = get_allowed_base_dirs(&app);
    let Some(canonical) = validate_delete_path(&path, &allowed_dirs).await? else {
        return Ok(false);
    };
    tokio::fs::remove_file(&canonical)
        .await
        .map_err(|e| e.to_string())?;
    unregister_allowed_path(&canonical);
    Ok(true)
}

#[tauri::command]
async fn read_file_from_disk(app: tauri::AppHandle, path: String) -> Result<Vec<u8>, String> {
    let allowed_dirs = get_allowed_base_dirs(&app);
    let (canonical, _) = validate_read_path(&path, &allowed_dirs).await?;
    tokio::fs::read(&canonical).await.map_err(|e| e.to_string())
}

#[tauri::command]
async fn read_file_binary(
    app: tauri::AppHandle,
    path: String,
) -> Result<tauri::ipc::Response, String> {
    let allowed_dirs = get_allowed_base_dirs(&app);
    let (canonical, _) = validate_read_path(&path, &allowed_dirs).await?;
    let bytes = tokio::fs::read(&canonical)
        .await
        .map_err(|e| e.to_string())?;
    Ok(tauri::ipc::Response::new(bytes))
}

#[tauri::command]
fn take_pending_open_files() -> Vec<String> {
    file_open::mark_frontend_ready_and_take_pending()
}

#[tauri::command]
async fn write_allowed_file_binary(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<usize, String> {
    let raw_path = header_str(&request, "x-path")?;
    let data = raw_body(&request)?;
    if data.len() as u64 > MAX_READ_FILE_BYTES {
        return Err("File payload exceeds 512 MB safety limit".to_string());
    }
    let allowed_dirs = get_allowed_base_dirs(&app);
    let target = validate_write_path(&raw_path, &allowed_dirs).await?;
    let owned = data.to_vec();
    let written = owned.len();
    let target_for_write = target.clone();
    tokio::task::spawn_blocking(move || save_dialog::write_file_atomic(&target_for_write, &owned))
        .await
        .map_err(|e| format!("Atomic write worker failed: {}", e))??;
    register_allowed_path(&target);
    Ok(written)
}

#[tauri::command]
async fn recovery_init_session(
    app: tauri::AppHandle,
    session_id: String,
    manifest_json: String,
) -> Result<(), String> {
    recovery::init_session(&app, &session_id, &manifest_json).await?;
    raster_journal::baseline(&session_id);
    Ok(())
}

#[tauri::command]
async fn recovery_append_wal_entry(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<(), String> {
    let session_id = header_str(&request, "x-session-id")?;
    let entry_type: u8 = header_parse(&request, "x-entry-type")?;
    let payload = raw_body(&request)?;
    recovery::append_wal_entry(&app, &session_id, entry_type, payload).await
}

#[tauri::command]
async fn recovery_checkpoint(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<(), String> {
    let session_id = header_str(&request, "x-session-id")?;
    let body = raw_body(&request)?;
    let (manifest_json, base_snapshot, thumbnail_png) = recovery::unpack_checkpoint_payload(body)?;
    recovery::checkpoint(
        &app,
        &session_id,
        base_snapshot.to_vec(),
        manifest_json.to_string(),
        thumbnail_png.to_vec(),
        None,
    )
    .await
}

#[tauri::command]
async fn recovery_close_session(
    app: tauri::AppHandle,
    session_id: String,
) -> Result<(), String> {
    recovery::close_session(&app, &session_id).await
}

#[tauri::command]
async fn recovery_check_crashed_sessions(
    app: tauri::AppHandle,
) -> Result<Vec<recovery::CrashedSessionInfo>, String> {
    recovery::check_crashed_sessions(&app).await
}

#[tauri::command]
async fn recovery_load_session_data(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
    let session_id = header_str(&request, "x-session-id")?;
    let replay = recovery::load_session_data(&app, &session_id).await?;
    let encoded = recovery::encode_replay_data(&replay)?;
    Ok(tauri::ipc::Response::new(encoded))
}

#[tauri::command]
async fn timelapse_save_meta(
    app: tauri::AppHandle,
    session_id: String,
    meta_json: String,
) -> Result<(), String> {
    timelapse::save_session_meta(&app, &session_id, &meta_json).await
}

#[tauri::command]
async fn timelapse_load_session(
    app: tauri::AppHandle,
    session_id: String,
) -> Result<timelapse::LoadedTimelapseSession, String> {
    timelapse::load_session(&app, &session_id).await
}

#[tauri::command]
async fn timelapse_list_sessions(
    app: tauri::AppHandle,
) -> Result<Vec<timelapse::StoredTimelapseSummary>, String> {
    timelapse::list_sessions(&app).await
}

#[tauri::command]
async fn timelapse_write_frame(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<(), String> {
    let session_id = header_str(&request, "x-session-id")?;
    let frame_index: u32 = header_parse(&request, "x-frame-index")?;
    let ext = header_str(&request, "x-ext")?;
    let data = raw_body(&request)?;
    let meta = match (
        header_opt_parse::<u64>(&request, "x-timestamp"),
        header_opt_parse::<u32>(&request, "x-width"),
        header_opt_parse::<u32>(&request, "x-height"),
    ) {
        (Some(timestamp), Some(width), Some(height)) => Some(timelapse::FrameWriteMeta {
            timestamp,
            width,
            height,
            capture_area: header_opt_str(&request, "x-capture-area"),
        }),
        _ => None,
    };
    timelapse::write_frame(&app, &session_id, frame_index, &ext, data, meta).await
}

#[tauri::command]
async fn timelapse_write_frames_batch(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<usize, String> {
    let session_id = header_str(&request, "x-session-id")?;
    let body = raw_body(&request)?;
    let entries = timelapse::unpack_frame_batch(body)?;
    timelapse::write_frames_batch(&app, &session_id, entries).await
}

#[tauri::command]
async fn timelapse_list_frames(
    app: tauri::AppHandle,
    session_id: String,
) -> Result<Vec<(u32, String)>, String> {
    timelapse::list_frames(&app, &session_id).await
}

#[tauri::command]
async fn timelapse_read_frame(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
    let session_id = header_str(&request, "x-session-id")?;
    let frame_index: u32 = header_parse(&request, "x-frame-index")?;
    let ext = header_str(&request, "x-ext")?;
    let bytes = timelapse::read_frame(&app, &session_id, frame_index, &ext).await?;
    Ok(tauri::ipc::Response::new(bytes))
}

#[tauri::command]
async fn timelapse_clear(app: tauri::AppHandle, session_id: String) -> Result<(), String> {
    timelapse::clear_session(&app, &session_id).await
}

#[tauri::command]
async fn timelapse_check_ffmpeg() -> bool {
    timelapse::check_ffmpeg().await
}

#[tauri::command]
async fn timelapse_export_ffmpeg(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
    let session_id = header_str(&request, "x-session-id")?;
    let ext = header_str(&request, "x-ext")?;
    let fps: u32 = header_parse(&request, "x-fps")?;
    let width: u32 = header_parse(&request, "x-width")?;
    let height: u32 = header_parse(&request, "x-height")?;
    let bg_color = header_opt_str(&request, "x-bg-color").unwrap_or_else(|| "#ffffff".to_string());
    let bg_blur = header_opt_str(&request, "x-bg-blur")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    let quality = header_opt_str(&request, "x-quality").unwrap_or_else(|| "high".to_string());
    let wm_len: usize = header_opt_parse(&request, "x-watermark-bytes").unwrap_or(0);
    let wm_x: i32 = header_opt_parse(&request, "x-watermark-x").unwrap_or(0);
    let wm_y: i32 = header_opt_parse(&request, "x-watermark-y").unwrap_or(0);

    let body = raw_body(&request)?;
    if wm_len > body.len() {
        return Err("Invalid watermark byte length header".to_string());
    }
    let indices_len = body.len() - wm_len;
    let frame_indices = timelapse::unpack_frame_indices(&body[..indices_len])?;
    let watermark_png = if wm_len > 0 {
        Some(&body[indices_len..])
    } else {
        None
    };

    let bytes = timelapse::export_ffmpeg(
        &app,
        timelapse::FfmpegExportParams {
            session_id: &session_id,
            frame_indices,
            ext: &ext,
            fps,
            width,
            height,
            bg_color: &bg_color,
            bg_blur,
            quality: &quality,
            watermark_png,
            watermark_x: wm_x,
            watermark_y: wm_y,
        },
    )
    .await?;
    Ok(tauri::ipc::Response::new(bytes))
}

#[tauri::command]
async fn timelapse_capture_app_window(
    app: tauri::AppHandle,
    max_dim: u32,
) -> Result<tauri::ipc::Response, String> {
    let bytes = timelapse::capture_app_window(&app, max_dim).await?;
    Ok(tauri::ipc::Response::new(bytes))
}

#[tauri::command]
async fn native_pick_save_path(
    app: tauri::AppHandle,
    suggested_name: String,
    filters: Vec<save_dialog::SaveFilterSpec>,
    default_filter_index: Option<usize>,
    title: Option<String>,
    initial_dir: Option<String>,
) -> Result<save_dialog::NativePickSavePathResult, String> {
    let res = save_dialog::pick_save_path_with_dialog(
        &app,
        suggested_name,
        filters,
        default_filter_index.unwrap_or(0),
        title,
        initial_dir,
    )
    .await?;
    if !res.canceled {
        if let Some(ref chosen_path) = res.path {
            register_allowed_write_path(Path::new(chosen_path));
        }
    }
    Ok(res)
}

#[tauri::command]
async fn native_save_file_with_dialog(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<save_dialog::NativeSaveDialogResult, String> {
    let suggested_name = header_str(&request, "x-suggested-name")?;
    let filter_name = header_opt_str(&request, "x-filter-name").unwrap_or_else(|| "File".to_string());
    let extensions = header_opt_str(&request, "x-extensions").unwrap_or_default();
    let title = header_opt_str(&request, "x-dialog-title");
    let initial_dir = header_opt_str(&request, "x-initial-dir");
    let data = raw_body(&request)?.to_vec();
    let res = save_dialog::save_file_with_dialog(
        &app,
        suggested_name,
        filter_name,
        extensions,
        title,
        initial_dir,
        data,
    )
    .await?;
    if res.saved {
        if let Some(ref saved_path) = res.path {
            register_allowed_path(Path::new(saved_path));
        }
    }
    Ok(res)
}

#[tauri::command]
async fn parse_sut_sqlite(
    request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
    let body = raw_body(&request)?;
    if body.len() as u64 > MAX_READ_FILE_BYTES {
        return Err("SUT file exceeds 512 MB safety limit".to_string());
    }
    let owned = body.to_vec();
    let wire = tokio::task::spawn_blocking(move || clip_parser::extract_sut_sqlite_binary(&owned))
        .await
        .map_err(|e| format!("SUT parser worker failed: {}", e))??;
    Ok(tauri::ipc::Response::new(wire))
}

#[tauri::command]
async fn native_flate_compress(
    request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
    let op = header_str(&request, "x-op")?;
    let level: u32 = header_parse(&request, "x-level").unwrap_or(1);
    let owned = raw_body(&request)?.to_vec();
    let out = tokio::task::spawn_blocking(move || raster_ops::flate_compress(&op, &owned, level))
        .await
        .map_err(|e| format!("Flate compress worker failed: {}", e))??;
    Ok(tauri::ipc::Response::new(out))
}

#[tauri::command]
async fn native_flate_decompress(
    request: tauri::ipc::Request<'_>,
) -> Result<tauri::ipc::Response, String> {
    let op = header_str(&request, "x-op")?;
    let max_out: usize = header_parse(&request, "x-max-output-bytes")
        .unwrap_or(raster_ops::MAX_RASTER_BYTES);
    let owned = raw_body(&request)?.to_vec();
    let out =
        tokio::task::spawn_blocking(move || raster_ops::flate_decompress(&op, &owned, max_out))
            .await
            .map_err(|e| format!("Flate decompress worker failed: {}", e))??;
    Ok(tauri::ipc::Response::new(out))
}

#[tauri::command]
fn tablet_start_input(
    window: tauri::WebviewWindow,
    mode: Option<String>,
    on_samples: tauri::ipc::Channel<tauri::ipc::InvokeResponseBody>,
) -> Result<tablet_input::TabletStatus, String> {
    tablet_input::start_tablet_input(&window, mode.as_deref().unwrap_or("auto"), on_samples)
}

#[tauri::command]
fn tablet_stop_input() {
    tablet_input::stop_tablet_input();
}

#[tauri::command]
fn tablet_get_status() -> tablet_input::TabletStatus {
    tablet_input::get_tablet_status()
}

#[tauri::command]
fn native_engine_is_active() -> bool {
    native_engine::is_active()
}

#[tauri::command]
fn native_engine_is_stroke_active() -> bool {
    native_engine::is_stroke_active()
}

#[tauri::command]
fn native_engine_set_viewport(
    x_px: i32,
    y_px: i32,
    width_px: u32,
    height_px: u32,
    dpr: f32,
    visible: bool,
) -> Result<(), String> {
    native_engine::set_viewport(
        ink_engine::ViewportRect {
            x_px,
            y_px,
            width_px,
            height_px,
            dpr,
        },
        visible,
    )
}

#[tauri::command]
fn native_engine_set_occluded_rects(rects: Vec<ink_engine::UiRect>) {
    native_engine::set_occluded_rects(rects);
}

#[tauri::command]
fn native_engine_set_document(width: u32, height: u32, show_checkerboard: bool) {
    native_engine::set_document(width, height, show_checkerboard);
}

#[tauri::command]
fn native_engine_set_appearance(matte_rgba: [f32; 4], show_checkerboard: bool) {
    native_engine::set_appearance(matte_rgba, show_checkerboard);
}

#[tauri::command]
fn native_engine_set_display_config(config: ink_engine::CompositorDisplayConfig) {
    native_engine::set_display_config(config);
}

#[tauri::command]
fn native_engine_invalidate_compositor_cache() {
    native_engine::invalidate_compositor_cache();
}

#[tauri::command]
fn native_engine_flush_gpu_pool() {
    native_engine::flush_gpu_pool();
}

/// Packs `[width: u32 LE, height: u32 LE, straight_rgba8...]` as a raw binary IPC response
/// (zero base64 overhead) for PNG/JPEG/WebP/Webtoon export and Navigator preview.
fn pack_rgba_ipc_response(w: u32, h: u32, rgba: Vec<u8>) -> tauri::ipc::Response {
    let mut out = Vec::with_capacity(8 + rgba.len());
    out.extend_from_slice(&w.to_le_bytes());
    out.extend_from_slice(&h.to_le_bytes());
    out.extend_from_slice(&rgba);
    tauri::ipc::Response::new(out)
}

#[tauri::command]
async fn native_engine_flatten_document(
    doc_id: Option<String>,
    options: Option<ink_engine::FlattenOptions>,
) -> Result<tauri::ipc::Response, String> {
    let opts = options.unwrap_or_default();
    let (w, h, rgba) = tokio::task::spawn_blocking(move || {
        native_docs::flatten_document_rgba(doc_id, opts)
    })
    .await
    .map_err(|e| format!("GPU flatten worker failed: {e}"))??;
    Ok(pack_rgba_ipc_response(w, h, rgba))
}

#[tauri::command]
async fn native_engine_render_navigator_preview(
    doc_id: Option<String>,
    max_dim: Option<u32>,
    show_checkerboard: Option<bool>,
    apply_soft_proof: Option<bool>,
    soft_proof: Option<ink_engine::SoftProofConfig>,
    apply_value_check: Option<bool>,
) -> Result<tauri::ipc::Response, String> {
    let opts = ink_engine::FlattenOptions {
        max_dim: Some(max_dim.unwrap_or(512).clamp(64, 1024)),
        region: None,
        fill_white_background: !show_checkerboard.unwrap_or(false),
        show_checkerboard: show_checkerboard.unwrap_or(false),
        apply_soft_proof: apply_soft_proof.unwrap_or(false),
        soft_proof: soft_proof.unwrap_or_default(),
        apply_value_check: apply_value_check.unwrap_or(false),
        cel_visibility_overrides: std::collections::HashMap::new(),
        onion_skin_frames: Vec::new(),
    };
    let (w, h, rgba) = tokio::task::spawn_blocking(move || {
        native_docs::flatten_document_rgba(doc_id, opts)
    })
    .await
    .map_err(|e| format!("Navigator preview worker failed: {e}"))??;
    Ok(pack_rgba_ipc_response(w, h, rgba))
}

#[tauri::command]
fn native_engine_set_camera(camera: ink_engine::CameraState) {
    native_engine::set_camera(camera);
}

#[tauri::command]
fn native_engine_set_cursor(config: ink_engine::CursorConfig) {
    native_engine::set_cursor(config);
}

#[tauri::command]
fn native_engine_set_brush(params: ink_engine::BrushParams) {
    native_engine::set_brush(params);
}

#[tauri::command]
fn native_engine_set_full_brush(config: ink_engine::NativeBrushConfig) {
    native_engine::set_full_brush(config);
}

#[tauri::command]
fn native_engine_clean_dirty_brush(preset_key: Option<String>) {
    native_engine::clean_dirty_brush(preset_key);
}

#[tauri::command]
fn native_engine_set_mask_mode(enabled: bool) {
    native_engine::set_mask_mode(enabled);
}

#[tauri::command]
async fn native_engine_render_brush_preview(
    brush: ink_engine::NativeBrushConfig,
    width: u32,
    height: u32,
) -> Result<tauri::ipc::Response, String> {
    let (w, h, rgba) = tauri::async_runtime::spawn_blocking(move || {
        native_engine::render_brush_preview(brush, width, height)
    })
    .await
    .map_err(|e| format!("Brush preview worker failed: {e}"))??;
    Ok(pack_rgba_ipc_response(w, h, rgba))
}

#[tauri::command]
async fn native_engine_render_scratchpad_preview(
    brush: ink_engine::NativeBrushConfig,
    strokes: Vec<ink_engine::ScratchpadStrokeInput>,
    width: u32,
    height: u32,
) -> Result<tauri::ipc::Response, String> {
    let (w, h, rgba) = tauri::async_runtime::spawn_blocking(move || {
        native_engine::render_scratchpad_preview(brush, strokes, width, height)
    })
    .await
    .map_err(|e| format!("Scratchpad preview worker failed: {e}"))??;
    Ok(pack_rgba_ipc_response(w, h, rgba))
}

#[tauri::command]
fn native_engine_set_pressure_curve(curve: ink_engine::GlobalPressureCurve) {
    native_engine::set_pressure_curve(curve);
}

#[tauri::command]
fn native_engine_set_rulers(
    straight: Option<ink_engine::StraightRulerConfig>,
    perspective: Option<ink_engine::PerspectiveRulerConfig>,
) {
    native_engine::set_rulers(straight, perspective);
}

#[tauri::command]
async fn native_engine_upload_brush_texture(req: tauri::ipc::Request<'_>) -> Result<(), String> {
    let headers = req.headers();
    let hash = headers
        .get("x-hash")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| "Missing x-hash header".to_string())?;
    let kind = match headers
        .get("x-kind")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("tip")
    {
        "paper" => ink_engine::BrushTextureKind::Paper,
        _ => ink_engine::BrushTextureKind::Tip,
    };
    let is_png = headers
        .get("x-format")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("png")
        == "png";
    let width = headers
        .get("x-width")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<u32>().ok())
        .unwrap_or(0);
    let height = headers
        .get("x-height")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<u32>().ok())
        .unwrap_or(0);
    let data = match req.body() {
        tauri::ipc::InvokeBody::Raw(bytes) => bytes.clone(),
        _ => return Err("Expected raw binary body for brush texture upload".to_string()),
    };
    tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
        // Decode PNG on the blocking worker thread instead of stalling the DX12 render thread.
        let (final_w, final_h, rgba8) = if is_png {
            ink_engine::io::decode_png_rgba8(&data)?
        } else {
            (width, height, data)
        };
        native_engine::upload_brush_texture(hash, kind, false, final_w, final_h, rgba8);
        Ok(())
    })
    .await
    .map_err(|e| format!("Brush texture upload worker failed: {e}"))?
}

#[tauri::command]
fn native_engine_set_policy(policy: ink_engine::InteractionPolicy) {
    native_engine::set_policy(policy);
}

#[tauri::command]
fn native_engine_set_collab_points_enabled(enabled: bool) {
    native_engine::set_collab_points_enabled(enabled);
}

#[tauri::command]
fn native_engine_clear_canvas() {
    native_engine::clear_canvas();
}

#[tauri::command]
fn native_engine_get_diagnostics() -> ink_engine::EngineDiagnostics {
    native_engine::get_diagnostics()
}

// ---------------------------------------------------------------------------
// Phase 2: Native Rust Document Store, Layer Tree, CoW Undo/Redo & Zero-Copy I/O
// ---------------------------------------------------------------------------

#[tauri::command]
async fn native_engine_create_document(
    doc_id: String,
    name: String,
    dimensions: ink_engine::CanvasDimensions,
    color_mode: Option<ink_engine::CanvasColorMode>,
    background_hex: Option<String>,
    default_tone_frequency: Option<f32>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    tauri::async_runtime::spawn_blocking(move || {
        native_docs::create_document(
            doc_id,
            name,
            dimensions,
            color_mode.unwrap_or(ink_engine::CanvasColorMode::Color),
            background_hex.as_deref().unwrap_or("#ffffff"),
            default_tone_frequency.unwrap_or(60.0),
        )
    })
    .await
    .map_err(|e| format!("Create document worker failed: {e}"))
}

#[tauri::command]
async fn native_engine_open_file(
    app: tauri::AppHandle,
    doc_id: String,
    path: String,
) -> Result<native_docs::OpenNativeDocumentResult, String> {
    let allowed_dirs = get_allowed_base_dirs(&app);
    let (canonical, _) = validate_read_path(&path, &allowed_dirs).await?;
    let file_name = canonical
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "Untitled.ink".to_string());
    let bytes = tokio::fs::read(&canonical)
        .await
        .map_err(|e| format!("Failed to read file {}: {}", canonical.display(), e))?;
    tokio::task::spawn_blocking(move || {
        native_docs::open_document_from_bytes(doc_id, file_name, &bytes)
    })
    .await
    .map_err(|e| format!("Native open worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_open_file_bytes(
    request: tauri::ipc::Request<'_>,
) -> Result<native_docs::OpenNativeDocumentResult, String> {
    let doc_id = header_str(&request, "x-doc-id")?;
    let file_name = header_str(&request, "x-file-name")?;
    let body = raw_body(&request)?;
    if body.len() as u64 > MAX_READ_FILE_BYTES {
        return Err("File exceeds 512 MB safety limit".to_string());
    }
    let owned = body.to_vec();
    tokio::task::spawn_blocking(move || {
        native_docs::open_document_from_bytes(doc_id, file_name, &owned)
    })
    .await
    .map_err(|e| format!("Native open bytes worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_save_ink(
    app: tauri::AppHandle,
    doc_id: String,
    path: String,
) -> Result<native_docs::SaveNativeInkResult, String> {
    let allowed_dirs = get_allowed_base_dirs(&app);
    let target = validate_write_path(&path, &allowed_dirs).await?;
    let doc_id_clone = doc_id.clone();
    let serialized = tokio::task::spawn_blocking(move || {
        native_docs::serialize_document_ink(&doc_id_clone)
    })
    .await
    .map_err(|e| format!("Native .ink serialize worker failed: {e}"))??;

    let bytes_written = serialized.bytes.len();
    let preview_data_url = serialized.preview_data_url;
    let tile_count = serialized.tile_count;
    let mask_count = serialized.mask_count;
    let zip_bytes = serialized.bytes;
    let target_for_write = target.clone();
    tokio::task::spawn_blocking(move || {
        save_dialog::write_file_atomic(&target_for_write, &zip_bytes)
    })
    .await
    .map_err(|e| format!("Atomic .ink save worker failed: {e}"))??;

    register_allowed_path(&target);
    Ok(native_docs::SaveNativeInkResult {
        path: Some(target.to_string_lossy().into_owned()),
        bytes_written,
        preview_data_url,
        tile_count,
        mask_count,
    })
}

#[tauri::command]
async fn native_engine_save_ink_with_dialog(
    app: tauri::AppHandle,
    doc_id: String,
    suggested_name: String,
    initial_dir: Option<String>,
) -> Result<native_docs::SaveNativeInkResult, String> {
    let pick = save_dialog::pick_save_path_with_dialog(
        &app,
        suggested_name,
        vec![save_dialog::SaveFilterSpec {
            name: "InkStudio Document".to_string(),
            extensions: vec!["ink".to_string()],
        }],
        0,
        Some("Save InkStudio Document".to_string()),
        initial_dir,
    )
    .await?;
    if pick.canceled {
        return Ok(native_docs::SaveNativeInkResult {
            path: None,
            bytes_written: 0,
            preview_data_url: None,
            tile_count: 0,
            mask_count: 0,
        });
    }
    let chosen_path = pick
        .path
        .ok_or_else(|| "Save dialog returned no path".to_string())?;
    register_allowed_write_path(Path::new(&chosen_path));
    native_engine_save_ink(app, doc_id, chosen_path).await
}

#[tauri::command]
async fn native_engine_switch_document(
    doc_id: String,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::switch_document(&doc_id))
        .await
        .map_err(|e| format!("Switch document worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_close_document(doc_id: String) -> Result<bool, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::close_document(&doc_id))
        .await
        .map_err(|e| format!("Close document worker failed: {e}"))
}

#[tauri::command]
async fn native_engine_get_document_state(
    doc_id: Option<String>,
) -> Result<Option<ink_engine::DocumentMetaSnapshot>, String> {
    tauri::async_runtime::spawn_blocking(move || {
        native_docs::get_document_state(doc_id.as_deref())
    })
    .await
    .map_err(|e| format!("Get document state worker failed: {e}"))
}

fn emit_doc_history(
    app: &tauri::AppHandle,
    doc_id: &str,
    history: &ink_engine::HistoryStateSnapshot,
) {
    let _ = app.emit(
        native_engine::EVENT_HISTORY,
        native_engine::NativeHistoryEventPayload {
            doc_id: doc_id.to_string(),
            history: history.clone(),
        },
    );
}

#[tauri::command]
async fn native_engine_set_active_layer(
    doc_id: String,
    layer_id: Option<String>,
) -> Result<(), String> {
    tauri::async_runtime::spawn_blocking(move || {
        native_docs::set_active_layer(&doc_id, layer_id)
    })
    .await
    .map_err(|e| format!("Set active layer worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_sync_document_meta(
    doc_id: String,
    name: Option<String>,
    perspective_ruler: Option<serde_json::Value>,
    straight_ruler: Option<serde_json::Value>,
    animation_timeline: Option<serde_json::Value>,
    timelapse: Option<serde_json::Value>,
    work_time_ms: Option<u64>,
) -> Result<(), String> {
    tauri::async_runtime::spawn_blocking(move || {
        native_docs::sync_document_meta(
            &doc_id,
            name,
            perspective_ruler,
            straight_ruler,
            animation_timeline,
            timelapse,
            work_time_ms,
        )
    })
    .await
    .map_err(|e| format!("Sync document meta worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_add_layer(
    app: tauri::AppHandle,
    doc_id: String,
    layer: ink_engine::LayerNodeMeta,
    insert_index: Option<usize>,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::add_layer(&doc_id, layer, insert_index, rec)
    })
    .await
    .map_err(|e| format!("Add layer worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_delete_layer(
    app: tauri::AppHandle,
    doc_id: String,
    layer_id: String,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::delete_layer(&doc_id, &layer_id, rec)
    })
    .await
    .map_err(|e| format!("Delete layer worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_duplicate_layer(
    app: tauri::AppHandle,
    doc_id: String,
    source_layer_id: String,
    new_layer_id: String,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::duplicate_layer(&doc_id, &source_layer_id, new_layer_id, rec)
    })
    .await
    .map_err(|e| format!("Duplicate layer worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_reorder_layers(
    app: tauri::AppHandle,
    doc_id: String,
    ordered_ids: Vec<String>,
    parent_overrides: Option<std::collections::HashMap<String, Option<String>>>,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::reorder_layers(&doc_id, &ordered_ids, parent_overrides.as_ref(), rec)
    })
    .await
    .map_err(|e| format!("Reorder layers worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_update_layer(
    app: tauri::AppHandle,
    doc_id: String,
    layer_id: String,
    patch: ink_engine::LayerPropsPatch,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = patch.record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::update_layer(&doc_id, &layer_id, patch)
    })
    .await
    .map_err(|e| format!("Update layer worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_sync_layers(
    app: tauri::AppHandle,
    doc_id: String,
    layers: Vec<ink_engine::LayerNodeMeta>,
    active_layer_id: Option<String>,
    record_history: Option<bool>,
    history_label: Option<String>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(false);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::sync_layers(&doc_id, layers, active_layer_id, rec, history_label)
    })
    .await
    .map_err(|e| format!("Sync layers worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_clear_layer(
    app: tauri::AppHandle,
    doc_id: String,
    layer_id: String,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::clear_layer(&doc_id, &layer_id, rec)
    })
    .await
    .map_err(|e| format!("Clear layer worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_merge_down(
    app: tauri::AppHandle,
    doc_id: String,
    src_layer_id: String,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::merge_down(&doc_id, &src_layer_id)
    })
    .await
    .map_err(|e| format!("Merge down worker failed: {e}"))??;
    emit_doc_history(&app, &doc_id_emit, &snap.history);
    Ok(snap)
}

#[tauri::command]
async fn native_engine_merge_folder(
    app: tauri::AppHandle,
    doc_id: String,
    folder_id: String,
    new_layer_id: String,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::merge_folder(&doc_id, &folder_id, new_layer_id)
    })
    .await
    .map_err(|e| format!("Merge folder worker failed: {e}"))??;
    emit_doc_history(&app, &doc_id_emit, &snap.history);
    Ok(snap)
}

#[tauri::command]
async fn native_engine_add_mask(
    app: tauri::AppHandle,
    doc_id: String,
    layer_id: String,
    default_value: Option<u8>,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::add_mask(&doc_id, &layer_id, default_value.unwrap_or(255), rec)
    })
    .await
    .map_err(|e| format!("Add mask worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_remove_mask(
    app: tauri::AppHandle,
    doc_id: String,
    layer_id: String,
    apply_to_raster: Option<bool>,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::remove_mask(&doc_id, &layer_id, apply_to_raster.unwrap_or(false), rec)
    })
    .await
    .map_err(|e| format!("Remove mask worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_resize_canvas(
    app: tauri::AppHandle,
    doc_id: String,
    dimensions: ink_engine::CanvasDimensions,
    offset_x: Option<i32>,
    offset_y: Option<i32>,
    scale_content: Option<bool>,
    bg_hex: Option<String>,
    record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let rec = record_history.unwrap_or(true);
    let doc_id_emit = doc_id.clone();
    let snap = tauri::async_runtime::spawn_blocking(move || {
        native_docs::resize_canvas(
            &doc_id,
            dimensions,
            offset_x.unwrap_or(0),
            offset_y.unwrap_or(0),
            scale_content.unwrap_or(false),
            bg_hex.as_deref().unwrap_or("#ffffff"),
            rec,
        )
    })
    .await
    .map_err(|e| format!("Resize canvas worker failed: {e}"))??;
    if rec {
        emit_doc_history(&app, &doc_id_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_ingest_dirty_rect(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    let doc_id = header_str(&request, "x-doc-id")?;
    let layer_id = header_str(&request, "x-layer-id")?;
    let x: i32 = header_parse(&request, "x-x")?;
    let y: i32 = header_parse(&request, "x-y")?;
    let width: u32 = header_parse(&request, "x-width")?;
    let height: u32 = header_parse(&request, "x-height")?;
    let is_mask: bool = header_opt_parse::<u8>(&request, "x-is-mask").unwrap_or(0) != 0;
    let record_history: bool = header_opt_parse::<u8>(&request, "x-record-history").unwrap_or(1) != 0;
    let action_type =
        header_opt_str(&request, "x-action-type").unwrap_or_else(|| "raster".to_string());
    let label = header_opt_str(&request, "x-label").unwrap_or_else(|| "Edit Layer".to_string());
    let peer_id = header_opt_str(&request, "x-peer-id");
    let stroke_id = header_opt_str(&request, "x-stroke-id");
    let body = raw_body(&request)?.to_vec();

    let doc_id_for_emit = doc_id.clone();
    let snap = tokio::task::spawn_blocking(move || {
        native_docs::ingest_dirty_rect(
            &doc_id,
            &layer_id,
            ink_engine::RectI32::new(x, y, width, height),
            &body,
            is_mask,
            record_history,
            &action_type,
            &label,
            peer_id,
            stroke_id,
        )
    })
    .await
    .map_err(|e| format!("Native dirty-rect ingest worker failed: {e}"))??;
    if record_history {
        emit_doc_history(&app, &doc_id_for_emit, &snap.history);
    }
    Ok(snap)
}

#[tauri::command]
async fn native_engine_undo(
    doc_id: String,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::undo(&doc_id))
        .await
        .map_err(|e| format!("Undo worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_redo(
    doc_id: String,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::redo(&doc_id))
        .await
        .map_err(|e| format!("Redo worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_jump_history(
    doc_id: String,
    target_index: usize,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::jump_history(&doc_id, target_index))
        .await
        .map_err(|e| format!("Jump history worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_selective_undo(
    doc_id: String,
    peer_id: Option<String>,
    stroke_id: Option<String>,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
    tauri::async_runtime::spawn_blocking(move || {
        native_docs::selective_undo(&doc_id, peer_id.as_deref(), stroke_id.as_deref())
    })
    .await
    .map_err(|e| format!("Selective undo worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_selective_redo(
    doc_id: String,
    peer_id: Option<String>,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
    tauri::async_runtime::spawn_blocking(move || {
        native_docs::selective_redo(&doc_id, peer_id.as_deref())
    })
    .await
    .map_err(|e| format!("Selective redo worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_push_history_meta(
    app: tauri::AppHandle,
    doc_id: String,
    action_type: String,
    label: String,
    layer_id: Option<String>,
    document_state_delta: Option<serde_json::Value>,
    coalesce_key: Option<String>,
) -> Result<ink_engine::HistoryStateSnapshot, String> {
    let doc_id_emit = doc_id.clone();
    let history = tauri::async_runtime::spawn_blocking(move || {
        native_docs::push_history_meta(
            &doc_id,
            action_type,
            label,
            layer_id,
            document_state_delta,
            coalesce_key,
        )
    })
    .await
    .map_err(|e| format!("Push history meta worker failed: {e}"))??;
    emit_doc_history(&app, &doc_id_emit, &history);
    Ok(history)
}

#[tauri::command]
async fn native_engine_get_history(
    doc_id: String,
) -> Result<ink_engine::HistoryStateSnapshot, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::get_history(&doc_id))
        .await
        .map_err(|e| format!("Get history worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_reset_history(
    app: tauri::AppHandle,
    doc_id: String,
    label: Option<String>,
) -> Result<ink_engine::HistoryStateSnapshot, String> {
    let doc_id_emit = doc_id.clone();
    let history = tauri::async_runtime::spawn_blocking(move || {
        native_docs::reset_history(&doc_id, label)
    })
    .await
    .map_err(|e| format!("Reset history worker failed: {e}"))??;
    emit_doc_history(&app, &doc_id_emit, &history);
    Ok(history)
}

#[tauri::command]
async fn native_engine_get_memory_stats() -> Result<ink_engine::MemoryStats, String> {
    tauri::async_runtime::spawn_blocking(native_docs::get_memory_stats)
        .await
        .map_err(|e| format!("Get memory stats worker failed: {e}"))
}

#[tauri::command]
async fn native_engine_set_memory_budget(
    input: native_docs::NativeMemoryBudgetInput,
) -> Result<ink_engine::MemoryStats, String> {
    tauri::async_runtime::spawn_blocking(move || native_docs::set_memory_budget(input))
        .await
        .map_err(|e| format!("Set memory budget worker failed: {e}"))?
}

#[tauri::command]
async fn native_engine_purge_memory() -> Result<ink_engine::MemoryStats, String> {
    tauri::async_runtime::spawn_blocking(native_docs::purge_memory)
        .await
        .map_err(|e| format!("Purge memory worker failed: {e}"))?
}

#[tauri::command]
fn native_engine_request_thumbnails(
    app: tauri::AppHandle,
    doc_id: String,
    layer_ids: Option<Vec<String>>,
) {
    native_docs::spawn_thumbnail_generation(app, doc_id, layer_ids.unwrap_or_default());
}

#[tauri::command]
async fn native_engine_capture_timelapse_frame(
    app: tauri::AppHandle,
    doc_id: String,
    session_id: String,
    frame_index: u32,
    max_dim: Option<u32>,
    capture_area: Option<String>,
) -> Result<native_docs::NativeTimelapseCaptureResult, String> {
    native_docs::capture_timelapse_frame(
        &app,
        doc_id,
        session_id,
        frame_index,
        max_dim.unwrap_or(1920),
        capture_area,
    )
    .await
}

#[tauri::command]
async fn native_engine_recovery_checkpoint(
    app: tauri::AppHandle,
    doc_id: String,
    session_id: String,
    manifest_json: Option<String>,
) -> Result<native_docs::NativeRecoveryCheckpointResult, String> {
    native_docs::recovery_checkpoint_document(&app, doc_id, session_id, manifest_json).await
}

#[tauri::command]
async fn native_engine_recovery_restore(
    app: tauri::AppHandle,
    session_id: String,
    doc_id: String,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
    native_docs::recovery_restore_document(&app, session_id, doc_id).await
}

#[tauri::command]
async fn os_hotkeys_sync(
    window: tauri::WebviewWindow,
    bindings: Vec<os_hotkeys::NativeOsHotkeyBinding>,
    recording: bool,
    on_event: tauri::ipc::Channel<os_hotkeys::NativeOsHotkeyEvent>,
) -> Result<os_hotkeys::OsHotkeyStatus, String> {
    tauri::async_runtime::spawn_blocking(move || {
        os_hotkeys::sync_os_hotkeys(&window, bindings, recording, on_event)
    })
    .await
    .map_err(|e| format!("OS hotkeys sync worker failed: {e}"))?
}

#[tauri::command]
fn os_hotkeys_stop() {
    os_hotkeys::stop_os_hotkeys();
}

#[tauri::command]
async fn get_system_hardware_info() -> Result<system_perf::SystemHardwareInfo, String> {
    tokio::task::spawn_blocking(system_perf::collect_system_hardware_info)
        .await
        .map_err(|e| format!("Failed to query system hardware info: {}", e))
}

#[tauri::command]
async fn get_scratch_disk_usage() -> Result<system_perf::ScratchDiskUsageReport, String> {
    tokio::task::spawn_blocking(system_perf::collect_scratch_disk_usage)
        .await
        .map_err(|e| format!("Failed to query scratch disk usage: {}", e))
}

#[tauri::command]
async fn apply_performance_config(
    config: system_perf::StartupPerformanceConfig,
) -> Result<system_perf::SystemHardwareInfo, String> {
    tokio::task::spawn_blocking(move || -> Result<system_perf::SystemHardwareInfo, String> {
        let validated_dir = system_perf::validate_custom_scratch_dir(&config.scratch_disk_path)?;
        let saved = system_perf::save_startup_config(system_perf::StartupPerformanceConfig {
            scratch_disk_path: validated_dir
                .as_ref()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_default(),
            ..config
        })?;

        scratch_disk::set_custom_scratch_dir(validated_dir);
        scratch_disk::set_scratch_compression_enabled(saved.scratch_disk_compression != "none");
        let _ = system_perf::set_cpu_worker_threads(saved.cpu_worker_threads)?;
        Ok(system_perf::collect_system_hardware_info())
    })
    .await
    .map_err(|e| format!("Failed to apply performance config: {}", e))?
}

#[tauri::command]
async fn purge_unused_scratch_files(active_session_ids: Vec<String>) -> Result<u64, String> {
    tokio::task::spawn_blocking(move || -> Result<u64, String> {
        let active_sanitized: HashSet<String> = active_session_ids
            .iter()
            .map(|id| sanitize_id(id))
            .collect();
        let mut freed: u64 = 0;

        for base in [
            scratch_disk::get_scratch_base_dir(),
            system_perf::get_undo_cache_base_dir(),
        ] {
            if !base.exists() {
                continue;
            }
            let Ok(entries) = std::fs::read_dir(&base) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if !path.is_dir() {
                    continue;
                }
                let name = entry.file_name().to_string_lossy().to_string();
                if active_sanitized.contains(&name) {
                    continue;
                }
                let bytes = system_perf::compute_dir_bytes(&path);
                if std::fs::remove_dir_all(&path).is_ok() {
                    freed = freed.saturating_add(bytes);
                }
            }
        }
        Ok(freed)
    })
    .await
    .map_err(|e| format!("Failed to purge unused scratch files: {}", e))?
}

fn focus_main_window(app: &tauri::AppHandle) {
    if let Some(main_window) = app.get_webview_window("main") {
        let _ = main_window.unminimize();
        let _ = main_window.show();
        let _ = main_window.set_focus();
    }
}

fn deliver_open_files(app: &tauri::AppHandle, paths: Vec<String>) {
    if let Some(to_emit) = file_open::enqueue_or_take_for_emit(paths) {
        let _ = app.emit(file_open::OPEN_FILES_EVENT, to_emit);
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    // Load persisted desktop performance settings BEFORE WebView2 initializes
    let startup_perf = system_perf::load_startup_config();
    if !startup_perf.scratch_disk_path.is_empty() {
        if let Ok(Some(valid_dir)) =
            system_perf::validate_custom_scratch_dir(&startup_perf.scratch_disk_path)
        {
            scratch_disk::set_custom_scratch_dir(Some(valid_dir));
        }
    }
    scratch_disk::set_scratch_compression_enabled(startup_perf.scratch_disk_compression != "none");
    if startup_perf.cpu_worker_threads > 0 {
        let _ = system_perf::set_cpu_worker_threads(startup_perf.cpu_worker_threads);
    }

    // Disable Windows 11 WebView2 Shell Handwriting / DirectInk overlay so stylus input on
    // sidebar text fields (e.g. layer rename) never draws ink strokes over the UI,
    // and apply user-configured GPU adapter / ANGLE backend flags.
    #[cfg(target_os = "windows")]
    {
        const HANDWRITING_DISABLE_FLAG: &str =
            "--disable-features=StylusHandwritingWin,StylusHandwriting,msAbydos,msAbydosHandwritingAttr,msAbydosGestureSupport";
        let mut merged = match std::env::var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS") {
            Ok(existing) if !existing.trim().is_empty() => {
                if existing.contains("StylusHandwritingWin") {
                    existing
                } else {
                    format!("{} {}", existing, HANDWRITING_DISABLE_FLAG)
                }
            }
            _ => HANDWRITING_DISABLE_FLAG.to_string(),
        };
        for flag in system_perf::build_webview_perf_args(&startup_perf) {
            if !merged.contains(&flag) {
                merged.push(' ');
                merged.push_str(&flag);
            }
        }
        std::env::set_var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", merged);
        // Ensure WebView2 initializes with a transparent default background (ARGB 0x00000000)
        // so the DirectComposition DX12 canvas visual underneath is visible without white flashes.
        std::env::set_var("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "0");
    }

    let builder = tauri::Builder::default();

    // Register single-instance FIRST so any second launch (e.g. double-clicking a `.ink` file
    // while Ink Studio is already open) forwards its arguments to the running instance and exits
    // immediately without spawning a second window or WebView2 process.
    #[cfg(desktop)]
    let builder = builder.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
        focus_main_window(app);
        let cwd_path = if cwd.trim().is_empty() {
            None
        } else {
            Some(PathBuf::from(&cwd))
        };
        let paths = file_open::extract_openable_file_paths(
            argv.iter().skip(1),
            cwd_path.as_deref(),
            register_allowed_path,
        );
        deliver_open_files(app, paths);
    }));

    let app = builder
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_process::init())
        .setup(|app| {
            // Register and queue any files passed via OS file association / CLI args on cold launch.
            let launch_args: Vec<String> = std::env::args_os()
                .skip(1)
                .map(|s| s.to_string_lossy().into_owned())
                .collect();
            let launch_cwd = std::env::current_dir().ok();
            let launch_paths = file_open::extract_openable_file_paths(
                &launch_args,
                launch_cwd.as_deref(),
                register_allowed_path,
            );
            let _ = file_open::enqueue_or_take_for_emit(launch_paths);

            #[cfg(desktop)]
            {
                app.handle()
                    .plugin(tauri_plugin_updater::Builder::new().build())?;
                if let Some(main_window) = app.get_webview_window("main") {
                    let _ = main_window.maximize();
                    #[cfg(target_os = "windows")]
                    {
                        if let Err(err) = native_engine::init_for_main_window(
                            app.handle().clone(),
                            &main_window,
                        ) {
                            eprintln!("[native_engine] initialization failed (falling back): {err}");
                            // Still disable built-in browser accelerator keys if native engine failed
                            let _ = main_window.with_webview(|webview| {
                                use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;
                                use windows_core::Interface;
                                unsafe {
                                    if let Ok(core) = webview.controller().CoreWebView2() {
                                        if let Ok(settings) = core.Settings() {
                                            if let Ok(settings3) =
                                                settings.cast::<ICoreWebView2Settings3>()
                                            {
                                                let _ = settings3
                                                    .SetAreBrowserAcceleratorKeysEnabled(false);
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            }
            Ok(())
        })
        .on_window_event(|_window, event| {
            if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
                for p in paths {
                    register_allowed_path(p);
                }
            }
        })
        .invoke_handler(tauri::generate_handler![
            start_collab_server,
            stop_collab_server,
            get_collab_server_status,
            download_cloudflared,
            is_cloudflared_installed,
            get_os_username,
            get_local_lan_ip,
            delete_file_from_disk,
            read_file_from_disk,
            read_file_binary,
            write_allowed_file_binary,
            take_pending_open_files,
            recovery_init_session,
            recovery_append_wal_entry,
            recovery_checkpoint,
            recovery_close_session,
            recovery_check_crashed_sessions,
            recovery_load_session_data,
            timelapse_save_meta,
            timelapse_load_session,
            timelapse_list_sessions,
            timelapse_write_frame,
            timelapse_write_frames_batch,
            timelapse_list_frames,
            timelapse_read_frame,
            timelapse_clear,
            timelapse_check_ffmpeg,
            timelapse_export_ffmpeg,
            timelapse_capture_app_window,
            native_pick_save_path,
            native_save_file_with_dialog,
            parse_sut_sqlite,
            native_flate_compress,
            native_flate_decompress,
            tablet_start_input,
            tablet_stop_input,
            tablet_get_status,
            native_engine_is_active,
            native_engine_is_stroke_active,
            native_engine_set_viewport,
            native_engine_set_occluded_rects,
            native_engine_set_document,
            native_engine_set_appearance,
            native_engine_set_display_config,
            native_engine_invalidate_compositor_cache,
            native_engine_flush_gpu_pool,
            native_engine_flatten_document,
            native_engine_render_navigator_preview,
            native_engine_set_camera,
            native_engine_set_cursor,
            native_engine_set_brush,
            native_engine_set_full_brush,
            native_engine_clean_dirty_brush,
            native_engine_set_mask_mode,
            native_engine_render_brush_preview,
            native_engine_render_scratchpad_preview,
            native_engine_set_pressure_curve,
            native_engine_set_rulers,
            native_engine_upload_brush_texture,
            native_engine_set_policy,
            native_engine_set_collab_points_enabled,
            native_engine_clear_canvas,
            native_engine_get_diagnostics,
            native_engine_create_document,
            native_engine_open_file,
            native_engine_open_file_bytes,
            native_engine_save_ink,
            native_engine_save_ink_with_dialog,
            native_engine_switch_document,
            native_engine_close_document,
            native_engine_get_document_state,
            native_engine_set_active_layer,
            native_engine_sync_document_meta,
            native_engine_add_layer,
            native_engine_delete_layer,
            native_engine_duplicate_layer,
            native_engine_reorder_layers,
            native_engine_update_layer,
            native_engine_sync_layers,
            native_engine_clear_layer,
            native_engine_merge_down,
            native_engine_merge_folder,
            native_engine_add_mask,
            native_engine_remove_mask,
            native_engine_resize_canvas,
            native_engine_ingest_dirty_rect,
            native_engine_undo,
            native_engine_redo,
            native_engine_jump_history,
            native_engine_selective_undo,
            native_engine_selective_redo,
            native_engine_push_history_meta,
            native_engine_get_history,
            native_engine_reset_history,
            native_engine_get_memory_stats,
            native_engine_set_memory_budget,
            native_engine_purge_memory,
            native_engine_request_thumbnails,
            native_engine_capture_timelapse_frame,
            native_engine_recovery_checkpoint,
            native_engine_recovery_restore,
            native_tools::native_select_rect,
            native_tools::native_select_lasso,
            native_tools::native_select_magic_wand,
            native_tools::native_select_all,
            native_tools::native_deselect,
            native_tools::native_selection_invert,
            native_tools::native_selection_expand,
            native_tools::native_selection_feather,
            native_tools::native_selection_clear_pixels,
            native_tools::native_selection_clear_outside,
            native_tools::native_selection_fill_color,
            native_tools::native_selection_copy,
            native_tools::native_selection_cut,
            native_tools::native_selection_paste,
            native_tools::native_selection_move_to_new_layer,
            native_tools::native_selection_lift_floating,
            native_tools::native_selection_move_floating,
            native_tools::native_selection_commit_floating,
            native_tools::native_selection_get_state,
            native_tools::native_liquify_begin,
            native_tools::native_liquify_step_gpu,
            native_tools::native_liquify_commit,
            native_tools::native_liquify_cancel,
            native_tools::native_flood_fill_doc,
            native_tools::native_lasso_fill_doc,
            native_tools::native_enclose_fill_doc,
            native_tools::native_paint_unfilled_doc,
            native_tools::native_pick_color,
            native_tools::native_transform_begin,
            native_tools::native_transform_update,
            native_tools::native_transform_switch_mode,
            native_tools::native_transform_commit,
            native_tools::native_transform_cancel,
            native_tools::native_retouch_step,
            native_tools::native_retouch_commit,
            native_tools::native_retouch_cancel,
            native_tools::native_gradient_preview,
            native_tools::native_gradient_commit,
            native_tools::native_shape_preview,
            native_tools::native_shape_commit,
            native_tools::native_recognize_quick_shape,
            native_tools::native_clear_tool_preview,
            native_tools::native_image_op_preview,
            native_tools::native_image_op_apply,
            native_tools::native_layer_histogram,
            native_tools::native_rasterize_vector_layer,
            native_tools::native_rasterize_bezier,
            native_tools::native_collab_remote_stroke_start,
            native_tools::native_collab_remote_stroke_chunk,
            native_tools::native_collab_remote_stroke_finish,
            native_tools::native_collab_remote_stroke_dispose,
            native_tools::native_collab_remote_peer_dispose,
            native_tools::native_collab_encode_tiles,
            native_tools::native_collab_apply_tile_delta,
            native_tools::native_collab_encode_mask,
            native_tools::native_collab_apply_mask,
            native_tools::native_collab_checksum,
            native_tools::native_engine_export_image,
            native_tools::native_engine_import_image_layer,
            native_tools::native_engine_read_layer_rgba,
            native_tools::native_engine_read_layer_mask_rgba,
            os_hotkeys_sync,
            os_hotkeys_stop,
            get_system_hardware_info,
            get_scratch_disk_usage,
            apply_performance_config,
            purge_unused_scratch_files
        ])
        .build(tauri::generate_context!())
        .expect("error while building tauri application");

    app.run(|app_handle, event| {
        #[cfg(any(target_os = "macos", target_os = "ios"))]
        if let tauri::RunEvent::Opened { urls } = &event {
            let url_strings: Vec<String> = urls.iter().map(|u| u.as_str().to_string()).collect();
            let paths = file_open::extract_openable_file_paths(
                &url_strings,
                None,
                register_allowed_path,
            );
            focus_main_window(app_handle);
            deliver_open_files(app_handle, paths);
        }
        let _ = app_handle;
        if let tauri::RunEvent::Exit = event {
            os_hotkeys::stop_os_hotkeys();
            tablet_input::stop_tablet_input();
            native_engine::shutdown();
            server::shutdown_sync();
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_path_authorization_blocks_arbitrary_and_traversal() {
        let base = std::env::temp_dir().join(format!(
            "inkstudio_path_auth_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let allowed_dir = base.join("allowed");
        let outside_dir = base.join("outside");
        std::fs::create_dir_all(&allowed_dir).unwrap();
        std::fs::create_dir_all(&outside_dir).unwrap();

        let inside_file = allowed_dir.join("art.ink");
        let outside_file = outside_dir.join("secret.png");
        std::fs::write(&inside_file, b"ok").unwrap();
        std::fs::write(&outside_file, b"secret").unwrap();

        let canon_allowed = std::fs::canonicalize(&allowed_dir).unwrap();
        let allowed_dirs = vec![canon_allowed];

        // Allowed directory file passes
        assert!(validate_read_path(inside_file.to_str().unwrap(), &allowed_dirs)
            .await
            .is_ok());

        // Outside file blocked for read & delete
        assert!(validate_read_path(outside_file.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());
        assert!(validate_delete_path(outside_file.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        // Traversal out of allowed_dir blocked
        let traversal = allowed_dir.join("..").join("outside").join("secret.png");
        assert!(validate_read_path(traversal.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        // Explicit registry grant allows outside file, unregister revokes it
        register_allowed_path(&outside_file);
        assert!(validate_read_path(outside_file.to_str().unwrap(), &allowed_dirs)
            .await
            .is_ok());
        let canon_outside = std::fs::canonicalize(&outside_file).unwrap();
        unregister_allowed_path(&canon_outside);
        assert!(validate_read_path(outside_file.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        // Non-existent file outside allowed dir returns Access Denied (no existence oracle)
        let missing_outside = outside_dir.join("missing.ink");
        assert!(validate_delete_path(missing_outside.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        // Non-existent file inside allowed dir returns Ok(None)
        let missing_inside = allowed_dir.join("missing.ink");
        assert_eq!(
            validate_delete_path(missing_inside.to_str().unwrap(), &allowed_dirs)
                .await
                .unwrap(),
            None
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    #[tokio::test]
    async fn test_write_path_authorization_requires_explicit_grant_and_allowed_ext() {
        let base = std::env::temp_dir().join(format!(
            "inkstudio_write_auth_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let outside_dir = base.join("outside");
        std::fs::create_dir_all(&outside_dir).unwrap();

        let new_ink = outside_dir.join("FreshArt.ink");
        let bad_ext = outside_dir.join("evil.exe");
        let allowed_dirs: Vec<PathBuf> = Vec::new();

        // Unauthorized new file outside allowed dirs is rejected
        assert!(validate_write_path(new_ink.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        // Granting via dialog pick authorizes writing this specific new .ink path
        register_allowed_write_path(&new_ink);
        assert!(validate_write_path(new_ink.to_str().unwrap(), &allowed_dirs)
            .await
            .is_ok());

        // Disallowed extensions can never be granted or written
        register_allowed_write_path(&bad_ext);
        assert!(validate_write_path(bad_ext.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        if let Ok(resolved) = resolve_canonical_target_path(&new_ink, DIRECT_SAVE_ALLOWED_EXTS) {
            unregister_allowed_path(&resolved);
        }
        assert!(validate_write_path(new_ink.to_str().unwrap(), &allowed_dirs)
            .await
            .is_err());

        let _ = std::fs::remove_dir_all(&base);
    }
}