From 1a454edd099675ee82188d064434de2122d1ce42 Mon Sep 17 00:00:00 2001 From: Christopher Linnett Date: Fri, 30 Oct 2026 15:09:25 +0800 Subject: [PATCH] M8: .fig import budgets four values per compressed canvas byte instead of one (#574) The .fig import gave a file one decoded value per byte of its compressed canvas (at least 20M, at most 128M). Dense legitimate files decode past that, further since every scalar field counts, and the whole import was refused as "not a valid FigCraft file: .fig file: message: too many values". The budget is now four values per compressed byte; the floor and both ceilings (128M, 32M on 32-bit targets) are unchanged, so a small file that unpacks past the floor is still refused and no file decodes more values than the ceiling allowed before. Generated 21 MB and 15 MB canvases (220,044 and 108,012 layers) and a 49.7 MB one budgeted at the ceiling (530,106 layers) now open whole without warnings; the 49.7 MB one's test peaks at about 9 GB. --- crates/format/src/fig.rs | 2 + crates/format/src/fig/export.rs | 2 +- crates/format/src/fig/kiwi.rs | 19 ++- crates/format/src/fig/tests.rs | 36 +++-- crates/format/src/fig/value_budget_tests.rs | 165 ++++++++++++++++++++ docs/file-format-parity.md | 7 +- 6 files changed, 208 insertions(+), 23 deletions(-) create mode 100644 crates/format/src/fig/value_budget_tests.rs diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index dc10cc55c..766dc42cc 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -50,6 +50,8 @@ mod text_skip_ink_tests; mod text_style_tests; #[cfg(test)] mod text_wrap_tests; +#[cfg(test)] +mod value_budget_tests; use std::collections::BTreeMap; use std::io::Read; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index b475a9cb6..9e2c4b364 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -216,7 +216,7 @@ fn too_large() -> FormatError { } /// `canvas.fig`: the magic, the version and the two deflated chunks, each after its length. -fn canvas(schema: &[u8], message: &[u8]) -> Result, FormatError> { +pub(super) fn canvas(schema: &[u8], message: &[u8]) -> Result, FormatError> { let mut out = b"fig-kiwi".to_vec(); out.extend_from_slice(&VERSION.to_le_bytes()); for chunk in [schema, message] { diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs index 82bdc6cdc..d34b3774d 100644 --- a/crates/format/src/fig/kiwi.rs +++ b/crates/format/src/fig/kiwi.rs @@ -11,11 +11,20 @@ use std::fmt; /// Deepest struct/message nesting decoded. const MAX_DEPTH: usize = 64; /// Most values decoded from one message (every scalar, array element and field counts): at least -/// [`MIN_VALUES`], and one per byte of the file's compressed canvas up to [`MAX_VALUES`], so a -/// large real file decodes while a small one can't expand into a huge tree, however far its -/// chunks inflate. 32-bit targets (wasm32) have a 4 GB address space in all, so their ceiling is -/// lower: past it the file is refused cleanly instead of running out of memory. +/// [`MIN_VALUES`], and [`VALUES_PER_PACKED_BYTE`] per byte of the file's compressed canvas up to +/// [`MAX_VALUES`], so a large real file decodes while a small one can't expand into a huge tree, +/// however far its chunks inflate. 32-bit targets (wasm32) have a 4 GB address space in all, so +/// their ceiling is lower: past it the file is refused cleanly instead of running out of memory. const MIN_VALUES: usize = 20_000_000; +/// Value budget per compressed canvas byte. The real files measured in +/// `large_files_get_a_larger_value_budget` hold up to 0.75 values per compressed byte without their +/// single scalar fields; counting those too adds 15–43% on the generated files in +/// `value_budget_tests` and up to 3.2 times on a rectangle carrying only geometry and paint, so a +/// dense file may reach about 2.4 per byte. Four leaves two-thirds more room than that. The +/// trade-off: from 32 MiB of canvas (8 MiB on 32-bit targets) a file gets all of [`MAX_VALUES`], +/// and above the floor it may decode four values for every byte it carries; [`MIN_VALUES`] and +/// [`MAX_VALUES`] still bound every file. +const VALUES_PER_PACKED_BYTE: usize = 4; #[cfg(not(target_pointer_width = "32"))] const MAX_VALUES: usize = 128 << 20; #[cfg(target_pointer_width = "32")] @@ -306,7 +315,7 @@ impl Schema { /// Most values decoded from a file whose compressed canvas is `packed` bytes. pub(crate) fn value_budget(packed: usize) -> usize { - packed.clamp(MIN_VALUES, MAX_VALUES) + packed.saturating_mul(VALUES_PER_PACKED_BYTE).clamp(MIN_VALUES, MAX_VALUES) } struct Decoder<'s, 'b> { diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index 697f949de..70bdb7c84 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -79,41 +79,41 @@ message Blob byte[] bytes message Message NodeChange[] nodeChanges, Blob[] blobs "; -fn schema() -> Schema { +pub(super) fn schema() -> Schema { Schema::parse(SCHEMA).unwrap() } -fn o(fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { +pub(super) fn o(fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { Kv::Object(fields) } -fn f(x: f64) -> Kv<'static> { +pub(super) fn f(x: f64) -> Kv<'static> { Kv::Float(x as f32) } -fn u(x: u64) -> Kv<'static> { +pub(super) fn u(x: u64) -> Kv<'static> { Kv::Uint(x) } fn e(n: &'static str) -> Kv<'static> { Kv::Enum(n) } -fn s(x: &str) -> Kv<'static> { +pub(super) fn s(x: impl Into) -> Kv<'static> { Kv::Str(x.into()) } -fn g(l: u64) -> Kv<'static> { +pub(super) fn g(l: u64) -> Kv<'static> { o(vec![("sessionID", u(1)), ("localID", u(l))]) } -fn arr(v: Vec>) -> Kv<'static> { +pub(super) fn arr(v: Vec>) -> Kv<'static> { Kv::Array(v) } -fn xy(x: f64, y: f64) -> Kv<'static> { +pub(super) fn xy(x: f64, y: f64) -> Kv<'static> { o(vec![("x", f(x)), ("y", f(y))]) } -fn at(x: f64, y: f64) -> Kv<'static> { +pub(super) fn at(x: f64, y: f64) -> Kv<'static> { o(vec![("m00", f(1.0)), ("m01", f(0.0)), ("m02", f(x)), ("m10", f(0.0)), ("m11", f(1.0)), ("m12", f(y))]) } fn rgb(r: f64, gr: f64, b: f64) -> Kv<'static> { o(vec![("r", f(r)), ("g", f(gr)), ("b", f(b)), ("a", f(1.0))]) } -fn solid(r: f64, gr: f64, b: f64) -> Kv<'static> { +pub(super) fn solid(r: f64, gr: f64, b: f64) -> Kv<'static> { o(vec![("type", e("SOLID")), ("color", rgb(r, gr, b)), ("opacity", f(1.0)), ("visible", Kv::Bool(true))]) } fn root_guid() -> Kv<'static> { @@ -128,7 +128,7 @@ fn prop_ref(def: u64, field: &'static str) -> Kv<'static> { } /// A node: id (0: the document), parent (id, position), type, name and further fields. -fn node(id: u64, par: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { +pub(super) fn node(id: u64, par: Option<(u64, &str)>, ty: &'static str, name: &str, mut more: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { let mut v = vec![("guid", if id == 0 { root_guid() } else { g(id) })]; if let Some((p, pos)) = par { v.push(("parentIndex", o(vec![("guid", if p == 0 { root_guid() } else { g(p) }), ("position", s(pos))]))); @@ -803,10 +803,10 @@ fn other_files_are_not_fig() { assert!(try_import(&native, "x").is_none()); } -/// A cheap deterministic generator for the mangle tests. -struct Lcg(u64); +/// A cheap deterministic generator (mangled inputs, generated fixtures). +pub(super) struct Lcg(pub(super) u64); impl Lcg { - fn next(&mut self) -> u64 { + pub(super) fn next(&mut self) -> u64 { self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); self.0 >> 33 } @@ -889,6 +889,14 @@ fn large_files_get_a_larger_value_budget() { assert!(kiwi::value_budget(39_528_420) > 29_703_730); // Still bounded by the largest canvas read. assert!(kiwi::value_budget(MAX_CANVAS as usize) <= 128 << 20); + // Counting every scalar field, a dense file may reach about 2.4 values per compressed byte (the + // 15 MB text-heavy fixture in `value_budget_tests` measures 1.8): below the ceiling the budget must + // cover that, the floor still holds up to 5 MB of canvas, and 32 MiB is enough for the ceiling. + assert!(kiwi::value_budget(8 << 20) >= (8 << 20) * 12 / 5); + #[cfg(not(target_pointer_width = "32"))] + assert!(kiwi::value_budget(30_000_000) >= 30_000_000 * 12 / 5); + assert_eq!(kiwi::value_budget(5_000_000), 20_000_000); + assert_eq!(kiwi::value_budget(32 << 20), kiwi::value_budget(MAX_CANVAS as usize)); } #[test] diff --git a/crates/format/src/fig/value_budget_tests.rs b/crates/format/src/fig/value_budget_tests.rs new file mode 100644 index 000000000..7046b1d50 --- /dev/null +++ b/crates/format/src/fig/value_budget_tests.rs @@ -0,0 +1,165 @@ +//! Dense legitimate canvases must open whole within the value budget their size gives them, and a +//! small canvas that unpacks past the floor (tens of millions of values) must stay refused. The dense ones take seconds and gigabytes: +//! `cargo test -p figcraft-format --release --lib value_budget -- --ignored --test-threads=1`. + +use super::kiwi::{Kv, Schema, encode}; +use super::tests::{Lcg, arr, at, f, g, node, o, s, schema, solid, u, xy}; +use super::{decode_canvas, export, import, kiwi}; + +fn frac(r: &mut Lcg, hi: f64) -> f64 { + (r.next() % 100_000) as f64 / 100_000.0 * hi +} + +fn hex(r: &mut Lcg, nibbles: usize) -> String { + (0..nibbles).map(|_| format!("{:x}", r.next() % 16)).collect() +} + +fn word(r: &mut Lcg) -> &'static str { + const WORDS: &[&str] = &[ + "frame", "card", "hero", "row", "cell", "icon", "badge", "button", "input", "label", "group", "section", "header", "footer", "nav", "list", + "item", "menu", "panel", "view", "page", "modal", "form", "field", "text", "title", "body", "caption", "avatar", "thumb", "chart", "graph", + "axis", "grid", "slot", "chip", "tag", "pill", "note", "hint", "tip", "alert", "toast", "banner", "strip", "rail", "tabs", "tab", "step", + "flow", "state", "theme", "mode", "token", + ]; + WORDS[(r.next() as usize) % WORDS.len()] +} + +/// Strings and GUIDs with real entropy on every record (a key, a version, a path of GUIDs), so +/// deflate packs the fixture about as tightly as a real file rather than far tighter. +fn identity(r: &mut Lcg, depth: usize) -> Vec<(&'static str, Kv<'static>)> { + let path = (0..depth).map(|_| g(r.next() % (1 << 30))).collect(); + vec![ + ("key", s(format!("{}:{}{}", hex(r, 4), hex(r, 4), r.next() % 997))), + ("version", s(format!("{}:0", hex(r, 6)))), + ("guidPath", o(vec![("guids", arr(path))])), + ] +} + +/// Somewhere on a page the size of a large design file. +fn placed(r: &mut Lcg) -> (&'static str, Kv<'static>) { + ("transform", at(frac(r, 12_000.0), frac(r, 8_000.0))) +} + +fn rect(id: u64, page: u64, r: &mut Lcg) -> Kv<'static> { + let name = format!("{} {} {}", word(r), word(r), r.next() % 9_999); + let mut fields = vec![ + ("size", xy(24.0 + frac(r, 300.0), 16.0 + frac(r, 200.0))), + placed(r), + ("fillPaints", arr(vec![solid(frac(r, 1.0), frac(r, 1.0), frac(r, 1.0))])), + ("strokeWeight", f(1.0 + frac(r, 3.0))), + ("cornerRadius", f(frac(r, 24.0))), + ("opacity", f(0.5 + frac(r, 0.5))), + ("visible", Kv::Bool(true)), + ]; + fields.extend(identity(r, 3)); + node(id, Some((page, "A")), "RECTANGLE", &name, fields) +} + +/// Text saved with per-character styles: its characters and one style id per character. +fn text(id: u64, page: u64, chars: usize, r: &mut Lcg) -> Kv<'static> { + let mut characters = String::new(); + while characters.len() < chars { + characters.push_str(word(r)); + characters.push_str(if r.next().is_multiple_of(5) { ". " } else { " " }); + } + characters.truncate(chars); + let styles = arr((0..characters.chars().count()).map(|_| u(0)).collect()); + let mut fields = vec![ + ("size", xy(320.0, 18.0)), + placed(r), + ("fontSize", f(11.0 + frac(r, 26.0))), + ("fontName", o(vec![("family", s("Inter")), ("style", s("Regular"))])), + ("fillPaints", arr(vec![solid(0.1, 0.1, 0.1)])), + ("textData", o(vec![("characters", s(characters)), ("characterStyleIDs", styles)])), + ]; + fields.extend(identity(r, 4)); + node(id, Some((page, "A")), "TEXT", "Body", fields) +} + +/// A canvas whose message writes one list field (field 1) of `count` already-encoded elements. +fn one_list_canvas(sc: &Schema, count: u32, elements: impl IntoIterator) -> Vec { + let mut head = encode::Writer::default(); + head.var_uint(1); + head.var_uint(count); + let mut msg = head.0; + msg.extend(elements); + msg.push(0); + export::canvas(&encode::schema(sc), &msg).unwrap() +} + +/// `pages` pages of `rects` rectangles and `texts` texts of `chars` characters, framed the way the +/// exporter frames a file. +fn canvas(pages: usize, rects: usize, texts: usize, chars: usize) -> Vec { + let sc = schema(); + let nc = sc.find("NodeChange").unwrap(); + let mut r = Lcg(0x5eed_1234_abcd_9999); + // Layers are encoded one at a time into the one field written (`nodeChanges`): one Kv tree of + // the whole message would take gigabytes of its own. + let mut layers = Vec::new(); + let mut count = 0u32; + let mut add = |n: Kv<'static>| { + layers.extend(encode::message(&sc, nc, &n).unwrap()); + count += 1; + }; + add(node(0, None, "DOCUMENT", "Fixture", vec![])); + let mut id = 10; + for p in 0..pages { + let page = id; + id += 1; + add(node(page, Some((0, "A")), "CANVAS", &format!("Page {p}"), vec![])); + for _ in 0..rects { + add(rect(id, page, &mut r)); + id += 1; + } + for _ in 0..texts { + add(text(id, page, chars, &mut r)); + id += 1; + } + } + one_list_canvas(&sc, count, layers) +} + +/// Every layer comes in and nothing is reported — and the fixture makes its point: one value per +/// compressed byte refuses it, and it decodes within 90% of its budget. Returns the canvas size. +fn opens_whole(label: &str, pages: usize, rects: usize, texts: usize, chars: usize) -> usize { + let file = canvas(pages, rects, texts, chars); + let (sc, msg) = decode_canvas(&file).unwrap(); + let root = sc.find("Message").unwrap(); + let one_per_byte = file.len().clamp(kiwi::value_budget(0), kiwi::value_budget(usize::MAX)); + let refused = sc.decode_message_within(root, &msg, one_per_byte).is_err_and(|e| e.0 == "message: too many values"); + assert!(refused, "{label}: one value per compressed byte no longer refuses it"); + let (doc, warnings) = import(&file, label).unwrap_or_else(|e| panic!("{label}: refused: {e}")); + assert_eq!(doc.node_count(), pages * (rects + texts) + pages, "{label}: layers"); + assert!(warnings.is_empty(), "{label}: {warnings:?}"); + println!("{label}: {} canvas bytes, {} layers", file.len(), doc.node_count()); + drop(doc); + assert!(sc.decode_message_within(root, &msg, kiwi::value_budget(file.len()) / 10 * 9).is_ok(), "{label}: not within 90% of its budget"); + file.len() +} + +#[test] +#[ignore = "heavy: --release --ignored, about 4.5 GB"] +fn dense_canvases_open_whole() { + opens_whole("21 MB design-shape canvas", 44, 3000, 2000, 140); + opens_whole("15 MB text-heavy canvas", 12, 4500, 4500, 400); +} + +/// From 32 MiB of canvas the budget is the ceiling. Its 83 million values are past the 32-bit +/// ceiling, so this one is for 64-bit targets. +#[cfg(not(target_pointer_width = "32"))] +#[test] +#[ignore = "heavy: --release --ignored, about 9 GB"] +fn a_canvas_budgeted_at_the_ceiling_opens_whole() { + let packed = opens_whole("50 MB text-heavy canvas", 106, 0, 5000, 100); + assert_eq!(kiwi::value_budget(packed), kiwi::value_budget(usize::MAX), "budgeted at the ceiling"); +} + +/// However far a small canvas inflates, the floor bounds what it may decode. +#[test] +fn a_small_canvas_that_unpacks_to_millions_of_values_is_refused() { + let n = 30_000_000; + let file = one_list_canvas(&Schema::parse("message Message uint[] xs").unwrap(), n, std::iter::repeat_n(0, n as usize)); + assert!(file.len() < 100_000, "{} bytes", file.len()); + let Err(e) = import(&file, "x") else { panic!("a {} byte canvas holding {n} values opened", file.len()) }; + assert_eq!(e.to_string(), "not a valid FigCraft file: .fig file: message: too many values"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b9cdd36e9..33ee4f3c6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (`.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -17,8 +17,8 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234). Budgets come from the file's own size (one value per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows), so a 15.4 MB synthetic file with 300,000 layers opens whole; the file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Not read: elbowed or curved connectors without a saved path (drawn straight) and labels of connectors without a saved snapshot, table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | -| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (one value per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows), so a 15.4 MB synthetic file with 300,000 layers opens whole; the file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Not read: elbowed or curved connectors without a saved path (drawn straight) and labels of connectors without a saved snapshot, table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | +| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; the file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Not read: elbowed or curved connectors without a saved path (drawn straight) and labels of connectors without a saved snapshot, table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | +| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations, components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; the file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Not read: elbowed or curved connectors without a saved path (drawn straight) and labels of connectors without a saved snapshot, table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | | `.penpot` (Penpot 2.x ZIP export) | — | **yes, offline** (open, import, drop, CLI, MCP) | **yes, offline** (export, CLI convert) | Editable layers, supported flex/grid layout, components, tokens and prototypes using the existing model. Unsupported layouts retain saved positions and bounded metadata; toggle-overlay and embedded font binaries are reported. Font references remain editable; no downloads. Synthetic regression coverage; live Penpot and cross-platform QA remain open. See [Penpot reference](penpot.md). | further live Penpot and cross-platform QA | | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with generated sticky and shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors, with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | @@ -185,6 +185,7 @@ source paint coordinates. | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | M8, #574: `.fig` import budgets four decoded values per compressed canvas byte instead of one; the 20M floor and the 128M ceiling (32M on 32-bit targets) are unchanged. Dense legitimate files went past one value per compressed byte (further since every scalar field counts) and were refused whole as "not a valid FigCraft file: .fig file: message: too many values". Generated 21 MB and 15 MB canvases (220,044 and 108,012 layers) and a 49.7 MB one budgeted at the ceiling (530,106 layers) now open whole without warnings; a 29 KB canvas that unpacks to 30 million values is still refused. Files that now open instead of being refused take the memory they need: the 49.7 MB canvas's test peaks at about 9 GB. Tests: `crates/format/src/fig/value_budget_tests.rs` (the heavy ones with `--ignored`) and `large_files_get_a_larger_value_budget` in `crates/format/src/fig/tests.rs`. Numbers unchanged. | | 2026-10-30 | minor | M8, #1114: a document opened or imported by path must be a regular file of at most 16 GiB, and an image placed by path one of at most 256 MiB: a folder, a device or a pipe is refused before anything is read. Real files open as before. Numbers unchanged. | | 2026-10-30 | minor | M8, #1101: `.fig` and REST imports of files nested 256 levels deep (the cap) fit the browser's 1 MB stack: the REST layer walk no longer recurses. Numbers unchanged. | | 2026-10-30 | minor | M8, #1082: SVG and PDF exports draw a pattern's source one level below the layer it fills, and the images they embed of layers and pattern cells go on from the layer's depth, so one depth cap bounds a whole export. Numbers unchanged. |