A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
//! Phase 2 In-Process Rust Document Store, Zero-Copy `.clip`/`.psd`/`.ink` Hydration,
//! In-Process Scratch Disk Backend, Async Thumbnails, Timelapse & Crash Recovery Bridge.
//!
//! Eliminates all full-res pixel IPC between React and Rust: React receives ONLY compact
//! metadata (`DocumentMetaSnapshot`, `HistoryStateSnapshot`, `MemoryStats`) and tiny 64x64
//! layer/mask thumbnails.
use crate::clip_parser;
use crate::doc_wire::ParsedDocumentAssembled;
use crate::native_engine;
use crate::psd_parser;
use crate::recovery;
use crate::scratch_disk;
use crate::timelapse;
use ink_engine::document::{
BlendMode, CanvasColorMode, CanvasDimensions, Document, DocumentManager, DocumentMetaSnapshot,
ExpressionColor, LayerNode, LayerNodeMeta, LayerPropsPatch, LayerType,
};
use ink_engine::history::{HistoryItemMeta, HistoryStateSnapshot, SelectiveUndoOutcome};
use ink_engine::io::{
compositor_cpu, encode_document_checkpoint, encode_rgba8_to_png, parse_ink_document,
png_bytes_to_data_url, replay_recovery_into_document, serialize_ink_document,
SerializedInkResult, WalRawEntry,
};
use ink_engine::memory::{MemoryBudgetConfig, MemoryStats, ScratchBackend, ScratchTileWrite};
use ink_engine::tiles::{
parse_hex_rgba8, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind,
};
use ink_engine::{FlattenOptions, ThumbnailUpdate};
use parking_lot::RwLock;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock, Mutex};
use tauri::Emitter;
/// In-process [`ScratchBackend`] wired directly into `src-tauri/src/scratch_disk.rs`
/// with zero Tauri IPC overhead.
pub struct TauriScratchDiskBackend;
impl ScratchBackend for TauriScratchDiskBackend {
fn init_session(&self, session_id: &str) -> Result<(), String> {
scratch_disk::init_scratch_disk_sync(session_id).map(|_| ())
}
fn write_tiles(&self, session_id: &str, tiles: Vec<ScratchTileWrite>) -> Result<usize, String> {
let payloads = tiles
.into_iter()
.map(|t| scratch_disk::TileWritePayload {
layer_id: t.layer_key,
tile_x: t.tx,
tile_y: t.ty,
data: t.data,
})
.collect();
scratch_disk::write_tiles_sync(session_id, payloads)
}
fn read_tile(
&self,
session_id: &str,
layer_key: &str,
tx: i32,
ty: i32,
) -> Result<Vec<u8>, String> {
scratch_disk::read_tile_sync(session_id, layer_key, tx, ty)
}
fn clear_session(&self, session_id: &str) -> Result<(), String> {
scratch_disk::clear_scratch_disk_sync(session_id)
}
}
static ATTACHED_DOCS: LazyLock<Mutex<Option<Arc<RwLock<DocumentManager>>>>> =
LazyLock::new(|| Mutex::new(None));
static FALLBACK_DOCS: LazyLock<Arc<RwLock<DocumentManager>>> = LazyLock::new(|| {
Arc::new(RwLock::new(DocumentManager::new(
MemoryBudgetConfig::default(),
Arc::new(TauriScratchDiskBackend),
)))
});
/// Attaches the active `EngineHandle`'s shared `DocumentManager` so all Tauri commands operate
/// on the exact same in-memory document store that the DX12 render thread reads.
pub fn attach_engine_documents(docs: Arc<RwLock<DocumentManager>>) {
if let Ok(mut guard) = ATTACHED_DOCS.lock() {
*guard = Some(docs);
}
}
/// Detaches the DX12 `EngineHandle`'s `DocumentManager` on shutdown.
pub fn detach_engine_documents() {
if let Ok(mut guard) = ATTACHED_DOCS.lock() {
*guard = None;
}
}
/// Returns the active [`DocumentManager`] handle (either the running DX12 engine's store or
/// the in-process fallback store for headless/test execution).
pub fn documents_handle() -> Arc<RwLock<DocumentManager>> {
if let Ok(guard) = ATTACHED_DOCS.lock() {
if let Some(ref docs) = *guard {
return Arc::clone(docs);
}
}
Arc::clone(&FALLBACK_DOCS)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenNativeDocumentResult {
pub doc: DocumentMetaSnapshot,
pub preview_data_url: Option<String>,
pub source_format: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SaveNativeInkResult {
pub path: Option<String>,
pub bytes_written: usize,
pub preview_data_url: Option<String>,
pub tile_count: usize,
pub mask_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeHistoryMutationResult {
pub doc: DocumentMetaSnapshot,
pub dimensions_changed: bool,
pub layers_changed: bool,
pub changed_layer_ids: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub document_state_delta: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selective_outcome: Option<SelectiveUndoOutcome>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeMemoryBudgetInput {
#[serde(default)]
pub ram_budget_mb: Option<u64>,
#[serde(default)]
pub vram_budget_mb: Option<u64>,
#[serde(default)]
pub max_history_steps: Option<usize>,
#[serde(default)]
pub offload_inactive_tabs: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeTimelapseCaptureResult {
pub width: u32,
pub height: u32,
pub bytes: usize,
pub frame_index: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeRecoveryCheckpointResult {
pub snapshot_bytes: usize,
pub thumbnail_bytes: usize,
}
fn parse_blend_mode_str(s: &str) -> BlendMode {
serde_json::from_value(serde_json::Value::String(s.to_string())).unwrap_or(BlendMode::Normal)
}
fn parse_expression_color_str(s: Option<&str>) -> Option<ExpressionColor> {
match s {
Some("monochrome") => Some(ExpressionColor::Monochrome),
Some("gray") => Some(ExpressionColor::Gray),
Some("color") => Some(ExpressionColor::Color),
_ => None,
}
}
pub(crate) fn render_layer_thumb_url(
node: &LayerNode,
doc_w: u32,
doc_h: u32,
scratch: Option<&dyn ScratchBackend>,
) -> Option<String> {
let (tw, th, rgba) =
compositor_cpu::render_layer_thumbnail_rgba(node, doc_w, doc_h, 64, 64, scratch).ok()?;
let png = encode_rgba8_to_png(tw, th, &rgba).ok()?;
Some(png_bytes_to_data_url(&png))
}
pub(crate) fn render_mask_thumb_url(
node: &LayerNode,
doc_w: u32,
doc_h: u32,
scratch: Option<&dyn ScratchBackend>,
) -> Option<String> {
let (tw, th, rgba) =
compositor_cpu::render_mask_thumbnail_rgba(node, doc_w, doc_h, 64, 64, scratch).ok()?;
let png = encode_rgba8_to_png(tw, th, &rgba).ok()?;
Some(png_bytes_to_data_url(&png))
}
/// Hydrates a [`ParsedDocumentAssembled`] (from `.clip` or `.psd`/`.psb`) directly into an
/// `ink-engine` [`Document`] in parallel using Rayon — zero `INKD` serialization and zero
/// JS pixel copies!
pub fn hydrate_assembled_document(
parsed: ParsedDocumentAssembled,
doc_id: impl Into<String>,
name: impl Into<String>,
max_history_steps: usize,
) -> (Document, Option<String>) {
let color_mode = match parsed.color_mode.as_str() {
"grayscale" => CanvasColorMode::Grayscale,
_ => CanvasColorMode::Color,
};
let dims = CanvasDimensions {
width: parsed.width.max(1),
height: parsed.height.max(1),
dpi: parsed.dpi.max(1),
};
let preview_data_url = parsed
.preview
.as_ref()
.map(|(bytes, mime)| format!("data:{};base64,{}", mime, ink_engine::io::to_base64(bytes)));
// Parallel hydrate each layer's sparse tiles, masks, and 64x64 thumbnails
let mut layer_nodes: Vec<LayerNode> = parsed
.layers
.into_par_iter()
.map(|al| {
let is_folder = al.layer_type == "folder";
let expr = parse_expression_color_str(al.expression_color.as_deref());
let tile_fmt = expr
.map(|e| e.to_tile_format())
.unwrap_or(TileFormat::Color32Bit);
let mut meta = if is_folder {
LayerNodeMeta::new_folder(al.id.clone(), al.name.clone())
} else {
LayerNodeMeta::new_raster(al.id.clone(), al.name.clone())
};
meta.visible = al.visible;
meta.opacity = al.opacity.clamp(0.0, 1.0);
meta.blend_mode = parse_blend_mode_str(&al.blend_mode);
meta.locked = al.locked;
meta.alpha_locked = Some(al.alpha_locked);
meta.clipped = Some(al.clipped);
meta.collapsed = Some(al.collapsed);
meta.parent_id = al.parent_id.clone();
meta.expression_color = expr;
meta.mono_express_black = al.mono_express_black;
meta.mono_express_white = al.mono_express_white;
meta.layer_color_enabled = al.layer_color_enabled;
meta.layer_color = al.layer_color.clone();
meta.layer_sub_color = al.layer_sub_color.clone();
let mut grid = SparseLayerGrid::new(tile_fmt);
if !is_folder {
if let Some(ref hex) = al.solid_fill_hex {
if let Some(rgba) = parse_hex_rgba8(hex) {
grid.fill_solid_layer(dims.width, dims.height, rgba);
}
}
for raw_tile in al.tiles {
let coord = TileCoord::new(raw_tile.tx, raw_tile.ty);
// Convert RGBA8 tile into target expression format + auto-compact uniform solid tiles
let td = match tile_fmt {
TileFormat::Color32Bit => TileData::from_raw_auto_compact(
TileFormat::Color32Bit,
TileKind::Raster,
raw_tile.rgba,
),
TileFormat::Grayscale8Bit => {
let mut gray = vec![0u8; ink_engine::tiles::BYTES_8BIT];
ink_engine::tiles::pack_rgba8_to_8bit(&raw_tile.rgba, &mut gray);
TileData::from_raw_auto_compact(
TileFormat::Grayscale8Bit,
TileKind::Raster,
gray,
)
}
TileFormat::Monochrome1Bit => {
let mut mono = vec![0u8; ink_engine::tiles::BYTES_1BIT];
ink_engine::tiles::pack_rgba8_to_1bit(&raw_tile.rgba, &mut mono, 128);
TileData::from_raw_auto_compact(
TileFormat::Monochrome1Bit,
TileKind::Raster,
mono,
)
}
TileFormat::Rgba16Float => {
let mut f16b = vec![0u8; ink_engine::tiles::BYTES_16F];
ink_engine::tiles::rgba8_to_rgba16f(&raw_tile.rgba, &mut f16b);
TileData::from_raw_auto_compact(
TileFormat::Rgba16Float,
TileKind::Raster,
f16b,
)
}
TileFormat::Height16Float => TileData::from_raw_auto_compact(
TileFormat::Color32Bit,
TileKind::Raster,
raw_tile.rgba,
),
};
grid.tiles.insert(coord, Arc::new(td));
}
if !grid.tiles.is_empty() {
grid.mark_all_lods_dirty();
}
}
if let Some(raw_mask) = al.mask {
grid.init_mask(raw_mask.default_color);
if raw_mask.width > 0 && raw_mask.height > 0 && !raw_mask.gray.is_empty() {
let rect = RectI32::new(
raw_mask.left,
raw_mask.top,
raw_mask.width,
raw_mask.height,
);
let _ = grid.write_mask8_rect(&raw_mask.gray, rect, None);
}
meta.has_mask = true;
meta.mask_enabled = Some(raw_mask.enabled);
meta.mask_linked = Some(raw_mask.linked);
}
let mut node = LayerNode { meta, grid };
if !is_folder && !node.grid.tiles.is_empty() {
node.meta.thumbnail_url = render_layer_thumb_url(&node, dims.width, dims.height, None);
}
if node.grid.has_mask {
node.meta.mask_thumbnail_url =
render_mask_thumb_url(&node, dims.width, dims.height, None);
}
node
})
.collect();
if layer_nodes.is_empty() {
let mut bg = LayerNode {
meta: LayerNodeMeta::new_raster("layer-bg", "Background"),
grid: SparseLayerGrid::new(TileFormat::Color32Bit),
};
bg.grid
.fill_solid_layer(dims.width, dims.height, [255, 255, 255, 255]);
layer_nodes.push(bg);
}
let active_layer_id = layer_nodes
.iter()
.find(|l| l.meta.layer_type == LayerType::Raster && l.meta.visible)
.or_else(|| layer_nodes.first())
.map(|l| l.meta.id.clone());
let mut doc = Document::from_layers(
doc_id,
name,
dims,
color_mode,
layer_nodes,
active_layer_id,
max_history_steps,
);
doc.preview_data_url = preview_data_url.clone();
(doc, preview_data_url)
}
/// Creates a blank multi-layer document directly in Rust and activates it.
pub fn create_document(
doc_id: String,
name: String,
dimensions: CanvasDimensions,
color_mode: CanvasColorMode,
background_hex: &str,
default_tone_frequency: f32,
) -> DocumentMetaSnapshot {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let snap = mgr.create_document(
doc_id,
name,
dimensions,
color_mode,
background_hex,
default_tone_frequency,
);
let _ = mgr.enforce_memory_budget();
snap
};
native_engine::sync_active_document();
snap
}
/// Opens a `.ink`, `.clip`/`.csp`/`.lip`, or `.psd`/`.psb` file directly from raw bytes into
/// Rust `DocumentManager` without sending any full-res pixel arrays across IPC.
pub fn open_document_from_bytes(
doc_id: String,
file_name: String,
bytes: &[u8],
) -> Result<OpenNativeDocumentResult, String> {
let lower = file_name.to_ascii_lowercase();
let max_history = documents_handle().read().budget_config().max_history_steps;
let (doc, preview_data_url, source_format) = if lower.ends_with(".clip")
|| lower.ends_with(".csp")
|| lower.ends_with(".lip")
{
let assembled = clip_parser::parse_clip_assembled(bytes)?;
let (doc, preview) = hydrate_assembled_document(assembled, doc_id, file_name, max_history);
(doc, preview, "clip".to_string())
} else if lower.ends_with(".psd") || lower.ends_with(".psb") {
let assembled = psd_parser::parse_psd_assembled(bytes)?;
let (doc, preview) = hydrate_assembled_document(assembled, doc_id, file_name, max_history);
(doc, preview, "psd".to_string())
} else if lower.ends_with(".png")
|| lower.ends_with(".jpg")
|| lower.ends_with(".jpeg")
|| lower.ends_with(".webp")
|| lower.ends_with(".bmp")
|| lower.ends_with(".gif")
|| lower.ends_with(".ico")
|| lower.ends_with(".tif")
|| lower.ends_with(".tiff")
{
let (w, h, rgba) = crate::wic_codec::decode_image_rgba8(bytes)?;
let stem = std::path::Path::new(&file_name)
.file_stem()
.and_then(|s| s.to_str())
.filter(|s| !s.trim().is_empty())
.unwrap_or("Untitled")
.to_string();
let dims = CanvasDimensions {
width: w.max(1),
height: h.max(1),
dpi: 300,
};
let mut img_grid = SparseLayerGrid::new(TileFormat::Color32Bit);
img_grid.write_rgba8_rect(&rgba, RectI32::new(0, 0, w, h), 128, None)?;
let mut img_node = LayerNode {
meta: LayerNodeMeta::new_raster(format!("layer-img-{}", doc_id), stem.clone()),
grid: img_grid,
};
img_node.meta.thumbnail_url = render_layer_thumb_url(&img_node, dims.width, dims.height, None);
let mut bg_grid = SparseLayerGrid::new(TileFormat::Color32Bit);
bg_grid.fill_solid_layer(dims.width, dims.height, [255, 255, 255, 255]);
let mut bg_meta = LayerNodeMeta::new_raster(format!("layer-bg-{}", doc_id), "Background");
bg_meta.locked = true;
let mut bg_node = LayerNode {
meta: bg_meta,
grid: bg_grid,
};
bg_node.meta.thumbnail_url = render_layer_thumb_url(&bg_node, dims.width, dims.height, None);
let active_id = Some(img_node.meta.id.clone());
let mut doc = Document::from_layers(
doc_id,
stem,
dims,
CanvasColorMode::Color,
vec![img_node, bg_node],
active_id,
max_history,
);
let preview = compositor_cpu::composite_document_downscaled_rgba(&doc, 320, true, None)
.ok()
.and_then(|(pw, ph, prgba)| encode_rgba8_to_png(pw, ph, &prgba).ok())
.map(|p| png_bytes_to_data_url(&p));
doc.preview_data_url = preview.clone();
(doc, preview, "image".to_string())
} else {
// Default: InkStudio `.ink` v2 ZIP archive (parallel decode directly into SparseLayerGrid)
let doc = parse_ink_document(bytes, doc_id, &file_name, max_history)?;
let preview = doc.preview_data_url.clone();
(doc, preview, "ink".to_string())
};
let docs = documents_handle();
let meta = {
let mut mgr = docs.write();
let meta = mgr.insert_and_activate(doc);
let _ = mgr.enforce_memory_budget();
meta
};
native_engine::sync_active_document();
Ok(OpenNativeDocumentResult {
doc: meta,
preview_data_url,
source_format,
})
}
/// Serializes an open Rust document directly into `.ink` v2 ZIP bytes (parallelized with Rayon).
/// Takes a microsecond zero-copy `Arc<TileData>` + metadata snapshot under `docs.read()` and
/// immediately releases the read guard before running DEFLATE/ZIP/PNG compression!
pub fn serialize_document_ink(doc_id: &str) -> Result<SerializedInkResult, String> {
let docs = documents_handle();
serialize_document_ink_from_docs(&docs, doc_id)
}
pub(crate) fn serialize_document_ink_from_docs(
docs: &RwLock<DocumentManager>,
doc_id: &str,
) -> Result<SerializedInkResult, String> {
let (snapshot, scratch) = {
let mgr = docs.read();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
(doc.clone_cow_snapshot(), scratch)
};
serialize_ink_document(&snapshot, 1, Some(scratch.as_ref()))
}
pub fn switch_document(doc_id: &str) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
mgr.switch_document(doc_id)?
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn close_document(doc_id: &str) -> bool {
let docs = documents_handle();
let removed = {
let mut mgr = docs.write();
mgr.close_document(doc_id)
};
native_engine::sync_active_document();
removed
}
pub fn get_document_state(doc_id: Option<&str>) -> Option<DocumentMetaSnapshot> {
let docs = documents_handle();
let mgr = docs.read();
let doc = match doc_id {
Some(id) => mgr.get_document(id),
None => mgr.active_document(),
}?;
Some(doc.snapshot_meta())
}
pub fn add_layer(
doc_id: &str,
meta: LayerNodeMeta,
insert_index: Option<usize>,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.add_layer(meta, insert_index, true, record_history);
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn delete_layer(
doc_id: &str,
layer_id: &str,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.delete_layer(layer_id, record_history)?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn duplicate_layer(
doc_id: &str,
source_layer_id: &str,
new_layer_id: String,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.duplicate_layer(source_layer_id, new_layer_id, record_history)?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn reorder_layers(
doc_id: &str,
ordered_ids: &[String],
parent_overrides: Option<&HashMap<String, Option<String>>>,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.reorder_layers(ordered_ids, parent_overrides, record_history)?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn update_layer(
doc_id: &str,
layer_id: &str,
patch: LayerPropsPatch,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.update_layer_props(layer_id, patch, Some(scratch.as_ref()))?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn sync_layers(
doc_id: &str,
layers: Vec<LayerNodeMeta>,
active_layer_id: Option<String>,
record_history: bool,
history_label: Option<String>,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let before_layers = if record_history {
Some(doc.layers.iter().map(|l| l.meta.clone()).collect::<Vec<_>>())
} else {
None
};
let before_active = if record_history {
doc.active_layer_id.clone()
} else {
None
};
let before_grids = if record_history {
let incoming_ids: std::collections::HashSet<&str> =
layers.iter().map(|l| l.id.as_str()).collect();
doc.layers
.iter()
.filter(|l| !incoming_ids.contains(l.meta.id.as_str()))
.map(|l| (l.meta.id.clone(), l.grid.clone_cow()))
.collect::<Vec<_>>()
} else {
Vec::new()
};
doc.sync_layers_metadata(layers, active_layer_id);
if let Some(bl) = before_layers {
let target_id = doc.active_layer_id.clone();
doc.record_tree_history(
"layer",
history_label.unwrap_or_else(|| "Update Layers".to_string()),
target_id,
bl,
before_active,
before_grids,
Vec::new(),
Vec::new(),
None,
);
}
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn set_active_layer(doc_id: &str, layer_id: Option<String>) -> Result<(), String> {
let docs = documents_handle();
let changed = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.set_active_layer(layer_id)
};
if changed {
native_engine::sync_active_document();
}
Ok(())
}
pub fn sync_document_meta(
doc_id: &str,
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> {
let docs = documents_handle();
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
if let Some(n) = name {
if !n.trim().is_empty() {
doc.name = n;
}
}
if let Some(pr) = perspective_ruler {
doc.perspective_ruler = if pr.is_null() { None } else { Some(pr) };
}
if let Some(sr) = straight_ruler {
doc.straight_ruler = if sr.is_null() { None } else { Some(sr) };
}
if let Some(at) = animation_timeline {
doc.animation_timeline = if at.is_null() { None } else { Some(at) };
}
if let Some(tl) = timelapse {
doc.timelapse = if tl.is_null() { None } else { Some(tl) };
}
if let Some(wt) = work_time_ms {
doc.work_time_ms = wt;
}
Ok(())
}
pub fn clear_layer(
doc_id: &str,
layer_id: &str,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.clear_layer(layer_id, record_history)?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn merge_down(doc_id: &str, src_layer_id: &str) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.merge_down(src_layer_id, Some(scratch.as_ref()))?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn merge_folder(
doc_id: &str,
folder_id: &str,
new_layer_id: String,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.merge_folder(folder_id, new_layer_id, Some(scratch.as_ref()))?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn add_mask(
doc_id: &str,
layer_id: &str,
default_value: u8,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.add_layer_mask(layer_id, default_value, record_history)?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn remove_mask(
doc_id: &str,
layer_id: &str,
apply_to_raster: bool,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.remove_layer_mask(layer_id, apply_to_raster, record_history, Some(scratch.as_ref()))?;
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn resize_canvas(
doc_id: &str,
new_dims: CanvasDimensions,
offset_x: i32,
offset_y: i32,
scale_content: bool,
bg_hex: &str,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.resize_canvas(
new_dims,
offset_x,
offset_y,
scale_content,
bg_hex,
record_history,
Some(scratch.as_ref()),
)?;
let _ = mgr.enforce_memory_budget();
mgr.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?
.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
#[allow(clippy::too_many_arguments)]
pub fn ingest_dirty_rect(
doc_id: &str,
layer_id: &str,
rect: RectI32,
bytes: &[u8],
is_mask: bool,
record_history: bool,
action_type: &str,
label: &str,
peer_id: Option<String>,
stroke_id: Option<String>,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
doc.ingest_dirty_rect(
layer_id,
rect,
bytes,
is_mask,
record_history,
action_type,
label,
peer_id,
stroke_id,
Some(scratch.as_ref()),
)?;
let _ = mgr.enforce_memory_budget();
mgr.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?
.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
pub fn undo(doc_id: &str) -> Result<NativeHistoryMutationResult, String> {
let docs = documents_handle();
let res = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let change = doc.undo();
NativeHistoryMutationResult {
doc: doc.snapshot_meta(),
dimensions_changed: change.dimensions_changed,
layers_changed: change.layers_changed,
changed_layer_ids: change.changed_layer_ids.into_iter().collect(),
document_state_delta: change.document_state_delta,
selective_outcome: None,
}
};
native_engine::sync_active_document();
Ok(res)
}
pub fn redo(doc_id: &str) -> Result<NativeHistoryMutationResult, String> {
let docs = documents_handle();
let res = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let change = doc.redo();
NativeHistoryMutationResult {
doc: doc.snapshot_meta(),
dimensions_changed: change.dimensions_changed,
layers_changed: change.layers_changed,
changed_layer_ids: change.changed_layer_ids.into_iter().collect(),
document_state_delta: change.document_state_delta,
selective_outcome: None,
}
};
native_engine::sync_active_document();
Ok(res)
}
pub fn jump_history(doc_id: &str, target_index: usize) -> Result<NativeHistoryMutationResult, String> {
let docs = documents_handle();
let res = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let change = doc.jump_to_history(target_index);
NativeHistoryMutationResult {
doc: doc.snapshot_meta(),
dimensions_changed: change.dimensions_changed,
layers_changed: change.layers_changed,
changed_layer_ids: change.changed_layer_ids.into_iter().collect(),
document_state_delta: change.document_state_delta,
selective_outcome: None,
}
};
native_engine::sync_active_document();
Ok(res)
}
pub fn selective_undo(
doc_id: &str,
peer_id: Option<&str>,
stroke_id: Option<&str>,
) -> Result<NativeHistoryMutationResult, String> {
let docs = documents_handle();
let res = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let outcome = doc.selective_undo(peer_id, stroke_id);
let changed = outcome.layer_id.clone().into_iter().collect();
NativeHistoryMutationResult {
doc: doc.snapshot_meta(),
dimensions_changed: false,
layers_changed: false,
changed_layer_ids: changed,
document_state_delta: None,
selective_outcome: Some(outcome),
}
};
native_engine::sync_active_document();
Ok(res)
}
pub fn selective_redo(
doc_id: &str,
peer_id: Option<&str>,
) -> Result<NativeHistoryMutationResult, String> {
let docs = documents_handle();
let res = {
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let outcome = doc.selective_redo(peer_id);
let changed = outcome.layer_id.clone().into_iter().collect();
NativeHistoryMutationResult {
doc: doc.snapshot_meta(),
dimensions_changed: false,
layers_changed: false,
changed_layer_ids: changed,
document_state_delta: None,
selective_outcome: Some(outcome),
}
};
native_engine::sync_active_document();
Ok(res)
}
pub fn push_history_meta(
doc_id: &str,
action_type: String,
label: String,
layer_id: Option<String>,
document_state_delta: Option<serde_json::Value>,
_coalesce_key: Option<String>,
) -> Result<HistoryStateSnapshot, String> {
let docs = documents_handle();
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let entry = ink_engine::history::HistoryEntry {
meta: HistoryItemMeta {
id: ink_engine::history::next_history_id("hist-meta", now),
action_type,
label,
timestamp: now,
time_formatted: ink_engine::history::format_time_hms(now),
thumbnail_url: String::new(),
layer_id,
undone: false,
},
tile_deltas: Vec::new(),
layer_tree_delta: None,
canvas_resize_delta: None,
document_state_delta,
peer_id: None,
stroke_id: None,
is_mask_edit: false,
};
doc.history.push(entry);
Ok(doc.history.snapshot())
}
pub fn get_history(doc_id: &str) -> Result<HistoryStateSnapshot, String> {
let docs = documents_handle();
let mgr = docs.read();
let doc = mgr
.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
Ok(doc.history.snapshot())
}
pub fn reset_history(doc_id: &str, label: Option<String>) -> Result<HistoryStateSnapshot, String> {
let docs = documents_handle();
let mut mgr = docs.write();
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let initial_label = label.unwrap_or_else(|| "Initial State".to_string());
let active_id = doc.active_layer_id.clone();
doc.history
.reset_with_initial(initial_label, active_id, String::new());
Ok(doc.history.snapshot())
}
fn attach_gpu_pool_stats(mut stats: MemoryStats) -> MemoryStats {
let pool = native_engine::gpu_pool_stats();
if pool.slots_capacity > 0 {
stats.vram_used_bytes = pool.used_bytes;
stats.vram_budget_bytes = pool.capacity_bytes;
stats.vram_slots_used = pool.slots_used;
stats.vram_slots_capacity = pool.slots_capacity;
}
stats
}
pub fn get_memory_stats() -> MemoryStats {
let docs = documents_handle();
let mgr = docs.read();
attach_gpu_pool_stats(mgr.memory_stats())
}
pub fn set_memory_budget(input: NativeMemoryBudgetInput) -> Result<MemoryStats, String> {
let docs = documents_handle();
let mut vram_to_apply: Option<u64> = None;
let stats = {
let mut mgr = docs.write();
let mut cfg = mgr.budget_config();
if let Some(ram_mb) = input.ram_budget_mb {
cfg.ram_budget_bytes = ram_mb.clamp(64, 32768) * 1024 * 1024;
}
if let Some(vram_mb) = input.vram_budget_mb {
let vbytes = vram_mb.clamp(64, 8192) * 1024 * 1024;
cfg.vram_budget_bytes = vbytes;
vram_to_apply = Some(vbytes);
}
if let Some(steps) = input.max_history_steps {
cfg.max_history_steps = steps.clamp(10, 1000);
}
if let Some(offload) = input.offload_inactive_tabs {
cfg.offload_inactive_tabs = offload;
}
mgr.set_memory_budget(cfg)?
};
if let Some(vbytes) = vram_to_apply {
native_engine::set_vram_budget(vbytes);
}
Ok(attach_gpu_pool_stats(stats))
}
pub fn purge_memory() -> Result<MemoryStats, String> {
native_engine::flush_gpu_pool();
let docs = documents_handle();
let mut mgr = docs.write();
let outcome = mgr.purge_memory(false)?;
Ok(attach_gpu_pool_stats(outcome.stats))
}
/// Generates 64x64 layer & mask thumbnails asynchronously on Tauri's blocking pool and emits
/// `native-engine://thumbnails` back to React (never blocking the main UI or GPU thread, and
/// safe to call from synchronous `#[tauri::command]` handlers outside a Tokio runtime context).
pub fn spawn_thumbnail_generation(
app: tauri::AppHandle,
doc_id: String,
layer_ids: Vec<String>,
) {
spawn_thumbnail_generation_with_sink(doc_id, layer_ids, move |doc_id, updates| {
let _ = app.emit(
native_engine::EVENT_THUMBNAILS,
native_engine::NativeThumbnailsEventPayload { doc_id, updates },
);
});
}
fn spawn_thumbnail_generation_with_sink<F>(doc_id: String, layer_ids: Vec<String>, on_updates: F)
where
F: FnOnce(String, Vec<ThumbnailUpdate>) + Send + 'static,
{
tauri::async_runtime::spawn_blocking(move || {
let docs = documents_handle();
let gpu_active = native_engine::is_active();
let (target_ids, gpu_thumb_ids): (Vec<String>, HashSet<String>) = {
let mgr = docs.read();
let Some(doc) = mgr.get_document(&doc_id) else {
return;
};
let ids: Vec<String> = if layer_ids.is_empty() {
doc.layers
.iter()
.filter(|l| l.meta.layer_type.has_tiles() || l.grid.has_mask)
.map(|l| l.meta.id.clone())
.collect()
} else {
layer_ids
};
let gpu_ids: HashSet<String> = if gpu_active {
ids.iter()
.filter(|lid| {
doc.layer(lid).is_some_and(|l| {
l.meta.layer_type.has_tiles()
&& (l.meta.tone_enabled.unwrap_or(false)
|| l.meta.layer_color_enabled.unwrap_or(false)
|| l.meta.expression_color.is_some_and(|e| e != ExpressionColor::Color)
|| l.grid.has_mask)
})
})
.cloned()
.collect()
} else {
HashSet::new()
};
(ids, gpu_ids)
};
// Render effect-bearing layer thumbnails via DX12 GPU (no lock held while waiting)
let mut gpu_rendered: HashMap<String, String> = HashMap::new();
for lid in &gpu_thumb_ids {
if let Ok((tw, th, rgba)) =
native_engine::render_layer_thumbnail_gpu(Some(doc_id.clone()), lid.clone(), 64)
{
if let Ok(png) = encode_rgba8_to_png(tw, th, &rgba) {
gpu_rendered.insert(lid.clone(), png_bytes_to_data_url(&png));
}
}
}
struct ThumbLayerSnapshot {
layer_id: String,
layer_version: u64,
has_tiles: bool,
tiles: HashMap<TileCoord, Arc<TileData>>,
tint: Option<([u8; 4], [u8; 4])>,
has_mask: bool,
mask_tiles: HashMap<TileCoord, Arc<TileData>>,
mask_default_value: u8,
}
// Microsecond zero-copy Arc<TileData> snapshot under docs.read(); release guard
// BEFORE Rayon CPU thumbnail rendering and PNG encoding!
let (dims, scratch, layer_snaps): (
CanvasDimensions,
Arc<dyn ScratchBackend>,
Vec<ThumbLayerSnapshot>,
) = {
let mgr = docs.read();
let scratch = Arc::clone(mgr.scratch_backend());
let Some(doc) = mgr.get_document(&doc_id) else {
return;
};
let dims = doc.dimensions;
let snaps = target_ids
.into_iter()
.filter_map(|lid| {
let node = doc.layer(&lid)?;
let has_tiles = node.meta.layer_type.has_tiles();
let need_cpu_tiles = has_tiles && !gpu_rendered.contains_key(&lid);
Some(ThumbLayerSnapshot {
layer_id: lid,
layer_version: node.grid.layer_version,
has_tiles,
tiles: if need_cpu_tiles {
node.grid.tiles.clone()
} else {
HashMap::new()
},
tint: if need_cpu_tiles {
compositor_cpu::extract_layer_tint(node)
} else {
None
},
has_mask: node.grid.has_mask,
mask_tiles: if node.grid.has_mask {
node.grid.mask_tiles.clone()
} else {
HashMap::new()
},
mask_default_value: node.grid.mask_default_value,
})
})
.collect();
(dims, scratch, snaps)
};
let updates_with_ver: Vec<(u64, ThumbnailUpdate)> = layer_snaps
.into_par_iter()
.filter_map(|snap| {
let thumb = if snap.has_tiles {
gpu_rendered.get(&snap.layer_id).cloned().or_else(|| {
compositor_cpu::render_layer_thumbnail_rgba_from_tiles(
&snap.tiles,
snap.tint,
dims.width,
dims.height,
64,
64,
Some(scratch.as_ref()),
)
.ok()
.and_then(|(tw, th, rgba)| encode_rgba8_to_png(tw, th, &rgba).ok())
.map(|png| png_bytes_to_data_url(&png))
})
} else {
None
};
let mask_thumb = if snap.has_mask {
compositor_cpu::render_mask_thumbnail_rgba_from_tiles(
&snap.mask_tiles,
snap.mask_default_value,
dims.width,
dims.height,
64,
64,
Some(scratch.as_ref()),
)
.ok()
.and_then(|(tw, th, rgba)| encode_rgba8_to_png(tw, th, &rgba).ok())
.map(|png| png_bytes_to_data_url(&png))
} else {
None
};
if thumb.is_none() && mask_thumb.is_none() {
return None;
}
Some((
snap.layer_version,
ThumbnailUpdate {
layer_id: snap.layer_id,
thumbnail_url: thumb,
mask_thumbnail_url: mask_thumb,
},
))
})
.collect();
if updates_with_ver.is_empty() {
return;
}
// Cache thumbnails on Document metadata as well (skip stale writes if layer changed)
{
let mut mgr = docs.write();
if let Some(doc) = mgr.get_document_mut(&doc_id) {
for (ver, u) in &updates_with_ver {
if let Some(node) = doc.layer_mut(&u.layer_id) {
if node.grid.layer_version == *ver {
if let Some(ref url) = u.thumbnail_url {
node.meta.thumbnail_url = Some(url.clone());
}
if let Some(ref murl) = u.mask_thumbnail_url {
node.meta.mask_thumbnail_url = Some(murl.clone());
}
}
}
}
}
}
let updates: Vec<ThumbnailUpdate> =
updates_with_ver.into_iter().map(|(_, u)| u).collect();
on_updates(doc_id, updates);
});
}
/// Renders the document (full-res or scaled preview) natively on the DX12 GPU via
/// `WgpuCompositor::render_document_flattened` (supporting all 28 blend modes, screentones,
/// adjustments, layer styles, comic frames, soft proof, and value check), falling back cleanly
/// to CPU compositing if the DX12 engine is inactive (e.g. headless unit tests).
pub fn flatten_document_rgba(
doc_id: Option<String>,
options: FlattenOptions,
) -> Result<(u32, u32, Vec<u8>), String> {
if native_engine::is_active() {
if let Ok(res) = native_engine::render_document_flattened(doc_id.clone(), options.clone()) {
return Ok(res);
}
}
let (snapshot, scratch) = {
let docs = documents_handle();
let mgr = docs.read();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = match doc_id.as_deref() {
Some(id) => mgr.get_document(id),
None => mgr.active_document(),
}
.ok_or_else(|| "Document not found for flatten".to_string())?;
(doc.clone_cow_snapshot(), scratch)
};
if let Some(max_dim) = options.max_dim {
compositor_cpu::composite_document_downscaled_rgba(
&snapshot,
max_dim.max(1),
options.fill_white_background,
Some(scratch.as_ref()),
)
} else {
let mut rgba =
compositor_cpu::composite_document_full_rgba(&snapshot, Some(scratch.as_ref()))?;
if options.fill_white_background {
for px in rgba.as_chunks_mut::<4>().0 {
let a = px[3] as u32;
let inv = 255 - a;
px[0] = ((px[0] as u32 * a + 255 * inv + 127) / 255) as u8;
px[1] = ((px[1] as u32 * a + 255 * inv + 127) / 255) as u8;
px[2] = ((px[2] as u32 * a + 255 * inv + 127) / 255) as u8;
px[3] = 255;
}
}
Ok((snapshot.dimensions.width, snapshot.dimensions.height, rgba))
}
}
/// Flattens a document (on GPU when active, CPU fallback otherwise) and encodes directly into
/// PNG, JPEG, or WebP bytes in Rust — zero WebView2 `<canvas>` allocation!
pub fn export_document_image_bytes(
doc_id: Option<String>,
format: &str,
quality: f32,
options: FlattenOptions,
) -> Result<(u32, u32, Vec<u8>), String> {
let (w, h, rgba) = flatten_document_rgba(doc_id, options)?;
let encoded = crate::wic_codec::encode_image_rgba8(w, h, &rgba, format, quality)?;
Ok((w, h, encoded))
}
/// Decodes an image buffer (PNG/JPEG/WebP/BMP/GIF) directly in Rust and inserts it as a new
/// centered raster layer in the document (with CoW Undo).
pub fn import_image_as_layer(
doc_id: &str,
layer_id: String,
name: String,
bytes: &[u8],
offset_x: Option<i32>,
offset_y: Option<i32>,
record_history: bool,
) -> Result<DocumentMetaSnapshot, String> {
let (img_w, img_h, rgba) = crate::wic_codec::decode_image_rgba8(bytes)?;
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let doc_u32_w = doc.dimensions.width;
let doc_u32_h = doc.dimensions.height;
let doc_w = doc_u32_w as i32;
let doc_h = doc_u32_h as i32;
let ox = offset_x.unwrap_or((doc_w - img_w as i32) / 2);
let oy = offset_y.unwrap_or((doc_h - img_h as i32) / 2);
let before_layers: Vec<LayerNodeMeta> =
doc.layers.iter().map(|l| l.meta.clone()).collect();
let before_active = doc.active_layer_id.clone();
let meta = LayerNodeMeta::new_raster(layer_id.clone(), name.clone());
doc.add_layer(meta, Some(0), true, false);
let mut after_grids = Vec::new();
if let Some(node) = doc.layer_mut(&layer_id) {
let rect = RectI32::new(ox, oy, img_w, img_h);
let _ = node.grid.write_rgba8_rect(&rgba, rect, 128, Some(scratch.as_ref()));
node.meta.thumbnail_url = render_layer_thumb_url(
node,
doc_u32_w,
doc_u32_h,
Some(scratch.as_ref()),
);
after_grids.push((layer_id.clone(), node.grid.clone_cow()));
}
if record_history {
doc.record_tree_history(
"layer",
format!("Import {name}"),
Some(layer_id),
before_layers,
before_active,
Vec::new(),
after_grids,
Vec::new(),
None,
);
}
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
/// Reads the tight non-empty pixel bounding box and straight RGBA8 bytes of a single layer
/// (used for zero-canvas PSD export via `ag-psd` `imageData`).
pub fn read_layer_bounds_rgba(
doc_id: &str,
layer_id: &str,
) -> Result<Option<(i32, i32, u32, u32, Vec<u8>)>, String> {
let docs = documents_handle();
let mgr = docs.read();
let scratch = mgr.scratch_backend();
let doc = mgr
.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let Some(node) = doc.layer(layer_id) else {
return Ok(None);
};
let Some(bounds) = node.grid.tile_bounds() else {
return Ok(None);
};
let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
let clipped = bounds.intersect(doc_rect);
if clipped.is_empty() {
return Ok(None);
}
let rgba = node
.grid
.read_rgba8_rect(clipped, false, Some(scratch.as_ref()))?;
Ok(Some((
clipped.x,
clipped.y,
clipped.width,
clipped.height,
rgba,
)))
}
/// Reads a layer's full 8-bit mask as RGBA grayscale bytes (for zero-canvas PSD mask export).
pub fn read_layer_mask_rgba(
doc_id: &str,
layer_id: &str,
) -> Result<Option<(u32, u32, u8, Vec<u8>)>, String> {
let docs = documents_handle();
let mgr = docs.read();
let scratch = mgr.scratch_backend();
let doc = mgr
.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
let Some(node) = doc.layer(layer_id) else {
return Ok(None);
};
if !node.grid.has_mask {
return Ok(None);
}
let w = doc.dimensions.width;
let h = doc.dimensions.height;
let rect = RectI32::new(0, 0, w, h);
let mask8 = node
.grid
.read_mask8_rect(rect, Some(scratch.as_ref()))?;
let mut rgba = vec![255u8; (w as usize) * (h as usize) * 4];
for (i, &m) in mask8.iter().enumerate() {
let base = i * 4;
rgba[base] = m;
rgba[base + 1] = m;
rgba[base + 2] = m;
rgba[base + 3] = 255;
}
Ok(Some((w, h, node.grid.mask_default_value, rgba)))
}
/// Renders a downscaled flattened PNG directly on the DX12 GPU from the Rust `Document` and
/// persists it directly into `src-tauri/src/timelapse.rs` (zero JS pixel transfer!).
pub async fn capture_timelapse_frame(
app: &tauri::AppHandle,
doc_id: String,
session_id: String,
frame_index: u32,
max_dim: u32,
capture_area: Option<String>,
) -> Result<NativeTimelapseCaptureResult, String> {
let clamped_dim = max_dim.clamp(256, 3840);
let (w, h, png_bytes) =
tokio::task::spawn_blocking(move || -> Result<(u32, u32, Vec<u8>), String> {
let (w, h, rgba) = flatten_document_rgba(
Some(doc_id),
FlattenOptions {
max_dim: Some(clamped_dim),
fill_white_background: true,
..Default::default()
},
)?;
let png = encode_rgba8_to_png(w, h, &rgba)?;
Ok((w, h, png))
})
.await
.map_err(|e| format!("Timelapse capture worker failed: {e}"))??;
let bytes_len = png_bytes.len();
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
timelapse::write_frame(
app,
&session_id,
frame_index,
"png",
&png_bytes,
Some(timelapse::FrameWriteMeta {
timestamp: now_ms,
width: w,
height: h,
capture_area,
}),
)
.await?;
Ok(NativeTimelapseCaptureResult {
width: w,
height: h,
bytes: bytes_len,
frame_index,
})
}
/// Snapshots the document under a microsecond `docs.read()` guard, releases the lock immediately,
/// and encodes the crash-recovery checkpoint completely lock-free.
pub(crate) fn encode_recovery_checkpoint_from_docs(
docs: &RwLock<DocumentManager>,
doc_id: &str,
) -> Result<(String, Vec<u8>, Vec<u8>), String> {
let (snapshot, scratch) = {
let mgr = docs.read();
let scratch = Arc::clone(mgr.scratch_backend());
let doc = mgr
.get_document(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
(doc.clone_cow_snapshot(), scratch)
};
encode_document_checkpoint(&snapshot, Some(scratch.as_ref()))
}
/// Writes an atomic crash-recovery checkpoint (`INKG v1` base snapshot + manifest + PNG thumbnail)
/// directly from the Rust `Document` into `src-tauri/src/recovery.rs` (zero JS pixel IPC!).
pub async fn recovery_checkpoint_document(
app: &tauri::AppHandle,
doc_id: String,
session_id: String,
manifest_override: Option<String>,
) -> Result<NativeRecoveryCheckpointResult, String> {
// Take the WAL watermark BEFORE capturing the snapshot: frames below it are contained in
// the snapshot; frames journaled while it encodes are kept (see `recovery::checkpoint`).
let wal_watermark = recovery::wal_watermark(app, &session_id).await;
let (generated_manifest, snapshot_bytes, thumb_png) =
tokio::task::spawn_blocking(move || -> Result<(String, Vec<u8>, Vec<u8>), String> {
let docs = documents_handle();
encode_recovery_checkpoint_from_docs(&docs, &doc_id)
})
.await
.map_err(|e| format!("Recovery checkpoint worker failed: {e}"))??;
let manifest_json = manifest_override
.filter(|s| !s.trim().is_empty())
.unwrap_or(generated_manifest);
let snap_len = snapshot_bytes.len();
let thumb_len = thumb_png.len();
recovery::checkpoint(
app,
&session_id,
snapshot_bytes,
manifest_json,
thumb_png,
Some(wal_watermark),
)
.await?;
Ok(NativeRecoveryCheckpointResult {
snapshot_bytes: snap_len,
thumbnail_bytes: thumb_len,
})
}
/// Restores a crashed recovery session directly in Rust (replaying `INKG v1` base snapshot +
/// `TD v1` WAL frames straight into `DocumentManager`) and returns compact metadata to React!
pub async fn recovery_restore_document(
app: &tauri::AppHandle,
session_id: String,
doc_id: String,
) -> Result<DocumentMetaSnapshot, String> {
let replay = recovery::load_session_data(app, &session_id).await?;
let max_history = documents_handle().read().budget_config().max_history_steps;
let doc = tokio::task::spawn_blocking(move || -> Result<Document, String> {
let wal_entries: Vec<WalRawEntry> = replay
.wal_entries
.into_iter()
.map(|w| WalRawEntry {
entry_type: w.entry_type,
payload: w.payload,
})
.collect();
let (mut doc, _strokes, _mutations) = replay_recovery_into_document(
doc_id,
&replay.manifest_json,
replay.base_snapshot.as_deref(),
&wal_entries,
max_history,
)?;
// Refresh 64x64 thumbnails in parallel
let dims = doc.dimensions;
doc.layers.par_iter_mut().for_each(|node| {
if node.meta.layer_type.has_tiles() && !node.grid.tiles.is_empty() {
node.meta.thumbnail_url =
render_layer_thumb_url(node, dims.width, dims.height, None);
}
if node.grid.has_mask {
node.meta.mask_thumbnail_url =
render_mask_thumb_url(node, dims.width, dims.height, None);
}
});
Ok(doc)
})
.await
.map_err(|e| format!("Recovery restore worker failed: {e}"))??;
let docs = documents_handle();
let snap = {
let mut mgr = docs.write();
mgr.insert_and_activate(doc)
};
native_engine::sync_active_document();
Ok(snap)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tauri_scratch_disk_backend_in_process_roundtrip() {
let backend = TauriScratchDiskBackend;
let session = format!(
"ink_engine_inproc_{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
backend.init_session(&session).expect("init_session failed");
let tile_payload: Vec<u8> = (0..65536).map(|i| ((i * 7) & 0xff) as u8).collect();
let written = backend
.write_tiles(
&session,
vec![ScratchTileWrite {
layer_key: "layer-alpha".to_string(),
tx: 3,
ty: -2,
data: tile_payload.clone(),
}],
)
.expect("write_tiles failed");
assert_eq!(written, 1);
let loaded = backend
.read_tile(&session, "layer-alpha", 3, -2)
.expect("read_tile failed");
assert_eq!(loaded, tile_payload);
backend
.clear_session(&session)
.expect("clear_session failed");
}
#[test]
fn test_zero_copy_psd_to_ink_engine_hydration_and_ink_roundtrip() {
// Minimal 8x2 1-bit Bitmap PSD (bit 1 = black, bit 0 = white)
let mut psd = Vec::new();
psd.extend_from_slice(b"8BPS");
psd.extend_from_slice(&1u16.to_be_bytes());
psd.extend_from_slice(&[0u8; 6]);
psd.extend_from_slice(&1u16.to_be_bytes());
psd.extend_from_slice(&2u32.to_be_bytes()); // height
psd.extend_from_slice(&8u32.to_be_bytes()); // width
psd.extend_from_slice(&1u16.to_be_bytes()); // 1-bit
psd.extend_from_slice(&0u16.to_be_bytes()); // Bitmap
psd.extend_from_slice(&0u32.to_be_bytes());
psd.extend_from_slice(&0u32.to_be_bytes());
psd.extend_from_slice(&0u32.to_be_bytes());
psd.extend_from_slice(&0u16.to_be_bytes()); // raw
psd.push(0b1000_0000);
psd.push(0b0100_0000);
let assembled = psd_parser::parse_psd_assembled(&psd).expect("parse_psd_assembled failed");
let (doc, _preview) = hydrate_assembled_document(assembled, "doc-psd-test", "Manga.psd", 50);
assert_eq!(doc.dimensions.width, 8);
assert_eq!(doc.dimensions.height, 2);
assert_eq!(doc.color_mode, CanvasColorMode::Grayscale);
assert_eq!(doc.layers.len(), 1);
assert!(doc.layers[0].meta.thumbnail_url.is_some());
// Verify exact pixels directly in Rust SparseLayerGrid
let rgba = doc.layers[0]
.grid
.read_rgba8_rect(RectI32::new(0, 0, 8, 2), false, None)
.expect("read_rgba8_rect failed");
assert_eq!(&rgba[0..4], &[0, 0, 0, 255]); // (0, 0) black
assert_eq!(&rgba[4..8], &[255, 255, 255, 255]); // (1, 0) white
assert_eq!(&rgba[(8 + 1) * 4..(8 + 1) * 4 + 4], &[0, 0, 0, 255]); // (1, 1) black
// Round-trip save directly from Rust into `.ink` v2 ZIP and reload
let saved = serialize_ink_document(&doc, 1, None).expect("serialize_ink_document failed");
assert!(saved.preview_png.is_some());
let reloaded = parse_ink_document(&saved.bytes, "doc-psd-reloaded", "Manga.ink", 50)
.expect("parse_ink_document failed");
assert!(reloaded.preview_data_url.is_some());
let reloaded_rgba = reloaded.layers[0]
.grid
.read_rgba8_rect(RectI32::new(0, 0, 8, 2), false, None)
.expect("reloaded read failed");
assert_eq!(reloaded_rgba, rgba);
}
#[test]
fn test_zero_copy_clip_to_ink_engine_hydration_and_ink_roundtrip() {
let clip_bytes = crate::clip_parser::tests::build_synthetic_clip_fixture();
let assembled =
clip_parser::parse_clip_assembled(&clip_bytes).expect("parse_clip_assembled failed");
let (doc, _preview) =
hydrate_assembled_document(assembled, "doc-clip-test", "Synthetic.clip", 50);
assert_eq!(doc.dimensions.width, 512);
assert_eq!(doc.dimensions.height, 256);
assert_eq!(doc.dimensions.dpi, 600);
assert_eq!(doc.layers.len(), 2);
assert_eq!(doc.layers[0].meta.name, "Ink");
assert_eq!(doc.layers[0].meta.blend_mode, BlendMode::Multiply);
assert_eq!(doc.layers[0].meta.alpha_locked, Some(true));
assert_eq!(doc.layers[0].meta.clipped, Some(true));
assert!(doc.layers[0].meta.thumbnail_url.is_some());
assert_eq!(doc.layers[1].meta.name, "Paper");
// Exact pixel at (3, 5) hydrated directly into Rust SparseLayerGrid without INKD IPC!
let px = doc.layers[0]
.grid
.read_rgba8_rect(RectI32::new(3, 5, 1, 1), false, None)
.expect("read_rgba8_rect failed");
assert_eq!(px, [240, 20, 10, 200]);
// Paper layer uses zero-allocation SolidColor tiles
let paper_px = doc.layers[1]
.grid
.read_rgba8_rect(RectI32::new(100, 100, 1, 1), false, None)
.expect("paper read failed");
assert_eq!(paper_px, [255, 255, 255, 255]);
// Round-trip save directly from Rust into `.ink` v2 ZIP and reload
let saved = serialize_ink_document(&doc, 1, None).expect("serialize_ink_document failed");
let reloaded = parse_ink_document(&saved.bytes, "doc-clip-reloaded", "Synthetic.ink", 50)
.expect("parse_ink_document failed");
assert_eq!(reloaded.layers.len(), 2);
let reloaded_px = reloaded.layers[0]
.grid
.read_rgba8_rect(RectI32::new(3, 5, 1, 1), false, None)
.expect("reloaded read failed");
assert_eq!(reloaded_px, [240, 20, 10, 200]);
}
#[test]
fn test_spawn_thumbnail_generation_safe_outside_tokio_runtime() {
// Confirm this test thread has NO active Tokio runtime context (matching synchronous
// #[tauri::command] handlers called inline inside WebView2's COM callback).
assert!(tokio::runtime::Handle::try_current().is_err());
let doc_id = "doc-thumb-sync-test".to_string();
let layer_id = {
let docs = documents_handle();
let mut mgr = docs.write();
let snap = mgr.create_document(
doc_id.clone(),
"ThumbTest".to_string(),
CanvasDimensions {
width: 64,
height: 64,
dpi: 300,
},
CanvasColorMode::Color,
"#ffffff",
60.0,
);
// Pick the solid-filled Background layer so a non-empty PNG thumbnail is produced
snap.layers
.last()
.expect("blank doc should have background layer")
.id
.clone()
};
let (tx, rx) = std::sync::mpsc::channel();
spawn_thumbnail_generation_with_sink(
doc_id.clone(),
vec![layer_id.clone()],
move |id, updates| {
let _ = tx.send((id, updates));
},
);
let (emitted_doc_id, updates) = rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("thumbnail worker did not complete");
assert_eq!(emitted_doc_id, doc_id);
assert_eq!(updates.len(), 1);
assert_eq!(updates[0].layer_id, layer_id);
assert!(updates[0]
.thumbnail_url
.as_deref()
.is_some_and(|u| u.starts_with("data:image/png;base64,")));
// Clean up temporary document from fallback store
let docs = documents_handle();
let _ = docs.write().close_document(&doc_id);
}
struct BlockingTestScratch {
store: Mutex<HashMap<(String, String, i32, i32), Vec<u8>>>,
entered_tx: Mutex<Option<std::sync::mpsc::Sender<()>>>,
release_rx: Mutex<Option<std::sync::mpsc::Receiver<()>>>,
}
impl BlockingTestScratch {
fn new(
entered_tx: std::sync::mpsc::Sender<()>,
release_rx: std::sync::mpsc::Receiver<()>,
) -> Self {
Self {
store: Mutex::new(HashMap::new()),
entered_tx: Mutex::new(Some(entered_tx)),
release_rx: Mutex::new(Some(release_rx)),
}
}
}
impl ScratchBackend for BlockingTestScratch {
fn init_session(&self, _session_id: &str) -> Result<(), String> {
Ok(())
}
fn write_tiles(
&self,
session_id: &str,
tiles: Vec<ScratchTileWrite>,
) -> Result<usize, String> {
let mut g = self.store.lock().unwrap();
let n = tiles.len();
for t in tiles {
g.insert((session_id.to_string(), t.layer_key, t.tx, t.ty), t.data);
}
Ok(n)
}
fn read_tile(
&self,
session_id: &str,
layer_key: &str,
tx: i32,
ty: i32,
) -> Result<Vec<u8>, String> {
// Pause on the first tile read so the test thread can deterministically verify
// that `docs.write()` is NOT blocked during checkpoint / `.ink` ZIP encoding!
let entered = self.entered_tx.lock().unwrap().take();
let release = self.release_rx.lock().unwrap().take();
if let Some(etx) = entered {
let _ = etx.send(());
}
if let Some(rrx) = release {
let _ = rrx.recv_timeout(std::time::Duration::from_secs(5));
}
let g = self.store.lock().unwrap();
g.get(&(session_id.to_string(), layer_key.to_string(), tx, ty))
.cloned()
.ok_or_else(|| "missing scratch tile".to_string())
}
fn clear_session(&self, _session_id: &str) -> Result<(), String> {
Ok(())
}
}
fn make_doc_with_paged_tile(
scratch: Arc<dyn ScratchBackend>,
doc_id: &str,
) -> Arc<RwLock<DocumentManager>> {
let mgr_arc = Arc::new(RwLock::new(DocumentManager::new(
MemoryBudgetConfig::default(),
Arc::clone(&scratch),
)));
{
let mut mgr = mgr_arc.write();
mgr.create_document(
doc_id.to_string(),
"LockFreeTest".to_string(),
CanvasDimensions {
width: 256,
height: 256,
dpi: 300,
},
CanvasColorMode::Color,
"#ffffff",
60.0,
);
let doc = mgr.get_document_mut(doc_id).unwrap();
let layer = &mut doc.layers[0];
// Create a non-solid raw tile and demote it to PagedToDisk so serialization triggers `read_tile`
let mut raw = vec![0u8; 256 * 256 * 4];
raw[0..4].copy_from_slice(&[200, 40, 20, 255]);
raw[4..8].copy_from_slice(&[10, 180, 90, 255]);
let mut td = TileData::from_raw_auto_compact(
TileFormat::Color32Bit,
TileKind::Raster,
raw,
);
td.demote_to_disk(
doc_id,
&layer.meta.id,
TileCoord::new(0, 0),
scratch.as_ref(),
)
.expect("demote_to_disk failed");
layer.grid.set_tile(TileCoord::new(0, 0), Arc::new(td));
}
mgr_arc
}
#[test]
fn test_recovery_checkpoint_releases_doc_read_lock_before_deflate() {
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let scratch: Arc<dyn ScratchBackend> =
Arc::new(BlockingTestScratch::new(entered_tx, release_rx));
let docs = make_doc_with_paged_tile(scratch, "doc-wal-lockfree");
let docs_worker = Arc::clone(&docs);
let handle = std::thread::spawn(move || {
encode_recovery_checkpoint_from_docs(&docs_worker, "doc-wal-lockfree")
});
// Wait until worker is actively inside `encode_document_checkpoint` (reading & deflating tiles)
entered_rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("worker never reached tile materialization");
// Concurrent `docs.write()` MUST succeed immediately without blocking!
let write_guard = docs.try_write();
assert!(
write_guard.is_some(),
"docs.write() was blocked while recovery checkpoint compression was running!"
);
drop(write_guard);
let _ = release_tx.send(());
let (manifest_json, snapshot_bytes, thumb_png) = handle
.join()
.expect("worker panicked")
.expect("checkpoint failed");
assert!(!manifest_json.is_empty());
assert!(!snapshot_bytes.is_empty());
assert!(!thumb_png.is_empty());
}
#[test]
fn test_serialize_document_ink_releases_doc_read_lock_before_zip() {
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
let scratch: Arc<dyn ScratchBackend> =
Arc::new(BlockingTestScratch::new(entered_tx, release_rx));
let docs = make_doc_with_paged_tile(scratch, "doc-ink-lockfree");
let docs_worker = Arc::clone(&docs);
let handle = std::thread::spawn(move || {
serialize_document_ink_from_docs(&docs_worker, "doc-ink-lockfree")
});
// Wait until worker is actively inside `serialize_ink_document`
entered_rx
.recv_timeout(std::time::Duration::from_secs(5))
.expect("worker never reached tile materialization");
// Concurrent `docs.write()` MUST succeed immediately without blocking!
let write_guard = docs.try_write();
assert!(
write_guard.is_some(),
"docs.write() was blocked while .ink ZIP serialization was running!"
);
drop(write_guard);
let _ = release_tx.send(());
let saved = handle
.join()
.expect("worker panicked")
.expect("serialize_document_ink failed");
assert!(!saved.bytes.is_empty());
assert!(saved.tile_count >= 1);
}
}