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
//! Direct Rust Crash Recovery WAL (`TD v1`) & Checkpoint (`INKG v1`) binary codecs.
//!
//! Produces wire-compatible payloads consumed directly in-process by `src-tauri/src/recovery.rs`
//! (zero JS serialization or IPC pixel transfers!).
use crate::document::{
CanvasColorMode, CanvasDimensions, Document, ExpressionColor, LayerNode, LayerNodeMeta,
};
use crate::memory::ScratchBackend;
use crate::tiles::{
reserve_tile_version, CowTileDelta, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind,
};
use flate2::read::DeflateDecoder;
use flate2::write::DeflateEncoder;
use flate2::Compression;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::sync::Arc;
pub const WAL_ENTRY_STROKE_TILE_DELTA: u8 = 1;
pub const WAL_ENTRY_VECTOR_STROKE: u8 = 2;
pub const WAL_ENTRY_LAYER_MUTATION: u8 = 3;
const MAX_DECOMPRESSED_BYTES: usize = 512 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct WalRawEntry {
pub entry_type: u8,
pub payload: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RecoveryManifest {
session_id: String,
document_name: String,
width: u32,
height: u32,
#[serde(default = "default_dpi")]
dpi: u32,
#[serde(default)]
color_mode: CanvasColorMode,
#[serde(default)]
layers: Vec<LayerNodeMeta>,
#[serde(default)]
active_layer_id: Option<String>,
#[serde(default)]
timestamp: u64,
#[serde(default)]
work_time_ms: u64,
#[serde(default)]
timelapse: Option<serde_json::Value>,
}
fn default_dpi() -> u32 {
300
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct LayerMutationWalPayload {
#[serde(default)]
layers: Vec<LayerNodeMeta>,
#[serde(default)]
active_layer_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VectorStrokeWalPayload {
#[serde(default)]
layer_id: Option<String>,
#[serde(default)]
strokes: Vec<serde_json::Value>,
}
fn deflate_fast(raw: &[u8]) -> Result<Vec<u8>, String> {
let mut enc = DeflateEncoder::new(Vec::with_capacity(raw.len() / 3 + 32), Compression::fast());
enc.write_all(raw)
.map_err(|e| format!("WAL deflate error: {e}"))?;
enc.finish()
.map_err(|e| format!("WAL deflate finish error: {e}"))
}
fn inflate_or_raw(bytes: &[u8], expected_magic: &[u8]) -> Result<Vec<u8>, String> {
// Multi-byte binary magic headers ("TD", "INKG") cannot collide reliably with valid deflate,
// whereas single-byte JSON prefix ("{", 0x7B) is a valid fixed-Huffman DEFLATE lead byte.
// For single-byte prefixes, try inflating first and fall back to raw bytes if valid!
if expected_magic.len() >= 2 && bytes.starts_with(expected_magic) {
return Ok(bytes.to_vec());
}
let mut dec = DeflateDecoder::new(bytes);
let mut out = Vec::new();
let mut limited = dec.by_ref().take((MAX_DECOMPRESSED_BYTES + 1) as u64);
match limited.read_to_end(&mut out) {
Ok(_) => {
if out.len() > MAX_DECOMPRESSED_BYTES {
return Err("WAL payload exceeded safety ceiling".to_string());
}
if expected_magic.is_empty() || out.starts_with(expected_magic) {
return Ok(out);
}
if bytes.starts_with(expected_magic) {
return Ok(bytes.to_vec());
}
Ok(out)
}
Err(e) => {
if !expected_magic.is_empty() && bytes.starts_with(expected_magic) {
return Ok(bytes.to_vec());
}
Err(format!("WAL inflate error: {e}"))
}
}
}
/// Encodes CoW tile deltas directly into deflate-compressed `TD v1` WAL frame payload bytes
/// (`['T','D'][1u8][count:u32 LE] ([keyLen:u16][key][fmt:u8][hasBefore:u8][len?][bytes?][hasAfter:u8][len?][bytes?])*`).
pub fn encode_cow_deltas_to_wal_payload(
deltas: &[CowTileDelta],
scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<u8>, String> {
let mut raw = Vec::with_capacity(7 + deltas.len() * 64);
raw.extend_from_slice(b"TD");
raw.push(1u8);
raw.extend_from_slice(&(deltas.len() as u32).to_le_bytes());
for d in deltas {
let key = match d.kind {
TileKind::Raster => format!("{}:{}:{}", d.layer_id, d.coord.tx, d.coord.ty),
TileKind::Mask => format!("{}__mask:{}:{}", d.layer_id, d.coord.tx, d.coord.ty),
TileKind::ImpastoHeight => format!("{}__impasto:{}:{}", d.layer_id, d.coord.tx, d.coord.ty),
};
let key_bytes = key.as_bytes();
raw.extend_from_slice(&(key_bytes.len() as u16).to_le_bytes());
raw.extend_from_slice(key_bytes);
let fmt = d
.after
.as_ref()
.or(d.before.as_ref())
.map(|t| t.format.io_storage_format())
.unwrap_or(TileFormat::Color32Bit);
raw.push(fmt.to_ink_byte());
if let Some(ref before) = d.before {
let bytes = before.to_format_raw(fmt, 128, true, scratch)?;
raw.push(1);
raw.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
raw.extend_from_slice(&bytes);
} else {
raw.push(0);
}
if let Some(ref after) = d.after {
let bytes = after.to_format_raw(fmt, 128, true, scratch)?;
raw.push(1);
raw.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
raw.extend_from_slice(&bytes);
} else {
raw.push(0);
}
}
deflate_fast(&raw)
}
/// Encodes an entire [`Document`] into a recovery checkpoint tuple:
/// `(manifest_json, deflate(INKG v1 snapshot), thumbnail_png)`.
pub fn encode_document_checkpoint(
doc: &Document,
scratch: Option<&dyn ScratchBackend>,
) -> Result<(String, Vec<u8>, Vec<u8>), String> {
let mut inkg = Vec::with_capacity(16 * 1024);
inkg.extend_from_slice(b"INKG");
inkg.push(1u8); // version 1
// Layer formats section
let format_entries: Vec<(&str, TileFormat)> = doc
.layers
.iter()
.filter(|l| l.meta.layer_type.has_tiles())
.map(|l| (l.meta.id.as_str(), l.grid.format.io_storage_format()))
.collect();
inkg.extend_from_slice(&(format_entries.len() as u32).to_le_bytes());
for (lid, fmt) in &format_entries {
let kb = lid.as_bytes();
inkg.extend_from_slice(&(kb.len() as u16).to_le_bytes());
inkg.extend_from_slice(kb);
inkg.push(fmt.to_ink_byte());
}
// Tiles section (raster tiles + mask tiles encoded under `<layerId>__mask`)
enum WalTileKind {
Raster { io_fmt: TileFormat, thresh: u8 },
Mask,
Impasto,
}
struct WalTileTask {
key: String,
coord: TileCoord,
kind: WalTileKind,
tile: Arc<TileData>,
}
let mut tasks: Vec<WalTileTask> = Vec::new();
for layer in &doc.layers {
let io_fmt = layer.grid.format.io_storage_format();
let thresh = layer.meta.mono_threshold.unwrap_or(128);
for (&coord, tile) in &layer.grid.tiles {
tasks.push(WalTileTask {
key: layer.meta.id.clone(),
coord,
kind: WalTileKind::Raster { io_fmt, thresh },
tile: Arc::clone(tile),
});
}
if layer.grid.has_mask {
let mask_key = format!("{}__mask", layer.meta.id);
for (&coord, tile) in &layer.grid.mask_tiles {
tasks.push(WalTileTask {
key: mask_key.clone(),
coord,
kind: WalTileKind::Mask,
tile: Arc::clone(tile),
});
}
}
if !layer.grid.impasto_tiles.is_empty() {
let imp_key = format!("{}__impasto", layer.meta.id);
for (&coord, tile) in &layer.grid.impasto_tiles {
tasks.push(WalTileTask {
key: imp_key.clone(),
coord,
kind: WalTileKind::Impasto,
tile: Arc::clone(tile),
});
}
}
}
let materialize = |task: WalTileTask| -> Result<(String, TileCoord, u8, u32, Vec<u8>), String> {
let (fmt_byte, raw) = match task.kind {
WalTileKind::Raster { io_fmt, thresh } => (
io_fmt.to_ink_byte(),
task.tile.to_format_raw(io_fmt, thresh, true, scratch)?,
),
WalTileKind::Mask => (
TileFormat::Grayscale8Bit.to_ink_byte(),
task.tile.materialize_raw(scratch)?,
),
WalTileKind::Impasto => (
TileFormat::Height16Float.to_ink_byte(),
task.tile.to_r16f(scratch)?,
),
};
Ok((
task.key,
task.coord,
fmt_byte,
task.tile.version as u32,
raw,
))
};
let encoded_tiles: Vec<(String, TileCoord, u8, u32, Vec<u8>)> = if tasks.len() >= 8 {
tasks
.into_par_iter()
.map(materialize)
.collect::<Result<Vec<_>, String>>()?
} else {
tasks
.into_iter()
.map(materialize)
.collect::<Result<Vec<_>, String>>()?
};
let tile_count = encoded_tiles.len() as u32;
inkg.extend_from_slice(&tile_count.to_le_bytes());
for (key, coord, fmt_byte, version, raw) in &encoded_tiles {
let kb = key.as_bytes();
inkg.extend_from_slice(&(kb.len() as u16).to_le_bytes());
inkg.extend_from_slice(kb);
inkg.extend_from_slice(&coord.tx.to_le_bytes());
inkg.extend_from_slice(&coord.ty.to_le_bytes());
inkg.push(*fmt_byte);
inkg.extend_from_slice(&version.to_le_bytes());
inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());
inkg.extend_from_slice(raw);
}
let compressed_snapshot = deflate_fast(&inkg)?;
let manifest = RecoveryManifest {
session_id: doc.id.clone(),
document_name: doc.name.clone(),
width: doc.dimensions.width,
height: doc.dimensions.height,
dpi: doc.dimensions.dpi,
color_mode: doc.color_mode,
layers: doc
.layers
.iter()
.map(|l| {
let mut m = l.meta.clone();
m.thumbnail_url = None;
m.mask_thumbnail_url = None;
m
})
.collect(),
active_layer_id: doc.active_layer_id.clone(),
timestamp: crate::history::unix_now_ms(),
work_time_ms: doc.work_time_ms,
timelapse: doc.timelapse.clone(),
};
let manifest_json = serde_json::to_string(&manifest)
.map_err(|e| format!("Failed to serialize recovery manifest: {e}"))?;
let thumbnail_png = doc
.render_flattened_png(256, true, scratch)
.map(|(_, _, png)| png)
.unwrap_or_default();
Ok((manifest_json, compressed_snapshot, thumbnail_png))
}
/// Replays a recovery manifest, optional `INKG v1` base snapshot, and `journal.wal` frames
/// directly into a hydrated Rust [`Document`]. Returns `(doc, strokes_replayed, mutations_replayed)`.
pub fn replay_recovery_into_document(
doc_id: impl Into<String>,
manifest_json: &str,
base_snapshot: Option<&[u8]>,
wal_entries: &[WalRawEntry],
max_history_steps: usize,
) -> Result<(Document, usize, usize), String> {
let manifest: RecoveryManifest = serde_json::from_str(manifest_json)
.map_err(|e| format!("Failed to parse recovery manifest: {e}"))?;
let dims = CanvasDimensions {
width: manifest.width.max(1),
height: manifest.height.max(1),
dpi: manifest.dpi.max(1),
};
let mut grids_by_layer: HashMap<String, SparseLayerGrid> = HashMap::new();
for l in &manifest.layers {
let fmt = l
.expression_color
.map(ExpressionColor::to_tile_format)
.unwrap_or(TileFormat::Color32Bit);
let mut g = SparseLayerGrid::new(fmt);
if l.has_mask {
g.init_mask(255);
}
grids_by_layer.insert(l.id.clone(), g);
}
// 1. Hydrate optional INKG v1 base snapshot
if let Some(snap_bytes) = base_snapshot {
if !snap_bytes.is_empty() {
let inkg = inflate_or_raw(snap_bytes, b"INKG")?;
apply_inkg_snapshot(&inkg, &mut grids_by_layer)?;
}
}
let mut current_layers = manifest.layers;
let mut active_layer_id = manifest.active_layer_id;
let mut strokes_replayed = 0usize;
let mut mutations_replayed = 0usize;
// 2. Replay WAL entries chronologically
for entry in wal_entries {
match entry.entry_type {
WAL_ENTRY_STROKE_TILE_DELTA => {
if let Ok(raw_td) = inflate_or_raw(&entry.payload, b"TD") {
if apply_td_wal_frame(&raw_td, &mut grids_by_layer).is_ok() {
strokes_replayed += 1;
}
}
}
WAL_ENTRY_VECTOR_STROKE => {
if let Ok(raw_json) = inflate_or_raw(&entry.payload, b"{") {
if let Ok(vec_payload) =
serde_json::from_slice::<VectorStrokeWalPayload>(&raw_json)
{
if let Some(lid) = vec_payload.layer_id.as_deref() {
if let Some(layer_meta) =
current_layers.iter_mut().find(|l| l.id == lid)
{
layer_meta.vector_strokes =
Some(serde_json::Value::Array(vec_payload.strokes));
strokes_replayed += 1;
}
}
}
}
}
WAL_ENTRY_LAYER_MUTATION => {
if let Ok(raw_json) = inflate_or_raw(&entry.payload, b"{") {
if let Ok(mut_payload) =
serde_json::from_slice::<LayerMutationWalPayload>(&raw_json)
{
if !mut_payload.layers.is_empty() {
// Preserve vectorStrokes when layer mutation WAL frames stripped them
let prev_vectors: HashMap<String, serde_json::Value> = current_layers
.iter()
.filter_map(|l| {
l.vector_strokes
.as_ref()
.map(|vs| (l.id.clone(), vs.clone()))
})
.collect();
let mut next_layers = mut_payload.layers;
for l in &mut next_layers {
if l.vector_strokes.is_none() {
if let Some(vs) = prev_vectors.get(&l.id) {
l.vector_strokes = Some(vs.clone());
}
}
}
current_layers = next_layers;
if mut_payload.active_layer_id.is_some() {
active_layer_id = mut_payload.active_layer_id;
}
mutations_replayed += 1;
}
}
}
}
_ => {}
}
}
let nodes: Vec<LayerNode> = current_layers
.into_iter()
.map(|meta| {
let fmt = meta
.expression_color
.map(ExpressionColor::to_tile_format)
.unwrap_or(TileFormat::Color32Bit);
let mut grid = grids_by_layer
.remove(&meta.id)
.unwrap_or_else(|| SparseLayerGrid::new(fmt));
if meta.has_mask && !grid.has_mask {
grid.init_mask(255);
}
LayerNode { meta, grid }
})
.collect();
let mut doc = Document::from_layers(
doc_id,
manifest.document_name,
dims,
manifest.color_mode,
nodes,
active_layer_id,
max_history_steps,
);
doc.work_time_ms = manifest.work_time_ms;
doc.timelapse = manifest.timelapse;
Ok((doc, strokes_replayed, mutations_replayed))
}
fn apply_inkg_snapshot(
buf: &[u8],
grids: &mut HashMap<String, SparseLayerGrid>,
) -> Result<(), String> {
if buf.len() < 9 || &buf[0..4] != b"INKG" || buf[4] != 1 {
return Err("Invalid INKG v1 snapshot header".to_string());
}
let mut off = 5usize;
let fmt_count = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;
off += 4;
for _ in 0..fmt_count {
if off + 2 > buf.len() {
return Err("Truncated INKG format table".to_string());
}
let klen = u16::from_le_bytes(buf[off..off + 2].try_into().unwrap()) as usize;
off += 2;
if off + klen + 1 > buf.len() {
return Err("Truncated INKG format entry".to_string());
}
let lid = std::str::from_utf8(&buf[off..off + klen])
.map_err(|_| "Invalid UTF-8 layer ID in INKG".to_string())?
.to_string();
off += klen;
let fmt = TileFormat::from_ink_byte(buf[off]).unwrap_or(TileFormat::Color32Bit);
off += 1;
grids
.entry(lid)
.or_insert_with(|| SparseLayerGrid::new(fmt))
.format = fmt;
}
if off + 4 > buf.len() {
return Err("Truncated INKG tile count".to_string());
}
let tile_count = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;
off += 4;
for _ in 0..tile_count {
if off + 2 > buf.len() {
return Err("Truncated INKG tile key length".to_string());
}
let klen = u16::from_le_bytes(buf[off..off + 2].try_into().unwrap()) as usize;
off += 2;
if off + klen + 17 > buf.len() {
return Err("Truncated INKG tile metadata".to_string());
}
let raw_lid = std::str::from_utf8(&buf[off..off + klen])
.map_err(|_| "Invalid UTF-8 layer ID in INKG tile".to_string())?;
off += klen;
let tx = i32::from_le_bytes(buf[off..off + 4].try_into().unwrap());
let ty = i32::from_le_bytes(buf[off + 4..off + 8].try_into().unwrap());
let fmt = TileFormat::from_ink_byte(buf[off + 8]).unwrap_or(TileFormat::Color32Bit);
let version = u32::from_le_bytes(buf[off + 9..off + 13].try_into().unwrap()) as u64;
let dlen = u32::from_le_bytes(buf[off + 13..off + 17].try_into().unwrap()) as usize;
off += 17;
if off + dlen > buf.len() {
return Err("Truncated INKG tile data".to_string());
}
let data = buf[off..off + dlen].to_vec();
off += dlen;
if dlen != fmt.byte_size() {
continue;
}
let coord = TileCoord::new(tx, ty);
if let Some(real_lid) = raw_lid.strip_suffix("__mask") {
let g = grids
.entry(real_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(TileFormat::Color32Bit));
let mut td = TileData::from_raw_auto_compact(TileFormat::Grayscale8Bit, TileKind::Mask, data);
if version > 0 {
td.version = version;
reserve_tile_version(version);
}
g.set_mask_tile(coord, Arc::new(td));
} else if let Some(real_lid) = raw_lid.strip_suffix("__impasto") {
let g = grids
.entry(real_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(TileFormat::Color32Bit));
let mut td = TileData::from_raw_auto_compact(
TileFormat::Height16Float,
TileKind::ImpastoHeight,
data,
);
if version > 0 {
td.version = version;
reserve_tile_version(version);
}
g.set_impasto_tile(coord, Arc::new(td));
} else {
let g = grids
.entry(raw_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(fmt));
let mut td = TileData::from_raw_auto_compact(fmt, TileKind::Raster, data);
if version > 0 {
td.version = version;
reserve_tile_version(version);
}
g.set_tile(coord, Arc::new(td));
}
}
Ok(())
}
fn apply_td_wal_frame(
buf: &[u8],
grids: &mut HashMap<String, SparseLayerGrid>,
) -> Result<(), String> {
if buf.len() < 7 || &buf[0..2] != b"TD" || buf[2] != 1 {
return Err("Invalid TD v1 WAL frame".to_string());
}
let count = u32::from_le_bytes(buf[3..7].try_into().unwrap()) as usize;
let mut off = 7usize;
for _ in 0..count {
if off + 2 > buf.len() {
return Err("Truncated TD key len".to_string());
}
let klen = u16::from_le_bytes(buf[off..off + 2].try_into().unwrap()) as usize;
off += 2;
if off + klen + 2 > buf.len() {
return Err("Truncated TD key".to_string());
}
let key = std::str::from_utf8(&buf[off..off + klen])
.map_err(|_| "Invalid UTF-8 key in TD WAL".to_string())?;
off += klen;
let fmt = TileFormat::from_ink_byte(buf[off]).unwrap_or(TileFormat::Color32Bit);
off += 1;
let has_before = buf[off];
off += 1;
if has_before == 1 {
if off + 4 > buf.len() {
return Err("Truncated TD before len".to_string());
}
let blen = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;
off += 4;
if off + blen > buf.len() {
return Err("Truncated TD before data".to_string());
}
off += blen;
}
if off >= buf.len() {
return Err("Truncated TD after flag".to_string());
}
let has_after = buf[off];
off += 1;
let after_data = if has_after == 1 {
if off + 4 > buf.len() {
return Err("Truncated TD after len".to_string());
}
let alen = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()) as usize;
off += 4;
if off + alen > buf.len() {
return Err("Truncated TD after data".to_string());
}
let d = buf[off..off + alen].to_vec();
off += alen;
Some(d)
} else {
None
};
// Key format: `layerId:tx:ty` or `layerId__mask:tx:ty`
let parts: Vec<&str> = key.rsplitn(3, ':').collect();
if parts.len() != 3 {
continue;
}
let (Ok(ty), Ok(tx)) = (parts[0].parse::<i32>(), parts[1].parse::<i32>()) else {
continue;
};
let raw_lid = parts[2];
let coord = TileCoord::new(tx, ty);
if let Some(real_lid) = raw_lid.strip_suffix("__mask") {
let g = grids
.entry(real_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(TileFormat::Color32Bit));
if let Some(d) = after_data {
if d.len() == TileFormat::Grayscale8Bit.byte_size() {
g.set_mask_tile(
coord,
Arc::new(TileData::from_raw_auto_compact(
TileFormat::Grayscale8Bit,
TileKind::Mask,
d,
)),
);
}
} else {
g.remove_mask_tile(coord);
}
} else if let Some(real_lid) = raw_lid.strip_suffix("__impasto") {
let g = grids
.entry(real_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(TileFormat::Color32Bit));
if let Some(d) = after_data {
if d.len() == TileFormat::Height16Float.byte_size() {
g.set_impasto_tile(
coord,
Arc::new(TileData::from_raw_auto_compact(
TileFormat::Height16Float,
TileKind::ImpastoHeight,
d,
)),
);
}
} else {
g.remove_impasto_tile(coord);
}
} else {
let g = grids
.entry(raw_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(fmt));
if let Some(d) = after_data {
// Only a frame that carries pixels may define the layer's storage format. A
// removal-only frame (eraser cleared a tile) encodes a placeholder format and
// used to silently convert 1-bit/grayscale layers to 32-bit color on recovery.
g.format = fmt;
if d.len() == fmt.byte_size() {
g.set_tile(
coord,
Arc::new(TileData::from_raw_auto_compact(fmt, TileKind::Raster, d)),
);
}
} else {
g.remove_tile(coord);
}
}
}
Ok(())
}