diff --git a/Cargo.lock b/Cargo.lock
index 554a78937..d23f7dea2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -138,19 +138,34 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "alloc-no-stdlib"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
+
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
+[[package]]
+name = "alloc-stdlib"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
+dependencies = [
+ "alloc-no-stdlib 2.0.4",
+]
+
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
- "alloc-no-stdlib",
+ "alloc-no-stdlib 3.0.0",
]
[[package]]
@@ -658,14 +673,24 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "brotli-decompressor"
+version = "5.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
+dependencies = [
+ "alloc-no-stdlib 2.0.4",
+ "alloc-stdlib 0.2.4",
+]
+
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
- "alloc-no-stdlib",
- "alloc-stdlib",
+ "alloc-no-stdlib 3.0.0",
+ "alloc-stdlib 0.3.0",
]
[[package]]
@@ -1195,11 +1220,46 @@ dependencies = [
"egui",
]
+[[package]]
+name = "craft-cms"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "md-5",
+ "rayon",
+]
+
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+[[package]]
+name = "craft-color"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "craft-color-transform"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "craft-cms",
+ "craft-color",
+ "serde",
+]
+
+[[package]]
+name = "craft-crw"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "craft-dds"
version = "0.1.0"
@@ -1208,6 +1268,33 @@ dependencies = [
"rayon",
]
+[[package]]
+name = "craft-develop"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "craft-color",
+ "craft-color-transform",
+ "craft-develop-model",
+ "craft-geom",
+ "craft-raw",
+ "rayon",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "craft-develop-model"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "craft-geom",
+ "craft-metadata",
+ "miniz_oxide 0.9.1",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "craft-docpath"
version = "0.1.0"
@@ -1305,6 +1392,14 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+[[package]]
+name = "craft-geom"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "craft-gif"
version = "0.1.0"
@@ -1433,7 +1528,7 @@ name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
- "brotli-decompressor",
+ "brotli-decompressor 6.3.2",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
@@ -1505,6 +1600,24 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "craft-raw"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
+dependencies = [
+ "chrono",
+ "craft-crw",
+ "craft-metadata",
+ "craft-tiff",
+ "jxl-oxide",
+ "miniz_oxide 0.9.1",
+ "rayon",
+ "serde",
+ "thiserror 2.0.21",
+ "zune-core",
+ "zune-jpeg",
+]
+
[[package]]
name = "craft-settings"
version = "0.1.0"
@@ -2549,6 +2662,7 @@ dependencies = [
"clap",
"clap_complete",
"clap_mangen",
+ "figcraft-collab-net",
"figcraft-doc",
"figcraft-engine",
"figcraft-format",
@@ -2631,6 +2745,7 @@ dependencies = [
"craft-docpath",
"craft-font-catalog",
"craft-font-store",
+ "craft-raw",
"deunicode",
"figcraft-collab",
"figcraft-color",
@@ -2661,12 +2776,16 @@ dependencies = [
name = "figcraft-format"
version = "0.18.1"
dependencies = [
+ "craft-color-transform",
+ "craft-develop",
"craft-fig",
"craft-figcraft-format",
"craft-figma-rest",
+ "craft-geom",
"craft-image-codecs",
"craft-jpeg",
"craft-penpot",
+ "craft-raw",
"craft-sketch",
"craft-zip",
"figcraft-doc",
@@ -4089,6 +4208,182 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "jxl-bitstream"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
+dependencies = [
+ "tracing",
+]
+
+[[package]]
+name = "jxl-coding"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
+dependencies = [
+ "jxl-bitstream",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-color"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-frame"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "jxl-vardct",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-grid"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
+dependencies = [
+ "tracing",
+]
+
+[[package]]
+name = "jxl-image"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-grid",
+ "jxl-oxide-common",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-jbr"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
+dependencies = [
+ "brotli-decompressor 5.0.3",
+ "jxl-bitstream",
+ "jxl-frame",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "jxl-vardct",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-modular"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-oxide"
+version = "0.12.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
+dependencies = [
+ "brotli-decompressor 5.0.3",
+ "jxl-bitstream",
+ "jxl-color",
+ "jxl-frame",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-jbr",
+ "jxl-oxide-common",
+ "jxl-render",
+ "jxl-threadpool",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-oxide-common"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
+dependencies = [
+ "jxl-bitstream",
+]
+
+[[package]]
+name = "jxl-render"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
+dependencies = [
+ "bytemuck",
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-color",
+ "jxl-frame",
+ "jxl-grid",
+ "jxl-image",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "jxl-vardct",
+ "tracing",
+]
+
+[[package]]
+name = "jxl-threadpool"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
+dependencies = [
+ "tracing",
+]
+
+[[package]]
+name = "jxl-vardct"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
+dependencies = [
+ "jxl-bitstream",
+ "jxl-coding",
+ "jxl-grid",
+ "jxl-modular",
+ "jxl-oxide-common",
+ "jxl-threadpool",
+ "tracing",
+]
+
[[package]]
name = "keyboard-types"
version = "0.8.3"
@@ -4323,6 +4618,16 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest 0.10.7",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -8073,7 +8378,7 @@ version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd"
dependencies = [
- "brotli-decompressor",
+ "brotli-decompressor 6.3.2",
"bytes",
]
diff --git a/Cargo.toml b/Cargo.toml
index e0d9ac6b8..f05ad8b41 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -76,6 +76,12 @@ craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev =
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
+# Camera raw files (craft-libs): the container decoders, and the shared develop stages that turn
+# sensor data into a picture (demosaic, white balance, colour matrices, tone).
+craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
+craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
+craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
+craft-geom = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["frames"] }
# foundation
diff --git a/README.md b/README.md
index 9fae6ff68..aaef0a360 100644
--- a/README.md
+++ b/README.md
@@ -208,7 +208,7 @@ exposes to agents, and exported at 2x by FigCraft's own renderer. The source fil
Prototype and hand off
- Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like count + 1), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF.
+ Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like count + 1), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter, Uno C# Markup) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF.
|
diff --git a/ROADMAP.md b/ROADMAP.md
index f581f7313..0b390d201 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
-> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); 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; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); 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); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); 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); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below; CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
+> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (Uno C# Markup code generation for layers, with auto layout and vectors as paths; M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); 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; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); 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); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); 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); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below; CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
@@ -379,6 +379,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
| 2026-11-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |
+| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it; `bound` holds the ids `meta.variables` is keyed by for variables of the exported collections, so an export filtered by `collections` can name variables it doesn't include), and `variable.import` reads it back (styles merged by name, bindings re-pointed; a binding to a variable the JSON lacks is kept without a warning when the existing style already holds that same variable, and otherwise dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only |
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). |
| 2026-11-15 | patch | Document HTTP(S) links without a host are refused before opening; regressions retain valid query, fragment, IPv6 and mail links. |
@@ -386,6 +387,8 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| 2026-11-15 | patch | CLI export and render help and docs name the existing first non-divider page default, including the all-divider fallback and explicit page selection. Behavior unchanged. |
| 2026-11-15 | patch | CLI export and render reject repeated scale suffixes such as `2xx` as usage errors (exit 2); numeric values and one optional `x` suffix retain the existing limits. |
| 2026-11-16 | patch | M9, #2365: native and browser clients accept the complete legacy `Welcome` layout without its later reconnect secret, preserving explicit access and rejecting incomplete or trailing data. A host that supplies no secret is rejoined with the share link instead of an unauthenticated `Resume`. Numbers unchanged. |
+| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). |
+| 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. |
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
diff --git a/apps/figcraft-cli/Cargo.toml b/apps/figcraft-cli/Cargo.toml
index f0c28add4..b37642bfd 100644
--- a/apps/figcraft-cli/Cargo.toml
+++ b/apps/figcraft-cli/Cargo.toml
@@ -19,6 +19,7 @@ workspace = true
[dependencies]
figcraft-engine = { workspace = true }
+figcraft-collab-net = { workspace = true }
figcraft-doc = { workspace = true }
figcraft-render = { workspace = true }
figcraft-text = { workspace = true }
diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs
index 601800ae3..04cfcd508 100644
--- a/apps/figcraft-cli/src/args.rs
+++ b/apps/figcraft-cli/src/args.rs
@@ -14,7 +14,8 @@ use figcraft_doc::{PrintSettings, VdCompat};
///
/// Files: .figcraft (native), .penpot (Penpot 2.x), .json (FigCraft or REST API file JSON), .fig
/// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort),
-/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer).
+/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer), camera raw files such as .rw2, .cr2,
+/// .cr3, .nef, .arw, .raf, .orf and .dng (developed as shot into an image layer).
#[derive(Parser)]
#[command(
name = "figcraft-cli",
@@ -225,6 +226,9 @@ pub struct McpArgs {
/// How long the attached app may take over each request, in seconds (1–600; default 60)
#[arg(long, value_name = "SECONDS", requires = "attach", value_parser = clap::value_parser!(u64).range(1..=600))]
pub timeout: Option,
+ /// Allow a confined headless MCP session to join collaboration links from this server (repeatable)
+ #[arg(long = "automation-allow-server", value_name = "URL", conflicts_with = "attach")]
+ pub automation_allow_servers: Vec,
#[command(flatten)]
pub roots: RootArgs,
}
@@ -570,6 +574,7 @@ mod tests {
(&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation),
(&["mcp", "--timeout", "300"], MissingRequiredArgument),
(&["mcp", "--attach", "7979", "--automation-read-root", "."], ArgumentConflict),
+ (&["mcp", "--attach", "7979", "--automation-allow-server", "wss://figcraft.example.com/"], ArgumentConflict),
(&["mcp", "--automation-write-root"], InvalidValue),
(&["mcp", "stray"], UnknownArgument),
(&["convert", "a"], MissingRequiredArgument),
@@ -603,6 +608,7 @@ mod tests {
assert_eq!(e.as_ref().map(clap::Error::kind), Some(ErrorKind::DisplayHelp), "{args:?}");
assert_eq!(e.map(|e| e.exit_code()), Some(0), "{args:?}");
}
+
// The help is the subcommand's, even after a mistake.
let help = try_parse(&["plugin", "publish", "--bogus", "--help"]).err().map(|e| e.to_string()).unwrap_or_default();
assert!(help.contains("Usage: figcraft-cli plugin publish"), "{help}");
@@ -611,6 +617,23 @@ mod tests {
assert_eq!(a.file, "-h");
}
+ #[test]
+ fn mcp_accepts_repeated_server_allowlists() {
+ let Command::Mcp(a) = ok(&[
+ "mcp",
+ "--automation-read-root",
+ "in",
+ "--automation-write-root",
+ "out",
+ "--automation-allow-server",
+ "wss://figcraft.example.com/",
+ "--automation-allow-server=wss://team.example.com/design/",
+ ]) else {
+ panic!("mcp")
+ };
+ assert_eq!(a.automation_allow_servers, ["wss://figcraft.example.com/", "wss://team.example.com/design/"]);
+ }
+
/// Every subcommand's help renders and documents each of its options.
#[test]
fn every_subcommand_has_help() {
diff --git a/apps/figcraft-cli/src/lib.rs b/apps/figcraft-cli/src/lib.rs
index c555c6cac..0cb6baaf4 100644
--- a/apps/figcraft-cli/src/lib.rs
+++ b/apps/figcraft-cli/src/lib.rs
@@ -76,6 +76,12 @@ pub type CliResult = Result;
fn dispatch(cli: Cli, io: &mut Io) -> CliResult {
check(&cli.command)?;
+ // Headless MCP is always confined (AGENTS.md: agent entry points refuse to start without both
+ // roots); checked before the fonts are scanned, so a usage error comes back at once.
+ let mcp_roots = match &cli.command {
+ Command::Mcp(a) if a.attach.is_none() => Some(mcp_roots(&a.roots, &a.automation_allow_servers)?),
+ _ => None,
+ };
if !cli.no_system_fonts {
// Text lays out with the installed fonts, like the desktop app, so headless renders and
// auto layout sizes match what users see.
@@ -99,7 +105,7 @@ fn dispatch(cli: Cli, io: &mut Io) -> CliResult {
Ok(0)
}
// `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them.
- Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, roots_of(&a.roots)?, io),
+ Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, mcp_roots, io),
Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server, a.key.as_deref(), io),
Command::Connect { command: ConnectCommand::Publish(a) } => {
confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run, io))
@@ -180,6 +186,29 @@ fn mcp(attach: Option<&str>, timeout: Option, roots: Option CliResult {
+ if roots.automation_read_root.is_empty() || roots.automation_write_root.is_empty() {
+ return Err(CliError::Usage("headless mcp requires both --automation-read-root and --automation-write-root".into()));
+ }
+ let roots = figcraft_engine::file_access::Roots::new(&roots.automation_read_root, &roots.automation_write_root).map_err(CliError::Failed)?;
+ let mut servers = Vec::with_capacity(allowed_servers.len());
+ for server in allowed_servers {
+ if server.contains('?') {
+ return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into()));
+ }
+ let (endpoint, query) = figcraft_collab_net::Endpoint::parse(server)
+ .map_err(|_| CliError::Usage("--automation-allow-server must be a ws:// or wss:// server URL".into()))?;
+ if !query.is_empty() {
+ return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into()));
+ }
+ servers.push(endpoint.url());
+ }
+ Ok(roots.with_allowed_servers(servers))
+}
+
/// What the arguments can't say alone: an output that would replace its input needs `--in-place`.
fn check(command: &Command) -> CliResult<()> {
let refuse = |flag: &str, path: &str, input: &str, allowed: bool| -> CliResult<()> {
@@ -255,3 +284,33 @@ where
}
}
}
+
+#[cfg(test)]
+mod mcp_roots_tests {
+ use super::{CliError, mcp_roots};
+ use crate::args::RootArgs;
+
+ #[test]
+ fn headless_mcp_requires_both_roots_and_allowlist_cannot_carry_a_key() {
+ let server = "wss://figcraft.example.com/".to_string();
+ let no_roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: Vec::new() };
+ assert!(matches!(mcp_roots(&no_roots, &[]), Err(CliError::Usage(_))));
+ assert!(matches!(mcp_roots(&no_roots, std::slice::from_ref(&server)), Err(CliError::Usage(_))));
+
+ let path = std::env::temp_dir().join(format!("figcraft-cli-roots-{}", std::process::id()));
+ std::fs::create_dir_all(&path).unwrap();
+ let root = path.to_string_lossy().into_owned();
+ let read_only = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: Vec::new() };
+ assert!(matches!(mcp_roots(&read_only, &[]), Err(CliError::Usage(_))));
+ let roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: vec![path.to_string_lossy().into_owned()] };
+ assert!(matches!(mcp_roots(&roots, &[]), Err(CliError::Usage(_))));
+
+ let roots = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: vec![root] };
+ let allowed = mcp_roots(&roots, &[server]).unwrap();
+ assert_eq!(allowed.allowed_servers(), ["wss://figcraft.example.com:443/"]);
+
+ let with_key = "wss://figcraft.example.com/?key=secret".to_string();
+ assert!(matches!(mcp_roots(&roots, &[with_key]), Err(CliError::Usage(message)) if !message.contains("secret")));
+ let _ = std::fs::remove_dir_all(path);
+ }
+}
diff --git a/apps/figcraft-cli/tests/it/cli.rs b/apps/figcraft-cli/tests/it/cli.rs
index efc1f0e29..eb0be8aa8 100644
--- a/apps/figcraft-cli/tests/it/cli.rs
+++ b/apps/figcraft-cli/tests/it/cli.rs
@@ -244,7 +244,18 @@ fn run_takes_the_documented_gradient_shorthand() {
#[test]
fn mcp_over_stdio() {
- let mut child = bin().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
+ let d = tmp("mcp-over-stdio");
+ let mut child = bin()
+ .arg("mcp")
+ .arg("--automation-read-root")
+ .arg(&d)
+ .arg("--automation-write-root")
+ .arg(&d)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
{
let stdin = child.stdin.as_mut().unwrap();
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
@@ -261,6 +272,7 @@ fn mcp_over_stdio() {
assert_eq!(lines[0]["result"]["protocolVersion"], "2025-06-18");
assert_eq!(lines[1]["error"]["code"], -32700);
assert_eq!(lines[2]["result"]["isError"], false);
+ let _ = std::fs::remove_dir_all(d);
}
#[test]
@@ -270,8 +282,18 @@ fn mcp_over_stdio_confined_to_automation_roots() {
std::fs::create_dir_all(d.join(sub)).unwrap();
}
let p = |rel: &str| d.join(rel).to_string_lossy().into_owned();
- // A root that isn't a folder stops the server before it serves.
- let out = bin().args(["mcp", "--automation-read-root", &p("missing")]).output().unwrap();
+ for args in [
+ vec!["mcp".to_owned()],
+ vec!["mcp".to_owned(), "--automation-read-root".to_owned(), p("in")],
+ vec!["mcp".to_owned(), "--automation-write-root".to_owned(), p("out")],
+ ] {
+ let out = bin().args(args).output().unwrap();
+ assert_eq!(out.status.code(), Some(2));
+ assert!(String::from_utf8_lossy(&out.stderr).contains("requires both --automation-read-root and --automation-write-root"));
+ }
+
+ // Both roots are required; a root that isn't a folder stops the server before it serves.
+ let out = bin().args(["mcp", "--automation-read-root", &p("missing"), "--automation-write-root", &p("out")]).output().unwrap();
assert_eq!(out.status.code(), Some(1));
assert!(String::from_utf8_lossy(&out.stderr).contains("--automation-read-root"));
let mut child = bin()
diff --git a/contributors/people.toml b/contributors/people.toml
index 6629165ad..8db486ad1 100644
--- a/contributors/people.toml
+++ b/contributors/people.toml
@@ -141,3 +141,7 @@ real_name = "Ibuchukwu Umeano"
[people.Terra854]
display_name = "Terra854"
+
+[people.andrejskvorc]
+real_name = "Andrej Skvorc"
+sync_github_name = true
diff --git a/crates/collab-net/src/invite.rs b/crates/collab-net/src/invite.rs
index ace18d299..4f41051ef 100644
--- a/crates/collab-net/src/invite.rs
+++ b/crates/collab-net/src/invite.rs
@@ -84,6 +84,15 @@ impl Endpoint {
}
}
+ /// Whether this endpoint is within an explicitly allowed server origin and path prefix.
+ pub fn is_within(&self, allowed: &Endpoint) -> bool {
+ self.secure == allowed.secure
+ && self.host.eq_ignore_ascii_case(&allowed.host)
+ && safe_path(&self.path)
+ && safe_path(&allowed.path)
+ && (allowed.path == "/" || self.path.starts_with(&allowed.path))
+ }
+
/// Read `ws(s)://host[:port][/path][?query]` (a missing port is the scheme's: 80 or 443): the
/// endpoint and the query's decoded pairs. Errors say what's wrong without echoing `url`.
pub fn parse(url: &str) -> Result<(Endpoint, Vec<(String, String)>), String> {
@@ -261,6 +270,10 @@ fn valid_path(p: &str) -> bool {
p.starts_with('/') && p.len() <= 256 && p.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~'))
}
+fn safe_path(p: &str) -> bool {
+ !p.split('/').any(|part| matches!(part, "." | ".."))
+}
+
/// `%XX` escapes decoded (UTF-8); `None` for broken escapes.
fn percent_decode(s: &str) -> Option {
let bytes = s.as_bytes();
diff --git a/crates/collab-net/src/invite_tests.rs b/crates/collab-net/src/invite_tests.rs
index b7618dc28..1bb2730dc 100644
--- a/crates/collab-net/src/invite_tests.rs
+++ b/crates/collab-net/src/invite_tests.rs
@@ -3,6 +3,8 @@
use proptest::prelude::*;
+use figcraft_engine::live::LiveLink;
+
use crate::invite::{Endpoint, Invite};
const TOKEN: &str = "AbCdEfGhIjKlMnOpQrStUv";
@@ -58,6 +60,28 @@ fn server_links_carry_tls_and_a_path() {
assert!(plain.link().starts_with("figcraft://join?host=10.0.0.5:47900&"));
}
+#[test]
+fn an_automation_server_allowlist_matches_the_parsed_origin_and_path_prefix() {
+ let net = crate::NetLink::new(std::sync::Arc::new(|| {}));
+ let allowed = vec!["wss://figcraft.example.com/team/".to_string()];
+ let invite = |server: &str| Invite { server: Endpoint::parse(server).unwrap().0, ..invite() }.link();
+
+ assert!(net.automation_join_allowed(&invite("wss://FIGCRAFT.example.com/team/live/"), &allowed));
+ assert!(net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &allowed));
+ assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/teams/"), &allowed));
+ assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/../outside/"), &allowed));
+ assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/live/"), &["wss://figcraft.example.com/team/../".to_string()]));
+ assert!(!net.automation_join_allowed(&invite("ws://figcraft.example.com/team/"), &allowed));
+ assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com:444/team/"), &allowed));
+ assert!(!net.automation_join_allowed(&invite("wss://other.example.com/team/"), &allowed));
+ assert!(!net.automation_join_allowed(
+ "figcraft://join?server=wss://other.example.com/team/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv",
+ &allowed
+ ));
+ assert!(!net.automation_join_allowed("figcraft://join?host=192.168.1.20:47900&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv", &allowed));
+ assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &["wss://figcraft.example.com/team/?key=secret".to_string()]));
+}
+
#[test]
fn server_addresses_with_a_key() {
let (e, q) = Endpoint::parse("ws://127.0.0.1:47900/?key=KeyKeyKeyKeyKeyKeyKey0").unwrap();
diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs
index 198022a09..1145be6ff 100644
--- a/crates/collab-net/src/link.rs
+++ b/crates/collab-net/src/link.rs
@@ -151,6 +151,15 @@ pub(crate) fn reachable(addr: SocketAddr) -> SocketAddr {
}
impl LiveLink for NetLink {
+ fn automation_join_allowed(&self, link: &str, allowed_servers: &[String]) -> bool {
+ let Ok((invite, _)) = Invite::parse_join(link) else {
+ return false;
+ };
+ allowed_servers
+ .iter()
+ .any(|allowed| Endpoint::parse(allowed).is_ok_and(|(endpoint, query)| query.is_empty() && invite.server.is_within(&endpoint)))
+ }
+
/// Host the open file on `o.bind`: a join code's short secret when `o.short`, and a second,
/// view-only secret with its invite link when `o.view`.
fn host(&mut self, session: SessionId, o: HostOptions) -> Result {
diff --git a/crates/collab-net/src/loopback_tests.rs b/crates/collab-net/src/loopback_tests.rs
index 7af598bf9..48b19549d 100644
--- a/crates/collab-net/src/loopback_tests.rs
+++ b/crates/collab-net/src/loopback_tests.rs
@@ -189,9 +189,13 @@ fn guests_join_and_see_each_other() {
let Some(Event::Welcome { info, peers }) = ap.events.iter().rev().find(|e| matches!(e, Event::Welcome { .. })) else { panic!("no welcome") };
assert_eq!(info.name, "Ada");
assert!(
- ap.events.iter().any(
- |e| matches!(e, Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty())
- ),
+ ap.events.iter().any(|e| matches!(
+ e,
+ Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty()
+ ) || matches!(
+ e,
+ Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::DeltaSnapshot(bytes), .. }) if !bytes.is_empty()
+ )),
"the welcome carries the document for the sync client"
);
assert_eq!(peers.iter().map(|p| p.name.as_str()).collect::>(), ["Hana"], "the host is already here");
@@ -670,12 +674,21 @@ fn welcomes_are_packed_only_for_clients_that_read_them() {
let addr: SocketAddr = invite.server.host.parse().unwrap();
let mut old = Raw::connect(addr);
let ClientMsg::Hello(h) = Client::hello(FILE, TOKEN, "Old", "") else { panic!("not a hello") };
- assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h })));
+ assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h.clone() })));
let Some(ServerMsg::Welcome { catch_up: CatchUp::Snapshot(plain), .. }) = old.next() else { panic!("no plain welcome") };
+ let mut mid = Raw::connect(addr);
+ assert!(mid.send(&ClientMsg::Hello(Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..h })));
+ let Some(mut packed_welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = mid.next() else { panic!("no packed welcome") };
+ message::unpack(&mut packed_welcome, 64 << 20).unwrap();
+ assert!(matches!(packed_welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document");
let mut new = Raw::hello(addr, TOKEN);
- let Some(mut welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = new.next() else { panic!("no packed welcome") };
- message::unpack(&mut welcome, 64 << 20).unwrap();
- assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document");
+ let Some(mut delta_welcome @ ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }) = new.next() else {
+ panic!("no delta snapshot welcome")
+ };
+ message::unpack(&mut delta_welcome, 64 << 20).unwrap();
+ let delta_doc = Client::join(delta_welcome).unwrap().document().clone();
+ let plain_doc = figcraft_collab::Replica::from_snapshot(&plain).unwrap().document().clone();
+ assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document");
host.stop();
}
diff --git a/crates/collab/src/client.rs b/crates/collab/src/client.rs
index da83aca84..ba1c3b44c 100644
--- a/crates/collab/src/client.rs
+++ b/crates/collab/src/client.rs
@@ -86,10 +86,19 @@ impl Client {
/// Start from the server's `Welcome` (which must carry a snapshot).
pub fn join(welcome: ServerMsg) -> Result {
- let ServerMsg::Welcome { session, client_id, seq, catch_up: CatchUp::Snapshot(snapshot), processed, peers, access, secret } = welcome else {
+ let ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret } = welcome else {
return Err(Error::Protocol("expected a welcome with the document".into()));
};
- let mut confirmed = Replica::from_snapshot(&snapshot)?;
+ let mut confirmed = match catch_up {
+ CatchUp::Snapshot(snapshot) => Replica::from_snapshot(&snapshot)?,
+ CatchUp::DeltaSnapshot(bytes) => {
+ let limits = crate::Limits::default();
+ crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?
+ }
+ CatchUp::Delta(_) | CatchUp::Packed(_) => {
+ return Err(Error::Protocol("expected a welcome with the document".into()));
+ }
+ };
confirmed.document_mut().set_client_id(client_id);
let next_id = confirmed.document().next_id();
Ok(Client {
@@ -597,26 +606,13 @@ impl Client {
CatchUp::Snapshot(snapshot) => {
let mut confirmed = Replica::from_snapshot(&snapshot)?;
confirmed.document_mut().set_client_id(self.id);
- self.confirmed = confirmed;
- self.seq = seq;
- // What the server accepted meanwhile is in the snapshot. Which of the batches since
- // were others' isn't known, so the steps check every value they wrote below.
- while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() {
- self.pending.pop_front();
- if processed.refused.contains(&p.batch_id) {
- self.refused(&p, offline());
- } else if p.kind != BatchKind::FollowUp
- && let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id))
- {
- s.settle(p.kind);
- }
- }
- for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) {
- s.verify(&self.confirmed)?;
- }
- for p in &mut self.pending {
- p.rebased = true;
- }
+ self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
+ }
+ CatchUp::DeltaSnapshot(bytes) => {
+ let limits = crate::Limits::default();
+ let mut confirmed = crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?;
+ confirmed.document_mut().set_client_id(self.id);
+ self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
}
}
if self.seq != seq {
@@ -636,6 +632,31 @@ impl Client {
Ok(self.flush(recompute))
}
+ fn rejoin_with_confirmed(&mut self, confirmed: Replica, seq: u64, last_batch: u64, processed: &Processed) -> Result<(), Error> {
+ let offline = || "it no longer applied when the connection came back".to_string();
+ self.confirmed = confirmed;
+ self.seq = seq;
+ // What the server accepted meanwhile is in the snapshot. Which of the batches since
+ // were others' isn't known, so the steps check every value they wrote below.
+ while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() {
+ self.pending.pop_front();
+ if processed.refused.contains(&p.batch_id) {
+ self.refused(&p, offline());
+ } else if p.kind != BatchKind::FollowUp
+ && let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id))
+ {
+ s.settle(p.kind);
+ }
+ }
+ for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) {
+ s.verify(&self.confirmed)?;
+ }
+ for p in &mut self.pending {
+ p.rebased = true;
+ }
+ Ok(())
+ }
+
/// A session that doesn't know this client (it restarted without its saved state) welcomed
/// it as new: start over from its document; unconfirmed work and the undo history are gone.
fn restart(&mut self, welcome: ServerMsg) -> Result, Error> {
diff --git a/crates/collab/src/delta_dst_tests.rs b/crates/collab/src/delta_dst_tests.rs
new file mode 100644
index 000000000..2a0a08a0e
--- /dev/null
+++ b/crates/collab/src/delta_dst_tests.rs
@@ -0,0 +1,216 @@
+//! Multi-seed mixed-version DST for `CatchUp::DeltaSnapshot`.
+
+use figcraft_color::{Color, Paint};
+use figcraft_doc::{Document, NodeId};
+use figcraft_geom::Affine;
+
+use crate::delta_snapshot::{decode_delta_snapshot, encode_delta_snapshot};
+use crate::delta_snapshot_tests::{LEGACY_CLIENT_VERSION, assert_docs_json_eq, design_system_doc};
+use crate::message::{CatchUp, ClientMsg, Hello, ServerMsg};
+use crate::sim::Rng;
+use crate::{Client, Limits, NoRecompute, Outgoing, Server};
+
+fn deliver_outgoing(clients: &mut [(Client, Hello, bool)], outs: Vec) {
+ for out in outs {
+ match out {
+ Outgoing::All(m) => {
+ for (c, _, _) in clients.iter_mut() {
+ if c.is_online() {
+ let _ = c.receive(m.clone(), &NoRecompute).unwrap();
+ }
+ }
+ }
+ Outgoing::To(target, m) => {
+ for (c, _, _) in clients.iter_mut() {
+ if c.is_online() && c.id() == target {
+ let _ = c.receive(m.clone(), &NoRecompute).unwrap();
+ }
+ }
+ }
+ Outgoing::Others(skip, m) => {
+ for (c, _, _) in clients.iter_mut() {
+ if c.is_online() && c.id() != skip {
+ let _ = c.receive(m.clone(), &NoRecompute).unwrap();
+ }
+ }
+ }
+ }
+ }
+}
+
+fn reconnect_dst_client(server: &mut Server, clients: &mut [(Client, Hello, bool)], idx: usize) -> (bool, bool) {
+ let (c, base_h, delta_capable) = &mut clients[idx];
+ let ClientMsg::Hello(mut rh) = c.reconnect(base_h.clone()) else { panic!("expected Hello") };
+ if !*delta_capable {
+ rh.client_version = base_h.client_version.clone();
+ }
+ let (id, outs) = server.join(rh).unwrap();
+ let welcome = outs
+ .into_iter()
+ .find_map(|o| match o {
+ Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
+ _ => None,
+ })
+ .unwrap();
+ let is_delta_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. });
+ let is_legacy_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. });
+ let follow = c.receive(welcome, &NoRecompute).unwrap();
+ let cid = c.id();
+ for msg in follow {
+ let rep = server.receive(cid, msg);
+ deliver_outgoing(clients, rep);
+ }
+ (is_delta_snap, is_legacy_snap)
+}
+
+fn apply_random_dst_edit(edited: &mut Document, rng: &mut Rng, comp: NodeId, main_children: &[NodeId], seed: u64, step: usize) {
+ let all_ids: Vec = edited.ids().filter(|id| !edited.node(*id).unwrap().is_page()).collect();
+ match rng.below(4) {
+ 0 => {
+ let target = *rng.pick(main_children).unwrap();
+ if let Some(n) = edited.node_mut(target) {
+ n.fills = vec![Paint::solid(Color::from_rgb8_const(rng.below(255) as u8, 80, 140))];
+ }
+ }
+ 1 => {
+ let text_mirrors: Vec =
+ all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some() && n.kind.text().is_some())).collect();
+ if let Some(&target) = rng.pick(&text_mirrors)
+ && let Some(n) = edited.node_mut(target)
+ {
+ if let Some(t) = n.kind.text_mut() {
+ t.characters = format!("S{seed}-T{step}");
+ }
+ if rng.chance(0.5) {
+ n.overrides.clear();
+ } else {
+ n.overrides.insert("characters".to_string());
+ }
+ }
+ }
+ 2 => {
+ let mirrors: Vec = all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some())).collect();
+ if let Some(&target) = rng.pick(&mirrors)
+ && let Some(n) = edited.node_mut(target)
+ {
+ n.transform = Affine::translate((rng.below(400) as f64, rng.below(200) as f64));
+ n.width = 20.0 + rng.below(120) as f64;
+ }
+ }
+ _ => {
+ if let Some(n) = edited.node_mut(comp) {
+ n.name = format!("Card-v{step}");
+ }
+ }
+ }
+}
+
+fn assert_dst_invariants(server: &Server, clients: &[(Client, Hello, bool)], seed: u64, step: usize) {
+ let decoded = decode_delta_snapshot(&encode_delta_snapshot(server.replica()).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
+ assert_docs_json_eq(server.document(), decoded.document(), &format!("seed={seed} step={step} roundtrip"));
+ for (i, (c, _, _)) in clients.iter().enumerate() {
+ if c.is_online() {
+ assert_docs_json_eq(server.document(), c.document(), &format!("seed={seed} step={step} client {i}"));
+ }
+ }
+}
+
+fn run_dst_seed(seed: u64) {
+ let mut rng = Rng::new(seed);
+ let (doc, comp, main_children) = design_system_doc(6);
+ let limits = Limits { max_log_batches: 2, ..Limits::default() };
+ let mut server = Server::new(doc, "dst-secret", limits);
+
+ let join_client = |srv: &mut Server, name: &str, delta_capable: bool| -> (Client, Hello) {
+ let ClientMsg::Hello(mut h) = Client::hello("dst", "dst-secret", name, "#2266EE") else { panic!() };
+ if !delta_capable {
+ h.client_version = LEGACY_CLIENT_VERSION.into();
+ }
+ let (id, outs) = srv.join(h.clone()).unwrap();
+ let welcome = outs
+ .into_iter()
+ .find_map(|o| match o {
+ Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
+ _ => None,
+ })
+ .unwrap();
+ if delta_capable {
+ assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }));
+ } else {
+ assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }));
+ }
+ (Client::join(welcome).unwrap(), h)
+ };
+
+ let (c0, h0) = join_client(&mut server, "Delta-A", true);
+ let (c1, h1) = join_client(&mut server, "Delta-B", true);
+ let (c2, h2) = join_client(&mut server, "Legacy-C", false);
+ let mut clients = vec![(c0, h0, true), (c1, h1, true), (c2, h2, false)];
+ let (mut delta_snap_rejoins, mut legacy_snap_rejoins) = (0usize, 0usize);
+
+ for step in 0..30usize {
+ if step == 15 {
+ let saved = server.state().unwrap();
+ server = Server::restore(saved, "dst-secret", limits).unwrap();
+ for (c, _, _) in &mut clients {
+ c.disconnect();
+ }
+ for idx in 0..clients.len() {
+ let _ = reconnect_dst_client(&mut server, &mut clients, idx);
+ }
+ assert_dst_invariants(&server, &clients, seed, step);
+ continue;
+ }
+
+ if step == 6 || step == 20 {
+ let victim = if step == 6 { 1 } else { 2 };
+ clients[victim].0.disconnect();
+ server.leave(clients[victim].0.id());
+
+ let mut off_doc = clients[victim].0.document().clone();
+ if let Some(p) = off_doc.first_page()
+ && let Some(n) = off_doc.node_mut(p)
+ {
+ n.name = format!("Offline-{seed}-{step}");
+ }
+ let _ = clients[victim].0.edit(&off_doc).unwrap();
+
+ for sub in 0..4 {
+ let mut edited = clients[0].0.document().clone();
+ apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step * 10 + sub);
+ if let Some(msg) = clients[0].0.edit(&edited).unwrap() {
+ let outs = server.receive(clients[0].0.id(), msg);
+ deliver_outgoing(&mut clients, outs);
+ }
+ }
+
+ let (was_delta, was_legacy) = reconnect_dst_client(&mut server, &mut clients, victim);
+ delta_snap_rejoins += usize::from(was_delta);
+ legacy_snap_rejoins += usize::from(was_legacy);
+ assert_dst_invariants(&server, &clients, seed, step);
+ continue;
+ }
+
+ let actor_idx = rng.below(clients.len());
+ let mut edited = clients[actor_idx].0.document().clone();
+ apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step);
+ if let Some(msg) = clients[actor_idx].0.edit(&edited).unwrap() {
+ let outs = server.receive(clients[actor_idx].0.id(), msg);
+ deliver_outgoing(&mut clients, outs);
+ }
+ assert_dst_invariants(&server, &clients, seed, step);
+ }
+
+ assert!(delta_snap_rejoins > 0 && legacy_snap_rejoins > 0, "seed={seed}: must exercise both snapshot rejoin paths");
+}
+
+#[test]
+fn dst_mixed_delta_and_legacy_clients_converge_under_faults_and_restarts() {
+ let seeds: Vec = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse::().ok()) {
+ Some(single) => vec![single],
+ None => vec![1, 7, 42, 1337, 2026],
+ };
+ for seed in seeds {
+ run_dst_seed(seed);
+ }
+}
diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs
new file mode 100644
index 000000000..512cde16e
--- /dev/null
+++ b/crates/collab/src/delta_snapshot/decode.rs
@@ -0,0 +1,431 @@
+//! Streaming decode and memory-budget enforcement for `CatchUp::DeltaSnapshot`.
+
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::fmt;
+use std::io::Read;
+use std::mem::size_of;
+use std::sync::Arc;
+
+use figcraft_doc::color::Paint;
+use figcraft_doc::proto::Interaction;
+use figcraft_doc::{
+ Annotation, CodeLink, DevResource, Document, Effect, ExportSetting, Guide, LayoutGrid, Measurement, Node, NodeId, NodeKind, Region, Segment,
+ VectorNetwork, Vertex,
+};
+use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
+
+use super::fields::{FieldDelta, apply_field_delta};
+use super::{DEFAULT_MAX_MATERIALIZED_BYTES, HEADER_LEN, WireMeta, WireRecord, parse_header};
+use crate::Error;
+use crate::docprops::{clamp_design_review_config, validate_image_base64};
+use crate::frac;
+use crate::replica::{Positions, Replica};
+
+/// Maximum ratio of estimated materialized bytes to declared uncompressed JSON bytes.
+/// Heavy design-system files sit around 15x to 35x; amplification bombs exceed 1,000x.
+const MAX_AMPLIFICATION_FACTOR: usize = 64;
+const MIN_MATERIALIZED_FLOOR: usize = 16 << 20;
+
+/// Effective materialized-byte ceiling shared by encoder and decoder.
+pub(super) fn materialized_budget(declared: usize, ceiling: usize) -> usize {
+ let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR);
+ ceiling.min(cap)
+}
+
+/// Decode a compressed `CatchUp::DeltaSnapshot` payload into a validated [`Replica`].
+pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) -> Result {
+ decode_delta_snapshot_with_budget(bytes, max_bytes, max_nodes, DEFAULT_MAX_MATERIALIZED_BYTES)
+}
+
+/// Decode a compressed `CatchUp::DeltaSnapshot` with an explicit ceiling on estimated
+/// materialized memory, also capped at `max(16 MiB, 64 * declared_bytes)`.
+pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nodes: usize, max_materialized_bytes: usize) -> Result {
+ let declared = parse_header(bytes)?;
+ if declared > max_bytes {
+ return Err(Error::TooLarge(max_bytes));
+ }
+ let body = bytes.get(HEADER_LEN..).ok_or_else(|| Error::Decode("delta snapshot body missing".into()))?;
+ // Stop inflating at `declared + 1` so a forged small length aborts immediately.
+ let limit = u64::try_from(declared).unwrap_or(u64::MAX).saturating_add(1);
+ let prealloc = declared.min(bytes.len().saturating_mul(8)).min(1 << 20);
+ let mut raw = Vec::with_capacity(prealloc);
+ flate2::read::DeflateDecoder::new(body).take(limit).read_to_end(&mut raw).map_err(|e| Error::Decode(format!("delta snapshot deflate: {e}")))?;
+ if raw.len() > declared {
+ return Err(Error::TooLarge(declared));
+ }
+ if raw.len() != declared {
+ return Err(Error::Decode(format!("delta snapshot truncated: header declared {declared} bytes, inflated {}", raw.len())));
+ }
+
+ stream_decode_wire(&raw, max_nodes, materialized_budget(declared, max_materialized_bytes))
+}
+
+fn est_str_map(m: &BTreeMap) -> usize {
+ m.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len()).saturating_add(48))
+}
+
+pub(super) fn est_vector_bytes(net: &VectorNetwork) -> usize {
+ let regs = net.regions.iter().fold(0usize, |acc, r| {
+ let loops = r.loops.iter().fold(0usize, |a, l| a.saturating_add(l.len().saturating_mul(size_of::())));
+ let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::()));
+ acc.saturating_add(size_of::()).saturating_add(loops).saturating_add(fills)
+ });
+ size_of::()
+ .saturating_add(net.vertices.len().saturating_mul(size_of::()))
+ .saturating_add(net.segments.len().saturating_mul(size_of::()))
+ .saturating_add(regs)
+}
+
+fn est_kind_bytes(kind: &NodeKind) -> usize {
+ match kind {
+ NodeKind::Vector { network } => est_vector_bytes(network),
+ NodeKind::Text(t) => t.characters.len().saturating_add(t.runs.len().saturating_mul(64)),
+ NodeKind::Component { description, props, prop_order } => {
+ description.len().saturating_add(props.len().saturating_mul(96)).saturating_add(prop_order.len().saturating_mul(32))
+ }
+ NodeKind::Instance { props, .. } => props.len().saturating_mul(96),
+ _ => 0,
+ }
+}
+
+pub(super) fn est_node_bytes(n: &Node) -> usize {
+ let ov: usize = n.overrides.iter().fold(0, |a, s| a.saturating_add(s.len()).saturating_add(24));
+ size_of::()
+ .saturating_add(n.name.len())
+ .saturating_add(n.dev_note.len())
+ .saturating_add(n.fills.len().saturating_mul(size_of::()))
+ .saturating_add(n.strokes.len().saturating_mul(size_of::()))
+ .saturating_add(n.effects.len().saturating_mul(size_of::()))
+ .saturating_add(n.grids.len().saturating_mul(size_of::()))
+ .saturating_add(n.guides.len().saturating_mul(size_of::()))
+ .saturating_add(n.exports.len().saturating_mul(size_of::()))
+ .saturating_add(n.interactions.len().saturating_mul(size_of::()))
+ .saturating_add(n.annotations.len().saturating_mul(size_of::()))
+ .saturating_add(n.code_links.len().saturating_mul(size_of::()))
+ .saturating_add(n.dev_resources.len().saturating_mul(size_of::()))
+ .saturating_add(n.measurements.len().saturating_mul(size_of::()))
+ .saturating_add(est_kind_bytes(&n.kind))
+ .saturating_add(ov)
+ .saturating_add(est_str_map(&n.bound))
+ .saturating_add(est_str_map(&n.var_modes))
+ .saturating_add(est_str_map(&n.plugin_data))
+ .saturating_add(est_str_map(&n.prop_refs))
+}
+
+pub(super) fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize {
+ deltas.iter().fold(0usize, |acc, d| {
+ let extra = match d {
+ FieldDelta::Name(s) | FieldDelta::DevNote(s) => s.len(),
+ FieldDelta::Kind(k) => est_kind_bytes(k),
+ FieldDelta::VectorRef(idx) => usize::try_from(*idx).ok().and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0),
+ FieldDelta::Fills(v) | FieldDelta::Strokes(v) => v.len().saturating_mul(size_of::()),
+ FieldDelta::Effects(v) => v.len().saturating_mul(size_of::()),
+ FieldDelta::Bound(m) | FieldDelta::VarModes(m) | FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m),
+ FieldDelta::Annotations(v) => v.len().saturating_mul(size_of::()),
+ FieldDelta::CodeLinks(v) => v.len().saturating_mul(size_of::()),
+ _ => 0,
+ };
+ acc.saturating_add(extra)
+ })
+}
+
+pub(super) fn est_meta_bytes(meta: &WireMeta) -> usize {
+ let images = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.key.len()).saturating_add(i.bytes.len()));
+ let comments = meta.comments.iter().fold(0usize, |a, c| {
+ let replies = c.replies.iter().fold(0usize, |r, m| r.saturating_add(m.author.len()).saturating_add(m.text.len()).saturating_add(64));
+ a.saturating_add(c.first.author.len()).saturating_add(c.first.text.len()).saturating_add(replies).saturating_add(128)
+ });
+ let styles = meta.styles.iter().fold(0usize, |a, s| a.saturating_add(s.id.len()).saturating_add(s.name.len()).saturating_add(128));
+ let dev_snaps = meta.dev_snapshots.values().fold(0usize, |a, s| s.nodes.iter().fold(a, |b, n| b.saturating_add(est_node_bytes(n))));
+ let vars = meta.variables.collections.len().saturating_mul(128).saturating_add(meta.variables.variables.len().saturating_mul(128));
+ let libs = meta.libraries.components.len().saturating_mul(128).saturating_add(meta.libraries.styles.len().saturating_mul(128));
+ let votes = meta.votes.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len().saturating_mul(size_of::())));
+ let categories = meta
+ .annotation_categories
+ .iter()
+ .flatten()
+ .fold(0usize, |a, c| a.saturating_add(c.id.len()).saturating_add(c.name.len()).saturating_add(128));
+ meta.name
+ .len()
+ .saturating_add(images)
+ .saturating_add(comments)
+ .saturating_add(styles)
+ .saturating_add(dev_snaps)
+ .saturating_add(vars)
+ .saturating_add(libs)
+ .saturating_add(votes)
+ .saturating_add(categories)
+ .saturating_add(meta.vote_history.len().saturating_mul(128))
+ .saturating_add(meta.image_presets.len().saturating_mul(64))
+ .saturating_add(meta.document_colors.len().saturating_mul(32))
+}
+
+struct DecodeState {
+ doc: Document,
+ positions: Positions,
+ touched: BTreeSet,
+ vectors: Vec>,
+ vector_sizes: Vec,
+ node_sizes: HashMap,
+ meta: Option,
+ records_seen: usize,
+ max_nodes: usize,
+ materialized_bytes: usize,
+ max_materialized_bytes: usize,
+ abort: Option,
+}
+
+impl DecodeState {
+ fn new(max_nodes: usize, max_materialized_bytes: usize) -> Self {
+ Self {
+ doc: Document::without_pages(""),
+ positions: Positions::new(),
+ touched: BTreeSet::new(),
+ vectors: Vec::new(),
+ vector_sizes: Vec::new(),
+ node_sizes: HashMap::new(),
+ meta: None,
+ records_seen: 0,
+ max_nodes,
+ materialized_bytes: 0,
+ max_materialized_bytes,
+ abort: None,
+ }
+ }
+
+ fn charge(&mut self, bytes: usize) -> Result<(), Error> {
+ self.materialized_bytes = self.materialized_bytes.saturating_add(bytes);
+ if self.materialized_bytes > self.max_materialized_bytes {
+ return Err(Error::TooLarge(self.max_materialized_bytes));
+ }
+ Ok(())
+ }
+
+ fn fail(&mut self, err: Error) -> E {
+ let msg = err.to_string();
+ self.abort = Some(err);
+ E::custom(msg)
+ }
+
+ fn ingest_record(&mut self, rec: WireRecord) -> Result<(), Error> {
+ let (node, pos, size) = match rec {
+ WireRecord::Full { pos, mut node, vref } => {
+ frac::validate(&pos).map_err(|e| Error::Invalid(e.to_string()))?;
+ if self.doc.contains(node.id) {
+ return Err(Error::Invalid(format!("node {} already exists", node.id)));
+ }
+ node.children.clear();
+ let mut est = est_node_bytes(&node).saturating_add(pos.len());
+ if let Some(idx) = vref {
+ let i = usize::try_from(idx).map_err(|_| Error::Decode(format!("invalid vector ref {idx}")))?;
+ let vsize = self.vector_sizes.get(i).copied().ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
+ est = est.saturating_add(vsize);
+ self.charge(est)?;
+ let net = self.vectors.get(i).ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
+ node.kind = NodeKind::Vector { network: net.clone() };
+ } else {
+ self.charge(est)?;
+ }
+ (*node, pos, est)
+ }
+ WireRecord::Mirror(m) => {
+ frac::validate(&m.pos).map_err(|e| Error::Invalid(e.to_string()))?;
+ if self.doc.contains(m.id) {
+ return Err(Error::Invalid(format!("node {} already exists", m.id)));
+ }
+ let missing = || Error::Invalid(format!("mirror {} references missing or cyclic source {}", m.id, m.source));
+ let src_size = self.node_sizes.get(&m.source).copied().ok_or_else(missing)?;
+ let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &self.vector_sizes)).saturating_add(m.pos.len());
+ self.charge(est)?;
+ let src = self.doc.node(m.source).ok_or_else(missing)?;
+ let mut node = src.clone();
+ node.id = m.id;
+ node.parent = m.parent;
+ node.children.clear();
+ node.source = Some(m.source);
+ node.overrides = m.overrides;
+ for delta in m.deltas {
+ apply_field_delta(&mut node, delta, &self.vectors)?;
+ }
+ let actual = est_node_bytes(&node).saturating_add(m.pos.len());
+ (node, m.pos, actual)
+ }
+ };
+
+ let id = node.id;
+ insert_decoded_node(&mut self.doc, &mut self.positions, node, pos)?;
+ self.touched.insert(id);
+ self.node_sizes.insert(id, size);
+ Ok(())
+ }
+}
+
+struct VectorsSeed<'a>(&'a mut DecodeState);
+impl<'de> DeserializeSeed<'de> for VectorsSeed<'_> {
+ type Value = ();
+ fn deserialize>(self, d: D) -> Result<(), D::Error> {
+ d.deserialize_seq(self)
+ }
+}
+impl<'de> Visitor<'de> for VectorsSeed<'_> {
+ type Value = ();
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("vector networks")
+ }
+ fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> {
+ while let Some(net) = seq.next_element::()? {
+ let size = est_vector_bytes(&net);
+ if let Err(err) = self.0.charge(size) {
+ return Err(self.0.fail(err));
+ }
+ self.0.vector_sizes.push(size);
+ self.0.vectors.push(figcraft_doc::Shared::new(net));
+ }
+ Ok(())
+ }
+}
+
+struct RecordsSeed<'a>(&'a mut DecodeState);
+impl<'de> DeserializeSeed<'de> for RecordsSeed<'_> {
+ type Value = ();
+ fn deserialize>(self, d: D) -> Result<(), D::Error> {
+ d.deserialize_seq(self)
+ }
+}
+impl<'de> Visitor<'de> for RecordsSeed<'_> {
+ type Value = ();
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("delta snapshot records")
+ }
+ fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> {
+ loop {
+ if self.0.records_seen >= self.0.max_nodes {
+ if seq.next_element::()?.is_some() {
+ let max = self.0.max_nodes;
+ return Err(self.0.fail(Error::Invalid(format!("delta snapshot exceeds the {max}-node limit"))));
+ }
+ break;
+ }
+ let Some(rec) = seq.next_element::()? else {
+ break;
+ };
+ self.0.records_seen += 1;
+ if let Err(err) = self.0.ingest_record(rec) {
+ return Err(self.0.fail(err));
+ }
+ }
+ Ok(())
+ }
+}
+
+struct DeltaWireSeed<'a>(&'a mut DecodeState);
+impl<'de> DeserializeSeed<'de> for DeltaWireSeed<'_> {
+ type Value = ();
+ fn deserialize>(self, d: D) -> Result<(), D::Error> {
+ d.deserialize_map(self)
+ }
+}
+impl<'de> Visitor<'de> for DeltaWireSeed<'_> {
+ type Value = ();
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("delta snapshot payload")
+ }
+ fn visit_map>(self, mut map: A) -> Result<(), A::Error> {
+ while let Some(key) = map.next_key::()? {
+ match key.as_str() {
+ "meta" => {
+ let meta: WireMeta = map.next_value()?;
+ if let Err(err) = self.0.charge(est_meta_bytes(&meta)) {
+ return Err(self.0.fail(err));
+ }
+ self.0.meta = Some(meta);
+ }
+ "vectors" => map.next_value_seed(VectorsSeed(self.0))?,
+ "records" => map.next_value_seed(RecordsSeed(self.0))?,
+ _ => {
+ let _ = map.next_value::()?;
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+fn stream_decode_wire(raw: &[u8], max_nodes: usize, max_materialized_bytes: usize) -> Result {
+ let mut state = DecodeState::new(max_nodes, max_materialized_bytes);
+ let mut de = serde_json::Deserializer::from_slice(raw);
+ let res = DeltaWireSeed(&mut state).deserialize(&mut de);
+ if let Some(err) = state.abort {
+ return Err(err);
+ }
+ res.map_err(|e| Error::Decode(format!("delta snapshot json: {e}")))?;
+ de.end().map_err(|e| Error::Decode(format!("delta snapshot trailing data: {e}")))?;
+
+ let meta = state.meta.ok_or_else(|| Error::Decode("delta snapshot missing meta".into()))?;
+ apply_meta(&mut state.doc, meta);
+ relist_pages(&mut state.doc, &state.positions);
+ if state.doc.pages.is_empty() {
+ return Err(Error::Invalid("a snapshot needs a page".into()));
+ }
+ state.doc.published = None;
+ state.doc.take_dirty();
+ let replica = Replica::from_parts(state.doc, state.positions);
+ replica.check(&state.touched)?;
+ Ok(replica)
+}
+
+fn insert_decoded_node(doc: &mut Document, positions: &mut Positions, node: Node, pos: String) -> Result<(), Error> {
+ let (id, is_page, parent) = (node.id, node.is_page(), node.parent);
+ match (is_page, parent) {
+ (true, None) => {
+ doc.insert_page(node).map_err(|e| Error::Invalid(e.to_string()))?;
+ }
+ (false, Some(p)) => {
+ let siblings = &doc.get(p).map_err(|e| Error::Invalid(e.to_string()))?.children;
+ let at = siblings.partition_point(|c| (positions.get(c).map_or("", String::as_str), *c) < (pos.as_str(), id));
+ doc.insert(node, p, Some(at)).map_err(|e| Error::Invalid(e.to_string()))?;
+ }
+ _ => return Err(Error::Invalid("pages, and only pages, have no parent".into())),
+ }
+ positions.insert(id, pos);
+ Ok(())
+}
+
+fn apply_meta(doc: &mut Document, mut meta: WireMeta) {
+ doc.name = meta.name;
+ doc.kind = meta.kind;
+ doc.styles = meta.styles;
+ doc.variables = meta.variables;
+ doc.current_page = meta.current_page;
+ doc.document_colors = meta.document_colors;
+ doc.comments = meta.comments;
+ doc.libraries = Arc::new(meta.libraries);
+ doc.color_profile = meta.color_profile;
+ doc.image_presets = meta.image_presets;
+ clamp_design_review_config(&mut meta.design_review);
+ doc.design_review = meta.design_review;
+ doc.annotation_categories = meta.annotation_categories;
+ doc.dev_snapshots = meta.dev_snapshots.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
+ doc.timer = meta.timer;
+ doc.vote = meta.vote;
+ doc.votes = meta.votes;
+ doc.vote_history = meta.vote_history;
+ for wi in meta.images {
+ // Leave out images that fail validation or attempt to replace bytes under an existing
+ // key, matching legacy `Replica::from_snapshot_leaving_out`.
+ let Ok(img) = validate_image_base64(&wi.key, wi.width, wi.height, &wi.bytes) else {
+ continue;
+ };
+ if doc.images.get(&wi.key).is_some_and(|old| old.bytes != img.bytes) {
+ continue;
+ }
+ doc.images.insert(wi.key, img);
+ }
+}
+
+fn relist_pages(doc: &mut Document, positions: &Positions) {
+ let store = doc.libraries.store;
+ let mut pages: Vec = doc.nodes().filter(|n| n.is_page() && Some(n.id) != store).map(|n| n.id).collect();
+ pages.sort_by(|a, b| (positions.get(a).map_or("", String::as_str), *a).cmp(&(positions.get(b).map_or("", String::as_str), *b)));
+ doc.pages = pages;
+}
diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs
new file mode 100644
index 000000000..bcee23a11
--- /dev/null
+++ b/crates/collab/src/delta_snapshot/encode.rs
@@ -0,0 +1,262 @@
+//! Topological ordering, vector interning and deflate framing for `CatchUp::DeltaSnapshot`.
+
+use std::collections::{HashMap, HashSet, VecDeque};
+use std::io::{BufWriter, Write};
+
+use figcraft_doc::{Document, Node, NodeId, NodeKind, VectorNetwork};
+use sha2::{Digest as _, Sha256};
+
+use super::decode::{est_deltas_extra_bytes, est_meta_bytes, est_node_bytes, est_vector_bytes, materialized_budget};
+use super::fields::{diff_mirror_fields, exact_vector_network_eq};
+use super::{DEFAULT_MAX_MATERIALIZED_BYTES, DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord};
+use crate::Error;
+use crate::replica::Replica;
+
+/// Content-addressed deduplicator for `VectorNetwork`s within one snapshot.
+#[derive(Default)]
+pub(super) struct VectorInterner {
+ by_hash: HashMap<[u8; 32], Vec>,
+ table: Vec,
+}
+
+impl VectorInterner {
+ pub(super) fn intern(&mut self, net: &VectorNetwork) -> Result {
+ let raw = serde_json::to_vec(net).map_err(|e| Error::Encode(e.to_string()))?;
+ let digest: [u8; 32] = Sha256::digest(&raw).into();
+ if let Some(bucket) = self.by_hash.get(&digest) {
+ for &idx in bucket {
+ if usize::try_from(idx).ok().and_then(|i| self.table.get(i)).is_some_and(|existing| exact_vector_network_eq(existing, net)) {
+ return Ok(idx);
+ }
+ }
+ }
+ let idx = u32::try_from(self.table.len()).map_err(|_| Error::Encode("too many distinct vector networks".into()))?;
+ self.table.push(net.clone());
+ self.by_hash.entry(digest).or_default().push(idx);
+ Ok(idx)
+ }
+}
+
+/// Kahn topological order over `(parent, source)` edges (in-degree at most 2 per node).
+///
+/// Every parent precedes its children and every acyclic source precedes its mirrors. Nodes
+/// caught in a `source` cycle are appended in parent-first order and emitted as `Full`.
+fn topo_order(doc: &Document) -> Vec {
+ let mut roots = doc.pages.clone();
+ roots.extend(doc.nodes().filter(|n| n.parent.is_none() && !doc.pages.contains(&n.id)).map(|n| n.id));
+ let mut parent_order = Vec::with_capacity(doc.node_count());
+ for r in roots {
+ parent_order.extend(doc.subtree(r));
+ }
+
+ let present: HashSet = parent_order.iter().copied().collect();
+ let mut indeg: HashMap = HashMap::with_capacity(present.len());
+ let mut deps_of: HashMap> = HashMap::with_capacity(present.len());
+
+ for &id in &parent_order {
+ let Some(n) = doc.node(id) else { continue };
+ let mut d: u8 = 0;
+ let p = n.parent.filter(|p| *p != id && present.contains(p));
+ let s = n.source.filter(|s| *s != id && Some(*s) != p && present.contains(s));
+ if let Some(pid) = p {
+ deps_of.entry(pid).or_default().push(id);
+ d += 1;
+ }
+ if let Some(sid) = s {
+ deps_of.entry(sid).or_default().push(id);
+ d += 1;
+ }
+ indeg.insert(id, d);
+ }
+
+ let mut q: VecDeque = parent_order.iter().copied().filter(|id| indeg.get(id).copied() == Some(0)).collect();
+ let mut ordered = Vec::with_capacity(parent_order.len());
+ let mut placed: HashSet = HashSet::with_capacity(parent_order.len());
+
+ while let Some(u) = q.pop_front() {
+ if !placed.insert(u) {
+ continue;
+ }
+ ordered.push(u);
+ if let Some(nexts) = deps_of.get(&u) {
+ for &v in nexts {
+ if let Some(deg) = indeg.get_mut(&v)
+ && *deg > 0
+ {
+ *deg -= 1;
+ if *deg == 0 {
+ q.push_back(v);
+ }
+ }
+ }
+ }
+ }
+
+ if ordered.len() < parent_order.len() {
+ for id in parent_order {
+ if placed.insert(id) {
+ ordered.push(id);
+ }
+ }
+ }
+ ordered
+}
+
+/// Encode `replica` as a compressed `CatchUp::DeltaSnapshot` payload.
+///
+/// Returns `Error::TooLarge` if the payload would exceed the client decoder's materialized-memory
+/// budget, allowing callers such as `Server::join_as` to fall back to `CatchUp::Snapshot`.
+pub fn encode_delta_snapshot(replica: &Replica) -> Result, Error> {
+ let doc = replica.document();
+ let order = topo_order(doc);
+ let mut interner = VectorInterner::default();
+ let mut seen: HashMap = HashMap::with_capacity(order.len());
+ let mut records = Vec::with_capacity(order.len());
+
+ for id in order {
+ let Some(node) = doc.node(id) else { continue };
+ let pos = replica.key(id).to_string();
+ let rec = encode_one_node(node, pos, &seen, &mut interner)?;
+ records.push(rec);
+ seen.insert(id, node);
+ }
+
+ let meta = build_meta(doc);
+ let est_materialized = estimate_decode_charge(&meta, &interner.table, &records);
+ let wire = DeltaWireRef { meta: &meta, vectors: &interner.table, records: &records };
+ let (out, written) = compress_wire(&wire)?;
+ let budget = materialized_budget(written, DEFAULT_MAX_MATERIALIZED_BYTES);
+ if est_materialized > budget {
+ return Err(Error::TooLarge(budget));
+ }
+ Ok(out)
+}
+
+/// Mirror the decoder's materialized-byte accounting so the server never emits a delta snapshot
+/// that a compliant client would reject with `Error::TooLarge`.
+fn estimate_decode_charge(meta: &WireMeta, vectors: &[VectorNetwork], records: &[WireRecord]) -> usize {
+ let vector_sizes: Vec = vectors.iter().map(est_vector_bytes).collect();
+ let mut total = est_meta_bytes(meta);
+ for &vs in &vector_sizes {
+ total = total.saturating_add(vs);
+ }
+ let mut node_sizes: HashMap = HashMap::with_capacity(records.len());
+ for rec in records {
+ match rec {
+ WireRecord::Full { pos, node, vref } => {
+ let vsize = vref.and_then(|idx| usize::try_from(idx).ok()).and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0);
+ let est = est_node_bytes(node).saturating_add(pos.len()).saturating_add(vsize);
+ total = total.saturating_add(est);
+ node_sizes.insert(node.id, est);
+ }
+ WireRecord::Mirror(m) => {
+ let src_size = node_sizes.get(&m.source).copied().unwrap_or(0);
+ let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &vector_sizes)).saturating_add(m.pos.len());
+ let overrides = m.overrides.iter().fold(0usize, |a, s| a.saturating_add(s.len()).saturating_add(24));
+ total = total.saturating_add(est);
+ node_sizes.insert(m.id, est.saturating_add(overrides));
+ }
+ }
+ }
+ total
+}
+
+fn encode_one_node(node: &Node, pos: String, seen: &HashMap, interner: &mut VectorInterner) -> Result {
+ if let Some(src_id) = node.source
+ && let Some(src) = seen.get(&src_id)
+ {
+ let deltas = diff_mirror_fields(src, node, interner)?;
+ return Ok(WireRecord::Mirror(Box::new(MirrorWire {
+ id: node.id,
+ parent: node.parent,
+ pos,
+ source: src_id,
+ overrides: node.overrides.clone(),
+ deltas,
+ })));
+ }
+
+ let mut stripped = node.clone();
+ // Children are rebuilt from `(parent, pos)` on decode.
+ stripped.children.clear();
+ let vref = match &mut stripped.kind {
+ NodeKind::Vector { network } if !network.vertices.is_empty() || !network.segments.is_empty() || !network.regions.is_empty() => {
+ let idx = interner.intern(network)?;
+ *network = figcraft_doc::Shared::default();
+ Some(idx)
+ }
+ _ => None,
+ };
+ Ok(WireRecord::Full { pos, node: Box::new(stripped), vref })
+}
+
+fn build_meta(doc: &Document) -> WireMeta {
+ use base64::Engine as _;
+ let images = doc
+ .images
+ .iter()
+ .map(|(key, img)| WireImage {
+ key: key.clone(),
+ width: img.width,
+ height: img.height,
+ bytes: base64::engine::general_purpose::STANDARD.encode(img.bytes.as_slice()),
+ })
+ .collect();
+ WireMeta {
+ name: doc.name.clone(),
+ kind: doc.kind,
+ styles: doc.styles.clone(),
+ variables: doc.variables.clone(),
+ current_page: doc.current_page,
+ document_colors: doc.document_colors.clone(),
+ comments: doc.comments.clone(),
+ libraries: (*doc.libraries).clone(),
+ color_profile: doc.color_profile,
+ image_presets: doc.image_presets.clone(),
+ design_review: doc.design_review.clone(),
+ annotation_categories: doc.annotation_categories.clone(),
+ dev_snapshots: doc.dev_snapshots.iter().map(|(k, v)| (*k, (**v).clone())).collect(),
+ timer: doc.timer,
+ vote: doc.vote.clone(),
+ votes: doc.votes.clone(),
+ vote_history: doc.vote_history.clone(),
+ images,
+ }
+}
+
+struct CountingWriter {
+ inner: W,
+ written: usize,
+}
+
+impl Write for CountingWriter {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result {
+ let n = self.inner.write(buf)?;
+ self.written = self.written.saturating_add(n);
+ Ok(n)
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ self.inner.flush()
+ }
+}
+
+fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<(Vec, usize), Error> {
+ let mut out = Vec::with_capacity(4096);
+ out.extend_from_slice(DELTA_MAGIC);
+ out.push(DELTA_VERSION);
+ out.extend_from_slice(&0u32.to_le_bytes());
+
+ // Buffer writes into 64 KiB chunks so serde_json's small token writes do not enter deflate individually.
+ let encoder = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast());
+ let mut buffered = BufWriter::with_capacity(64 * 1024, CountingWriter { inner: encoder, written: 0 });
+ serde_json::to_writer(&mut buffered, wire).map_err(|e| Error::Encode(e.to_string()))?;
+ let counting = buffered.into_inner().map_err(|e| Error::Encode(e.into_error().to_string()))?;
+ let written = counting.written;
+ let len_u32 = u32::try_from(written).map_err(|_| Error::TooLarge(u32::MAX as usize))?;
+ let mut out = counting.inner.finish().map_err(|e| Error::Encode(e.to_string()))?;
+ if let Some(slot) = out.get_mut(5..9) {
+ slot.copy_from_slice(&len_u32.to_le_bytes());
+ }
+ Ok((out, written))
+}
diff --git a/crates/collab/src/delta_snapshot/fields.rs b/crates/collab/src/delta_snapshot/fields.rs
new file mode 100644
index 000000000..240242d6e
--- /dev/null
+++ b/crates/collab/src/delta_snapshot/fields.rs
@@ -0,0 +1,285 @@
+//! Mirror field deltas and structural equality checks.
+//!
+//! `Paint` ignores `color_alpha` in `PartialEq`, and IEEE-754 equates `-0.0` with `0.0`.
+//! Float and paint fields therefore compare bit-for-bit or via serialized JSON so mirror
+//! encoding never drops data that legacy snapshots preserve.
+
+use std::collections::BTreeMap;
+
+use figcraft_doc::color::{BlendMode, Paint, PaintKind};
+use figcraft_doc::geom::Affine;
+use figcraft_doc::proto::{Interaction, Overflow, ScrollPosition};
+use figcraft_doc::{
+ Annotation, AutoLayout, BoardItem, BoolOp, ChildLayout, CodeLink, CollectionId, Constraints, Corners, DevResource, DevStatus, Effect,
+ ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, Shared, StrokeProps, StyleRefs, VariableId,
+ VectorNetwork, Vertex,
+};
+use serde::{Deserialize, Serialize};
+
+use super::encode::VectorInterner;
+use crate::Error;
+
+/// Defines `FieldDelta`, mirror diffing and delta application from one field table so adding
+/// or editing a field keeps all three in lockstep.
+///
+/// New variants must be appended and gated behind a version or capability bump because older
+/// clients reject unknown variants during deserialization.
+macro_rules! delta_fields {
+ (
+ boxed: [ $( $bvar:ident ( $bty:ty ) => $bfield:ident via $beq:ident ),* $(,)? ],
+ value: [ $( $vvar:ident ( $vty:ty ) => $vfield:ident via $veq:ident ),* $(,)? ]
+ ) => {
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ pub(super) enum FieldDelta {
+ Kind(Box),
+ VectorRef(u32),
+ $( $bvar(Box<$bty>), )*
+ $( $vvar($vty), )*
+ }
+
+ fn diff_table_fields(src: &Node, node: &Node, out: &mut Vec) {
+ $(
+ if !$beq(&node.$bfield, &src.$bfield) {
+ out.push(FieldDelta::$bvar(Box::new(node.$bfield.clone())));
+ }
+ )*
+ $(
+ if !$veq(&node.$vfield, &src.$vfield) {
+ out.push(FieldDelta::$vvar(node.$vfield.clone()));
+ }
+ )*
+ }
+
+ pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[Shared]) -> Result<(), Error> {
+ match delta {
+ FieldDelta::Kind(v) => node.kind = *v,
+ FieldDelta::VectorRef(idx) => {
+ let net = usize::try_from(idx)
+ .ok()
+ .and_then(|i| vectors.get(i))
+ .ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
+ node.kind = NodeKind::Vector { network: net.clone() };
+ }
+ $( FieldDelta::$bvar(v) => node.$bfield = *v, )*
+ $( FieldDelta::$vvar(v) => node.$vfield = v, )*
+ }
+ Ok(())
+ }
+ };
+}
+
+delta_fields! {
+ boxed: [
+ Stroke(StrokeProps) => stroke via eq_exact,
+ ChildLayout(ChildLayout) => child_layout via eq_exact,
+ Styles(StyleRefs) => styles via eq_plain,
+ ],
+ value: [
+ Name(String) => name via eq_plain,
+ Visible(bool) => visible via eq_plain,
+ Locked(bool) => locked via eq_plain,
+ Opacity(f32) => opacity via eq_f32,
+ Blend(BlendMode) => blend via eq_plain,
+ Transform(Affine) => transform via eq_affine,
+ Width(f64) => width via eq_f64,
+ Height(f64) => height via eq_f64,
+ Fills(Vec) => fills via eq_paint_vec,
+ Strokes(Vec) => strokes via eq_paint_vec,
+ Effects(Vec) => effects via eq_vec_exact,
+ Corners(Corners) => corners via eq_exact,
+ Constraints(Constraints) => constraints via eq_plain,
+ Layout(Option) => layout via eq_opt_exact,
+ Clip(bool) => clip via eq_plain,
+ IsMask(bool) => is_mask via eq_plain,
+ MaskType(MaskType) => mask_type via eq_plain,
+ Grids(Vec) => grids via eq_vec_exact,
+ Guides(Vec) => guides via eq_vec_exact,
+ Exports(Vec) => exports via eq_vec_exact,
+ Interactions(Vec) => interactions via eq_vec_exact,
+ Overflow(Overflow) => overflow via eq_plain,
+ ScrollPosition(ScrollPosition) => scroll_position via eq_exact,
+ Bound(BTreeMap) => bound via eq_plain,
+ VarModes(BTreeMap) => var_modes via eq_plain,
+ ScaleFactor(f64) => scale_factor via eq_f64,
+ BoolOp(Option) => bool_op via eq_plain,
+ ConstrainProportions(bool) => constrain_proportions via eq_plain,
+ Exposed(bool) => exposed via eq_plain,
+ DevStatus(DevStatus) => dev_status via eq_plain,
+ DevChanged(bool) => dev_changed via eq_plain,
+ DevNote(String) => dev_note via eq_plain,
+ PropRefs(BTreeMap) => prop_refs via eq_plain,
+ PluginData(BTreeMap) => plugin_data via eq_plain,
+ Annotations(Vec) => annotations via eq_vec_exact,
+ CodeLinks(Vec) => code_links via eq_plain,
+ DevResources(Vec) => dev_resources via eq_plain,
+ Measurements(Vec) => measurements via eq_vec_exact,
+ Board(Option) => board via eq_opt_exact,
+ ]
+}
+
+/// Fails to compile if a new field is added to `figcraft_doc::Node` without updating `delta_fields!`.
+#[allow(dead_code)]
+fn every_node_field_visited(n: &Node) {
+ let Node {
+ id: _,
+ name: _,
+ kind: _,
+ parent: _,
+ children: _,
+ visible: _,
+ locked: _,
+ opacity: _,
+ blend: _,
+ transform: _,
+ width: _,
+ height: _,
+ fills: _,
+ strokes: _,
+ stroke: _,
+ effects: _,
+ corners: _,
+ constraints: _,
+ layout: _,
+ child_layout: _,
+ clip: _,
+ is_mask: _,
+ mask_type: _,
+ grids: _,
+ guides: _,
+ exports: _,
+ interactions: _,
+ overflow: _,
+ scroll_position: _,
+ styles: _,
+ bound: _,
+ var_modes: _,
+ scale_factor: _,
+ bool_op: _,
+ constrain_proportions: _,
+ source: _,
+ exposed: _,
+ dev_status: _,
+ dev_changed: _,
+ dev_note: _,
+ overrides: _,
+ prop_refs: _,
+ plugin_data: _,
+ annotations: _,
+ code_links: _,
+ dev_resources: _,
+ measurements: _,
+ board: _,
+ } = n;
+}
+
+pub(super) fn diff_mirror_fields(src: &Node, node: &Node, interner: &mut VectorInterner) -> Result, Error> {
+ let mut deltas = Vec::new();
+ if !exact_kind_eq(&node.kind, &src.kind) {
+ match &node.kind {
+ NodeKind::Vector { network } => deltas.push(FieldDelta::VectorRef(interner.intern(network)?)),
+ other => deltas.push(FieldDelta::Kind(Box::new(other.clone()))),
+ }
+ }
+ diff_table_fields(src, node, &mut deltas);
+ Ok(deltas)
+}
+
+#[inline]
+fn eq_plain(a: &T, b: &T) -> bool {
+ a == b
+}
+
+#[inline]
+fn eq_f64(a: &f64, b: &f64) -> bool {
+ a.to_bits() == b.to_bits()
+}
+
+#[inline]
+fn eq_f32(a: &f32, b: &f32) -> bool {
+ a.to_bits() == b.to_bits()
+}
+
+#[inline]
+fn eq_affine(a: &Affine, b: &Affine) -> bool {
+ a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| x.to_bits() == y.to_bits())
+}
+
+fn eq_json(a: &T, b: &T) -> bool {
+ matches!((serde_json::to_vec(a), serde_json::to_vec(b)), (Ok(x), Ok(y)) if x == y)
+}
+
+fn eq_exact(a: &T, b: &T) -> bool {
+ a == b && eq_json(a, b)
+}
+
+fn eq_vec_exact(a: &[T], b: &[T]) -> bool {
+ (a.is_empty() && b.is_empty()) || (a == b && eq_json(a, b))
+}
+
+fn eq_opt_exact(a: &Option, b: &Option) -> bool {
+ match (a, b) {
+ (None, None) => true,
+ (Some(x), Some(y)) => x == y && eq_json(x, y),
+ _ => false,
+ }
+}
+
+fn eq_paint(a: &Paint, b: &Paint) -> bool {
+ if a.visible != b.visible || a.blend != b.blend || !eq_f32(&a.opacity, &b.opacity) || !eq_f32(&a.color_alpha, &b.color_alpha) {
+ return false;
+ }
+ match (&a.kind, &b.kind) {
+ (PaintKind::Solid { color: ca }, PaintKind::Solid { color: cb }) => {
+ eq_f32(&ca.r, &cb.r) && eq_f32(&ca.g, &cb.g) && eq_f32(&ca.b, &cb.b) && eq_f32(&ca.a, &cb.a)
+ }
+ _ => a.kind == b.kind && eq_json(&a.kind, &b.kind),
+ }
+}
+
+fn eq_paint_vec(a: &[Paint], b: &[Paint]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).all(|(x, y)| eq_paint(x, y))
+}
+
+fn eq_vertex(a: &Vertex, b: &Vertex) -> bool {
+ eq_f64(&a.x, &b.x) && eq_f64(&a.y, &b.y) && eq_f64(&a.radius, &b.radius) && a.mirror == b.mirror && a.cap == b.cap && a.join == b.join
+}
+
+fn eq_segment(a: &Segment, b: &Segment) -> bool {
+ a.a == b.a && a.b == b.b && eq_f64(&a.ta.0, &b.ta.0) && eq_f64(&a.ta.1, &b.ta.1) && eq_f64(&a.tb.0, &b.tb.0) && eq_f64(&a.tb.1, &b.tb.1)
+}
+
+fn eq_region(a: &Region, b: &Region) -> bool {
+ let fills_ok = match (&a.fills, &b.fills) {
+ (None, None) => true,
+ (Some(fa), Some(fb)) => eq_paint_vec(fa, fb),
+ _ => false,
+ };
+ let space_ok = match (a.paint_space, b.paint_space) {
+ (None, None) => true,
+ (Some(pa), Some(pb)) => eq_f64(&pa.width, &pb.width) && eq_f64(&pa.height, &pb.height) && eq_affine(&pa.transform, &pb.transform),
+ _ => false,
+ };
+ a.winding == b.winding && a.loops == b.loops && fills_ok && space_ok
+}
+
+pub(super) fn exact_vector_network_eq(a: &VectorNetwork, b: &VectorNetwork) -> bool {
+ a.vertices.len() == b.vertices.len()
+ && a.segments.len() == b.segments.len()
+ && a.regions.len() == b.regions.len()
+ && a.vertices.iter().zip(&b.vertices).all(|(x, y)| eq_vertex(x, y))
+ && a.segments.iter().zip(&b.segments).all(|(x, y)| eq_segment(x, y))
+ && a.regions.iter().zip(&b.regions).all(|(x, y)| eq_region(x, y))
+}
+
+fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool {
+ match (a, b) {
+ (NodeKind::Frame, NodeKind::Frame)
+ | (NodeKind::Group, NodeKind::Group)
+ | (NodeKind::Rectangle, NodeKind::Rectangle)
+ | (NodeKind::Line, NodeKind::Line) => true,
+ (NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => na.ptr_eq(nb) || exact_vector_network_eq(na, nb),
+ (NodeKind::Text(ta), NodeKind::Text(tb)) => ta.ptr_eq(tb) || eq_exact(&**ta, &**tb),
+ _ => eq_exact(a, b),
+ }
+}
diff --git a/crates/collab/src/delta_snapshot/mod.rs b/crates/collab/src/delta_snapshot/mod.rs
new file mode 100644
index 000000000..34c5dd25d
--- /dev/null
+++ b/crates/collab/src/delta_snapshot/mod.rs
@@ -0,0 +1,146 @@
+//! Direct mirror-delta and deduplicated-vector snapshots (`CatchUp::DeltaSnapshot`).
+//!
+//! Used for clients whose hello announces `delta-snapshot` and `design-review`.
+//! Nodes are ordered topologically over `(parent, source)` edges so parents precede
+//! children and acyclic sources precede their mirrors. Mirrors diff field values
+//! structurally instead of trusting `Node::overrides`. Decoding streams records
+//! one at a time under inflated-byte, exact declared-length, node-count and
+//! materialized-memory budgets.
+
+mod decode;
+mod encode;
+mod fields;
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use figcraft_doc::color::{Color, ColorProfile};
+use figcraft_doc::{
+ AnnotationCategory, Ballots, BoardTimer, Comment, DesignReview, DevSnapshot, FileKind, ImagePreset, Libraries, Node, NodeId, VectorNetwork, Vote,
+ VoteRecord,
+};
+use serde::{Deserialize, Serialize};
+
+use crate::Error;
+use fields::FieldDelta;
+
+pub use decode::{decode_delta_snapshot, decode_delta_snapshot_with_budget};
+pub use encode::encode_delta_snapshot;
+
+/// Wire header magic for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot).
+pub const DELTA_MAGIC: &[u8; 4] = b"FCDS";
+/// Wire format version for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot).
+pub const DELTA_VERSION: u8 = 1;
+/// Fixed header size: 4-byte magic, 1-byte version, 4-byte little-endian uncompressed length.
+const HEADER_LEN: usize = 9;
+/// Default ceiling on estimated materialized bytes during decode.
+pub const DEFAULT_MAX_MATERIALIZED_BYTES: usize = 512 << 20;
+
+/// Check the fixed header and declared uncompressed length in O(1).
+///
+/// Combined with [`decode_delta_snapshot_with_budget`] requiring `inflated.len() == declared`,
+/// this prevents a client from inflating past `max_bytes`.
+pub fn check_header_limit(bytes: &[u8], max_bytes: usize) -> Result<(), Error> {
+ let declared = parse_header(bytes)?;
+ if declared > max_bytes {
+ return Err(Error::TooLarge(max_bytes));
+ }
+ Ok(())
+}
+
+fn parse_header(bytes: &[u8]) -> Result {
+ let header = bytes.get(..HEADER_LEN).ok_or_else(|| Error::Decode("delta snapshot header is truncated".into()))?;
+ if header.get(..4) != Some(DELTA_MAGIC.as_slice()) {
+ return Err(Error::Decode("delta snapshot magic mismatch".into()));
+ }
+ let version = header.get(4).copied().ok_or_else(|| Error::Decode("delta snapshot version missing".into()))?;
+ if version != DELTA_VERSION {
+ return Err(Error::Decode(format!("unsupported delta snapshot version {version}")));
+ }
+ let len_slice = header.get(5..9).ok_or_else(|| Error::Decode("delta snapshot length missing".into()))?;
+ let len_bytes: [u8; 4] = len_slice.try_into().map_err(|_| Error::Decode("delta snapshot length".into()))?;
+ usize::try_from(u32::from_le_bytes(len_bytes)).map_err(|_| Error::TooLarge(usize::MAX))
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(tag = "r", rename_all = "camelCase")]
+enum WireRecord {
+ Full {
+ pos: String,
+ node: Box,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ vref: Option,
+ },
+ Mirror(Box),
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct MirrorWire {
+ id: NodeId,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ parent: Option,
+ pos: String,
+ source: NodeId,
+ #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
+ overrides: BTreeSet,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ deltas: Vec,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+struct WireImage {
+ key: String,
+ width: u32,
+ height: u32,
+ bytes: String,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct WireMeta {
+ name: String,
+ #[serde(default)]
+ kind: FileKind,
+ #[serde(default)]
+ styles: Vec,
+ #[serde(default)]
+ variables: figcraft_doc::Variables,
+ #[serde(default)]
+ current_page: Option,
+ #[serde(default)]
+ document_colors: Vec,
+ #[serde(default)]
+ comments: Vec,
+ #[serde(default)]
+ libraries: Libraries,
+ #[serde(default)]
+ color_profile: ColorProfile,
+ #[serde(default)]
+ image_presets: Vec,
+ #[serde(default)]
+ design_review: DesignReview,
+ #[serde(default)]
+ annotation_categories: Option>,
+ #[serde(default)]
+ dev_snapshots: BTreeMap,
+ #[serde(default)]
+ timer: Option,
+ #[serde(default)]
+ vote: Option,
+ #[serde(default)]
+ votes: Ballots,
+ #[serde(default)]
+ vote_history: Vec,
+ #[serde(default)]
+ images: Vec,
+}
+
+/// Serialization envelope written in canonical order (`meta`, `vectors`, `records`).
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct DeltaWireRef<'a> {
+ meta: &'a WireMeta,
+ #[serde(skip_serializing_if = "<[VectorNetwork]>::is_empty")]
+ vectors: &'a [VectorNetwork],
+ records: &'a [WireRecord],
+}
diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs
new file mode 100644
index 000000000..fb3a0a075
--- /dev/null
+++ b/crates/collab/src/delta_snapshot_tests.rs
@@ -0,0 +1,408 @@
+//! Parity, exact-equality and hostile-input tests for `CatchUp::DeltaSnapshot`.
+
+use std::collections::BTreeMap;
+use std::io::Write;
+use std::sync::Arc;
+
+use figcraft_color::{Color, Paint};
+use figcraft_doc::{
+ BoardTimer, Comment, DesignReview, DevSnapshot, Document, ImageData, ImagePreset, Libraries, NodeId, NodeKind, Segment, TextData, VectorNetwork,
+ Vertex, Vote, VoteRecord,
+};
+use figcraft_geom::Affine;
+
+use crate::delta_snapshot::{DELTA_MAGIC, DELTA_VERSION, decode_delta_snapshot, decode_delta_snapshot_with_budget, encode_delta_snapshot};
+use crate::message::{self, CatchUp, ClientMsg, ServerMsg};
+use crate::{Client, Error, Limits, Outgoing, Replica, Server};
+
+pub(crate) const LEGACY_CLIENT_VERSION: &str = "0.18.1 signals hosting comments packed design-review branches";
+
+/// Compare two documents via serialized JSON (excluding per-client `next_id`) so
+/// non-structural `PartialEq` cannot hide silent data loss.
+pub(crate) fn assert_docs_json_eq(left: &Document, right: &Document, context: &str) {
+ let mut lj = serde_json::to_value(left).expect("serialize left doc");
+ let mut rj = serde_json::to_value(right).expect("serialize right doc");
+ if let Some(m) = lj.as_object_mut() {
+ m.remove("next_id");
+ }
+ if let Some(m) = rj.as_object_mut() {
+ m.remove("next_id");
+ }
+ assert_eq!(lj, rj, "{context}: serialized JSON mismatch");
+}
+
+fn make_raw_delta_payload(json: &str, declared_override: Option) -> Vec {
+ let mut out = Vec::new();
+ out.extend_from_slice(DELTA_MAGIC);
+ out.push(DELTA_VERSION);
+ let len = declared_override.unwrap_or(u32::try_from(json.len()).unwrap());
+ out.extend_from_slice(&len.to_le_bytes());
+ let mut z = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast());
+ z.write_all(json.as_bytes()).unwrap();
+ z.finish().unwrap()
+}
+
+pub(crate) fn sample_vector_icon(seed: usize, vertex_count: usize) -> VectorNetwork {
+ let mut vertices = Vec::with_capacity(vertex_count);
+ let mut segments = Vec::with_capacity(vertex_count);
+ for i in 0..vertex_count {
+ let a = (i as f64) * std::f64::consts::TAU / (vertex_count as f64) + (seed as f64) * 0.1;
+ vertices.push(Vertex::new(16.0 + 12.0 * a.cos(), 16.0 + 12.0 * a.sin()));
+ segments.push(Segment { a: i, b: (i + 1) % vertex_count, ta: (1.5, -0.5), tb: (-1.5, 0.5) });
+ }
+ VectorNetwork { vertices, segments, regions: Vec::new() }
+}
+
+/// Build a document with cross-page instances (main component on page 2, instances on page 1),
+/// depth-2 mirror chains, repeated vector icons and stale empty `overrides` (#1819).
+pub(crate) fn design_system_doc(num_instances: usize) -> (Document, NodeId, Vec) {
+ let mut doc = Document::new("DesignSystemDST");
+ let page1 = doc.first_page().unwrap();
+ let page2 = doc.add_page("Components");
+
+ let comp = doc
+ .create(
+ page2,
+ NodeKind::Component { description: "Card".into(), props: BTreeMap::new(), prop_order: Vec::new() },
+ "Card",
+ 0.0,
+ 0.0,
+ 320.0,
+ 200.0,
+ )
+ .unwrap();
+
+ let icon_a = sample_vector_icon(1, 24);
+ let icon_b = sample_vector_icon(2, 24);
+ let mut main_children = Vec::new();
+ for i in 0..6 {
+ let kind = match i {
+ 0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}")).into()),
+ 2 => NodeKind::Vector { network: icon_a.clone().into() },
+ 3 => NodeKind::Vector { network: icon_b.clone().into() },
+ _ => NodeKind::Rectangle,
+ };
+ let cid = doc.create(comp, kind, &format!("Part {i}"), i as f64 * 24.0, 8.0, 32.0, 32.0).unwrap();
+ if let Some(n) = doc.node_mut(cid) {
+ n.fills = vec![Paint::solid(Color::from_rgb8_const(40, 100, (i * 30) as u8))];
+ }
+ main_children.push(cid);
+ }
+
+ let main_snapshots: Vec<_> = main_children.iter().map(|id| doc.node(*id).unwrap().clone()).collect();
+ let mut prev_inst_children: Option> = None;
+
+ for idx in 0..num_instances {
+ let mut root = doc.node(comp).unwrap().clone();
+ let inst_id = doc.alloc_id();
+ root.id = inst_id;
+ root.name = format!("Card #{idx}");
+ root.kind = NodeKind::Instance { component: comp, props: BTreeMap::new() };
+ root.children.clear();
+ root.parent = None;
+ root.source = Some(comp);
+ root.transform = Affine::translate((idx as f64 * 340.0, 0.0));
+ doc.insert(root, page1, None).unwrap();
+
+ let mut this_children = Vec::new();
+ for (j, src) in main_snapshots.iter().enumerate() {
+ let mut child = src.clone();
+ child.id = doc.alloc_id();
+ child.parent = None;
+ child.children.clear();
+ let chain_src = prev_inst_children.as_ref().filter(|_| idx % 3 == 2).map_or(src.id, |prev| prev[j]);
+ child.source = Some(chain_src);
+
+ if j == 0 && idx % 2 == 0 {
+ if let NodeKind::Text(t) = &mut child.kind {
+ t.characters = format!("Overridden {idx}");
+ }
+ if idx % 4 != 0 {
+ child.overrides.insert("characters".to_string());
+ }
+ }
+ if j == 4 && idx % 5 == 0 {
+ child.width = 99.0;
+ child.transform = Affine::translate((12.0, 24.0));
+ }
+ let child_id = child.id;
+ doc.insert(child, inst_id, None).unwrap();
+ this_children.push(child_id);
+ }
+ prev_inst_children = Some(this_children);
+ }
+
+ doc.take_dirty();
+ (doc, comp, main_children)
+}
+
+#[test]
+fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() {
+ let mut doc = Document::new("ExactEq");
+ let page = doc.first_page().unwrap();
+ let src = doc.create(page, NodeKind::Rectangle, "Src", 0.0, 0.0, 100.0, 50.0).unwrap();
+ let mut src_paint = Paint::solid(Color::from_rgb8_const(20, 80, 200));
+ src_paint.opacity = 0.5;
+ src_paint.color_alpha = 0.5;
+ if let Some(n) = doc.node_mut(src) {
+ n.fills = vec![src_paint.clone()];
+ n.strokes = vec![src_paint];
+ }
+
+ let mut mirror = doc.node(src).unwrap().clone();
+ mirror.id = doc.alloc_id();
+ mirror.parent = None;
+ mirror.source = Some(src);
+ mirror.fills[0].color_alpha = 1.0;
+ mirror.strokes[0].color_alpha = 0.25;
+ mirror.width = -0.0;
+ mirror.transform = Affine::translate((-0.0, 0.0));
+ assert_eq!(doc.node(src).unwrap().fills, mirror.fills, "Paint PartialEq ignores color_alpha");
+ doc.insert(mirror, page, None).unwrap();
+ doc.take_dirty();
+
+ let replica = Replica::new(doc);
+ let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap();
+ let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
+ assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality");
+ assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity");
+}
+
+#[test]
+fn corrupt_hash_image_matches_legacy_join_parity() {
+ let mut doc = Document::new("BadImage");
+ let page = doc.first_page().unwrap();
+ doc.create(page, NodeKind::Rectangle, "Box", 0.0, 0.0, 40.0, 40.0).unwrap();
+ let bad_key = "0".repeat(64);
+ doc.images.insert(bad_key.clone(), ImageData { bytes: Arc::new(b"not-matching-sha256".to_vec()), width: 10, height: 10 });
+ doc.images.insert("svg_icon_1".into(), ImageData { bytes: Arc::new(b"valid-bytes".to_vec()), width: 16, height: 16 });
+ doc.take_dirty();
+
+ let mut srv = Server::new(doc, "tok", Limits::default());
+ let join_with = |srv: &mut Server, ver: Option<&str>| -> Client {
+ let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "u", "#111") else { panic!() };
+ if let Some(v) = ver {
+ h.client_version = v.into();
+ }
+ let (id, outs) = srv.join(h).unwrap();
+ let w = outs
+ .into_iter()
+ .find_map(|o| match o {
+ Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
+ _ => None,
+ })
+ .unwrap();
+ Client::join(w).unwrap()
+ };
+
+ let legacy_client = join_with(&mut srv, Some(LEGACY_CLIENT_VERSION));
+ let delta_client = join_with(&mut srv, None);
+ assert!(!delta_client.document().images.contains_key(&bad_key));
+ assert!(delta_client.document().images.contains_key("svg_icon_1"));
+ assert_docs_json_eq(legacy_client.document(), delta_client.document(), "corrupt-image parity");
+}
+
+#[test]
+fn forged_declared_length_cannot_bypass_unpack_limit() {
+ let huge_json = format!(
+ r#"{{"meta":{{"name":"Bomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"{}","type":"page","width":0,"height":0}}}}]}}"#,
+ "A".repeat(4 << 20)
+ );
+ let mut welcome = ServerMsg::Welcome {
+ session: 1,
+ client_id: 1,
+ seq: 0,
+ catch_up: CatchUp::DeltaSnapshot(make_raw_delta_payload(&huge_json, Some(10))),
+ processed: message::Processed::default(),
+ peers: Vec::new(),
+ access: message::Access::Edit,
+ secret: 1,
+ };
+ message::unpack(&mut welcome, 1 << 20).unwrap();
+ let err = Client::join(welcome).unwrap_err();
+ assert!(matches!(err, Error::TooLarge(10)), "forged length must abort at declared+1, got {err:?}");
+}
+
+#[test]
+fn mirror_and_vref_amplification_bombs_are_rejected_within_memory_budget() {
+ let big_text = "X".repeat(256 * 1024);
+ let mut mirror_recs = String::from(
+ r#"{"meta":{"name":"MirrorBomb"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},"#,
+ );
+ mirror_recs.push_str(&format!(
+ r#"{{"r":"full","pos":"a0","node":{{"id":2,"name":"Big","parent":1,"type":"text","characters":"{big_text}","width":10,"height":10}}}}"#
+ ));
+ for i in 3..2003u64 {
+ mirror_recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#));
+ }
+ mirror_recs.push_str("]}");
+ let err1 = decode_delta_snapshot(&make_raw_delta_payload(&mirror_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
+ assert!(matches!(err1, Error::TooLarge(_)), "mirror bomb must fail TooLarge, got {err1:?}");
+
+ let net_json = serde_json::to_string(&sample_vector_icon(1, 20_000)).unwrap();
+ let mut vref_recs = format!(
+ r#"{{"meta":{{"name":"VrefBomb"}},"vectors":[{net_json}],"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}"#
+ );
+ for i in 2..3002u64 {
+ vref_recs.push_str(&format!(
+ r#",{{"r":"full","pos":"a{i:04}1","vref":0,"node":{{"id":{i},"name":"V","parent":1,"type":"vector","network":{{"vertices":[],"segments":[]}},"width":10,"height":10}}}}"#
+ ));
+ }
+ vref_recs.push_str("]}");
+ let err2 = decode_delta_snapshot(&make_raw_delta_payload(&vref_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
+ assert!(matches!(err2, Error::TooLarge(_)), "vref bomb must fail TooLarge, got {err2:?}");
+}
+
+#[test]
+fn streaming_node_budget_and_hostile_inputs_are_rejected_cleanly() {
+ let mut many =
+ String::from(r#"{"meta":{"name":"Many"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}}"#);
+ for i in 2..502u64 {
+ many.push_str(&format!(
+ r#",{{"r":"full","pos":"a{i:04}1","node":{{"id":{i},"name":"R","parent":1,"type":"rectangle","width":1,"height":1}}}}"#
+ ));
+ }
+ many.push_str("]}");
+ let err = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&many, None), 16 << 20, 10, 64 << 20).unwrap_err();
+ assert!(matches!(&err, Error::Invalid(msg) if msg.contains("10-node limit")), "got {err:?}");
+
+ let cyclic = r#"{"meta":{"name":"Evil"},"records":[
+ {"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},
+ {"r":"mirror","id":2,"parent":1,"pos":"a0","source":3},
+ {"r":"mirror","id":3,"parent":1,"pos":"a1","source":2}
+ ]}"#;
+ let self_cycle = r#"{"meta":{"name":"Self"},"records":[
+ {"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},
+ {"r":"mirror","id":2,"parent":1,"pos":"a0","source":2}
+ ]}"#;
+ assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(cyclic, None), 1 << 20, 100), Err(Error::Invalid(_))));
+ assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(self_cycle, None), 1 << 20, 100), Err(Error::Invalid(_))));
+
+ for bad in [vec![], b"FCD".to_vec(), b"XXXX\x01\x00\x00\x00\x00".to_vec(), b"FCDS\x99\x00\x00\x00\x00".to_vec(), vec![0xFF; 64]] {
+ assert!(decode_delta_snapshot(&bad, 1 << 20, 1000).is_err());
+ }
+}
+
+#[test]
+fn full_metadata_and_design_review_roundtrip_matches_legacy_json() {
+ let (mut doc, _, _) = design_system_doc(4);
+ let page = doc.first_page().unwrap();
+ doc.comments.push(Comment {
+ id: 7,
+ page,
+ x: 10.0,
+ y: 20.0,
+ anchor: None,
+ first: figcraft_doc::Message::new("Alice", "Check contrast", 1_700_000_000),
+ resolved: false,
+ replies: Vec::new(),
+ read_by: None,
+ });
+ doc.dev_snapshots.insert(page, Arc::new(DevSnapshot { nodes: vec![Arc::new(doc.node(page).unwrap().clone())] }));
+ doc.timer = Some(BoardTimer::Paused { left: 120_000 });
+ let vote = Vote { per_person: 3, scope: Default::default(), ended: false, by: "Alice".into() };
+ doc.vote = Some(vote.clone());
+ doc.votes.entry("alice".into()).or_default().push(page);
+ doc.vote_history.push(VoteRecord { vote, ballots: doc.votes.clone(), names: BTreeMap::new(), ended: 1_700_000_000 });
+ doc.libraries = Arc::new(Libraries::default());
+ doc.image_presets.push(ImagePreset { name: "Warm".into(), filters: Default::default() });
+ doc.images.insert("logo_1".into(), ImageData { bytes: Arc::new(b"png-bytes".to_vec()), width: 32, height: 32 });
+ doc.design_review = DesignReview { radii: vec![4.0; figcraft_doc::MAX_RADII + 10], ..DesignReview::default() };
+ doc.take_dirty();
+
+ let replica = Replica::new(doc);
+ let legacy = Replica::from_snapshot(&replica.snapshot().unwrap()).unwrap();
+ let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
+ assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII);
+ assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity");
+}
+
+#[test]
+fn encoder_safely_roundtrips_cyclic_source_references_as_full_records() {
+ let mut doc = Document::new("CyclicInMemory");
+ let page = doc.first_page().unwrap();
+ let a = doc.create(page, NodeKind::Rectangle, "A", 0.0, 0.0, 50.0, 50.0).unwrap();
+ let b = doc.create(page, NodeKind::Rectangle, "B", 60.0, 0.0, 50.0, 50.0).unwrap();
+ doc.node_mut(a).unwrap().source = Some(b);
+ doc.node_mut(b).unwrap().source = Some(a);
+ doc.take_dirty();
+
+ let replica = Replica::new(doc);
+ let back = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 1 << 20, 100).unwrap();
+ assert_docs_json_eq(replica.document(), back.document(), "cyclic source roundtrip");
+}
+
+#[test]
+fn delta_snapshot_never_panics_when_truncated_or_bit_flipped() {
+ let (doc, _, _) = design_system_doc(2);
+ let valid = encode_delta_snapshot(&Replica::new(doc)).unwrap();
+ // Truncations across header and compressed body.
+ for cut in [0, 1, 4, 8, 9, 10, valid.len() / 2, valid.len() - 1] {
+ assert!(decode_delta_snapshot(&valid[..cut], 16 << 20, 10_000).is_err());
+ }
+ // Single-bit flips across header and body must either error cleanly or produce a valid Replica.
+ let stride = (valid.len() / 64).max(1);
+ for idx in (0..valid.len()).step_by(stride) {
+ let mut mutated = valid.clone();
+ mutated[idx] ^= 0x80;
+ let _ = decode_delta_snapshot(&mutated, 16 << 20, 10_000);
+ }
+}
+
+#[test]
+fn bound_map_amplification_and_oversized_metadata_are_rejected_by_budget() {
+ // Source node with a large `bound` map mirrored 1,000 times must trip the memory budget.
+ let mut bound_entries = Vec::with_capacity(200);
+ for i in 0..200 {
+ bound_entries.push(format!(r#""k{i:03}":"{}""#, "v".repeat(512)));
+ }
+ let bound_json = bound_entries.join(",");
+ let mut recs = format!(
+ r#"{{"meta":{{"name":"BoundBomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}},{{"r":"full","pos":"a0","node":{{"id":2,"name":"Src","parent":1,"type":"rectangle","width":10,"height":10,"bound":{{{bound_json}}}}}}}"#
+ );
+ for i in 3..1003u64 {
+ recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#));
+ }
+ recs.push_str("]}");
+ let err = decode_delta_snapshot(&make_raw_delta_payload(&recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
+ assert!(matches!(err, Error::TooLarge(_)), "bound-map amplification must fail TooLarge, got {err:?}");
+
+ // Oversized metadata (`name` of 2 MiB) under a 1 MiB materialized budget must fail TooLarge.
+ let big_meta = format!(
+ r#"{{"meta":{{"name":"{}"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}]}}"#,
+ "M".repeat(2 << 20)
+ );
+ let err2 = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&big_meta, None), 16 << 20, 100, 1 << 20).unwrap_err();
+ assert!(matches!(err2, Error::TooLarge(_)), "oversized metadata must fail TooLarge, got {err2:?}");
+}
+
+#[test]
+fn server_falls_back_to_legacy_snapshot_when_delta_exceeds_decode_budget() {
+ // 2,000 mirrors of a 256 KiB text node exceed the client's 64x materialized ceiling:
+ // the server must fall back to `CatchUp::Snapshot` so capable clients still join cleanly.
+ let mut doc = Document::new("HighAmplificationHonest");
+ let page = doc.first_page().unwrap();
+ let src = doc.create(page, NodeKind::Text(TextData::new("T".repeat(256 * 1024)).into()), "Big", 0.0, 0.0, 100.0, 20.0).unwrap();
+ let src_snap = doc.node(src).unwrap().clone();
+ for _ in 0..2000 {
+ let mut m = src_snap.clone();
+ m.id = doc.alloc_id();
+ m.parent = None;
+ m.source = Some(src);
+ doc.insert(m, page, None).unwrap();
+ }
+ doc.take_dirty();
+
+ assert!(matches!(encode_delta_snapshot(&Replica::new(doc.clone())), Err(Error::TooLarge(_))));
+ let mut srv = Server::new(doc, "tok", Limits::default());
+ let ClientMsg::Hello(h) = Client::hello("f", "tok", "u", "#222") else { panic!() };
+ let (id, outs) = srv.join(h).unwrap();
+ let welcome = outs
+ .into_iter()
+ .find_map(|o| match o {
+ Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
+ _ => None,
+ })
+ .unwrap();
+ assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }));
+}
diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs
index ae7299511..6b50ffaea 100644
--- a/crates/collab/src/docprops.rs
+++ b/crates/collab/src/docprops.rs
@@ -290,27 +290,61 @@ fn image_of(key: &str, value: &Json) -> Result {
image_within(key, value, ImageData::MAX_BYTES)
}
-/// [`image_of`] with `max_bytes` for the decoded size.
-pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result {
+/// Validate raw image bytes and dimensions under the same security rules as [`image_of`] (#1086).
+pub(crate) fn validate_image_raw_within(key: &str, width: u32, height: u32, bytes: Vec, max_bytes: u64) -> Result {
if !ImageData::is_valid_key(key) {
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
}
- let v: ImageValue = value.read("image")?;
- if v.width > MAX_IMAGE_SIDE || v.height > MAX_IMAGE_SIDE {
- return Err(Error::Invalid(format!("image: {}×{} passes the {} a side may be", v.width, v.height, MAX_IMAGE_SIDE)));
+ if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
+ return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be")));
}
- let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4);
- if u64::try_from(v.bytes.len()).unwrap_or(u64::MAX) > max_encoded {
- return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes")));
- }
- let bytes = base64::engine::general_purpose::STANDARD.decode(v.bytes.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?;
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > max_bytes {
return Err(Error::Invalid(format!("image: {} bytes pass the {max_bytes} an image may be", bytes.len())));
}
if ImageData::claims_content_hash(key) && key != sha256_hex(&bytes) {
return Err(Error::Invalid(format!("image: the bytes aren't what their key {key} hashes to")));
}
- Ok(ImageData { bytes: Arc::new(bytes), width: v.width, height: v.height })
+ Ok(ImageData { bytes: Arc::new(bytes), width, height })
+}
+
+/// Validate base64-encoded image bytes and dimensions under [`ImageData::MAX_BYTES`].
+pub(crate) fn validate_image_base64(key: &str, width: u32, height: u32, encoded: &str) -> Result {
+ validate_image_base64_within(key, width, height, encoded, ImageData::MAX_BYTES)
+}
+
+fn validate_image_base64_within(key: &str, width: u32, height: u32, encoded: &str, max_bytes: u64) -> Result {
+ if !ImageData::is_valid_key(key) {
+ return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
+ }
+ if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
+ return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be")));
+ }
+ let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4);
+ if u64::try_from(encoded.len()).unwrap_or(u64::MAX) > max_encoded {
+ return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes")));
+ }
+ let bytes = base64::engine::general_purpose::STANDARD.decode(encoded.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?;
+ validate_image_raw_within(key, width, height, bytes, max_bytes)
+}
+
+/// Clamp oversized review settings in place (matches [`clamp_snapshot_design_review`]).
+pub(crate) fn clamp_design_review_config(config: &mut figcraft_doc::DesignReview) -> bool {
+ if config.over_limits().is_empty() {
+ return false;
+ }
+ config.radii.truncate(figcraft_doc::MAX_RADII);
+ config.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
+ config.disabled.truncate(figcraft_doc::MAX_DISABLED);
+ true
+}
+
+/// [`image_of`] with `max_bytes` for the decoded size.
+pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result {
+ if !ImageData::is_valid_key(key) {
+ return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
+ }
+ let v: ImageValue = value.read("image")?;
+ validate_image_base64_within(key, v.width, v.height, &v.bytes, max_bytes)
}
macro_rules! doc_scalars {
@@ -413,17 +447,12 @@ pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) -> bool {
let mut clamped_any = false;
for c in changes {
if let Change::SetDoc { prop: DocProp::DesignReview, value } = c
- && let Ok(config) = value.read::("design review")
- && !config.over_limits().is_empty()
+ && let Ok(mut clamped) = value.read::("design review")
+ && clamp_design_review_config(&mut clamped)
+ && let Ok(v) = Json::of(&clamped)
{
- let mut clamped = config;
- clamped.radii.truncate(figcraft_doc::MAX_RADII);
- clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
- clamped.disabled.truncate(figcraft_doc::MAX_DISABLED);
- if let Ok(v) = Json::of(&clamped) {
- *value = v;
- clamped_any = true;
- }
+ *value = v;
+ clamped_any = true;
}
}
clamped_any
diff --git a/crates/collab/src/journal_tests.rs b/crates/collab/src/journal_tests.rs
index a8a7c4c25..3562c81c4 100644
--- a/crates/collab/src/journal_tests.rs
+++ b/crates/collab/src/journal_tests.rs
@@ -303,7 +303,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() {
let (key, bytes) = crate::image_tests::forged();
state.snapshot.push(crate::image_tests::put(&key, 2, 1, bytes));
let mut r = Server::restore(state, "", Limits::default()).unwrap();
- assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on restore");
+ assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on restore");
// Left out on replay.
let mut s = Server::new(base(), "", Limits::default());
@@ -312,7 +312,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() {
let mut r = Server::restore(state.clone(), "", Limits::default()).unwrap();
let batch = vec![crate::image_tests::put(&key, 2, 1, bytes)];
r.replay(Journal::Accepted(message::Accepted { seq: state.seq + 1, author: a.id(), batch_id: 90, changes: batch })).unwrap();
- assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on replay");
+ assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on replay");
}
/// A restart that left nothing out keeps resuming clients on the cheaper delta.
diff --git a/crates/collab/src/lib.rs b/crates/collab/src/lib.rs
index 230e209b8..912af370f 100644
--- a/crates/collab/src/lib.rs
+++ b/crates/collab/src/lib.rs
@@ -24,6 +24,7 @@
pub mod change;
pub mod client;
pub mod code;
+pub mod delta_snapshot;
mod diff;
mod docprops;
pub mod frac;
@@ -143,6 +144,10 @@ mod comment_access_tests;
#[cfg(test)]
mod deleted_cap_tests;
#[cfg(test)]
+mod delta_dst_tests;
+#[cfg(test)]
+mod delta_snapshot_tests;
+#[cfg(test)]
mod diff_tests;
#[cfg(test)]
mod entry_ids_tests;
diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs
index a1bc84fba..36c691b85 100644
--- a/crates/collab/src/message.rs
+++ b/crates/collab/src/message.rs
@@ -44,9 +44,14 @@ pub const BRANCHES: &str = "branches";
/// (older ones couldn't decode the variant at all).
pub const DESIGN_REVIEW: &str = "design-review";
+/// The word a client puts in its [`Hello::client_version`] when it reads
+/// [`CatchUp::DeltaSnapshot`]: a server sends a direct value-checked mirror-delta + vector-dedup
+/// compressed snapshot instead of `Vec` (#1819, #2041).
+pub const DELTA_SNAPSHOT: &str = "delta-snapshot";
+
/// The `client_version` this build announces: its version, then what it reads beyond the protocol.
pub fn client_version() -> String {
- format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES}", env!("CARGO_PKG_VERSION"))
+ format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES} {DELTA_SNAPSHOT}", env!("CARGO_PKG_VERSION"))
}
/// Whether `client_version` announces `word`.
@@ -84,6 +89,11 @@ pub fn reads_branches(client_version: &str) -> bool {
announces(client_version, BRANCHES)
}
+/// A [`Hello::client_version`] that announces [`DELTA_SNAPSHOT`].
+pub fn reads_delta_snapshot(client_version: &str) -> bool {
+ announces(client_version, DELTA_SNAPSHOT)
+}
+
/// Join a file's session.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Hello {
@@ -353,6 +363,10 @@ pub enum CatchUp {
/// [`PACKED`]: a document's changes shrink several times over. The client reads it with
/// [`unpack`] before anything else sees the welcome.
Packed(Vec),
+ /// A direct compressed mirror-delta & vector-deduplicated snapshot
+ /// ([`crate::delta_snapshot`]), for a client whose hello announced [`DELTA_SNAPSHOT`].
+ /// Appended last so earlier postcard discriminants remain unchanged.
+ DeltaSnapshot(Vec),
}
/// Opens a connection that manages a server's files (instead of [`Hello`]): the server's admin
@@ -1175,19 +1189,25 @@ pub fn pack(msg: &mut ServerMsg) -> Result<(), Error> {
/// past `max_bytes` (untrusted input: the limit an unpacked welcome would have had to fit).
/// Anything else is left as it is.
pub fn unpack(msg: &mut ServerMsg, max_bytes: usize) -> Result<(), Error> {
- if let ServerMsg::Welcome { catch_up, .. } = msg
- && let CatchUp::Packed(packed) = catch_up
- {
- let mut raw = Vec::new();
- let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
- flate2::read::DeflateDecoder::new(packed.as_slice())
- .take(limit)
- .read_to_end(&mut raw)
- .map_err(|e| Error::Decode(format!("packed document: {e}")))?;
- if raw.len() > max_bytes {
- return Err(Error::TooLarge(max_bytes));
+ if let ServerMsg::Welcome { catch_up, .. } = msg {
+ match catch_up {
+ CatchUp::Packed(packed) => {
+ let mut raw = Vec::new();
+ let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
+ flate2::read::DeflateDecoder::new(packed.as_slice())
+ .take(limit)
+ .read_to_end(&mut raw)
+ .map_err(|e| Error::Decode(format!("packed document: {e}")))?;
+ if raw.len() > max_bytes {
+ return Err(Error::TooLarge(max_bytes));
+ }
+ *catch_up = CatchUp::Snapshot(from_postcard(&raw)?);
+ }
+ CatchUp::DeltaSnapshot(bytes) => {
+ crate::delta_snapshot::check_header_limit(bytes, max_bytes)?;
+ }
+ CatchUp::Snapshot(_) | CatchUp::Delta(_) => {}
}
- *catch_up = CatchUp::Snapshot(from_postcard(&raw)?);
}
Ok(())
}
diff --git a/crates/collab/src/packed_welcome_tests.rs b/crates/collab/src/packed_welcome_tests.rs
index c78208cc4..d8c48bcc7 100644
--- a/crates/collab/src/packed_welcome_tests.rs
+++ b/crates/collab/src/packed_welcome_tests.rs
@@ -23,7 +23,9 @@ fn welcome() -> ServerMsg {
}
doc.repair();
let mut s = Server::new(doc, "tok", Limits::default());
- let ClientMsg::Hello(h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") };
+ let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") };
+ // Test the legacy `packed` welcome path (a client from before `delta-snapshot`).
+ h.client_version = "0.18.1 signals hosting comments packed design-review branches".into();
let (_, out) = s.join(h).unwrap();
out.into_iter().find_map(|o| if let Outgoing::To(_, m @ ServerMsg::Welcome { .. }) = o { Some(m) } else { None }).unwrap()
}
diff --git a/crates/collab/src/reconnect_tests.rs b/crates/collab/src/reconnect_tests.rs
index af13b5042..5489069ee 100644
--- a/crates/collab/src/reconnect_tests.rs
+++ b/crates/collab/src/reconnect_tests.rs
@@ -117,7 +117,7 @@ fn a_long_absence_catches_up_with_a_snapshot() {
}
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
let (_, out) = s.join(h).unwrap();
- assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
+ assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
deliver(&mut a, &out);
assert_eq!(a.view(), s.replica());
// A short absence gets the missed batches only.
@@ -154,7 +154,7 @@ fn the_default_log_is_bounded_in_bytes_and_a_client_behind_it_catches_up_with_a_
assert!(s.log_bytes() > 0, "recent batches are still kept");
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
let (_, out) = s.join(h).unwrap();
- assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
+ assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
deliver(&mut a, &out);
assert_eq!(a.view(), s.replica());
// Within the log, a short absence still gets the missed batch only.
@@ -195,7 +195,7 @@ fn after_a_snapshot_undo_leaves_what_others_changed_meanwhile() {
}
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
let (_, out) = s.join(h).unwrap();
- assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
+ assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
deliver(&mut a, &out);
// Undo: the page name goes back, the frame keeps b's later name.
let msgs = a.undo(&NoRecompute).unwrap();
@@ -326,7 +326,7 @@ fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() {
let (id, out) = restored.join(h).unwrap();
assert_eq!(id, b.id(), "a reconnecting client keeps its id");
assert!(
- matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
+ matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })),
"a clamped session hands out the snapshot, not a batch past the limits: {out:?}"
);
deliver(&mut b, &out);
@@ -394,3 +394,33 @@ fn resume_needs_the_issued_secret() {
let resend = come_back(&mut s, &mut host);
assert!(resend.is_empty());
}
+
+#[test]
+fn a_legacy_client_without_delta_snapshot_catches_up_with_a_legacy_snapshot() {
+ let mut s = Server::new(base(), "tok", Limits { max_log_batches: 2, ..Limits::default() });
+ let legacy_hello = || Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..hello() };
+ let (_, out) = s.join(legacy_hello()).unwrap();
+ assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
+ let Outgoing::To(_, w) = out.into_iter().next().unwrap() else { panic!() };
+ let mut a = Client::join(w).unwrap();
+ let mut b = join(&mut s);
+ let page = s.document().first_page().unwrap();
+
+ // Disconnect legacy client `a` and overflow the 2-batch server log so `a` must catch up via
+ // legacy `CatchUp::Snapshot` (never `DeltaSnapshot`).
+ a.disconnect();
+ s.leave(a.id());
+ for i in 0..4 {
+ let m = edit(&mut b, |d| d.node_mut(page).unwrap().name = format!("Legacy {i}")).unwrap();
+ let out = s.receive(b.id(), m);
+ deliver(&mut b, &out);
+ }
+ let ClientMsg::Hello(h) = a.reconnect(legacy_hello()) else { panic!() };
+ let (_, out) = s.join(h).unwrap();
+ assert!(
+ matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
+ "legacy client without delta-snapshot must receive CatchUp::Snapshot on rejoin"
+ );
+ deliver(&mut a, &out);
+ assert_eq!(a.view(), s.replica());
+}
diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs
index 99f0d6d6d..0f2a648c8 100644
--- a/crates/collab/src/server.rs
+++ b/crates/collab/src/server.rs
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use crate::change::{Change, Entry, Family, Prop, Target};
use crate::message::{
Accepted, Access, BranchEvent, BranchReq, BranchStatus, CatchUp, ClientMsg, Hello, MAX_SHARED_BRANCHES, PROTOCOL, Peer, Presence, Processed,
- Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_design_review, reads_signals,
+ Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_delta_snapshot, reads_design_review, reads_signals,
};
use crate::replica::{Mode, Replica, create_change};
use crate::{Error, Limits, diff, docprops, same_secret};
@@ -126,6 +126,9 @@ pub struct Server {
/// resuming client other bytes under a key it holds): every resuming client catches up with
/// the snapshot, not the log.
resync: bool,
+ /// Cached compressed [`CatchUp::DeltaSnapshot`] for `self.seq`, so repeated joins of large
+ /// files pay ~0 ms server CPU while no edit has arrived (#1819).
+ delta_cache: Option<(u64, Vec)>,
}
/// The most client ids a session remembers for reconnecting (the oldest disconnected ones go
@@ -188,6 +191,7 @@ impl Server {
design_review: BTreeSet::new(),
spotlight: None,
resync: false,
+ delta_cache: None,
}
}
@@ -417,10 +421,21 @@ impl Server {
// The log holds every batch after `floor`.
let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1));
let reads_design_review = reads_design_review(&hello.client_version);
+ let reads_delta = reads_delta_snapshot(&hello.client_version);
let catch_up = match resume {
Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => {
CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect())
}
+ // Only send the cached delta snapshot to peers that also read `design-review`, since
+ // the compressed payload carries the document's review config without per-peer filtering,
+ // and only when the document fits within the client decoder's default node cap.
+ // If delta encoding fails (e.g. materialized budget exceeded), fall back to `Snapshot`.
+ _ if reads_delta && reads_design_review && self.state.document().node_count() <= Limits::default().max_nodes => {
+ match self.cached_delta_snapshot() {
+ Ok(bytes) => CatchUp::DeltaSnapshot(bytes),
+ Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
+ }
+ }
_ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
};
// A peer that doesn't read the review settings can't decode them: its catch-up carries
@@ -686,9 +701,27 @@ impl Server {
}
self.state = next;
self.seq += 1;
+ self.delta_cache = None;
Ok(())
}
+ /// Return the cached compressed delta snapshot for `self.seq`, building it once on cache miss.
+ /// Snapshots larger than 16 MiB compressed (e.g. files with large embedded images) are still
+ /// sent, but are not pinned in `self.delta_cache` so room memory stays bounded.
+ fn cached_delta_snapshot(&mut self) -> Result, Error> {
+ const MAX_DELTA_CACHE_BYTES: usize = 16 << 20;
+ if let Some((seq, bytes)) = &self.delta_cache
+ && *seq == self.seq
+ {
+ return Ok(bytes.clone());
+ }
+ let bytes = crate::delta_snapshot::encode_delta_snapshot(&self.state)?;
+ if bytes.len() <= MAX_DELTA_CACHE_BYTES {
+ self.delta_cache = Some((self.seq, bytes.clone()));
+ }
+ Ok(bytes)
+ }
+
/// The document-level entries (styles, variables, collections, comments) a batch adds or
/// removes, each with whether it is there afterwards. A new one is refused when its id lies in
/// the space of another client this session gave an id to, or in a space at or above
diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs
index 8979cb213..758c075b3 100644
--- a/crates/collab/src/server_tests.rs
+++ b/crates/collab/src/server_tests.rs
@@ -417,15 +417,15 @@ fn a_review_edit_reaches_only_the_peers_that_read_it() {
let for_new = for_client(&out, capable.id());
assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}");
- // A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings.
+ // A capable newcomer's catch-up (a fresh join, so a delta snapshot) carries the settings.
let (_, out) = s.join(hello("tok")).unwrap();
- let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) =
+ let Some(Outgoing::To(_, welcome @ ServerMsg::Welcome { .. })) =
out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. })))
else {
panic!("no welcome");
};
- let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") };
- assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}");
+ let joined = Client::join(welcome).unwrap();
+ assert!(!joined.document().design_review.is_default(), "capable newcomer carries design review settings");
// An old newcomer's catch-up carries none, and still has the rename.
let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
diff --git a/crates/collab/src/sim.rs b/crates/collab/src/sim.rs
index d6129b10a..d539ace27 100644
--- a/crates/collab/src/sim.rs
+++ b/crates/collab/src/sim.rs
@@ -291,7 +291,9 @@ impl Sim {
let ClientMsg::Hello(hello) = hello else { return Err(Error::Protocol("hello".into())) };
let seen = self.clients.get(i).map_or(0, Client::seq);
let (id, out) = self.server.join(hello).map_err(|m| Error::Protocol(format!("{m:?}")))?;
- if out.iter().any(|o| matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_), .. }) if *to == id)) {
+ if out.iter().any(|o| {
+ matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_) | crate::CatchUp::DeltaSnapshot(_), .. }) if *to == id)
+ }) {
self.snapshots += 1;
if let Some(g) = self.gaps.get_mut(i) {
g.push((seen, self.server.seq()));
diff --git a/crates/doc/src/boolean_hit_tests.rs b/crates/doc/src/boolean_hit_tests.rs
index 5a8a01128..158eed55d 100644
--- a/crates/doc/src/boolean_hit_tests.rs
+++ b/crates/doc/src/boolean_hit_tests.rs
@@ -57,7 +57,7 @@ fn ordinary_hit_uses_region_paints_without_layer_fill() {
Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(Vec::new()), ..Default::default() },
],
};
- let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
+ let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
d.get_mut(id).unwrap().fills.clear();
assert!(d.node(id).unwrap().fills.is_empty());
assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), Some(id));
@@ -71,7 +71,7 @@ fn inherited_paint_frames_use_per_region_hit_testing() {
let mut network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true);
network.regions[0].winding = WindingRule::EvenOdd;
network.regions.push(network.regions[0].clone());
- let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
+ let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), None, "legacy even-odd loops cancel");
let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind else { panic!("expected vector") };
network.regions[0].paint_space = Some(crate::RegionPaintSpace { width: 10.0, height: 10.0, transform: figcraft_geom::Affine::IDENTITY });
@@ -87,7 +87,7 @@ fn explicitly_unfilled_regions_keep_the_stroke_only_selection_band() {
let mut network =
VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)], true);
network.regions[0].fills = Some(Vec::new());
- let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
+ let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
let n = d.get_mut(id).unwrap();
n.fills.clear();
n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)];
diff --git a/crates/doc/src/colors_tests.rs b/crates/doc/src/colors_tests.rs
index ebf659594..84bb21659 100644
--- a/crates/doc/src/colors_tests.rs
+++ b/crates/doc/src/colors_tests.rs
@@ -13,7 +13,7 @@ fn colourful() -> (Document, NodeId) {
let mut d = Document::new("c");
let p = d.first_page().unwrap();
let r = d.create(p, NodeKind::Rectangle, "R", 0.0, 0.0, 10.0, 10.0).unwrap();
- let t = d.create(p, NodeKind::Text(TextData::default()), "T", 0.0, 0.0, 10.0, 10.0).unwrap();
+ let t = d.create(p, NodeKind::Text(TextData::default().into()), "T", 0.0, 0.0, 10.0, 10.0).unwrap();
{
let n = d.node_mut(r).unwrap();
n.fills = vec![Paint::solid(RED)];
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index c83c7eb85..ea546fffa 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -23,6 +23,7 @@ pub mod library;
pub mod node;
pub mod props;
pub mod proto;
+pub mod shared;
pub mod styles;
pub mod text;
pub mod vector;
@@ -43,6 +44,7 @@ pub use handoff::*;
pub use library::*;
pub use node::*;
pub use props::*;
+pub use shared::Shared;
pub use styles::*;
pub use text::*;
pub use vector::*;
@@ -978,7 +980,14 @@ impl Document {
pt.source = m.0;
}
}
- if let NodeKind::Vector { network } = &mut c.kind {
+ if let NodeKind::Vector { network } = &mut c.kind
+ && network
+ .regions
+ .iter()
+ .filter_map(|r| r.fills.as_deref())
+ .flatten()
+ .any(|p| matches!(&p.kind, figcraft_color::PaintKind::Pattern(pt) if map.contains_key(&NodeId(pt.source))))
+ {
for p in network.regions.iter_mut().filter_map(|r| r.fills.as_mut()).flatten() {
if let figcraft_color::PaintKind::Pattern(pt) = &mut p.kind
&& let Some(m) = map.get(&NodeId(pt.source))
@@ -1379,6 +1388,8 @@ mod proto_expr_tests;
#[cfg(test)]
mod proto_overlay_anchor_tests;
#[cfg(test)]
+mod shared_tests;
+#[cfg(test)]
mod tests;
#[cfg(test)]
mod vector_radius_tests;
diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs
index fad9d1a90..0514ffa5c 100644
--- a/crates/doc/src/node.rs
+++ b/crates/doc/src/node.rs
@@ -6,6 +6,7 @@ use crate::props::{
StrokeProps,
};
use crate::proto::{Interaction, Overflow, ScrollPosition};
+use crate::shared::Shared;
use crate::styles::{CollectionId, ModeId, StyleRefs, VariableId};
use crate::text::TextData;
use crate::vector::VectorNetwork;
@@ -78,9 +79,6 @@ pub fn ordered_props<'a>(props: &'a BTreeMap, order: &[String])
}
/// What a node is, with per-type data.
-// Text sets the size; the lint counts the gap to the next largest variant, which grew only because
-// Page's guides moved to the node (#1476).
-#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum NodeKind {
@@ -120,9 +118,9 @@ pub enum NodeKind {
},
Line,
Vector {
- network: VectorNetwork,
+ network: Shared,
},
- Text(TextData),
+ Text(Shared),
BooleanOp {
op: BoolOp,
},
diff --git a/crates/doc/src/shared.rs b/crates/doc/src/shared.rs
new file mode 100644
index 000000000..fc5ab039a
--- /dev/null
+++ b/crates/doc/src/shared.rs
@@ -0,0 +1,105 @@
+//! Copy-on-write `Arc` wrapper for shared layer payloads (`TextData`, `VectorNetwork`).
+//!
+//! Cloning a [`Shared`] payload is an O(1) atomic reference-count bump, so mirrored layers inside
+//! component instances and duplicated subtrees share identical vector networks and text data in
+//! memory. Mutating through [`DerefMut`] detaches via [`Arc::make_mut`], leaving every other
+//! holder unchanged. Serialization and deserialization are transparent.
+
+use std::ops::{Deref, DerefMut};
+use std::sync::Arc;
+
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+/// Copy-on-write reference-counted wrapper around `T`.
+#[derive(Debug, Default)]
+pub struct Shared(Arc);
+
+impl Shared {
+ /// Wrap `value` in a new shared allocation.
+ pub fn new(value: T) -> Self {
+ Self(Arc::new(value))
+ }
+
+ /// Wrap an existing [`Arc`].
+ pub fn from_arc(arc: Arc) -> Self {
+ Self(arc)
+ }
+
+ /// Borrow the underlying [`Arc`].
+ pub fn as_arc(&self) -> &Arc {
+ &self.0
+ }
+
+ /// Unwrap the underlying [`Arc`].
+ pub fn into_arc(self) -> Arc {
+ self.0
+ }
+
+ /// Whether `self` and `other` point to the exact same allocation.
+ pub fn ptr_eq(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.0, &other.0)
+ }
+
+ /// Current strong reference count of the underlying allocation.
+ pub fn strong_count(&self) -> usize {
+ Arc::strong_count(&self.0)
+ }
+}
+
+impl Clone for Shared {
+ fn clone(&self) -> Self {
+ Self(Arc::clone(&self.0))
+ }
+}
+
+impl Deref for Shared {
+ type Target = T;
+
+ fn deref(&self) -> &T {
+ &self.0
+ }
+}
+
+impl DerefMut for Shared {
+ fn deref_mut(&mut self) -> &mut T {
+ Arc::make_mut(&mut self.0)
+ }
+}
+
+impl PartialEq for Shared {
+ fn eq(&self, other: &Self) -> bool {
+ *self.0 == *other.0
+ }
+}
+
+impl Eq for Shared {}
+
+impl From for Shared {
+ fn from(value: T) -> Self {
+ Self::new(value)
+ }
+}
+
+impl From> for Shared {
+ fn from(arc: Arc) -> Self {
+ Self(arc)
+ }
+}
+
+impl AsRef for Shared {
+ fn as_ref(&self) -> &T {
+ &self.0
+ }
+}
+
+impl Serialize for Shared {
+ fn serialize(&self, serializer: S) -> Result {
+ self.0.serialize(serializer)
+ }
+}
+
+impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared {
+ fn deserialize>(deserializer: D) -> Result {
+ T::deserialize(deserializer).map(Self::new)
+ }
+}
diff --git a/crates/doc/src/shared_tests.rs b/crates/doc/src/shared_tests.rs
new file mode 100644
index 000000000..b2b8d7f34
--- /dev/null
+++ b/crates/doc/src/shared_tests.rs
@@ -0,0 +1,195 @@
+//! Copy-on-write structural sharing tests for [`Shared`] and `NodeKind` payloads.
+
+use figcraft_geom::Point;
+
+use crate::*;
+
+#[test]
+fn node_kind_stays_compact_with_shared_text_and_vector_payloads() {
+ use std::mem::size_of;
+ // Before wrapping TextData (352 B) and VectorNetwork (72 B) in Shared, NodeKind was 352 B
+ // and Node was 1608 B.
+ assert!(size_of::() <= 144, "NodeKind grew unexpectedly: {} bytes", size_of::());
+ assert!(size_of::() <= 1400, "Node grew unexpectedly: {} bytes", size_of::());
+}
+
+#[test]
+fn shared_clone_shares_pointer_and_deref_mut_detaches_without_mutating_source() {
+ let mut net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true);
+ let a = Shared::new(net.clone());
+ let mut b = a.clone();
+ assert!(a.ptr_eq(&b));
+ assert_eq!(a.strong_count(), 2);
+
+ // Mutating through DerefMut detaches b and leaves a untouched.
+ b.vertices[0].x = 42.0;
+ assert!(!a.ptr_eq(&b));
+ assert_eq!(a.strong_count(), 1);
+ assert_eq!(b.strong_count(), 1);
+ assert_eq!(a.vertices[0].x, 0.0);
+ assert_eq!(b.vertices[0].x, 42.0);
+
+ // Non-mutating reads never detach.
+ net.vertices[0].x = 42.0;
+ assert_eq!(*b, net);
+ let c = b.clone();
+ let _len = c.vertices.len();
+ assert!(b.ptr_eq(&c));
+}
+
+#[test]
+fn duplicated_text_and_vector_layers_share_payloads_until_edited() {
+ let mut doc = Document::new("CoW");
+ let page = doc.first_page().unwrap();
+ let group = doc.create(page, NodeKind::Frame, "Card", 0.0, 0.0, 200.0, 100.0).unwrap();
+ let net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(24.0, 0.0), Point::new(12.0, 24.0)], true);
+ let vec_id = doc.create(group, NodeKind::Vector { network: net.into() }, "Icon", 0.0, 0.0, 24.0, 24.0).unwrap();
+ let txt_id = doc.create(group, NodeKind::Text(TextData::new("Hello").into()), "Title", 32.0, 0.0, 100.0, 20.0).unwrap();
+
+ let copy = doc.duplicate_into(group, page, None).unwrap();
+ let copy_children = doc.node(copy).unwrap().children.clone();
+ let (copy_vec, copy_txt) = (copy_children[0], copy_children[1]);
+
+ // Both vector and text payloads share the exact same Arc right after duplication.
+ match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) {
+ (NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)),
+ _ => panic!("expected vector nodes"),
+ }
+ match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) {
+ (NodeKind::Text(a), NodeKind::Text(b)) => assert!(a.ptr_eq(b)),
+ _ => panic!("expected text nodes"),
+ }
+
+ // Editing the copy's text detaches only the copy's TextData; the vector stays shared.
+ if let Some(NodeKind::Text(t)) = doc.node_mut(copy_txt).map(|n| &mut n.kind) {
+ t.characters = "Edited".into();
+ }
+ match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) {
+ (NodeKind::Text(a), NodeKind::Text(b)) => {
+ assert!(!a.ptr_eq(b));
+ assert_eq!(a.characters, "Hello");
+ assert_eq!(b.characters, "Edited");
+ }
+ _ => panic!("expected text nodes"),
+ }
+ match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) {
+ (NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)),
+ _ => panic!("expected vector nodes"),
+ }
+}
+
+#[test]
+fn shared_serialization_is_transparent_in_json() {
+ let td = TextData::new("Transparent");
+ let raw = serde_json::to_string(&td).unwrap();
+ let wrapped = serde_json::to_string(&Shared::new(td.clone())).unwrap();
+ assert_eq!(raw, wrapped);
+ let back: Shared = serde_json::from_str(&wrapped).unwrap();
+ assert_eq!(*back, td);
+}
+
+#[test]
+#[ignore = "benchmark: run with cargo test --release -p figcraft-doc bench_cow_sharing -- --ignored --nocapture"]
+fn bench_cow_sharing() {
+ use std::collections::HashSet;
+ use std::mem::size_of;
+ use std::time::Instant;
+
+ let pts: Vec = (0..64)
+ .map(|i| {
+ let a = (i as f64) * std::f64::consts::TAU / 64.0;
+ let r = if i % 2 == 0 { 16.0 } else { 8.0 };
+ Point::new(a.cos() * r, a.sin() * r)
+ })
+ .collect();
+ let icon = VectorNetwork::from_points(&pts, true);
+
+ let mut doc = Document::new("BenchCoW");
+ let page = doc.first_page().unwrap();
+ let comp = doc
+ .create(
+ page,
+ NodeKind::Component { description: "Card".into(), props: Default::default(), prop_order: Vec::new() },
+ "Card",
+ 0.0,
+ 0.0,
+ 400.0,
+ 300.0,
+ )
+ .unwrap();
+ let mut kids = Vec::new();
+ for i in 0..40 {
+ let kind = match i % 4 {
+ 0 => NodeKind::Text(TextData::new(format!("Label {i}")).into()),
+ 1 => NodeKind::Vector { network: icon.clone().into() },
+ _ => NodeKind::Rectangle,
+ };
+ kids.push(doc.create(comp, kind, &format!("L{i}"), (i % 8) as f64 * 48.0, (i / 8) as f64 * 56.0, 40.0, 40.0).unwrap());
+ }
+
+ let t0 = Instant::now();
+ for k in 0..1024 {
+ let inst = doc
+ .create(
+ page,
+ NodeKind::Instance { component: comp, props: Default::default() },
+ "Card",
+ (k % 32) as f64 * 420.0,
+ (k / 32) as f64 * 320.0,
+ 400.0,
+ 300.0,
+ )
+ .unwrap();
+ doc.get_mut(inst).unwrap().source = Some(comp);
+ for &src_id in &kids {
+ let mut c = doc.node(src_id).unwrap().clone();
+ c.id = doc.alloc_id();
+ c.parent = None;
+ c.children.clear();
+ c.source = Some(src_id);
+ doc.insert(c, inst, None).unwrap();
+ }
+ }
+ let build_ms = t0.elapsed().as_secs_f64() * 1000.0;
+
+ let mut unique_vec_ptrs = HashSet::new();
+ let mut unique_txt_ptrs = HashSet::new();
+ let mut total_vecs = 0usize;
+ let mut total_txts = 0usize;
+ for n in doc.nodes() {
+ match &n.kind {
+ NodeKind::Vector { network } => {
+ total_vecs += 1;
+ unique_vec_ptrs.insert(std::sync::Arc::as_ptr(network.as_arc()) as usize);
+ }
+ NodeKind::Text(t) => {
+ total_txts += 1;
+ unique_txt_ptrs.insert(std::sync::Arc::as_ptr(t.as_arc()) as usize);
+ }
+ _ => {}
+ }
+ }
+
+ let vec_heap_one = icon.vertices.len() * size_of::()
+ + icon.segments.len() * size_of::()
+ + icon.regions.len() * size_of::()
+ + icon.regions.iter().map(|r| r.loops.iter().map(|l| l.len() * size_of::()).sum::()).sum::();
+ let vec_heap_naive = total_vecs * vec_heap_one;
+ let vec_heap_shared = unique_vec_ptrs.len() * vec_heap_one;
+
+ eprintln!(
+ "Node={} B (was 1608 B), NodeKind={} B (was 352 B)\n42k build: {:.1} ms, nodes={}\nVectors: {} total -> {} unique Arcs (heap {:.2} MB -> {:.3} MB, {:.1}x)\nTexts: {} total -> {} unique Arcs ({:.1}x)",
+ size_of::(),
+ size_of::(),
+ build_ms,
+ doc.node_count(),
+ total_vecs,
+ unique_vec_ptrs.len(),
+ vec_heap_naive as f64 / 1_048_576.0,
+ vec_heap_shared as f64 / 1_048_576.0,
+ vec_heap_naive as f64 / vec_heap_shared.max(1) as f64,
+ total_txts,
+ unique_txt_ptrs.len(),
+ total_txts as f64 / unique_txt_ptrs.len().max(1) as f64,
+ );
+}
diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs
index 9d922d6c8..7ff7e0524 100644
--- a/crates/doc/src/tests.rs
+++ b/crates/doc/src/tests.rs
@@ -137,7 +137,7 @@ fn region_paints_participate_in_colors_images_and_pattern_remapping() {
figcraft_color::Paint::image("region-image", figcraft_color::ImageScaleMode::Fill),
figcraft_color::Paint::pattern(source.0),
]);
- let vector = d.create(group, NodeKind::Vector { network }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap();
+ let vector = d.create(group, NodeKind::Vector { network: network.into() }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap();
assert!(used_images(&d).contains("region-image"));
let dup = d.duplicate_into(group, p, None).unwrap();
let copied_children = d.node(dup).unwrap().children.clone();
@@ -311,7 +311,7 @@ fn serde_roundtrip_and_repair() {
let p = page(&d);
let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 100.0, 100.0).unwrap();
d.get_mut(f).unwrap().layout = Some(AutoLayout::default());
- d.create(f, NodeKind::Text(TextData::new("Hi")), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap();
+ d.create(f, NodeKind::Text(TextData::new("Hi").into()), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap();
d.create(f, NodeKind::Star { count: 5, inner_ratio: 0.4 }, "S", 0.0, 0.0, 10.0, 10.0).unwrap();
let j = serde_json::to_string(&d).unwrap();
let back: Document = serde_json::from_str(&j).unwrap();
@@ -576,12 +576,12 @@ fn hit_test_even_odd_vector_hole_misses() {
};
let mut d = Document::new("x");
let p = page(&d);
- let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
+ let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
assert_eq!(d.hit_test(p, Point::new(20.0, 100.0), 0.0, None), Some(eo));
assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), None, "the hole is not filled");
let mut d = Document::new("x");
let p = page(&d);
- let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
+ let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), Some(nz));
}
@@ -832,7 +832,7 @@ fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() {
let smoothed = net.rounded_smoothed(1.0).unwrap();
let mut d = Document::new("x");
let p = page(&d);
- let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap();
+ let v = d.create(p, NodeKind::Vector { network: net.clone().into() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap();
let n = d.node_mut(v).unwrap();
n.corners.smoothing = 1.0;
n.strokes.clear();
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 11fb7f2fa..f587f4138 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -43,3 +43,5 @@ craft-font-catalog = { workspace = true }
zip = { workspace = true }
wat = { workspace = true }
image = { workspace = true }
+# Writes the DNG files the camera raw tests open.
+craft-raw = { workspace = true }
diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs
index 2e1f01b4e..e07fc3db7 100644
--- a/crates/engine/src/al_behaviour_tests.rs
+++ b/crates/engine/src/al_behaviour_tests.rs
@@ -458,6 +458,275 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() {
assert!(s.doc().unwrap().node(f).unwrap().layout.is_none());
}
+// ---- Add auto layout (Shift+A) defaults, measured in Figma's web app with synthetic rectangles ----
+
+fn rect_at(s: &mut Session, parent: Option, x: f64, y: f64, w: f64, h: f64) -> NodeId {
+ let mut p = json!({"x": x, "y": y, "width": w, "height": h});
+ if let (Some(parent), Some(o)) = (parent, p.as_object_mut()) {
+ o.insert("parent".into(), json!(parent));
+ }
+ id(s.execute("shape.rectangle", &p).unwrap())
+}
+
+fn add_layout(s: &mut Session, ids: &[NodeId]) -> NodeId {
+ let r = s.execute("layout.add", &json!({"ids": ids})).unwrap();
+ id_of(&r["ids"][0]).unwrap()
+}
+
+fn canvas(s: &Session, node: NodeId) -> (f64, f64) {
+ let c = s.doc().unwrap().world_transform(node).as_coeffs();
+ (c[4], c[5])
+}
+
+#[test]
+fn shift_a_on_two_rects_far_apart_spaces_them_between_at_a_fixed_width() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0);
+ let f = add_layout(&mut s, &[a, b]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.main_align, l.padding), (LayoutMode::Horizontal, MainAlign::SpaceBetween, [0.0; 4]));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
+ assert_eq!((n.width, n.height), (140.0, 40.0));
+ assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0));
+}
+
+#[test]
+fn shift_a_gap_auto_needs_a_gap_at_least_the_narrower_child() {
+ // (first size, second x, second width, second height, Auto?)
+ for (w, x2, w2, h2, auto) in [
+ (40.0, 72.0, 40.0, 40.0, false),
+ (40.0, 80.0, 40.0, 40.0, true),
+ (20.0, 52.0, 20.0, 20.0, true),
+ (100.0, 160.0, 100.0, 100.0, false),
+ (40.0, 100.0, 80.0, 60.0, true),
+ ] {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, w, w);
+ let b = rect_at(&mut s, None, x2, 0.0, w2, h2);
+ let f = add_layout(&mut s, &[a, b]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!(l.gap, x2 - w, "{w} {x2}");
+ if auto {
+ assert_eq!((l.main_align, n.child_layout.sizing_h, n.width), (MainAlign::SpaceBetween, Sizing::Fixed, x2 + w2), "{w} {x2}");
+ } else {
+ assert_eq!(l.main_align, MainAlign::Min, "{w} {x2}");
+ assert_eq!(n.child_layout.sizing_h, Sizing::Hug, "{w} {x2}");
+ }
+ }
+}
+
+#[test]
+fn shift_a_on_three_rects_in_a_row_uses_the_mean_gap_and_hugs() {
+ for (xs, gap, width) in [([0.0, 100.0, 200.0], 60.0, 240.0), ([0.0, 100.0, 180.0], 50.0, 220.0)] {
+ let mut s = Session::new();
+ let ids: Vec = xs.iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect();
+ let f = add_layout(&mut s, &ids);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!(l.gap, gap);
+ assert_eq!(l.main_align, MainAlign::Min);
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Hug, Sizing::Hug, width));
+ }
+}
+
+#[test]
+fn shift_a_on_stacked_rects_fixes_the_width_and_hugs_the_height() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0);
+ let f = add_layout(&mut s, &[a, b]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 60.0));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
+ assert_eq!((n.width, n.height), (80.0, 160.0));
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 0.0, 240.0, 40.0, 40.0);
+ let f = add_layout(&mut s, &[a, b]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 200.0));
+ assert_eq!(l.main_align, MainAlign::Min);
+ assert_eq!((n.child_layout.sizing_h, n.width), (Sizing::Fixed, 40.0));
+}
+
+#[test]
+fn shift_a_on_one_rect_pads_ten_and_keeps_it_in_place() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let f = add_layout(&mut s, &[a]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 10.0, [10.0; 4]));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
+ assert_eq!((n.width, n.height), (60.0, 60.0));
+ assert_eq!(canvas(&s, f), (-10.0, -10.0));
+ assert_eq!(canvas(&s, a), (0.0, 0.0));
+ assert_eq!(size(&s, a), (40.0, 40.0));
+}
+
+fn filled_frame(s: &mut Session) -> NodeId {
+ id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#ff0000"}})).unwrap())
+}
+
+#[test]
+fn shift_a_on_a_frame_mirrors_its_left_and_top_offsets() {
+ let mut s = Session::new();
+ let f = filled_frame(&mut s);
+ rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0);
+ rect_at(&mut s, Some(f), 120.0, 30.0, 40.0, 40.0);
+ let fills = s.doc().unwrap().node(f).unwrap().fills.len();
+ let clip = s.doc().unwrap().node(f).unwrap().clip;
+ add_layout(&mut s, &[f]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 60.0, [30.0, 20.0, 30.0, 20.0]));
+ assert_eq!(l.main_align, MainAlign::Min);
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
+ assert_eq!((n.width, n.height), (180.0, 100.0));
+ assert_eq!((n.fills.len(), n.clip), (fills, clip));
+}
+
+#[test]
+fn shift_a_on_a_frame_with_centred_content_spaces_it_between() {
+ let mut s = Session::new();
+ let f = filled_frame(&mut s);
+ rect_at(&mut s, Some(f), 49.0, 49.0, 40.0, 40.0);
+ rect_at(&mut s, Some(f), 211.0, 49.0, 40.0, 40.0);
+ add_layout(&mut s, &[f]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.main_align, l.padding), (MainAlign::SpaceBetween, [49.0; 4]));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
+ assert_eq!((n.width, n.height), (300.0, 138.0));
+}
+
+#[test]
+fn shift_a_on_a_frame_with_stacked_content_fixes_the_content_width() {
+ let mut s = Session::new();
+ let f = filled_frame(&mut s);
+ rect_at(&mut s, Some(f), 20.0, 20.0, 40.0, 40.0);
+ rect_at(&mut s, Some(f), 20.0, 100.0, 40.0, 40.0);
+ add_layout(&mut s, &[f]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Vertical, 40.0, [20.0; 4]));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
+ assert_eq!((n.width, n.height), (80.0, 160.0));
+}
+
+#[test]
+fn shift_a_on_a_group_follows_the_wrap_rule() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0);
+ let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
+ let f = add_layout(&mut s, &[g]);
+ assert_eq!(f, g);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!(l.main_align, MainAlign::SpaceBetween);
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
+ assert_eq!((n.width, n.height), (140.0, 40.0));
+ assert!(n.fills.is_empty() && !n.clip);
+ assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0));
+}
+
+#[test]
+fn shift_a_on_a_one_child_group_follows_the_group_rule_not_the_one_child_frame_exception() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let g = id(s.execute("object.group", &json!({"ids": [a]})).unwrap());
+ let r = s.execute("layout.add", &json!({"ids": [g], "direction": "vertical"})).unwrap();
+ assert_eq!(id_of(&r["ids"][0]), Some(g));
+ let n = s.doc().unwrap().node(g).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [0.0; 4]));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
+ assert!(n.fills.is_empty() && !n.clip);
+}
+
+fn add_layout_dir(s: &mut Session, ids: &[NodeId], direction: &str) -> NodeId {
+ let r = s.execute("layout.add", &json!({"ids": ids, "direction": direction})).unwrap();
+ id_of(&r["ids"][0]).unwrap()
+}
+
+#[test]
+fn shift_a_gap_auto_compares_the_narrower_width_not_the_mean() {
+ // Widths 40 and 100, gap 60: at least the narrower (40), below the mean (70).
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 100.0, 0.0, 100.0, 40.0);
+ let f = add_layout(&mut s, &[a, b]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.gap, l.main_align, n.child_layout.sizing_h, n.width), (60.0, MainAlign::SpaceBetween, Sizing::Fixed, 200.0));
+}
+
+#[test]
+fn shift_a_direction_vertical_on_a_horizontal_pair_stacks_with_a_fixed_width_and_no_space_between() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0);
+ let f = add_layout_dir(&mut s, &[a, b], "vertical");
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ // Measured along y the two overlap, so the gap clamps to 0.
+ assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Vertical, 0.0, MainAlign::Min));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Fixed, Sizing::Hug, 140.0));
+}
+
+#[test]
+fn shift_a_direction_horizontal_on_a_stacked_pair_hugs_the_width() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0);
+ let f = add_layout_dir(&mut s, &[a, b], "horizontal");
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Horizontal, 0.0, MainAlign::Min));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
+}
+
+#[test]
+fn shift_a_overlapping_children_clamp_the_gap_to_zero_and_fractions_round() {
+ let mut s = Session::new();
+ let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
+ let b = rect_at(&mut s, None, 30.0, 0.0, 40.0, 40.0);
+ let f = add_layout(&mut s, &[a, b]);
+ let l = s.doc().unwrap().node(f).unwrap().layout.clone().unwrap();
+ assert_eq!((l.gap, l.main_align), (0.0, MainAlign::Min));
+ // Gaps 5 and 6 average 5.5, which rounds to 6.
+ let mut s = Session::new();
+ let ids: Vec = [0.0, 45.0, 91.0].iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect();
+ let f = add_layout(&mut s, &ids);
+ assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().gap, 6.0);
+ // Fractional left and top offsets round to whole padding.
+ let mut s = Session::new();
+ let f = filled_frame(&mut s);
+ rect_at(&mut s, Some(f), 20.4, 30.6, 40.0, 40.0);
+ rect_at(&mut s, Some(f), 120.0, 30.6, 40.0, 40.0);
+ add_layout(&mut s, &[f]);
+ assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().padding, [31.0, 20.0, 31.0, 20.0]);
+}
+
+#[test]
+fn shift_a_on_a_frame_with_one_child_keeps_the_inferred_layout() {
+ let mut s = Session::new();
+ let f = filled_frame(&mut s);
+ rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0);
+ add_layout(&mut s, &[f]);
+ let n = s.doc().unwrap().node(f).unwrap();
+ let l = n.layout.clone().unwrap();
+ assert_eq!((l.mode, l.gap, l.padding, l.main_align), (LayoutMode::Horizontal, 10.0, [30.0, 240.0, 130.0, 20.0], MainAlign::Min));
+ assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
+ assert_eq!((n.width, n.height), (300.0, 200.0));
+}
+
#[test]
fn align_is_unavailable_for_a_child_in_an_auto_layout_flow() {
use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align};
diff --git a/crates/engine/src/al_drag_tests.rs b/crates/engine/src/al_drag_tests.rs
index 0c5119fc5..33793ea5f 100644
--- a/crates/engine/src/al_drag_tests.rs
+++ b/crates/engine/src/al_drag_tests.rs
@@ -76,7 +76,7 @@ fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) {
let kids: Vec =
(0..3).map(|_| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 60, "parent": f})).unwrap())).collect();
s.execute("layout.add", &json!({"ids": [f]})).unwrap();
- s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed"}})).unwrap();
+ s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed", "width": 300, "height": 300}})).unwrap();
s.execute("select.none", &json!({})).unwrap();
(f, [kids[0], kids[1], kids[2]])
}
diff --git a/crates/engine/src/al_nesting_tests.rs b/crates/engine/src/al_nesting_tests.rs
index f3ab62a06..cf7733927 100644
--- a/crates/engine/src/al_nesting_tests.rs
+++ b/crates/engine/src/al_nesting_tests.rs
@@ -170,6 +170,8 @@ fn the_dragged_frame_never_receives_itself_and_plain_frames_in_a_flow_are_items(
let list = frame(&mut s, None, 500.0, 0.0, 200.0, 400.0);
let cards: Vec = (0..3).map(|i| frame(&mut s, Some(list), 0.0, i as f64 * 70.0, 150.0, 60.0)).collect();
s.execute("layout.add", &json!({"ids": [list], "direction": "vertical"})).unwrap();
+ // The list now hugs its cards; padding gives it room around them to drop into.
+ s.execute("node.set", &json!({"id": list, "props": {"padding": 20, "sizingH": "hug"}})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let card0 = bounds(&s, cards[0]);
let grab = Point::new(bounds(&s, cards[2]).x0 + 3.0, bounds(&s, cards[2]).y0 + 3.0);
diff --git a/crates/engine/src/assets/playground.rs b/crates/engine/src/assets/playground.rs
index ddb969c25..d9186556e 100644
--- a/crates/engine/src/assets/playground.rs
+++ b/crates/engine/src/assets/playground.rs
@@ -52,7 +52,7 @@ pub fn specs() -> Vec {
vec![spec!(
"component.playground",
"Component playground",
- "{id? (an instance, a component or a component set; default the selection), properties? {name: value} (variant, boolean, text and instance-swap properties, as instance.setProperties takes them), language? css|html|react|leptos|vue|swiftui|compose|arkui|flutter (default react), path? (write the preview there as a PNG), scale? (the PNG's, default 2)} → {component, properties: [{name, type, options?, value}], language, code, width, height, path?} the component with those property values, tried on a copy: its code and its look. Nothing in the document changes",
+ "{id? (an instance, a component or a component set; default the selection), properties? {name: value} (variant, boolean, text and instance-swap properties, as instance.setProperties takes them), language? css|html|react|leptos|vue|swiftui|compose|arkui|flutter|uno (default react), path? (write the preview there as a PNG), scale? (the PNG's, default 2)} → {component, properties: [{name, type, options?, value}], language, code, width, height, path?} the component with those property values, tried on a copy: its code and its look. Nothing in the document changes",
false,
|s, p| {
let cmd = "component.playground";
@@ -63,7 +63,7 @@ pub fn specs() -> Vec {
Some(_) => return Err(bad(cmd, "properties: {name: value}")),
};
let lang = match string(p, "language") {
- Some(l) => CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|swiftui|compose|arkui|flutter"))?,
+ Some(l) => CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|swiftui|compose|arkui|flutter|uno"))?,
None => CodeLang::React,
};
let (copy, inst) = build(s.doc()?, target, &values)?;
diff --git a/crates/engine/src/auto_layout_move_tests.rs b/crates/engine/src/auto_layout_move_tests.rs
index 49256dc64..9cc02d92a 100644
--- a/crates/engine/src/auto_layout_move_tests.rs
+++ b/crates/engine/src/auto_layout_move_tests.rs
@@ -47,7 +47,7 @@ fn a_frame_moved_inside_auto_layout_still_moves_its_siblings() {
// A stack and a rectangle side by side in an outer auto layout frame: the outer layout still
// follows when the stack grows.
let (mut s, inner, [first, _]) = stack();
- let other = id_of(&s.execute("shape.rectangle", &json!({"x": 300, "y": 0, "width": 100, "height": 40})).unwrap()["id"]).unwrap();
+ let other = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 0, "width": 100, "height": 40})).unwrap()["id"]).unwrap();
s.execute("select.set", &json!({"ids": [inner.0, other.0]})).unwrap();
s.execute("layout.add", &json!({})).unwrap();
let outer = s.doc().unwrap().node(inner).and_then(|n| n.parent).unwrap();
diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs
index 5eba5a506..1d5bfebcd 100644
--- a/crates/engine/src/automation/file_access.rs
+++ b/crates/engine/src/automation/file_access.rs
@@ -40,6 +40,7 @@ pub enum Access {
pub struct Roots {
read: Vec,
write: Vec,
+ allowed_servers: Vec,
}
impl Roots {
@@ -55,7 +56,18 @@ impl Roots {
})
.collect::, String>>()
};
- Ok(Self { read: resolve("--automation-read-root", read)?, write: resolve("--automation-write-root", write)? })
+ Ok(Self { read: resolve("--automation-read-root", read)?, write: resolve("--automation-write-root", write)?, allowed_servers: Vec::new() })
+ }
+
+ /// Also allow headless collaboration joins to explicitly approved servers.
+ pub fn with_allowed_servers(mut self, servers: Vec) -> Self {
+ self.allowed_servers = servers;
+ self
+ }
+
+ /// Servers an automation session may join through its collaboration link.
+ pub fn allowed_servers(&self) -> &[String] {
+ &self.allowed_servers
}
/// The resolved path to use for `access` to `path`, or why it is refused.
@@ -91,7 +103,11 @@ impl Roots {
/// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`.
pub fn to_json(&self) -> serde_json::Value {
let list = |v: &[PathBuf]| v.iter().map(|p| shown(p)).collect::>();
- serde_json::json!({"read": list(&[self.read.as_slice(), self.write.as_slice()].concat()), "write": list(&self.write)})
+ serde_json::json!({
+ "read": list(&[self.read.as_slice(), self.write.as_slice()].concat()),
+ "write": list(&self.write),
+ "allowedServers": self.allowed_servers
+ })
}
}
diff --git a/crates/engine/src/board_code_tests.rs b/crates/engine/src/board_code_tests.rs
index 64f734f0b..666111e93 100644
--- a/crates/engine/src/board_code_tests.rs
+++ b/crates/engine/src/board_code_tests.rs
@@ -21,8 +21,8 @@ fn bx(s: &Session, id: NodeId) -> Rect {
fn td(s: &Session, block: NodeId) -> TextData {
let t = text_of(s.doc().unwrap(), block).unwrap();
- match node(s, t).kind {
- NodeKind::Text(td) => td,
+ match &node(s, t).kind {
+ NodeKind::Text(td) => (**td).clone(),
other => panic!("not text: {other:?}"),
}
}
@@ -392,8 +392,8 @@ fn key(s: &mut Session, key: &str, shift: bool) {
}
fn characters(s: &Session, t: NodeId) -> String {
- match node(s, t).kind {
- NodeKind::Text(td) => td.characters,
+ match &node(s, t).kind {
+ NodeKind::Text(td) => td.characters.clone(),
other => panic!("not text: {other:?}"),
}
}
diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs
index c83fddc22..0bb67a044 100644
--- a/crates/engine/src/board_mindmap_tests.rs
+++ b/crates/engine/src/board_mindmap_tests.rs
@@ -30,8 +30,8 @@ fn map(s: &mut Session) -> (NodeId, [NodeId; 3], [NodeId; 3]) {
fn text_data(s: &Session, n: NodeId) -> figcraft_doc::TextData {
let t = text_of(s.doc().unwrap(), n).unwrap();
- match node(s, t).kind {
- NodeKind::Text(td) => td,
+ match &node(s, t).kind {
+ NodeKind::Text(td) => (**td).clone(),
other => panic!("not text: {other:?}"),
}
}
diff --git a/crates/engine/src/boards/board/connectors.rs b/crates/engine/src/boards/board/connectors.rs
index 408de045a..7e285f679 100644
--- a/crates/engine/src/boards/board/connectors.rs
+++ b/crates/engine/src/boards/board/connectors.rs
@@ -85,7 +85,7 @@ pub(super) fn make(doc: &mut Document, page: NodeId, c: Connector, caps: (Stroke
if pts.windows(2).all(|w| w.first() == w.get(1)) {
return Err(bad(cmd, "the ends are in the same place"));
}
- let id = add(doc, page, NodeKind::Vector { network: VectorNetwork::default() }, "Connector", (0.0, 0.0), (0.0, 0.0), |n| {
+ let id = add(doc, page, NodeKind::Vector { network: VectorNetwork::default().into() }, "Connector", (0.0, 0.0), (0.0, 0.0), |n| {
n.fills.clear();
n.strokes = vec![Paint::solid(LINE)];
n.stroke.weight = LINE_WEIGHT;
diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs
index e62d41973..7b230cabc 100644
--- a/crates/engine/src/boards/board/derived.rs
+++ b/crates/engine/src/boards/board/derived.rs
@@ -263,13 +263,15 @@ pub(super) fn place_route(doc: &mut Document, id: NodeId, pts: &[Point], routing
_ => VectorNetwork::from_points(&rel.elements().iter().filter_map(PathEl::end_point).collect::>(), false),
};
let t = Affine::translate((b.x0, b.y0));
- let same =
- n.transform == t && n.width == b.width() && n.height == b.height() && matches!(&n.kind, NodeKind::Vector { network: old } if *old == network);
+ let same = n.transform == t
+ && n.width == b.width()
+ && n.height == b.height()
+ && matches!(&n.kind, NodeKind::Vector { network: old } if **old == network);
if same {
return;
}
if let Some(n) = doc.node_mut(id) {
- n.kind = NodeKind::Vector { network };
+ n.kind = NodeKind::Vector { network: network.into() };
n.transform = t;
(n.width, n.height) = (b.width(), b.height());
}
diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs
index 410699560..c6f8c33c4 100644
--- a/crates/engine/src/boards/board/edit.rs
+++ b/crates/engine/src/boards/board/edit.rs
@@ -178,7 +178,7 @@ fn reshape(doc: &mut Document, id: NodeId, new: BoardShape) -> Result<()> {
if let Some(o) = doc.get(id)?.children.first().copied()
&& let Some(on) = doc.node_mut(o)
{
- on.kind = NodeKind::Vector { network: VectorNetwork::from_path(&new.path(w, h)) };
+ on.kind = NodeKind::Vector { network: VectorNetwork::from_path(&new.path(w, h)).into() };
(on.width, on.height, on.transform) = (w, h, Affine::IDENTITY);
}
Ok(())
diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs
index 5cc660b84..6fa1bf0fb 100644
--- a/crates/engine/src/boards/board/items.rs
+++ b/crates/engine/src/boards/board/items.rs
@@ -44,7 +44,7 @@ pub(crate) fn add_text(doc: &mut Document, parent: NodeId, text: &str, size: f64
..TextData::default()
};
td.style.font_size = size;
- let id = add(doc, parent, NodeKind::Text(td), name, (0.0, 0.0), (width.max(1.0), size * 1.4), |n| {
+ let id = add(doc, parent, NodeKind::Text(td.into()), name, (0.0, 0.0), (width.max(1.0), size * 1.4), |n| {
n.fills = vec![Paint::solid(color)];
n.child_layout.sizing_h = Sizing::Fill;
})?;
@@ -297,7 +297,7 @@ fn make_shape(
});
n.board = Some(BoardItem::Shape { shape });
})?;
- add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&shape.path(w, h)) }, "Outline", (0.0, 0.0), size, |n| {
+ add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&shape.path(w, h)).into() }, "Outline", (0.0, 0.0), size, |n| {
n.fills = vec![Paint::solid(color)];
n.strokes = vec![Paint::solid(line_shade(color))];
n.stroke.weight = 1.5;
@@ -359,7 +359,7 @@ pub(super) fn stamp_cmd(s: &mut Session, p: &Value) -> Result {
})?;
for part in stamp.mark() {
let path = figcraft_geom::BezPath::from_svg(part.d).map_err(|e| EngineError::Other(format!("stamp mark: {e}")))?;
- add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&path) }, "Mark", (0.0, 0.0), (STAMP_SIZE, STAMP_SIZE), |n| {
+ add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&path).into() }, "Mark", (0.0, 0.0), (STAMP_SIZE, STAMP_SIZE), |n| {
if part.filled {
n.fills = vec![Paint::solid(Color::WHITE)];
} else {
diff --git a/crates/engine/src/boolean_cap_tests.rs b/crates/engine/src/boolean_cap_tests.rs
index b9d40e349..5f6e6b71b 100644
--- a/crates/engine/src/boolean_cap_tests.rs
+++ b/crates/engine/src/boolean_cap_tests.rs
@@ -27,7 +27,7 @@ fn flattening_a_boolean_past_the_caps_is_refused() {
.into_iter()
.map(|across| {
let network = VectorNetwork::from_path(&bars(750, across));
- s.doc_mut().unwrap().create(page, NodeKind::Vector { network }, "Bars", 0.0, 0.0, 3000.0, 3000.0).unwrap()
+ s.doc_mut().unwrap().create(page, NodeKind::Vector { network: network.into() }, "Bars", 0.0, 0.0, 3000.0, 3000.0).unwrap()
})
.collect();
let g = id_of(&s.execute("bool.union", &json!({"ids": ids})).unwrap()["id"]).unwrap();
diff --git a/crates/engine/src/canvas/shapebuilder.rs b/crates/engine/src/canvas/shapebuilder.rs
index fea91db25..bb2b8cbb2 100644
--- a/crates/engine/src/canvas/shapebuilder.rs
+++ b/crates/engine/src/canvas/shapebuilder.rs
@@ -323,12 +323,12 @@ fn reshape_vector_regions(doc: &mut Document, id: NodeId, areas: &[(usize, BezPa
}
let Some(bounds) = rebuilt.bounds() else {
let n = doc.get_mut(id)?;
- n.kind = NodeKind::Vector { network: rebuilt };
+ n.kind = NodeKind::Vector { network: rebuilt.into() };
return Ok(());
};
rebuilt.translate(-bounds.x0, -bounds.y0);
let n = doc.get_mut(id)?;
- n.kind = NodeKind::Vector { network: rebuilt };
+ n.kind = NodeKind::Vector { network: rebuilt.into() };
n.children.clear();
n.corners = Corners::default();
n.transform *= Affine::translate((bounds.x0, bounds.y0));
@@ -351,7 +351,7 @@ fn reshape(doc: &mut Document, id: NodeId, area: &BezPath) -> Result<()> {
}
}
let n = doc.get_mut(id)?;
- n.kind = NodeKind::Vector { network: net };
+ n.kind = NodeKind::Vector { network: net.into() };
n.children.clear();
n.corners = Corners::default();
crate::vectoredit::refit(doc, id)
@@ -388,7 +388,7 @@ fn create_merged(doc: &mut Document, style: Part, area: &BezPath) -> Result NodeId {
append(&mut network, box_path(50.0, 0.0, 100.0, 100.0));
network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("#ff0000").unwrap())]);
network.regions[1].fills = Some(vec![Paint::solid(Color::from_hex("#0000ff").unwrap())]);
- s.doc_mut().unwrap().get_mut(id).unwrap().kind = NodeKind::Vector { network };
+ s.doc_mut().unwrap().get_mut(id).unwrap().kind = NodeKind::Vector { network: network.into() };
id
}
@@ -104,7 +104,7 @@ fn legacy_unstyled_nested_evenodd_regions_keep_the_hole_unpainted() {
region.fills = None;
region.paint_space = None;
}
- s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net };
+ s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.into() };
let crossing = rect(&mut s, -5.0, 45.0, 15.0, 10.0, "#ffffff");
s.set_selection(vec![vector, crossing]);
let a = arrangement(&mut s, &[vector, crossing]).unwrap();
@@ -168,7 +168,7 @@ fn exceeding_arrangement_capacity_never_drops_unprocessed_regions() {
part.regions[0].fills = Some(vec![Paint::solid(Color::BLACK)]);
append(&mut net, part);
}
- s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.clone() };
+ s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.clone().into() };
s.set_selection(vec![vector]);
let error = s.execute("shapeBuilder.remove", &json!({"points": [[5, 5]]})).unwrap_err();
assert!(error.to_string().contains("too many fill regions"));
@@ -269,7 +269,7 @@ fn removal_preserves_holes_and_transformed_gradient_frames() {
{
let doc = s.doc_mut().unwrap();
let node = doc.get_mut(vector).unwrap();
- node.kind = NodeKind::Vector { network: outer };
+ node.kind = NodeKind::Vector { network: outer.into() };
node.transform = transform;
}
let before = normalized_paint_world(&s, vector, 0);
diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs
index 9508bfcb8..2c41c7d13 100644
--- a/crates/engine/src/canvas/textedit.rs
+++ b/crates/engine/src/canvas/textedit.rs
@@ -83,7 +83,7 @@ fn next_editing_session() -> u64 {
fn text_of(s: &Session, id: NodeId) -> Result {
match &s.doc()?.get(id)?.kind {
- NodeKind::Text(t) => Ok(t.clone()),
+ NodeKind::Text(t) => Ok((**t).clone()),
_ => Err(EngineError::Other(format!("{id} is not a text layer"))),
}
}
diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs
index 1e7a9f902..59100ce8d 100644
--- a/crates/engine/src/canvas/tools/click.rs
+++ b/crates/engine/src/canvas/tools/click.rs
@@ -231,7 +231,7 @@ impl Session {
let ds = self.ds_mut()?;
let d = ds.doc_mut();
let id = d.alloc_id();
- let mut n = Node::new(id, NodeKind::Text(TextData::default()), "Text", 1.0, 14.0);
+ let mut n = Node::new(id, NodeKind::Text(TextData::default().into()), "Text", 1.0, 14.0);
let pw = d.world_transform(parent);
let at = Point::new(ev.x.round(), (ev.y - 7.0).round());
n.transform = pw.inverse() * Affine::translate(at.to_vec2());
@@ -329,7 +329,7 @@ impl Session {
let ds = self.ds_mut()?;
let d = ds.doc_mut();
let id = d.alloc_id();
- let mut n = Node::new(id, NodeKind::Text(TextData::default()), "Text", pn.width, pn.height);
+ let mut n = Node::new(id, NodeKind::Text(TextData::default().into()), "Text", pn.width, pn.height);
n.name = String::new();
n.transform = pn.transform;
n.constraints = pn.constraints;
diff --git a/crates/engine/src/canvas/tools/pen.rs b/crates/engine/src/canvas/tools/pen.rs
index 097a2bf04..8df275a65 100644
--- a/crates/engine/src/canvas/tools/pen.rs
+++ b/crates/engine/src/canvas/tools/pen.rs
@@ -218,7 +218,7 @@ impl Session {
Some(id) if doc.contains(id) => id,
_ => {
let id = doc.alloc_id();
- let mut n = Node::new(id, NodeKind::Vector { network: VectorNetwork::default() }, "Vector", 0.0, 0.0);
+ let mut n = Node::new(id, NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector", 0.0, 0.0);
n.fills.clear();
n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)];
n.stroke.align = StrokeAlign::Center;
@@ -227,7 +227,7 @@ impl Session {
}
};
let n = doc.get_mut(id)?;
- n.kind = NodeKind::Vector { network: net };
+ n.kind = NodeKind::Vector { network: net.into() };
n.width = bb.width();
n.height = bb.height();
n.transform = Affine::translate((bb.x0, bb.y0));
diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs
index cf00a06de..99d58679a 100644
--- a/crates/engine/src/canvas/vectoredit.rs
+++ b/crates/engine/src/canvas/vectoredit.rs
@@ -341,7 +341,7 @@ pub fn ensure_vector(doc: &mut Document, id: NodeId) -> Result<()> {
}
}
let node = doc.get_mut(id)?;
- node.kind = NodeKind::Vector { network: net };
+ node.kind = NodeKind::Vector { network: net.into() };
node.children.clear();
if matches!(n.kind, NodeKind::Line) {
node.stroke.align = StrokeAlign::Center;
diff --git a/crates/engine/src/canvas/vectoredit/pointer.rs b/crates/engine/src/canvas/vectoredit/pointer.rs
index dadb1e3e8..2f32f5aef 100644
--- a/crates/engine/src/canvas/vectoredit/pointer.rs
+++ b/crates/engine/src/canvas/vectoredit/pointer.rs
@@ -1171,7 +1171,7 @@ impl Session {
// The preview starts again from the document before the drag: bring the moved layer.
self.preview(|doc, _| {
*doc.get_mut(id)? = moved;
- edit(doc, id, |net| *net = merged)
+ edit(doc, id, |net| *net = (*merged).clone())
})?;
set_state(self, |e| {
e.vertices = vec![if keep > v { keep - 1 } else { keep }];
diff --git a/crates/engine/src/canvas/vectoredit/regions_tests.rs b/crates/engine/src/canvas/vectoredit/regions_tests.rs
index a12fc0f84..fa57e02b5 100644
--- a/crates/engine/src/canvas/vectoredit/regions_tests.rs
+++ b/crates/engine/src/canvas/vectoredit/regions_tests.rs
@@ -51,7 +51,7 @@ fn editing_vector(s: &mut Session, n: VectorNetwork) -> NodeId {
let id = crate::params::id_of(&r["id"]).unwrap();
let doc = s.doc_mut().unwrap();
let node = doc.get_mut(id).unwrap();
- node.kind = figcraft_doc::NodeKind::Vector { network: n };
+ node.kind = figcraft_doc::NodeKind::Vector { network: n.into() };
node.transform = Affine::IDENTITY;
node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)];
super::refit(doc, id).unwrap();
diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs
index c5f02d122..636368ee7 100644
--- a/crates/engine/src/canvas/vectoredit/tests.rs
+++ b/crates/engine/src/canvas/vectoredit/tests.rs
@@ -188,7 +188,7 @@ fn a_handle_and_a_point_are_compared_on_the_page() {
let mut seg = figcraft_doc::Segment::line(0, 1);
seg.ta = (0.5, -0.9);
n.segments.push(seg);
- node.kind = figcraft_doc::NodeKind::Vector { network: n };
+ node.kind = figcraft_doc::NodeKind::Vector { network: n.into() };
node.transform = figcraft_geom::Affine::scale_non_uniform(10.0, 1.0);
}
ex(&mut s, "vector.edit.begin", json!({"id": id}));
@@ -215,7 +215,7 @@ fn a_handle_on_another_point_is_still_the_handles() {
let mut seg = figcraft_doc::Segment::line(0, 1);
seg.ta = (10.0, 0.0);
n.segments.push(seg);
- node.kind = figcraft_doc::NodeKind::Vector { network: n };
+ node.kind = figcraft_doc::NodeKind::Vector { network: n.into() };
node.transform = figcraft_geom::Affine::IDENTITY;
}
ex(&mut s, "vector.edit.begin", json!({"id": id}));
diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs
index 48fa80638..b96340c2f 100644
--- a/crates/engine/src/cmd/create.rs
+++ b/crates/engine/src/cmd/create.rs
@@ -173,8 +173,8 @@ pub fn kind_for(t: &str) -> Option<(NodeKind, &'static str)> {
"star" => (NodeKind::Star { count: 5, inner_ratio: 0.38 }, "Star"),
"line" => (NodeKind::Line, "Line"),
"arrow" => (NodeKind::Line, "Arrow"),
- "vector" | "path" => (NodeKind::Vector { network: VectorNetwork::default() }, "Vector"),
- "text" => (NodeKind::Text(TextData::default()), "Text"),
+ "vector" | "path" => (NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector"),
+ "text" => (NodeKind::Text(TextData::default().into()), "Text"),
"frame" => (NodeKind::Frame, "Frame"),
"section" => (NodeKind::Section { contents_hidden: false }, "Section"),
"component" => (NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Component"),
@@ -332,7 +332,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result {
if let NodeKind::Vector { network } = &mut kind {
if let Some(d) = string(p, "path") {
let shape = path_network(cmd, &d, asked.0, asked.1)?;
- *network = shape.network;
+ *network = (shape.network).into();
if boolean(p, "closed") == Some(false) {
network.regions.clear();
}
@@ -355,7 +355,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result {
}
let (sx, sy) = vector_scale(asked.0, asked.1, bb.width(), bb.height(), "a point set").map_err(|e| bad(cmd, e))?;
let local: Vec = pts.iter().map(|q| Point::new((q.x - bb.x0) * sx, (q.y - bb.y0) * sy)).collect();
- *network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false));
+ *network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false)).into();
w = bb.width() * sx;
h = bb.height() * sy;
offset = (bb.x0, bb.y0);
diff --git a/crates/engine/src/cmd/edit/vector_clipboard.rs b/crates/engine/src/cmd/edit/vector_clipboard.rs
index f52916ee8..107f60aaf 100644
--- a/crates/engine/src/cmd/edit/vector_clipboard.rs
+++ b/crates/engine/src/cmd/edit/vector_clipboard.rs
@@ -106,7 +106,7 @@ fn clip_node(doc: &Document, id: NodeId, mut sub: VectorNetwork) -> Option
n.transform = doc.world_transform(id) * Affine::translate((b.x0, b.y0));
n.width = b.width();
n.height = b.height();
- n.kind = NodeKind::Vector { network: sub };
+ n.kind = NodeKind::Vector { network: sub.into() };
n.parent = None;
n.children.clear();
n.name = "Vector".into();
@@ -181,7 +181,7 @@ pub fn clipboard_svg(s: &Session) -> Option {
/// frames, groups, instances, …). `doc` is the file the layer was copied from.
fn outline_network(doc: &Document, n: &Node) -> Option {
let net = match &n.kind {
- NodeKind::Vector { network } => network.clone(),
+ NodeKind::Vector { network } => (**network).clone(),
k if k.is_shape() || matches!(k, NodeKind::BooleanOp { .. }) => {
let (path, rule) = figcraft_render::node_outline(doc, n)?;
let mut net = VectorNetwork::from_path(&path);
diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs
index d204931ac..d3242a340 100644
--- a/crates/engine/src/cmd/file/load.rs
+++ b/crates/engine/src/cmd/file/load.rs
@@ -124,7 +124,7 @@ fn load_any(
font_notes.append(&mut notes); // Show missing-font details first in the UI toast.
Ok((figcraft_format::Loaded { issues: font_notes, ..doc.into() }, true))
}
- "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" => {
+ e if matches!(e, "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff") || figcraft_format::raw::is_extension(e) => {
let mut doc = Document::new(file_stem(name_hint));
let page = doc.first_page().ok_or(EngineError::NoDocument)?;
let (hash, w, h) = crate::cmd::create::add_readable_image(&mut doc, bytes.to_vec()).map_err(EngineError::Other)?;
@@ -787,7 +787,7 @@ mod penpot_font_warning_tests {
let mut doc = Document::new("External font refs");
let page = doc.first_page().unwrap();
let text = TextData::new("Playball");
- let id = doc.create(page, NodeKind::Text(text), "Custom caption", 0., 0., 120., 30.).unwrap();
+ let id = doc.create(page, NodeKind::Text(text.into()), "Custom caption", 0., 0., 120., 30.).unwrap();
doc.node_mut(id).unwrap().plugin_data.insert(
"penpot.customFontRefs".into(),
r#"[{"id":"custom-123abc","family":"Playball","variants":[{"weight":400,"italic":false}]}]"#.into(),
@@ -805,7 +805,7 @@ mod penpot_font_warning_tests {
let page = doc.first_page().unwrap();
let mut text = TextData::new("hello world");
text.style.font_family = "Rare Licensed Family".into();
- doc.create(page, NodeKind::Text(text), "Headline", 0.0, 0.0, 200.0, 30.0).unwrap();
+ doc.create(page, NodeKind::Text(text.into()), "Headline", 0.0, 0.0, 200.0, 30.0).unwrap();
let warnings = missing_penpot_font_warnings(&doc, &["Inter".into(), "Source Sans Pro".into()]);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("Rare Licensed Family"));
@@ -830,7 +830,7 @@ mod penpot_font_warning_tests {
let mut run = t.style.clone();
run.font_family = "Available Font".into();
t.runs.push(StyleRun { start: 0, end: 2, style: run });
- doc.create(page, NodeKind::Text(t), "Full run", 0.0, 0.0, 100.0, 30.0).unwrap();
+ doc.create(page, NodeKind::Text(t.into()), "Full run", 0.0, 0.0, 100.0, 30.0).unwrap();
assert!(missing_penpot_font_warnings(&doc, &["Available Font".into()]).is_empty());
}
}
@@ -875,7 +875,7 @@ mod penpot_svg_v10_tests {
let mut run = t.style.clone();
run.font_family = "Run Font".into();
t.runs = (0..50_000).map(|_| StyleRun { start: 0, end: 100_000, style: run.clone() }).collect();
- doc.create(page, NodeKind::Text(t), "Long", 0.0, 0.0, 100.0, 30.0).unwrap();
+ doc.create(page, NodeKind::Text(t.into()), "Long", 0.0, 0.0, 100.0, 30.0).unwrap();
let report = font_report_with_families(&doc, &[]);
assert_eq!(report["fonts"].as_array().map(Vec::len), Some(1), "{report}");
assert_eq!(report["fonts"][0]["family"], "Run Font");
@@ -921,7 +921,7 @@ mod penpot_svg_v10_tests {
let page = doc.first_page().unwrap();
let mut text = TextData::new("Example");
text.style.font_family = "Definitely Never Installed V10 Font Q7".into();
- doc.create(page, NodeKind::Text(text), "Caption", 0.0, 0.0, 100.0, 24.0).unwrap();
+ doc.create(page, NodeKind::Text(text.into()), "Caption", 0.0, 0.0, 100.0, 24.0).unwrap();
let report = font_report_with_families(&doc, &["Inter".into()]);
assert_eq!(report["missing"], 1);
assert_eq!(report["fonts"][0]["family"], "Definitely Never Installed V10 Font Q7");
diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs
index 79310056d..10291c20a 100644
--- a/crates/engine/src/cmd/props.rs
+++ b/crates/engine/src/cmd/props.rs
@@ -1271,7 +1271,7 @@ fn set_path(cmd: &str, doc: &mut Document, id: NodeId, v: &Value, props: &Map Result {
net.translate(-bb.x0, -bb.y0);
let vid = doc.alloc_id();
let name = first.as_ref().map(|f| f.name.clone()).unwrap_or_else(|| "Vector".into());
- let mut v = Node::new(vid, NodeKind::Vector { network: net }, name, bb.width(), bb.height());
+ let mut v = Node::new(vid, NodeKind::Vector { network: net.into() }, name, bb.width(), bb.height());
v.transform = Affine::translate((bb.x0, bb.y0));
if let Some(f) = first {
v.fills = output_fills;
@@ -620,7 +620,7 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result {
let parent = n.parent.ok_or_else(|| bad("vector.outlineStroke", "page"))?;
let idx = doc.index_in_parent(i);
let vid = doc.alloc_id();
- let mut v = Node::new(vid, NodeKind::Vector { network: net }, n.name.clone(), bb.width(), bb.height());
+ let mut v = Node::new(vid, NodeKind::Vector { network: net.into() }, n.name.clone(), bb.width(), bb.height());
v.transform = n.transform * Affine::translate((bb.x0, bb.y0));
// The stroke's paints (and its colour style) fill the outline.
v.fills = n.strokes.clone();
@@ -698,6 +698,78 @@ fn sort_layout_children(doc: &Document, kids: &mut [NodeId], vertical: bool) {
}
}
+/// What "Add auto layout" settled on for one frame, beyond the layout itself.
+struct AddPlan {
+ layout: AutoLayout,
+ /// Width stays fixed (Figma fixes it in a vertical flow and with an Auto gap); otherwise it hugs.
+ fixed_width: bool,
+ /// A converted frame in a vertical flow shrinks to its content plus padding.
+ set_width: Option,
+ /// A wrap of one layer: the frame grows by this much around the layer and stays put on the canvas.
+ grow: f64,
+}
+
+/// The layout "Add auto layout" gives a frame (measured in Figma's web app with synthetic
+/// rectangles, 2026-11-09): height hugs; the width is fixed in a vertical flow and with an Auto
+/// gap (main align Space between: two children, a gap at least the narrower child, and for a
+/// converted frame equal left and right offsets), and hugs otherwise; a converted frame takes its
+/// left and top offsets as padding, a wrap of several layers has none, a wrap of one layer pads 10.
+fn add_layout(doc: &Document, frame: NodeId, new_wrap: bool, group: bool, dir: Option<&str>) -> AddPlan {
+ let wrapped = new_wrap || group;
+ let flow = figcraft_layout::flow_children(doc, frame);
+ let mut al = infer_layout(doc, frame);
+ let mut plan = AddPlan { layout: AutoLayout::default(), fixed_width: false, set_width: None, grow: 0.0 };
+ if let Some(d) = dir {
+ al.mode = match d.to_ascii_lowercase().as_str() {
+ "vertical" | "column" => LayoutMode::Vertical,
+ "grid" => LayoutMode::Grid,
+ _ => LayoutMode::Horizontal,
+ };
+ }
+ let Some(f) = doc.node(frame) else {
+ plan.layout = al;
+ return plan;
+ };
+ if flow.is_empty() || (!wrapped && flow.len() == 1) {
+ plan.layout = al;
+ return plan;
+ }
+ if new_wrap && flow.len() == 1 {
+ al.padding = [10.0; 4];
+ al.gap = 10.0;
+ plan.grow = 10.0;
+ plan.layout = al;
+ return plan;
+ }
+ let mut boxes: Vec =
+ flow.iter().filter_map(|c| doc.node(*c)).map(|c| figcraft_geom::transform_rect_bbox(c.transform, c.local_rect())).collect();
+ let vertical = al.mode == LayoutMode::Vertical;
+ boxes.sort_by(|a, b| if vertical { a.y0.total_cmp(&b.y0) } else { a.x0.total_cmp(&b.x0) });
+ let gaps: Vec =
+ boxes.windows(2).filter_map(|w| Some(if vertical { w.get(1)?.y0 - w.first()?.y1 } else { w.get(1)?.x0 - w.first()?.x1 })).collect();
+ al.gap = if gaps.is_empty() { 10.0 } else { (gaps.iter().sum::() / gaps.len() as f64).max(0.0).round() };
+ let all = boxes.iter().copied().reduce(|a, b| a.union(b)).unwrap_or_default();
+ let (left, top) = (all.x0.max(0.0).round(), all.y0.max(0.0).round());
+ al.padding = if wrapped { [0.0; 4] } else { [top, left, top, left] };
+ let content_w = all.x1 - all.x0;
+ if vertical {
+ plan.fixed_width = true;
+ if !wrapped {
+ plan.set_width = Some(content_w + 2.0 * left);
+ }
+ } else if al.mode == LayoutMode::Horizontal && boxes.len() == 2 {
+ let narrower = boxes.iter().map(Rect::width).fold(f64::MAX, f64::min);
+ let gap = gaps.first().copied().unwrap_or(0.0);
+ let centred = wrapped || ((all.x0) - (f.width - all.x1)).abs() <= 0.5;
+ if gap > 0.0 && gap >= narrower && centred {
+ al.main_align = MainAlign::SpaceBetween;
+ plan.fixed_width = true;
+ }
+ }
+ plan.layout = al;
+ plan
+}
+
/// Add inferred auto layout to existing frames or one group converted in place; wrap other
/// selections. Preserve mask boundaries and a converted group's Fill sizing in its parent.
fn layout_add(s: &mut Session, p: &Value) -> Result {
@@ -725,29 +797,33 @@ fn layout_add(s: &mut Session, p: &Value) -> Result {
};
let doc = s.doc_mut()?;
for f in &targets {
- let mut al = infer_layout(doc, *f);
- if let Some(d) = &dir {
- al.mode = match d.to_ascii_lowercase().as_str() {
- "vertical" | "column" => LayoutMode::Vertical,
- "grid" => LayoutMode::Grid,
- _ => LayoutMode::Horizontal,
- };
- }
+ let plan = add_layout(doc, *f, !in_place, single_group, dir.as_deref());
+ let al = plan.layout;
let mut kids = doc.get(*f)?.children.clone();
sort_layout_children(doc, &mut kids, al.mode == LayoutMode::Vertical);
let empty = doc.node(*f).is_some_and(|n| n.children.iter().filter_map(|c| doc.node(*c)).all(|c| !c.visible || c.child_layout.absolute));
let n = doc.get_mut(*f)?;
n.children = kids;
n.layout = Some(al);
+ if single_group {
+ n.fills.clear();
+ n.clip = false;
+ }
+ if plan.grow > 0.0 {
+ n.transform = Affine::translate((-plan.grow, -plan.grow)) * n.transform;
+ }
if !in_place || !empty {
// A frame wrapped around the selection hugs it; an existing frame with no flow
// children keeps its size instead of collapsing to its padding.
if !single_group || n.child_layout.sizing_h != Sizing::Fill {
- n.child_layout.sizing_h = Sizing::Hug;
+ n.child_layout.sizing_h = if plan.fixed_width { Sizing::Fixed } else { Sizing::Hug };
}
if !single_group || n.child_layout.sizing_v != Sizing::Fill {
n.child_layout.sizing_v = Sizing::Hug;
}
+ if let Some(w) = plan.set_width {
+ n.width = w;
+ }
}
}
s.set_selection(targets.clone());
@@ -856,7 +932,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result {
net = VectorNetwork::from_path(&simplified);
net.regions.clear();
}
- *network = net;
+ *network = net.into();
}
}
ok()
@@ -888,7 +964,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result {
let bounds = result.bounding_box();
result.apply_affine(Affine::translate((-bounds.x0, -bounds.y0)));
let node = doc.get_mut(i)?;
- node.kind = NodeKind::Vector { network: VectorNetwork::from_path(&result) };
+ node.kind = NodeKind::Vector { network: VectorNetwork::from_path(&result).into() };
node.transform *= Affine::translate((bounds.x0, bounds.y0));
node.width = bounds.width();
node.height = bounds.height();
@@ -908,7 +984,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result {
let bb = res.bounding_box();
res.apply_affine(Affine::translate((-bb.x0, -bb.y0)));
let nm = doc.get_mut(i)?;
- nm.kind = NodeKind::Vector { network: VectorNetwork::from_path(&res) };
+ nm.kind = NodeKind::Vector { network: VectorNetwork::from_path(&res).into() };
nm.transform *= Affine::translate((bb.x0, bb.y0));
nm.width = bb.width();
nm.height = bb.height();
@@ -959,14 +1035,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result {
}
let Some(bb) = net.bounds() else {
let nm = doc.get_mut(i)?;
- nm.kind = NodeKind::Vector { network: net };
+ nm.kind = NodeKind::Vector { network: net.into() };
nm.width = 0.0;
nm.height = 0.0;
continue;
};
net.translate(-bb.x0, -bb.y0);
let nm = doc.get_mut(i)?;
- nm.kind = NodeKind::Vector { network: net };
+ nm.kind = NodeKind::Vector { network: net.into() };
nm.transform *= Affine::translate((bb.x0, bb.y0));
nm.width = bb.width();
nm.height = bb.height();
diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs
index 64252c97a..0c81717b5 100644
--- a/crates/engine/src/cmd/styles.rs
+++ b/crates/engine/src/cmd/styles.rs
@@ -256,6 +256,48 @@ fn text_style_json(cmd: &str, v: &Value) -> Result {
serde_json::from_value::(v).map(|t| t.as_text_style()).map_err(|e| bad(cmd, e.to_string()))
}
+/// A text style value from JSON: the character values from `style`, the paragraph values from
+/// `paragraph` (the same object for the flat `value` of `style.create`).
+fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result {
+ Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) })
+}
+
+/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its
+/// variable bindings from the document, the new value and the style it replaces. The style
+/// redefined is the local text style of that name with the exported `id` (so a file re-importing
+/// its own export keeps each style's identity when two share a name), else the first of that
+/// name; never one in `touched`. True when one existed (with the style's id); the caller settles
+/// and propagates.
+pub(crate) fn upsert_text_style(
+ doc: &mut Document,
+ name: &str,
+ id: Option<&str>,
+ description: &str,
+ style: &Value,
+ paragraph: &Value,
+ touched: &[StyleId],
+ bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap,
+) -> Result<(StyleId, bool)> {
+ let kind = text_kind("variable.import", style, paragraph)?;
+ let eligible = |x: &Style| {
+ x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id)
+ };
+ let same = id.and_then(|id| doc.styles.iter().position(|x| x.id == id && eligible(x))).or_else(|| doc.styles.iter().position(&eligible));
+ let updated = same.is_some();
+ let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i)));
+ let mut st = match same.and_then(|i| doc.styles.get(i)) {
+ Some(x) => Style { kind, bound, ..x.clone() },
+ None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound },
+ };
+ crate::style_vars::prune(&mut st);
+ let sid = st.id.clone();
+ match same.and_then(|i| doc.styles.get_mut(i)) {
+ Some(slot) => *slot = st,
+ None => doc.styles.push(st),
+ }
+ Ok((sid, updated))
+}
+
/// The text style definition a layer's chars from `at` (None = its base style) show.
fn text_style_of(n: &Node, at: Option) -> Option {
let t = n.kind.text()?;
@@ -361,7 +403,7 @@ fn create(s: &mut Session, p: &Value) -> Result {
let kind = if let Some(v) = get(p, "value") {
match t.as_str() {
"paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? },
- "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) },
+ "text" => text_kind(cmd, v, v)?,
"effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
"grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
_ => return Err(bad(cmd, "type: paint|text|effect|grid")),
@@ -567,7 +609,7 @@ fn update(s: &mut Session, p: &Value) -> Result {
let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint");
Some(match cur {
"paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? },
- "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) },
+ "text" => text_kind(cmd, v, v)?,
"effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
_ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? },
})
@@ -812,13 +854,13 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) {
}
let link = t2.text_style_link().flatten().map(str::to_string);
if t2 != *t || link != n.styles.text {
- updates.push((id, link, t2));
+ updates.push((id, link, (*t2).clone()));
}
}
for (id, link, t2) in updates {
if let Ok(n) = doc.get_mut(id) {
n.styles.text = link;
- n.kind = NodeKind::Text(t2);
+ n.kind = NodeKind::Text(t2.into());
}
}
}
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index c4f4eaffd..f959ec12b 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -24,7 +24,8 @@ fn style(s: &mut Session, p: &Value, f: impl Fn(&mut TextStyle)) -> Result Vec {
spec!(
"variable.export",
"Export variables",
- "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written",
+ "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-