Skip to content

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

31.7 KB
Raw Blame
//! Direct Rust `.ink` v2 binary ZIP serializer and parser — reading and writing directly
//! from `ink-engine`'s sparse tile grids with Rayon multi-core parallel DEFLATE compression
//! and zero JS pixel transfers.
//!
//! 100% wire-compatible with InkStudio `.ink` v2 format (`src/utils/saveManager/inkSerialize.ts`
//! & `inkParse.ts`):
//! - `manifest.json`
//! - `preview.png` (stored without re-deflation)
//! - `tiles/<safeKey>/<tx>_<ty>.bin` (`[format:u8][version:u32 LE][dataLen:u32 LE][rawTileBytes]`)
//! - `masks/<safeKey>.bin` (`[width:u32 LE][height:u32 LE][alpha8Bytes]`)

use crate::document::{
    CanvasColorMode, CanvasDimensions, Document, ExpressionColor, LayerNode, LayerNodeMeta,
};
use crate::history::unix_now_ms;
use crate::io::png_codec;
use crate::memory::ScratchBackend;
use crate::tiles::{
    reserve_tile_version, RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind,
    TILE_SIZE,
};
use flate2::read::DeflateDecoder;
use flate2::write::DeflateEncoder;
use flate2::Compression;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::io::{Read, Write};
use std::sync::Arc;

const TILE_BINARY_HEADER_BYTES: usize = 9;
const MASK_BINARY_HEADER_BYTES: usize = 8;
const MAX_MANIFEST_BYTES: usize = 64 * 1024 * 1024;
const MAX_DOCUMENT_DIM: u32 = 65536;
const MAX_TILE_ENTRIES: usize = 120_000;
const PREVIEW_MAX_DIM: u32 = 512;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PreviewManifestRef {
    path: String,
    width: u32,
    height: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MaskManifestMeta {
    width: u32,
    height: u32,
    format: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct InkProjectManifest {
    format: String,
    app: String,
    version: String,
    tile_size: usize,
    name: String,
    dimensions: CanvasDimensions,
    color_mode: CanvasColorMode,
    layers: Vec<LayerNodeMeta>,
    #[serde(default)]
    layer_formats: HashMap<String, TileFormat>,
    #[serde(default)]
    layer_tile_keys: HashMap<String, String>,
    #[serde(default)]
    masks_meta: HashMap<String, MaskManifestMeta>,
    #[serde(default)]
    perspective_ruler: Option<serde_json::Value>,
    #[serde(default)]
    straight_ruler: Option<serde_json::Value>,
    #[serde(default)]
    animation_timeline: Option<serde_json::Value>,
    #[serde(default)]
    timelapse: Option<serde_json::Value>,
    #[serde(default)]
    work_time_ms: u64,
    #[serde(default)]
    preview: Option<PreviewManifestRef>,
    #[serde(default)]
    saved_at: u64,
}

/// Result of direct Rust `.ink` serialization.
#[derive(Debug, Clone)]
pub struct SerializedInkResult {
    pub bytes: Vec<u8>,
    pub preview_png: Option<Vec<u8>>,
    pub preview_data_url: Option<String>,
    pub tile_count: usize,
    pub mask_count: usize,
}

fn to_safe_zip_key(raw_id: &str, used: &mut HashSet<String>) -> String {
    let mut base: String = raw_id
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if base.is_empty() || base == "." || base == ".." {
        base = "layer".to_string();
    }
    while base.contains("..") {
        base = base.replace("..", "_");
    }
    let mut candidate = base.clone();
    let mut suffix = 1u32;
    while !used.insert(candidate.clone()) {
        candidate = format!("{base}_{suffix}");
        suffix += 1;
    }
    candidate
}

fn is_safe_zip_path(path: &str) -> bool {
    if path.is_empty() || path.contains('\0') || path.contains('\\') || path.starts_with('/') {
        return false;
    }
    for seg in path.split('/') {
        if seg.is_empty() || seg == "." || seg == ".." {
            return false;
        }
    }
    true
}

struct PreparedZipEntry {
    name: String,
    compression_method: u16, // 0 = Store, 8 = Deflate
    crc32: u32,
    uncompressed_len: u32,
    compressed_data: Vec<u8>,
}

fn prepare_zip_entry(name: String, raw: &[u8], deflate_level: Option<u32>) -> Result<PreparedZipEntry, String> {
    let uncompressed_len = u32::try_from(raw.len())
        .map_err(|_| format!("ZIP entry {name} exceeds 4 GB limit"))?;
    let crc32 = crc32fast::hash(raw);
    let (compression_method, compressed_data) = if let Some(lvl) = deflate_level {
        let mut enc = DeflateEncoder::new(Vec::with_capacity(raw.len() / 2 + 32), Compression::new(lvl));
        enc.write_all(raw)
            .map_err(|e| format!("Failed to deflate ZIP entry {name}: {e}"))?;
        let data = enc
            .finish()
            .map_err(|e| format!("Failed to finalize ZIP entry {name}: {e}"))?;
        (8u16, data)
    } else {
        (0u16, raw.to_vec())
    };
    Ok(PreparedZipEntry {
        name,
        compression_method,
        crc32,
        uncompressed_len,
        compressed_data,
    })
}

/// Assembles pre-compressed entries into a standards-compliant ZIP archive.
fn assemble_zip(entries: Vec<PreparedZipEntry>) -> Result<Vec<u8>, String> {
    let est_size: usize = entries
        .iter()
        .map(|e| 96 + e.name.len() * 2 + e.compressed_data.len())
        .sum::<usize>()
        + 64;
    let mut out = Vec::with_capacity(est_size);
    let mut cd_records: Vec<(u32, PreparedZipEntry)> = Vec::with_capacity(entries.len());

    for entry in entries {
        let local_offset = u32::try_from(out.len())
            .map_err(|_| "ZIP archive exceeds 4 GB standard offset limit".to_string())?;
        let name_bytes = entry.name.as_bytes();
        let name_len = u16::try_from(name_bytes.len())
            .map_err(|_| "ZIP entry filename too long".to_string())?;
        let comp_len = u32::try_from(entry.compressed_data.len())
            .map_err(|_| "ZIP compressed entry exceeds 4 GB".to_string())?;

        // Local file header (30 bytes + name)
        out.extend_from_slice(&0x0403_4B50u32.to_le_bytes()); // PK\x03\x04
        out.extend_from_slice(&20u16.to_le_bytes()); // version needed 2.0
        out.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 filename flag
        out.extend_from_slice(&entry.compression_method.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes()); // mod time
        out.extend_from_slice(&0u16.to_le_bytes()); // mod date
        out.extend_from_slice(&entry.crc32.to_le_bytes());
        out.extend_from_slice(&comp_len.to_le_bytes());
        out.extend_from_slice(&entry.uncompressed_len.to_le_bytes());
        out.extend_from_slice(&name_len.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes()); // extra len
        out.extend_from_slice(name_bytes);
        out.extend_from_slice(&entry.compressed_data);

        cd_records.push((local_offset, entry));
    }

    let cd_offset = u32::try_from(out.len())
        .map_err(|_| "ZIP central directory exceeds 4 GB offset limit".to_string())?;
    let entry_count = u16::try_from(cd_records.len())
        .map_err(|_| "ZIP entry count exceeds 65535 limit".to_string())?;

    for (local_offset, entry) in &cd_records {
        let name_bytes = entry.name.as_bytes();
        let name_len = name_bytes.len() as u16;
        let comp_len = entry.compressed_data.len() as u32;

        // Central directory header (46 bytes + name)
        out.extend_from_slice(&0x0201_4B50u32.to_le_bytes()); // PK\x01\x02
        out.extend_from_slice(&20u16.to_le_bytes()); // version made by
        out.extend_from_slice(&20u16.to_le_bytes()); // version needed
        out.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 flag
        out.extend_from_slice(&entry.compression_method.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes()); // mod time
        out.extend_from_slice(&0u16.to_le_bytes()); // mod date
        out.extend_from_slice(&entry.crc32.to_le_bytes());
        out.extend_from_slice(&comp_len.to_le_bytes());
        out.extend_from_slice(&entry.uncompressed_len.to_le_bytes());
        out.extend_from_slice(&name_len.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes()); // extra len
        out.extend_from_slice(&0u16.to_le_bytes()); // comment len
        out.extend_from_slice(&0u16.to_le_bytes()); // disk number
        out.extend_from_slice(&0u16.to_le_bytes()); // internal attrs
        out.extend_from_slice(&0u32.to_le_bytes()); // external attrs
        out.extend_from_slice(&local_offset.to_le_bytes());
        out.extend_from_slice(name_bytes);
    }

    let cd_size = (out.len() as u32).saturating_sub(cd_offset);

    // End of Central Directory (22 bytes)
    out.extend_from_slice(&0x0605_4B50u32.to_le_bytes()); // PK\x05\x06
    out.extend_from_slice(&0u16.to_le_bytes()); // disk num
    out.extend_from_slice(&0u16.to_le_bytes()); // cd start disk
    out.extend_from_slice(&entry_count.to_le_bytes());
    out.extend_from_slice(&entry_count.to_le_bytes());
    out.extend_from_slice(&cd_size.to_le_bytes());
    out.extend_from_slice(&cd_offset.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes()); // comment len

    Ok(out)
}

#[derive(Debug, Clone)]
struct ParsedZipEntryRef<'a> {
    name: String,
    compression_method: u16,
    crc32: u32,
    uncompressed_len: usize,
    compressed_slice: &'a [u8],
}

fn parse_zip_directory(bytes: &[u8]) -> Result<Vec<ParsedZipEntryRef<'_>>, String> {
    if bytes.len() < 22 {
        return Err("Invalid .ink ZIP archive: file too short".to_string());
    }
    // Locate EOCD signature `PK\x05\x06` from the back (max 65557 bytes)
    let search_start = bytes.len().saturating_sub(65557);
    let mut eocd_pos = None;
    for pos in (search_start..=bytes.len() - 22).rev() {
        if &bytes[pos..pos + 4] == b"PK\x05\x06" {
            let comment_len = u16::from_le_bytes([bytes[pos + 20], bytes[pos + 21]]) as usize;
            if pos + 22 + comment_len == bytes.len() {
                eocd_pos = Some(pos);
                break;
            }
        }
    }
    let eocd = eocd_pos.ok_or_else(|| "Invalid .ink ZIP archive: missing EOCD".to_string())?;
    let total_entries = u16::from_le_bytes([bytes[eocd + 10], bytes[eocd + 11]]) as usize;
    let cd_size = u32::from_le_bytes(bytes[eocd + 12..eocd + 16].try_into().unwrap()) as usize;
    let cd_offset = u32::from_le_bytes(bytes[eocd + 16..eocd + 20].try_into().unwrap()) as usize;

    if cd_offset.checked_add(cd_size).is_none_or(|end| end > eocd) {
        return Err("Invalid .ink ZIP archive: corrupt central directory bounds".to_string());
    }

    let mut entries = Vec::with_capacity(total_entries);
    let mut pos = cd_offset;
    let cd_end = cd_offset + cd_size;

    while pos < cd_end {
        if pos + 46 > cd_end || &bytes[pos..pos + 4] != b"PK\x01\x02" {
            return Err("Invalid .ink ZIP archive: corrupt central directory header".to_string());
        }
        let method = u16::from_le_bytes([bytes[pos + 10], bytes[pos + 11]]);
        let crc32 = u32::from_le_bytes(bytes[pos + 16..pos + 20].try_into().unwrap());
        let comp_len = u32::from_le_bytes(bytes[pos + 20..pos + 24].try_into().unwrap()) as usize;
        let uncomp_len =
            u32::from_le_bytes(bytes[pos + 24..pos + 28].try_into().unwrap()) as usize;
        let name_len = u16::from_le_bytes([bytes[pos + 28], bytes[pos + 29]]) as usize;
        let extra_len = u16::from_le_bytes([bytes[pos + 30], bytes[pos + 31]]) as usize;
        let comment_len = u16::from_le_bytes([bytes[pos + 32], bytes[pos + 33]]) as usize;
        let local_off =
            u32::from_le_bytes(bytes[pos + 42..pos + 46].try_into().unwrap()) as usize;

        let name_start = pos + 46;
        let name_end = name_start + name_len;
        if name_end + extra_len + comment_len > cd_end {
            return Err("Invalid .ink ZIP archive: truncated entry metadata".to_string());
        }
        let name = std::str::from_utf8(&bytes[name_start..name_end])
            .map_err(|_| "Invalid UTF-8 filename in .ink archive".to_string())?
            .to_string();
        if !is_safe_zip_path(&name) {
            return Err(format!("Unsafe archive path in .ink file: \"{name}\""));
        }

        // Read local file header to compute exact compressed payload slice
        if local_off + 30 > bytes.len() || &bytes[local_off..local_off + 4] != b"PK\x03\x04" {
            return Err(format!("Corrupt local file header for entry \"{name}\""));
        }
        let lh_name_len =
            u16::from_le_bytes([bytes[local_off + 26], bytes[local_off + 27]]) as usize;
        let lh_extra_len =
            u16::from_le_bytes([bytes[local_off + 28], bytes[local_off + 29]]) as usize;
        let data_start = local_off + 30 + lh_name_len + lh_extra_len;
        let data_end = data_start
            .checked_add(comp_len)
            .filter(|&end| end <= bytes.len())
            .ok_or_else(|| format!("Truncated payload for entry \"{name}\""))?;

        entries.push(ParsedZipEntryRef {
            name,
            compression_method: method,
            crc32,
            uncompressed_len: uncomp_len,
            compressed_slice: &bytes[data_start..data_end],
        });

        pos = name_end + extra_len + comment_len;
    }

    Ok(entries)
}

fn inflate_zip_entry(entry: &ParsedZipEntryRef<'_>, max_bytes: usize) -> Result<Vec<u8>, String> {
    if entry.uncompressed_len > max_bytes {
        return Err(format!(
            "Entry \"{}\" exceeds safety size limit ({} > {})",
            entry.name, entry.uncompressed_len, max_bytes
        ));
    }
    let raw = match entry.compression_method {
        0 => entry.compressed_slice.to_vec(),
        8 => {
            let mut decoder = DeflateDecoder::new(entry.compressed_slice);
            let mut out = Vec::with_capacity(entry.uncompressed_len.min(max_bytes));
            let mut limited = decoder.by_ref().take((max_bytes + 1) as u64);
            limited
                .read_to_end(&mut out)
                .map_err(|e| format!("Failed to inflate entry \"{}\": {e}", entry.name))?;
            if out.len() > max_bytes {
                return Err(format!("Decompressed entry \"{}\" exceeded safety cap", entry.name));
            }
            out
        }
        other => {
            return Err(format!(
                "Unsupported ZIP compression method {} for \"{}\"",
                other, entry.name
            ))
        }
    };
    let actual_crc = crc32fast::hash(&raw);
    if entry.crc32 != 0 && actual_crc != entry.crc32 {
        return Err(format!("CRC32 mismatch in .ink entry \"{}\"", entry.name));
    }
    Ok(raw)
}

/// Fast preview-only extraction from `.ink` ZIP bytes (does not inflate any tile entries).
pub fn extract_ink_preview(zip_bytes: &[u8]) -> Option<Vec<u8>> {
    let entries = parse_zip_directory(zip_bytes).ok()?;
    let preview = entries.iter().find(|e| e.name == "preview.png")?;
    inflate_zip_entry(preview, 16 * 1024 * 1024).ok()
}

/// Serializes `doc` directly from Rust's sparse tile grids into a `.ink` v2 ZIP archive
/// using Rayon multi-core parallel DEFLATE compression (zero JS pixel IPC!).
pub fn serialize_ink_document(
    doc: &Document,
    compression_level: u32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<SerializedInkResult, String> {
    let level = compression_level.min(6);
    let mut used_keys = HashSet::new();
    let mut layer_tile_keys = HashMap::new();
    let mut layer_formats = HashMap::new();
    let mut masks_meta = HashMap::new();

    struct TileWorkItem {
        zip_path: String,
        storage_format: TileFormat,
        mono_threshold: u8,
        tile: Arc<TileData>,
    }

    let mut tile_work: Vec<TileWorkItem> = Vec::new();
    let mut mask_work: Vec<(String, u32, u32, Vec<u8>)> = Vec::new();
    let mut manifest_layers: Vec<LayerNodeMeta> = Vec::with_capacity(doc.layers.len());

    for layer in &doc.layers {
        let safe_key = to_safe_zip_key(&layer.meta.id, &mut used_keys);
        layer_tile_keys.insert(layer.meta.id.clone(), safe_key.clone());

        if layer.meta.layer_type.has_tiles() {
            let io_fmt = layer.grid.format.io_storage_format();
            layer_formats.insert(layer.meta.id.clone(), io_fmt);
            let thresh = layer.meta.mono_threshold.unwrap_or(128);
            for (&coord, tile_arc) in &layer.grid.tiles {
                tile_work.push(TileWorkItem {
                    zip_path: format!("tiles/{safe_key}/{}_{}.bin", coord.tx, coord.ty),
                    storage_format: io_fmt,
                    mono_threshold: thresh,
                    tile: Arc::clone(tile_arc),
                });
            }
            for (&coord, imp_arc) in &layer.grid.impasto_tiles {
                tile_work.push(TileWorkItem {
                    zip_path: format!("impasto/{safe_key}/{}_{}.bin", coord.tx, coord.ty),
                    storage_format: TileFormat::Height16Float,
                    mono_threshold: 128,
                    tile: Arc::clone(imp_arc),
                });
            }
        }

        if layer.grid.has_mask && doc.dimensions.width > 0 && doc.dimensions.height > 0 {
            let mask_bytes = layer.grid.read_mask8_rect(
                RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height),
                scratch,
            )?;
            masks_meta.insert(
                layer.meta.id.clone(),
                MaskManifestMeta {
                    width: doc.dimensions.width,
                    height: doc.dimensions.height,
                    format: "alpha-8bit".to_string(),
                },
            );
            mask_work.push((
                format!("masks/{safe_key}.bin"),
                doc.dimensions.width,
                doc.dimensions.height,
                mask_bytes,
            ));
        }

        manifest_layers.push(layer.meta.clone());
    }

    let tile_count = tile_work.len();
    let mask_count = mask_work.len();

    // Generate preview.png directly in Rust from live tiles
    let preview = doc
        .render_flattened_png(PREVIEW_MAX_DIM, true, scratch)
        .ok();

    // Parallel-encode and deflate all tiles via Rayon
    let tile_entries: Result<Vec<PreparedZipEntry>, String> = tile_work
        .into_par_iter()
        .map(|item| {
            let raw = item.tile.to_format_raw(
                item.storage_format,
                item.mono_threshold,
                true, // Bayer-dither Rgba16Float -> Rgba8 on save boundary
                scratch,
            )?;
            let mut record = Vec::with_capacity(TILE_BINARY_HEADER_BYTES + raw.len());
            record.push(item.storage_format.to_ink_byte());
            record.extend_from_slice(&(item.tile.version as u32).to_le_bytes());
            record.extend_from_slice(&(raw.len() as u32).to_le_bytes());
            record.extend_from_slice(&raw);
            prepare_zip_entry(item.zip_path, &record, Some(level))
        })
        .collect();
    let tile_entries = tile_entries?;

    // Parallel-encode and deflate all masks via Rayon
    let mask_entries: Result<Vec<PreparedZipEntry>, String> = mask_work
        .into_par_iter()
        .map(|(path, mw, mh, alpha)| {
            let mut record = Vec::with_capacity(MASK_BINARY_HEADER_BYTES + alpha.len());
            record.extend_from_slice(&mw.to_le_bytes());
            record.extend_from_slice(&mh.to_le_bytes());
            record.extend_from_slice(&alpha);
            prepare_zip_entry(path, &record, Some(level))
        })
        .collect();
    let mask_entries = mask_entries?;

    let (preview_manifest, preview_png, preview_data_url) = if let Some((pw, ph, png_bytes)) = preview
    {
        let data_url = png_codec::png_bytes_to_data_url(&png_bytes);
        (
            Some(PreviewManifestRef {
                path: "preview.png".to_string(),
                width: pw,
                height: ph,
            }),
            Some(png_bytes),
            Some(data_url),
        )
    } else {
        (None, None, None)
    };

    let manifest = InkProjectManifest {
        format: "ink-v2".to_string(),
        app: "Ink Studio".to_string(),
        version: "2.0".to_string(),
        tile_size: TILE_SIZE,
        name: doc.name.clone(),
        dimensions: doc.dimensions,
        color_mode: doc.color_mode,
        layers: manifest_layers,
        layer_formats,
        layer_tile_keys,
        masks_meta,
        perspective_ruler: doc.perspective_ruler.clone(),
        straight_ruler: doc.straight_ruler.clone(),
        animation_timeline: doc.animation_timeline.clone(),
        timelapse: doc.timelapse.clone(),
        work_time_ms: doc.work_time_ms,
        preview: preview_manifest,
        saved_at: unix_now_ms(),
    };
    let manifest_bytes = serde_json::to_vec(&manifest)
        .map_err(|e| format!("Failed to serialize .ink manifest.json: {e}"))?;

    let mut all_entries = Vec::with_capacity(2 + tile_entries.len() + mask_entries.len());
    if let Some(ref png_bytes) = preview_png {
        all_entries.push(prepare_zip_entry("preview.png".to_string(), png_bytes, None)?);
    }
    all_entries.extend(tile_entries);
    all_entries.extend(mask_entries);
    all_entries.push(prepare_zip_entry(
        "manifest.json".to_string(),
        &manifest_bytes,
        Some(6),
    )?);

    let zip_bytes = assemble_zip(all_entries)?;
    Ok(SerializedInkResult {
        bytes: zip_bytes,
        preview_png,
        preview_data_url,
        tile_count,
        mask_count,
    })
}

/// Parses a `.ink` v2 ZIP archive directly into a Rust [`Document`] with parallel Rayon tile
/// decompression, zero-copy hydration, and parallel 64×64 thumbnail generation!
pub fn parse_ink_document(
    zip_bytes: &[u8],
    doc_id: impl Into<String>,
    fallback_name: &str,
    max_history_steps: usize,
) -> Result<Document, String> {
    let entries = parse_zip_directory(zip_bytes)?;
    let manifest_entry = entries
        .iter()
        .find(|e| e.name == "manifest.json")
        .ok_or_else(|| "Invalid .ink project: missing manifest.json".to_string())?;
    let manifest_raw = inflate_zip_entry(manifest_entry, MAX_MANIFEST_BYTES)?;
    let manifest: InkProjectManifest = serde_json::from_slice(&manifest_raw)
        .map_err(|e| format!("Invalid .ink manifest.json: {e}"))?;

    let width = manifest.dimensions.width;
    let height = manifest.dimensions.height;
    if width == 0 || height == 0 || width > MAX_DOCUMENT_DIM || height > MAX_DOCUMENT_DIM {
        return Err(format!("Invalid .ink dimensions: {width}x{height}"));
    }

    // Build reverse safeKey -> layerId mapping
    let mut key_to_layer_id: HashMap<String, String> = HashMap::new();
    for (lid, safe_key) in &manifest.layer_tile_keys {
        if !safe_key.is_empty() {
            key_to_layer_id.insert(safe_key.clone(), lid.clone());
        }
    }
    for layer in &manifest.layers {
        key_to_layer_id
            .entry(layer.id.clone())
            .or_insert_with(|| layer.id.clone());
    }

    // Classify tile, impasto heightfield, & mask ZIP entries
    let mut tile_refs: Vec<(&ParsedZipEntryRef<'_>, String, i32, i32, TileKind)> = Vec::new();
    let mut mask_refs: Vec<(&ParsedZipEntryRef<'_>, String)> = Vec::new();

    for entry in &entries {
        if let Some(rest) = entry.name.strip_prefix("tiles/") {
            if let Some((safe_key, file_part)) = rest.split_once('/') {
                if let Some(stem) = file_part.strip_suffix(".bin") {
                    if let Some((tx_s, ty_s)) = stem.split_once('_') {
                        if let (Ok(tx), Ok(ty), Some(lid)) = (
                            tx_s.parse::<i32>(),
                            ty_s.parse::<i32>(),
                            key_to_layer_id.get(safe_key),
                        ) {
                            tile_refs.push((entry, lid.clone(), tx, ty, TileKind::Raster));
                        }
                    }
                }
            }
        } else if let Some(rest) = entry.name.strip_prefix("impasto/") {
            if let Some((safe_key, file_part)) = rest.split_once('/') {
                if let Some(stem) = file_part.strip_suffix(".bin") {
                    if let Some((tx_s, ty_s)) = stem.split_once('_') {
                        if let (Ok(tx), Ok(ty), Some(lid)) = (
                            tx_s.parse::<i32>(),
                            ty_s.parse::<i32>(),
                            key_to_layer_id.get(safe_key),
                        ) {
                            tile_refs.push((entry, lid.clone(), tx, ty, TileKind::ImpastoHeight));
                        }
                    }
                }
            }
        } else if let Some(rest) = entry.name.strip_prefix("masks/") {
            if let Some(safe_key) = rest.strip_suffix(".bin") {
                if let Some(lid) = key_to_layer_id.get(safe_key) {
                    mask_refs.push((entry, lid.clone()));
                }
            }
        }
    }

    if tile_refs.len() > MAX_TILE_ENTRIES {
        return Err(format!(
            "Invalid .ink project: tile count {} exceeds limit",
            tile_refs.len()
        ));
    }

    // Parallel-inflate and decode all raster & impasto tiles via Rayon
    let decoded_tiles: Result<Vec<(String, TileKind, TileCoord, TileData)>, String> = tile_refs
        .into_par_iter()
        .map(|(entry, layer_id, tx, ty, kind)| {
            let payload = inflate_zip_entry(entry, 4 * 1024 * 1024)?;
            if payload.len() < TILE_BINARY_HEADER_BYTES {
                return Err(format!(
                    "Corrupted .ink tile ({layer_id} {tx}_{ty}): truncated header"
                ));
            }
            let fmt = TileFormat::from_ink_byte(payload[0]).ok_or_else(|| {
                format!(
                    "Corrupted .ink tile ({layer_id} {tx}_{ty}): unknown format {}",
                    payload[0]
                )
            })?;
            let version = u32::from_le_bytes(payload[1..5].try_into().unwrap()) as u64;
            let data_len = u32::from_le_bytes(payload[5..9].try_into().unwrap()) as usize;
            let expected = fmt.byte_size();
            if data_len != expected || payload.len() != TILE_BINARY_HEADER_BYTES + expected {
                return Err(format!(
                    "Corrupted .ink tile ({layer_id} {tx}_{ty}): length mismatch"
                ));
            }
            let mut td = TileData::from_raw_auto_compact(
                fmt,
                kind,
                payload[TILE_BINARY_HEADER_BYTES..].to_vec(),
            );
            if version > 0 {
                td.version = version;
                reserve_tile_version(version);
            }
            Ok((layer_id, kind, TileCoord::new(tx, ty), td))
        })
        .collect();
    let decoded_tiles = decoded_tiles?;

    // Parallel-inflate and decode all masks via Rayon
    type DecodedMaskEntry = (String, u32, u32, Vec<u8>);
    let decoded_masks: Result<Vec<DecodedMaskEntry>, String> = mask_refs
        .into_par_iter()
        .map(|(entry, layer_id)| {
            let payload = inflate_zip_entry(entry, 128 * 1024 * 1024)?;
            if payload.len() < MASK_BINARY_HEADER_BYTES {
                return Err(format!("Corrupted .ink mask ({layer_id}): truncated header"));
            }
            let mw = u32::from_le_bytes(payload[0..4].try_into().unwrap());
            let mh = u32::from_le_bytes(payload[4..8].try_into().unwrap());
            let expected = (mw as usize)
                .checked_mul(mh as usize)
                .ok_or_else(|| "Mask dimensions overflow".to_string())?;
            if payload.len() != MASK_BINARY_HEADER_BYTES + expected {
                return Err(format!("Corrupted .ink mask ({layer_id}): length mismatch"));
            }
            Ok((
                layer_id,
                mw,
                mh,
                payload[MASK_BINARY_HEADER_BYTES..].to_vec(),
            ))
        })
        .collect();
    let decoded_masks = decoded_masks?;

    // Group decoded tiles, impasto height tiles, & masks by layer ID
    let mut tiles_by_layer: HashMap<String, Vec<(TileCoord, TileData)>> = HashMap::new();
    let mut impasto_by_layer: HashMap<String, Vec<(TileCoord, TileData)>> = HashMap::new();
    for (lid, kind, coord, td) in decoded_tiles {
        match kind {
            TileKind::ImpastoHeight => {
                impasto_by_layer.entry(lid).or_default().push((coord, td));
            }
            _ => {
                tiles_by_layer.entry(lid).or_default().push((coord, td));
            }
        }
    }
    let mut masks_by_layer: HashMap<String, (u32, u32, Vec<u8>)> = HashMap::new();
    for (lid, mw, mh, data) in decoded_masks {
        masks_by_layer.insert(lid, (mw, mh, data));
    }

    // Assemble LayerNodes and generate 64×64 thumbnails in parallel
    let nodes: Vec<LayerNode> = manifest
        .layers
        .into_par_iter()
        .map(|mut meta| {
            let fmt = manifest
                .layer_formats
                .get(&meta.id)
                .copied()
                .or_else(|| meta.expression_color.map(ExpressionColor::to_tile_format))
                .unwrap_or(TileFormat::Color32Bit);
            let mut grid = SparseLayerGrid::new(fmt);
            if let Some(layer_tiles) = tiles_by_layer.get(&meta.id) {
                if let Some((_, first)) = layer_tiles.first() {
                    grid.format = first.format;
                }
                for (coord, td) in layer_tiles {
                    grid.set_tile(*coord, Arc::new(td.clone()));
                }
            }
            if let Some(imp_tiles) = impasto_by_layer.get(&meta.id) {
                for (coord, td) in imp_tiles {
                    grid.set_impasto_tile(*coord, Arc::new(td.clone()));
                }
            }
            if let Some((mw, mh, mask_bytes)) = masks_by_layer.get(&meta.id) {
                grid.init_mask(255);
                let _ = grid.write_mask8_rect(mask_bytes, RectI32::new(0, 0, *mw, *mh), None);
                meta.has_mask = true;
                if meta.mask_enabled.is_none() {
                    meta.mask_enabled = Some(true);
                }
                if meta.mask_linked.is_none() {
                    meta.mask_linked = Some(true);
                }
                meta.mask_version = Some(grid.mask_version);
            }

            let mut node = LayerNode { meta, grid };
            if node.meta.layer_type.has_tiles() {
                if let Ok((tw, th, rgba)) = crate::io::compositor_cpu::render_layer_thumbnail_rgba(
                    &node, width, height, 64, 64, None,
                ) {
                    if let Ok(png) = png_codec::encode_rgba8_to_png(tw, th, &rgba) {
                        node.meta.thumbnail_url = Some(png_codec::png_bytes_to_data_url(&png));
                    }
                }
            }
            if node.grid.has_mask {
                if let Ok((tw, th, rgba)) = crate::io::compositor_cpu::render_mask_thumbnail_rgba(
                    &node, width, height, 64, 64, None,
                ) {
                    if let Ok(png) = png_codec::encode_rgba8_to_png(tw, th, &rgba) {
                        node.meta.mask_thumbnail_url = Some(png_codec::png_bytes_to_data_url(&png));
                    }
                }
            }
            node
        })
        .collect();

    let preview_data_url = entries
        .iter()
        .find(|e| e.name == "preview.png")
        .and_then(|e| inflate_zip_entry(e, 16 * 1024 * 1024).ok())
        .map(|png| png_codec::png_bytes_to_data_url(&png));

    let doc_name = if manifest.name.trim().is_empty() {
        fallback_name.to_string()
    } else {
        manifest.name
    };

    let mut doc = Document::from_layers(
        doc_id,
        doc_name,
        manifest.dimensions,
        manifest.color_mode,
        nodes,
        None,
        max_history_steps,
    );
    doc.perspective_ruler = manifest.perspective_ruler;
    doc.straight_ruler = manifest.straight_ruler;
    doc.animation_timeline = manifest.animation_timeline;
    doc.timelapse = manifest.timelapse;
    doc.work_time_ms = manifest.work_time_ms;
    doc.preview_data_url = preview_data_url;

    Ok(doc)
}