Skip to content

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

59.9 KB
Raw Blame
//! Phase 6 Native Interactive Tool & Collab Tauri Commands (`native_tools.rs`).
//!
//! Routes Selection Mask & Marching Ants, GPU Liquify, Direct Rust Flood/Smart Fill & Eyedropper,
//! 5-mode Interactive GPU Transform/Warp, Retouch, Gradients, Shapes/QuickShape, Live GPU Filters
//! & Tonal Corrections, Vector/Bézier Rasterization, Multiplayer Collab GPU Drafts & Binary Tile
//! Sync, and Zero-Canvas Image Export/Import straight to `ink-engine` with zero WebView2 canvases.

use crate::native_docs::{self, documents_handle};
use crate::native_engine;
use ink_engine::collab::{
    apply_layer_mask_packet, apply_tile_delta_packet, compute_document_checksum,
    encode_layer_mask_packet, encode_layer_tile_packets, AppliedTileDeltaInfo, RemoteStrokePoint,
    RemoteStrokeStartParams,
};
use ink_engine::document::DocumentMetaSnapshot;
use ink_engine::selection::ops::{
    commit_floating_selection, lift_floating_selection, move_floating_selection,
};
use ink_engine::selection::{
    clear_outside_selection, clear_selection_pixels, copy_selection, cut_selection,
    fill_selection_color, move_selection_to_new_layer, paste_selection, select_lasso,
    select_magic_wand, select_rect, SelectionCombineMode, SelectionFillResult,
    SelectionMetaSnapshot, SparseSelectionMask, WandReferMode,
};
use ink_engine::tiles::{parse_hex_rgba8, RectI32, TileCoord};
use ink_engine::tools::{
    apply_image_op_to_document, commit_gradient_to_document, commit_shape_to_document,
    compute_layer_histogram, enclose_and_fill_document, flood_fill_document, lasso_fill_document,
    paint_unfilled_document, pick_color_document_for_layer, rasterize_bezier_path,
    rasterize_vector_layer,
    recognize_quick_shape, render_gradient_rgba8, render_image_op_preview_rgba, render_shape_rgba8,
    shape_bounds, BezierPathParams, EncloseFillParams, FillOutcome, FilterApplyResult,
    FloodFillParams, GradientCommitResult, GradientParams, ImageOpSpec, LassoFillParams,
    LayerHistogram, LiquifyStepParams, PaintUnfilledParams, PickedColorDto, QuickShapeResult,
    RetouchCommitResult, RetouchStepParams, ShapeCommitResult, ShapeParams, TransformCommitResult,
    TransformMode, TransformSessionSnapshot, TransformUpdatePayload, VectorRasterResult,
    VectorStrokePath,
};
use ink_engine::FlattenOptions;
use serde::{Deserialize, Serialize};
use tauri::Emitter;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiquifyCommitDto {
    pub layer_ids: Vec<String>,
    pub dirty_rect: RectI32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TileCoordDto {
    pub tx: i32,
    pub ty: i32,
}

fn resolve_doc_id(doc_id: Option<&str>) -> Result<String, String> {
    if let Some(id) = doc_id {
        if !id.is_empty() {
            return Ok(id.to_string());
        }
    }
    let docs = documents_handle();
    let mgr = docs.read();
    mgr.active_document()
        .map(|d| d.id.clone())
        .ok_or_else(|| "No active native document".to_string())
}

fn emit_selection_event(app: &tauri::AppHandle, doc_id: String, selection: &SelectionMetaSnapshot) {
    let _ = app.emit(
        native_engine::EVENT_SELECTION_CHANGED,
        native_engine::NativeSelectionChangedPayload {
            doc_id,
            selection: selection.clone(),
        },
    );
}

fn notify_after_doc_mutation(app: &tauri::AppHandle, doc_id: &str, dirty_layer_ids: Vec<String>) {
    let history_opt = {
        let docs = documents_handle();
        let mgr = docs.read();
        mgr.get_document(doc_id).map(|d| d.history.snapshot())
    };
    if let Some(history) = history_opt {
        let _ = app.emit(
            native_engine::EVENT_HISTORY,
            native_engine::NativeHistoryEventPayload {
                doc_id: doc_id.to_string(),
                history,
            },
        );
    }
    native_engine::sync_active_document();
    if !dirty_layer_ids.is_empty() {
        native_docs::spawn_thumbnail_generation(app.clone(), doc_id.to_string(), dirty_layer_ids);
    }
}

// ============================================================================
// 1. Native Selection Mask & GPU Marching Ants
// ============================================================================

#[tauri::command]
pub async fn native_select_rect(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    x: i32,
    y: i32,
    width: u32,
    height: u32,
    mode: Option<SelectionCombineMode>,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let snap = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let s = select_rect(
                    doc,
                    RectI32::new(x, y, width, height),
                    mode.unwrap_or(SelectionCombineMode::Replace),
                );
                doc.dirty_for_render = true;
                s
            };
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Select rect worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_select_lasso(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    points: Vec<[f32; 2]>,
    anti_alias: Option<bool>,
    mode: Option<SelectionCombineMode>,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let poly: Vec<(f32, f32)> = points.into_iter().map(|p| (p[0], p[1])).collect();
            let snap = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let s = select_lasso(
                    doc,
                    &poly,
                    anti_alias.unwrap_or(true),
                    mode.unwrap_or(SelectionCombineMode::Replace),
                );
                doc.dirty_for_render = true;
                s
            };
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Select lasso worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub async fn native_select_magic_wand(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    x: i32,
    y: i32,
    tolerance: Option<f32>,
    contiguous: Option<bool>,
    anti_alias: Option<bool>,
    refer_mode: Option<WandReferMode>,
    mode: Option<SelectionCombineMode>,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let s = select_magic_wand(
                doc,
                x,
                y,
                tolerance.unwrap_or(32.0),
                contiguous.unwrap_or(true),
                anti_alias.unwrap_or(true),
                refer_mode.unwrap_or(WandReferMode::Active),
                mode.unwrap_or(SelectionCombineMode::Replace),
                Some(scratch.as_ref()),
            )?;
            doc.dirty_for_render = true;
            Ok((did, s))
        },
    )
    .await
    .map_err(|e| format!("Magic wand worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_select_all(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let snap = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let sel = SparseSelectionMask::new_all(doc.dimensions.width, doc.dimensions.height);
                let s = sel.snapshot_meta();
                doc.selection = Some(sel);
                doc.dirty_for_render = true;
                s
            };
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Select all worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_deselect(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
    let app_for_worker = app.clone();
    let did = tauri::async_runtime::spawn_blocking(move || -> Result<String, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let mut dirty_layers = Vec::new();
        {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            if let Some(ref sel) = doc.selection {
                if let Some(ref fl) = sel.floating {
                    dirty_layers.push(fl.layer_id.clone());
                }
            }
            if !dirty_layers.is_empty() {
                let _ = commit_floating_selection(doc, Some(scratch.as_ref()));
            }
            doc.selection = None;
            doc.dirty_for_render = true;
        }
        notify_after_doc_mutation(&app_for_worker, &did, dirty_layers);
        Ok(did)
    })
    .await
    .map_err(|e| format!("Deselect worker failed: {e}"))??;
    let empty = SelectionMetaSnapshot::empty();
    emit_selection_event(&app, did, &empty);
    Ok(empty)
}

#[tauri::command]
pub async fn native_selection_invert(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let snap = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let w = doc.dimensions.width;
                let h = doc.dimensions.height;
                let sel = doc
                    .selection
                    .get_or_insert_with(|| SparseSelectionMask::new_empty(w, h));
                sel.invert();
                let s = if sel.is_empty() {
                    doc.selection = None;
                    SelectionMetaSnapshot::empty()
                } else {
                    sel.snapshot_meta()
                };
                doc.dirty_for_render = true;
                s
            };
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Selection invert worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_selection_expand(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    pixels: i32,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let docs = documents_handle();
            let mut mgr = docs.write();
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let s = if let Some(ref mut sel) = doc.selection {
                sel.expand_or_contract(pixels);
                if sel.is_empty() {
                    doc.selection = None;
                    SelectionMetaSnapshot::empty()
                } else {
                    sel.snapshot_meta()
                }
            } else {
                SelectionMetaSnapshot::empty()
            };
            doc.dirty_for_render = true;
            Ok((did, s))
        },
    )
    .await
    .map_err(|e| format!("Selection expand worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_selection_feather(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    radius: f32,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let docs = documents_handle();
            let mut mgr = docs.write();
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let s = if let Some(ref mut sel) = doc.selection {
                sel.feather(radius);
                if sel.is_empty() {
                    doc.selection = None;
                    SelectionMetaSnapshot::empty()
                } else {
                    sel.snapshot_meta()
                }
            } else {
                SelectionMetaSnapshot::empty()
            };
            doc.dirty_for_render = true;
            Ok((did, s))
        },
    )
    .await
    .map_err(|e| format!("Selection feather worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_selection_clear_pixels(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: Option<String>,
) -> Result<SelectionFillResult, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<SelectionFillResult, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let (res, lid) = {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let lid = layer_id
                .or_else(|| doc.active_layer_id.clone())
                .ok_or_else(|| "No active layer".to_string())?;
            let r = clear_selection_pixels(doc, &lid, Some(scratch.as_ref()))?;
            (r, lid)
        };
        if res.modified {
            notify_after_doc_mutation(&app, &did, vec![lid]);
        }
        Ok(res)
    })
    .await
    .map_err(|e| format!("Selection clear pixels worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_clear_outside(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: Option<String>,
) -> Result<SelectionFillResult, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<SelectionFillResult, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let (res, lid) = {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let lid = layer_id
                .or_else(|| doc.active_layer_id.clone())
                .ok_or_else(|| "No active layer".to_string())?;
            let r = clear_outside_selection(doc, &lid, Some(scratch.as_ref()))?;
            (r, lid)
        };
        if res.modified {
            notify_after_doc_mutation(&app, &did, vec![lid]);
        }
        Ok(res)
    })
    .await
    .map_err(|e| format!("Selection clear outside worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_fill_color(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: Option<String>,
    color: String,
    opacity: Option<f32>,
) -> Result<SelectionFillResult, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<SelectionFillResult, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let rgba8 = parse_hex_rgba8(&color).unwrap_or([0, 0, 0, 255]);
        let (res, lid) = {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let lid = layer_id
                .or_else(|| doc.active_layer_id.clone())
                .ok_or_else(|| "No active layer".to_string())?;
            let r = fill_selection_color(
                doc,
                &lid,
                rgba8,
                opacity.unwrap_or(1.0),
                Some(scratch.as_ref()),
            )?;
            (r, lid)
        };
        if res.modified {
            notify_after_doc_mutation(&app, &did, vec![lid]);
        }
        Ok(res)
    })
    .await
    .map_err(|e| format!("Selection fill color worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_copy(
    doc_id: Option<String>,
    layer_id: Option<String>,
) -> Result<bool, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<bool, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = mgr.scratch_backend();
        let clip = {
            let doc = mgr
                .get_document(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let lid = layer_id
                .or_else(|| doc.active_layer_id.clone())
                .ok_or_else(|| "No active layer".to_string())?;
            copy_selection(doc, &lid, Some(scratch.as_ref()))?
        };
        let ok = clip.is_some();
        if let Some(c) = clip {
            mgr.clipboard = Some(c);
        }
        Ok(ok)
    })
    .await
    .map_err(|e| format!("Selection copy worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_cut(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: Option<String>,
) -> Result<bool, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<bool, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let (ok, lid) = {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let (clip, lid) = {
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let lid = layer_id
                    .or_else(|| doc.active_layer_id.clone())
                    .ok_or_else(|| "No active layer".to_string())?;
                let c = cut_selection(doc, &lid, Some(scratch.as_ref()))?;
                (c, lid)
            };
            let ok = clip.is_some();
            if let Some(c) = clip {
                mgr.clipboard = Some(c);
            }
            (ok, lid)
        };
        if ok {
            notify_after_doc_mutation(&app, &did, vec![lid]);
        }
        Ok(ok)
    })
    .await
    .map_err(|e| format!("Selection cut worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_paste(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    new_layer_id: String,
) -> Result<Option<DocumentMetaSnapshot>, String> {
    tauri::async_runtime::spawn_blocking(
        move || -> Result<Option<DocumentMetaSnapshot>, String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let (snap, pasted_id) = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let Some(clip) = mgr.clipboard.clone() else {
                    return Ok(None);
                };
                let scratch = std::sync::Arc::clone(mgr.scratch_backend());
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let lid = paste_selection(doc, &clip, new_layer_id, Some(scratch.as_ref()))?;
                (Some(doc.snapshot_meta()), Some(lid))
            };
            if let Some(lid) = pasted_id {
                notify_after_doc_mutation(&app, &did, vec![lid]);
            }
            Ok(snap)
        },
    )
    .await
    .map_err(|e| format!("Selection paste worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_move_to_new_layer(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    src_layer_id: Option<String>,
    new_layer_id: String,
) -> Result<Option<DocumentMetaSnapshot>, String> {
    tauri::async_runtime::spawn_blocking(
        move || -> Result<Option<DocumentMetaSnapshot>, String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let (snap, dirty) = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let scratch = std::sync::Arc::clone(mgr.scratch_backend());
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let src_id = src_layer_id
                    .or_else(|| doc.active_layer_id.clone())
                    .ok_or_else(|| "No active layer".to_string())?;
                let moved =
                    move_selection_to_new_layer(doc, &src_id, new_layer_id, Some(scratch.as_ref()))?;
                if let Some(new_id) = moved {
                    (Some(doc.snapshot_meta()), vec![src_id, new_id])
                } else {
                    (None, Vec::new())
                }
            };
            if !dirty.is_empty() {
                notify_after_doc_mutation(&app, &did, dirty);
            }
            Ok(snap)
        },
    )
    .await
    .map_err(|e| format!("Selection move to new layer worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_selection_lift_floating(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let snap = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let scratch = std::sync::Arc::clone(mgr.scratch_backend());
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let lid = layer_id
                    .or_else(|| doc.active_layer_id.clone())
                    .ok_or_else(|| "No active layer".to_string())?;
                lift_floating_selection(doc, &lid, Some(scratch.as_ref()))?
            };
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Selection lift floating worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_selection_move_floating(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    x: i32,
    y: i32,
) -> Result<SelectionMetaSnapshot, String> {
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let snap = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                move_floating_selection(doc, x, y)
            };
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Selection move floating worker failed: {e}"))??;
    native_engine::sync_active_document();
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_selection_commit_floating(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
    let app_for_worker = app.clone();
    let (did, snap) = tauri::async_runtime::spawn_blocking(
        move || -> Result<(String, SelectionMetaSnapshot), String> {
            let did = resolve_doc_id(doc_id.as_deref())?;
            let (snap, dirty) = {
                let docs = documents_handle();
                let mut mgr = docs.write();
                let scratch = std::sync::Arc::clone(mgr.scratch_backend());
                let doc = mgr
                    .get_document_mut(&did)
                    .ok_or_else(|| format!("Document not found: {did}"))?;
                let fl_layer = doc
                    .selection
                    .as_ref()
                    .and_then(|s| s.floating.as_ref().map(|f| f.layer_id.clone()));
                let s = commit_floating_selection(doc, Some(scratch.as_ref()))?;
                (s, fl_layer.into_iter().collect::<Vec<_>>())
            };
            notify_after_doc_mutation(&app_for_worker, &did, dirty);
            Ok((did, snap))
        },
    )
    .await
    .map_err(|e| format!("Selection commit floating worker failed: {e}"))??;
    emit_selection_event(&app, did, &snap);
    Ok(snap)
}

#[tauri::command]
pub async fn native_selection_get_state(
    doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<SelectionMetaSnapshot, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let docs = documents_handle();
        let mgr = docs.read();
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        Ok(doc
            .selection
            .as_ref()
            .map(|s| s.snapshot_meta())
            .unwrap_or_else(SelectionMetaSnapshot::empty))
    })
    .await
    .map_err(|e| format!("Selection get state worker failed: {e}"))?
}

// ============================================================================
// 2. Interactive DX12 GPU Liquify
// ============================================================================

#[tauri::command]
pub async fn native_liquify_begin(
    multi_layer: Option<bool>,
    layer_ids: Option<Vec<String>>,
) -> Result<Vec<String>, String> {
    tokio::task::spawn_blocking(move || {
        native_engine::liquify_begin(multi_layer.unwrap_or(false), layer_ids)
    })
    .await
    .map_err(|e| format!("Liquify begin worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_liquify_step_gpu(step: LiquifyStepParams) -> Result<RectI32, String> {
    tokio::task::spawn_blocking(move || native_engine::liquify_step(step))
        .await
        .map_err(|e| format!("Liquify GPU step worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_liquify_commit(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<LiquifyCommitDto, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let (layer_ids, dirty_rect) = tokio::task::spawn_blocking(native_engine::liquify_commit)
        .await
        .map_err(|e| format!("Liquify commit worker failed: {e}"))??;
    if !layer_ids.is_empty() {
        notify_after_doc_mutation(&app, &did, layer_ids.clone());
    }
    Ok(LiquifyCommitDto {
        layer_ids,
        dirty_rect,
    })
}

#[tauri::command]
pub fn native_liquify_cancel() {
    native_engine::liquify_cancel();
}

// ============================================================================
// 3. Direct Rust Flood Fill, Lasso Fill, Smart Line Fill & Eyedropper
// ============================================================================

#[tauri::command]
pub async fn native_flood_fill_doc(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: FloodFillParams,
) -> Result<FillOutcome, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<FillOutcome, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        flood_fill_document(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Flood fill worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_lasso_fill_doc(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: LassoFillParams,
) -> Result<FillOutcome, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<FillOutcome, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        lasso_fill_document(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Lasso fill worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_enclose_fill_doc(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: EncloseFillParams,
) -> Result<FillOutcome, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<FillOutcome, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        enclose_and_fill_document(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Enclose fill worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_paint_unfilled_doc(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: PaintUnfilledParams,
) -> Result<FillOutcome, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<FillOutcome, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        paint_unfilled_document(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Paint unfilled worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_pick_color(
    doc_id: Option<String>,
    x: i32,
    y: i32,
    sample_all_layers: Option<bool>,
    layer_id: Option<String>,
) -> Result<PickedColorDto, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<PickedColorDto, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let docs = documents_handle();
        let mgr = docs.read();
        let scratch = mgr.scratch_backend();
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        Ok(pick_color_document_for_layer(
            doc,
            x,
            y,
            sample_all_layers.unwrap_or(true),
            layer_id.as_deref(),
            Some(scratch.as_ref()),
        ))
    })
    .await
    .map_err(|e| format!("Pick color worker failed: {e}"))?
}

// ============================================================================
// 4. Interactive 5-Mode GPU Transform & Warp
// ============================================================================

#[tauri::command]
pub async fn native_transform_begin(
    mode: TransformMode,
    layer_ids: Option<Vec<String>>,
) -> Result<TransformSessionSnapshot, String> {
    tokio::task::spawn_blocking(move || native_engine::transform_begin(mode, layer_ids))
        .await
        .map_err(|e| format!("Transform begin worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_transform_update(
    payload: TransformUpdatePayload,
) -> Result<TransformSessionSnapshot, String> {
    tokio::task::spawn_blocking(move || native_engine::transform_update(payload))
        .await
        .map_err(|e| format!("Transform update worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_transform_switch_mode(
    next_mode: TransformMode,
) -> Result<TransformSessionSnapshot, String> {
    tokio::task::spawn_blocking(move || native_engine::transform_switch_mode(next_mode))
        .await
        .map_err(|e| format!("Transform switch_mode worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_transform_commit(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<TransformCommitResult, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let res = tokio::task::spawn_blocking(native_engine::transform_commit)
        .await
        .map_err(|e| format!("Transform commit worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, res.layer_ids.clone());
    }
    Ok(res)
}

#[tauri::command]
pub fn native_transform_cancel() {
    native_engine::transform_cancel();
}

// ============================================================================
// 5. Direct Rust Retouch (Clone Stamp, Heal, Dodge/Burn/Sponge, Smudge/Blur)
// ============================================================================

#[tauri::command]
pub async fn native_retouch_step(
    doc_id: Option<String>,
    params: RetouchStepParams,
) -> Result<RectI32, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let dirty = tokio::task::spawn_blocking(move || -> Result<RectI32, String> {
        let sess_arc = native_engine::retouch_session();
        let mut sess = sess_arc
            .lock()
            .map_err(|_| "Retouch session lock poisoned".to_string())?;
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        let r = sess.apply_step(doc, &params, Some(scratch.as_ref()))?;
        doc.dirty_for_render = true;
        Ok(r)
    })
    .await
    .map_err(|e| format!("Retouch step worker failed: {e}"))??;
    native_engine::sync_active_document();
    Ok(dirty)
}

#[tauri::command]
pub async fn native_retouch_commit(
    app: tauri::AppHandle,
    doc_id: Option<String>,
) -> Result<RetouchCommitResult, String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<RetouchCommitResult, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let res = {
            let sess_arc = native_engine::retouch_session();
            let mut sess = sess_arc
                .lock()
                .map_err(|_| "Retouch session lock poisoned".to_string())?;
            let docs = documents_handle();
            let mut mgr = docs.write();
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            sess.commit(doc)
        };
        if res.modified {
            notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
        }
        Ok(res)
    })
    .await
    .map_err(|e| format!("Retouch commit worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_retouch_cancel(doc_id: Option<String>) -> Result<(), String> {
    tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
        let did = resolve_doc_id(doc_id.as_deref()).ok();
        let sess_arc = native_engine::retouch_session();
        let mut sess = sess_arc
            .lock()
            .map_err(|_| "Retouch session lock poisoned".to_string())?;
        let docs = documents_handle();
        let mut mgr = docs.write();
        let doc_opt = did.as_deref().and_then(|id| mgr.get_document_mut(id));
        sess.cancel(doc_opt);
        drop(mgr);
        native_engine::sync_active_document();
        Ok(())
    })
    .await
    .map_err(|e| format!("Retouch cancel worker failed: {e}"))?
}

// ============================================================================
// 6. Gradients, Shapes & QuickShape (Live GPU Preview + Commit)
// ============================================================================

#[tauri::command]
pub async fn native_gradient_preview(
    doc_id: Option<String>,
    params: GradientParams,
) -> Result<RectI32, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let (rect, rgba) = tokio::task::spawn_blocking(move || -> Result<(RectI32, Vec<u8>), String> {
        let docs = documents_handle();
        let mgr = docs.read();
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
        let target = doc
            .selection
            .as_ref()
            .filter(|s| !s.is_empty())
            .map(|s| s.bounds.intersect(doc_rect))
            .filter(|r| !r.is_empty())
            .unwrap_or(doc_rect);
        let mut rgba = render_gradient_rgba8(&params, target);
        if let Some(ref sel) = doc.selection {
            if !sel.is_empty() {
                let mask = sel.read_rect(target);
                for (i, &m) in mask.iter().enumerate() {
                    let a = (rgba[i * 4 + 3] as u32 * m as u32 + 127) / 255;
                    rgba[i * 4 + 3] = a as u8;
                }
            }
        }
        Ok((target, rgba))
    })
    .await
    .map_err(|e| format!("Gradient preview worker failed: {e}"))??;
    native_engine::set_tool_preview_rgba8(rect, rgba, 1.0, None);
    Ok(rect)
}

#[tauri::command]
pub async fn native_gradient_commit(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: GradientParams,
) -> Result<GradientCommitResult, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<GradientCommitResult, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        commit_gradient_to_document(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Gradient commit worker failed: {e}"))??;
    native_engine::clear_tool_preview();
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_shape_preview(
    doc_id: Option<String>,
    params: ShapeParams,
) -> Result<RectI32, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let (rect, rgba) = tokio::task::spawn_blocking(move || -> Result<(RectI32, Vec<u8>), String> {
        let docs = documents_handle();
        let mgr = docs.read();
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        let rect = shape_bounds(&params, doc.dimensions.width, doc.dimensions.height);
        if rect.is_empty() {
            return Ok((rect, Vec::new()));
        }
        let rgba = render_shape_rgba8(&params, rect);
        Ok((rect, rgba))
    })
    .await
    .map_err(|e| format!("Shape preview worker failed: {e}"))??;
    if rect.is_empty() {
        native_engine::clear_tool_preview();
    } else {
        native_engine::set_tool_preview_rgba8(rect, rgba, 1.0, None);
    }
    Ok(rect)
}

#[tauri::command]
pub async fn native_shape_commit(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: ShapeParams,
) -> Result<ShapeCommitResult, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<ShapeCommitResult, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        commit_shape_to_document(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Shape commit worker failed: {e}"))??;
    native_engine::clear_tool_preview();
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub fn native_recognize_quick_shape(points: Vec<[f32; 2]>) -> QuickShapeResult {
    recognize_quick_shape(&points)
}

#[tauri::command]
pub fn native_clear_tool_preview() {
    native_engine::clear_tool_preview();
}

// ============================================================================
// 7. Live GPU Filters, Tonal Corrections & Layer Histogram
// ============================================================================

#[tauri::command]
pub async fn native_image_op_preview(
    doc_id: Option<String>,
    layer_id: Option<String>,
    op: ImageOpSpec,
) -> Result<RectI32, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let (lid, rect, rgba, opacity) =
        tokio::task::spawn_blocking(move || -> Result<(String, RectI32, Vec<u8>, f32), String> {
            let docs = documents_handle();
            let mgr = docs.read();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            let (lid, rect, rgba) =
                render_image_op_preview_rgba(doc, layer_id.as_deref(), &op, Some(scratch.as_ref()))?;
            let op_val = doc.layer(&lid).map(|l| l.meta.opacity).unwrap_or(1.0);
            Ok((lid, rect, rgba, op_val))
        })
        .await
        .map_err(|e| format!("Image op preview worker failed: {e}"))??;
    if rect.is_empty() {
        native_engine::clear_tool_preview();
    } else {
        native_engine::set_tool_preview_rgba8(rect, rgba, opacity, Some(lid));
    }
    Ok(rect)
}

#[tauri::command]
pub async fn native_image_op_apply(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: Option<String>,
    op: ImageOpSpec,
) -> Result<FilterApplyResult, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<FilterApplyResult, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        apply_image_op_to_document(doc, layer_id.as_deref(), &op, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Image op apply worker failed: {e}"))??;
    native_engine::clear_tool_preview();
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_layer_histogram(
    doc_id: Option<String>,
    layer_id: Option<String>,
) -> Result<LayerHistogram, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    tokio::task::spawn_blocking(move || -> Result<LayerHistogram, String> {
        let docs = documents_handle();
        let mgr = docs.read();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        compute_layer_histogram(doc, layer_id.as_deref(), Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Histogram worker failed: {e}"))?
}

// ============================================================================
// 8. Vector Layer & Bézier Pen Fast Rasterization
// ============================================================================

#[tauri::command]
pub async fn native_rasterize_vector_layer(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    layer_id: String,
    strokes: Vec<VectorStrokePath>,
    record_history: Option<bool>,
) -> Result<VectorRasterResult, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<VectorRasterResult, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        rasterize_vector_layer(
            doc,
            &layer_id,
            &strokes,
            record_history.unwrap_or(true),
            Some(scratch.as_ref()),
        )
    })
    .await
    .map_err(|e| format!("Vector raster worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

#[tauri::command]
pub async fn native_rasterize_bezier(
    app: tauri::AppHandle,
    doc_id: Option<String>,
    params: BezierPathParams,
) -> Result<VectorRasterResult, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let did_clone = did.clone();
    let res = tokio::task::spawn_blocking(move || -> Result<VectorRasterResult, String> {
        let docs = documents_handle();
        let mut mgr = docs.write();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document_mut(&did_clone)
            .ok_or_else(|| format!("Document not found: {did_clone}"))?;
        rasterize_bezier_path(doc, &params, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Bezier raster worker failed: {e}"))??;
    if res.modified {
        notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
    }
    Ok(res)
}

// ============================================================================
// 9. Multiplayer Collab GPU Draft Fast-Path & Direct Binary Tile Delta Sync
// ============================================================================

#[tauri::command]
pub fn native_collab_remote_stroke_start(params: RemoteStrokeStartParams) {
    native_engine::remote_stroke_start(params);
}

#[tauri::command]
pub fn native_collab_remote_stroke_chunk(
    peer_id: String,
    stroke_id: String,
    points: Vec<RemoteStrokePoint>,
) {
    native_engine::remote_stroke_chunk(peer_id, stroke_id, points);
}

#[tauri::command]
pub fn native_collab_remote_stroke_finish(
    peer_id: String,
    stroke_id: String,
    expected_tiles: Option<u32>,
) {
    native_engine::remote_stroke_finish(peer_id, stroke_id, expected_tiles.unwrap_or(0));
}

#[tauri::command]
pub fn native_collab_remote_stroke_dispose(peer_id: String, stroke_id: String) {
    native_engine::remote_stroke_dispose(peer_id, stroke_id);
}

#[tauri::command]
pub fn native_collab_remote_peer_dispose(peer_id: String) {
    native_engine::remote_peer_dispose(peer_id);
}

/// Encodes selected (or all) tiles of a layer into a length-prefixed binary batch:
/// `[count: u32 LE, (len: u32 LE, tile_packet_bytes...)...]`, byte-for-byte compatible
/// with `src-tauri/src/server.rs` `CODE_TILE_DELTA`!
#[tauri::command]
pub async fn native_collab_encode_tiles(
    doc_id: Option<String>,
    layer_id: String,
    coords: Option<Vec<TileCoordDto>>,
) -> Result<tauri::ipc::Response, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let packed = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, String> {
        let docs = documents_handle();
        let mgr = docs.read();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        let coord_vec: Option<Vec<TileCoord>> =
            coords.map(|v| v.into_iter().map(|c| TileCoord::new(c.tx, c.ty)).collect());
        let packets =
            encode_layer_tile_packets(doc, &layer_id, coord_vec.as_deref(), Some(scratch.as_ref()))?;
        let total: usize = 4 + packets.iter().map(|p| 4 + p.len()).sum::<usize>();
        let mut out = Vec::with_capacity(total);
        out.extend_from_slice(&(packets.len() as u32).to_le_bytes());
        for pkt in packets {
            out.extend_from_slice(&(pkt.len() as u32).to_le_bytes());
            out.extend_from_slice(&pkt);
        }
        Ok(out)
    })
    .await
    .map_err(|e| format!("Collab encode tiles worker failed: {e}"))??;
    Ok(tauri::ipc::Response::new(packed))
}

/// Applies a single binary `CODE_TILE_DELTA` packet directly into Rust's `SparseLayerGrid`,
/// notifies the DX12 GPU remote draft manager for zero-flicker handoff, and triggers redraw!
#[tauri::command]
pub async fn native_collab_apply_tile_delta(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<AppliedTileDeltaInfo, String> {
    let doc_id_hdr = request
        .headers()
        .get("x-doc-id")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty());
    let layer_id = request
        .headers()
        .get("x-layer-id")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| "Missing x-layer-id header".to_string())?;
    let bump_epoch = request
        .headers()
        .get("x-bump-epoch")
        .and_then(|v| v.to_str().ok())
        .map(|s| s == "1" || s.eq_ignore_ascii_case("true"))
        .unwrap_or(true);
    let body = match request.body() {
        tauri::ipc::InvokeBody::Raw(bytes) => bytes.to_vec(),
        _ => return Err("Expected raw binary tile delta body".to_string()),
    };

    tauri::async_runtime::spawn_blocking(move || -> Result<AppliedTileDeltaInfo, String> {
        let did = resolve_doc_id(doc_id_hdr.as_deref())?;
        let info = {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            apply_tile_delta_packet(doc, &layer_id, &body, bump_epoch, Some(scratch.as_ref()))?
        };
        native_engine::remote_notify_tile_delta(layer_id.clone());
        native_engine::sync_active_document();
        native_docs::spawn_thumbnail_generation(app, did, vec![layer_id]);
        Ok(info)
    })
    .await
    .map_err(|e| format!("Collab apply tile delta worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_collab_encode_mask(
    doc_id: Option<String>,
    layer_id: String,
) -> Result<tauri::ipc::Response, String> {
    let bytes = tauri::async_runtime::spawn_blocking(move || -> Result<Vec<u8>, String> {
        let did = resolve_doc_id(doc_id.as_deref())?;
        let docs = documents_handle();
        let mgr = docs.read();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        encode_layer_mask_packet(doc, &layer_id, Some(scratch.as_ref()))
    })
    .await
    .map_err(|e| format!("Collab encode mask worker failed: {e}"))??;
    Ok(tauri::ipc::Response::new(bytes))
}

#[tauri::command]
pub async fn native_collab_apply_mask(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<(), String> {
    let doc_id_hdr = request
        .headers()
        .get("x-doc-id")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty());
    let layer_id = request
        .headers()
        .get("x-layer-id")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| "Missing x-layer-id header".to_string())?;
    let body = match request.body() {
        tauri::ipc::InvokeBody::Raw(bytes) => bytes.to_vec(),
        _ => return Err("Expected raw binary layer mask body".to_string()),
    };

    tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
        let did = resolve_doc_id(doc_id_hdr.as_deref())?;
        {
            let docs = documents_handle();
            let mut mgr = docs.write();
            let scratch = std::sync::Arc::clone(mgr.scratch_backend());
            let doc = mgr
                .get_document_mut(&did)
                .ok_or_else(|| format!("Document not found: {did}"))?;
            apply_layer_mask_packet(doc, &layer_id, &body, Some(scratch.as_ref()))?;
        }
        native_engine::sync_active_document();
        native_docs::spawn_thumbnail_generation(app, did, vec![layer_id]);
        Ok(())
    })
    .await
    .map_err(|e| format!("Collab apply mask worker failed: {e}"))?
}

#[tauri::command]
pub async fn native_collab_checksum(doc_id: Option<String>) -> Result<String, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    tokio::task::spawn_blocking(move || -> Result<String, String> {
        let docs = documents_handle();
        let mgr = docs.read();
        let scratch = std::sync::Arc::clone(mgr.scratch_backend());
        let doc = mgr
            .get_document(&did)
            .ok_or_else(|| format!("Document not found: {did}"))?;
        Ok(compute_document_checksum(doc, Some(scratch.as_ref())))
    })
    .await
    .map_err(|e| format!("Collab checksum worker failed: {e}"))?
}

// ============================================================================
// 10. Zero-Canvas Image Export, Import & Layer Read (for PNG/JPEG/WebP/PSD)
// ============================================================================

#[tauri::command]
pub async fn native_engine_export_image(
    doc_id: Option<String>,
    format: String,
    quality: Option<f32>,
    options: Option<FlattenOptions>,
) -> Result<tauri::ipc::Response, String> {
    let q = quality.unwrap_or(0.92);
    let opts = options.unwrap_or_default();
    let (_, _, encoded) = tokio::task::spawn_blocking(move || {
        native_docs::export_document_image_bytes(doc_id, &format, q, opts)
    })
    .await
    .map_err(|e| format!("Native image export worker failed: {e}"))??;
    Ok(tauri::ipc::Response::new(encoded))
}

#[tauri::command]
pub async fn native_engine_import_image_layer(
    app: tauri::AppHandle,
    request: tauri::ipc::Request<'_>,
) -> Result<DocumentMetaSnapshot, String> {
    let doc_id_hdr = request
        .headers()
        .get("x-doc-id")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty());
    let layer_id = request
        .headers()
        .get("x-layer-id")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| "Missing x-layer-id header".to_string())?;
    let name = request
        .headers()
        .get("x-name")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| crate::percent_decode(s).ok())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "Imported Image".to_string());
    let offset_x = request
        .headers()
        .get("x-offset-x")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<i32>().ok());
    let offset_y = request
        .headers()
        .get("x-offset-y")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<i32>().ok());
    let record_history = request
        .headers()
        .get("x-record-history")
        .and_then(|v| v.to_str().ok())
        .map(|s| s != "0" && !s.eq_ignore_ascii_case("false"))
        .unwrap_or(true);
    let owned = match request.body() {
        tauri::ipc::InvokeBody::Raw(bytes) => bytes.to_vec(),
        _ => return Err("Expected raw binary image bytes".to_string()),
    };
    let did = resolve_doc_id(doc_id_hdr.as_deref())?;
    let did_for_emit = did.clone();
    let snap = tokio::task::spawn_blocking(move || {
        native_docs::import_image_as_layer(
            &did,
            layer_id,
            name,
            &owned,
            offset_x,
            offset_y,
            record_history,
        )
    })
    .await
    .map_err(|e| format!("Image import worker failed: {e}"))??;
    if record_history {
        let _ = app.emit(
            native_engine::EVENT_HISTORY,
            native_engine::NativeHistoryEventPayload {
                doc_id: did_for_emit,
                history: snap.history.clone(),
            },
        );
    }
    Ok(snap)
}

/// Returns tight non-empty layer pixels as `[has: u8, x: i32 LE, y: i32 LE, w: u32 LE, h: u32 LE, rgba8...]`
/// so PSD export can pass `ImageData` straight to `ag-psd` without allocating any `<canvas>`.
#[tauri::command]
pub async fn native_engine_read_layer_rgba(
    doc_id: Option<String>,
    layer_id: String,
) -> Result<tauri::ipc::Response, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let bytes = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, String> {
        let Some((x, y, w, h, rgba)) = native_docs::read_layer_bounds_rgba(&did, &layer_id)? else {
            return Ok(vec![0u8]);
        };
        let mut out = Vec::with_capacity(17 + rgba.len());
        out.push(1u8);
        out.extend_from_slice(&x.to_le_bytes());
        out.extend_from_slice(&y.to_le_bytes());
        out.extend_from_slice(&w.to_le_bytes());
        out.extend_from_slice(&h.to_le_bytes());
        out.extend_from_slice(&rgba);
        Ok(out)
    })
    .await
    .map_err(|e| format!("Read layer RGBA worker failed: {e}"))??;
    Ok(tauri::ipc::Response::new(bytes))
}

/// Returns layer mask as `[has: u8, default_val: u8, w: u32 LE, h: u32 LE, rgba8...]` for zero-canvas PSD export.
#[tauri::command]
pub async fn native_engine_read_layer_mask_rgba(
    doc_id: Option<String>,
    layer_id: String,
) -> Result<tauri::ipc::Response, String> {
    let did = resolve_doc_id(doc_id.as_deref())?;
    let bytes = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, String> {
        let Some((w, h, def_val, rgba)) = native_docs::read_layer_mask_rgba(&did, &layer_id)? else {
            return Ok(vec![0u8]);
        };
        let mut out = Vec::with_capacity(10 + rgba.len());
        out.push(1u8);
        out.push(def_val);
        out.extend_from_slice(&w.to_le_bytes());
        out.extend_from_slice(&h.to_le_bytes());
        out.extend_from_slice(&rgba);
        Ok(out)
    })
    .await
    .map_err(|e| format!("Read layer mask worker failed: {e}"))??;
    Ok(tauri::ipc::Response::new(bytes))
}