Merge remote-tracking branch 'origin/main' into HEAD

# Conflicts:
#	crates/format/Cargo.toml
This commit is contained in:
bflatastic committed 2026-11-28 17:32:22 +07:00
commit 2cd906ddd8
175 files changed
+8384 -522

No files matched your search

Generated
+310 -5
View File
@@ -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",
]
+6
View File
@@ -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
+1 -1
View File
@@ -208,7 +208,7 @@ exposes to agents, and exported at 2x by FigCraft's own renderer. The source fil
</td>
<td width="50%" valign="top">
<h3>Prototype and hand off</h3>
Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like <code>count + 1</code>), 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 <code>count + 1</code>), 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.
</td>
</tr>
</table>
+4 -1
View File
@@ -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 earlieLine truncated
> **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 effeLine truncated
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/<name>.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. |
+1
View File
@@ -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 }
+24 -1
View File
@@ -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<u64>,
/// 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<String>,
#[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() {
+60 -1
View File
@@ -76,6 +76,12 @@ pub type CliResult<T> = Result<T, CliError>;
fn dispatch(cli: Cli, io: &mut Io) -> CliResult<i32> {
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<i32> {
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<u64>, roots: Option<figcraft_engine
Ok(0)
}
/// The roots a headless MCP session is confined to: both kinds are required, and the servers in
/// `allowed_servers` (ws:// or wss:// addresses without a query or key) are the only ones
/// `collab.join` may reach.
fn mcp_roots(roots: &RootArgs, allowed_servers: &[String]) -> CliResult<figcraft_engine::file_access::Roots> {
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);
}
}
+25 -3
View File
@@ -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()
+4
View File
@@ -141,3 +141,7 @@ real_name = "Ibuchukwu Umeano"
[people.Terra854]
display_name = "Terra854"
[people.andrejskvorc]
real_name = "Andrej Skvorc"
sync_github_name = true
+13
View File
@@ -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<String> {
let bytes = s.as_bytes();
+24
View File
@@ -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();
+9
View File
@@ -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<SessionInfo, String> {
+20 -7
View File
@@ -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::<Vec<_>>(), ["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();
}
+43 -22
View File
@@ -86,10 +86,19 @@ impl Client {
/// Start from the server's `Welcome` (which must carry a snapshot).
pub fn join(welcome: ServerMsg) -> Result<Client, Error> {
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<Vec<ClientMsg>, Error> {
+216
View File
@@ -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<Outgoing>) {
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<NodeId> = 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<NodeId> =
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<NodeId> = 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<u64> = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse::<u64>().ok()) {
Some(single) => vec![single],
None => vec![1, 7, 42, 1337, 2026],
};
for seed in seeds {
run_dst_seed(seed);
}
}
+431
View File
@@ -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<Replica, Error> {
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<Replica, Error> {
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<String, String>) -> 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::<usize>())));
let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::<Paint>()));
acc.saturating_add(size_of::<Region>()).saturating_add(loops).saturating_add(fills)
});
size_of::<VectorNetwork>()
.saturating_add(net.vertices.len().saturating_mul(size_of::<Vertex>()))
.saturating_add(net.segments.len().saturating_mul(size_of::<Segment>()))
.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::<Node>()
.saturating_add(n.name.len())
.saturating_add(n.dev_note.len())
.saturating_add(n.fills.len().saturating_mul(size_of::<Paint>()))
.saturating_add(n.strokes.len().saturating_mul(size_of::<Paint>()))
.saturating_add(n.effects.len().saturating_mul(size_of::<Effect>()))
.saturating_add(n.grids.len().saturating_mul(size_of::<LayoutGrid>()))
.saturating_add(n.guides.len().saturating_mul(size_of::<Guide>()))
.saturating_add(n.exports.len().saturating_mul(size_of::<ExportSetting>()))
.saturating_add(n.interactions.len().saturating_mul(size_of::<Interaction>()))
.saturating_add(n.annotations.len().saturating_mul(size_of::<Annotation>()))
.saturating_add(n.code_links.len().saturating_mul(size_of::<CodeLink>()))
.saturating_add(n.dev_resources.len().saturating_mul(size_of::<DevResource>()))
.saturating_add(n.measurements.len().saturating_mul(size_of::<Measurement>()))
.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::<Paint>()),
FieldDelta::Effects(v) => v.len().saturating_mul(size_of::<Effect>()),
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::<Annotation>()),
FieldDelta::CodeLinks(v) => v.len().saturating_mul(size_of::<CodeLink>()),
_ => 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::<NodeId>())));
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<NodeId>,
vectors: Vec<figcraft_doc::Shared<VectorNetwork>>,
vector_sizes: Vec<usize>,
node_sizes: HashMap<NodeId, usize>,
meta: Option<WireMeta>,
records_seen: usize,
max_nodes: usize,
materialized_bytes: usize,
max_materialized_bytes: usize,
abort: Option<Error>,
}
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<E: de::Error>(&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<D: de::Deserializer<'de>>(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<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
while let Some(net) = seq.next_element::<VectorNetwork>()? {
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<D: de::Deserializer<'de>>(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<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
loop {
if self.0.records_seen >= self.0.max_nodes {
if seq.next_element::<de::IgnoredAny>()?.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::<WireRecord>()? 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<D: de::Deserializer<'de>>(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<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
while let Some(key) = map.next_key::<String>()? {
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::<de::IgnoredAny>()?;
}
}
}
Ok(())
}
}
fn stream_decode_wire(raw: &[u8], max_nodes: usize, max_materialized_bytes: usize) -> Result<Replica, Error> {
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<NodeId> = 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;
}
+262
View File
@@ -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<u32>>,
table: Vec<VectorNetwork>,
}
impl VectorInterner {
pub(super) fn intern(&mut self, net: &VectorNetwork) -> Result<u32, Error> {
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<NodeId> {
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<NodeId> = parent_order.iter().copied().collect();
let mut indeg: HashMap<NodeId, u8> = HashMap::with_capacity(present.len());
let mut deps_of: HashMap<NodeId, Vec<NodeId>> = 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<NodeId> = 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<NodeId> = 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<Vec<u8>, Error> {
let doc = replica.document();
let order = topo_order(doc);
let mut interner = VectorInterner::default();
let mut seen: HashMap<NodeId, &Node> = 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<usize> = 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<NodeId, usize> = 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<NodeId, &Node>, interner: &mut VectorInterner) -> Result<WireRecord, Error> {
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<W> {
inner: W,
written: usize,
}
impl<W: Write> Write for CountingWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
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<u8>, 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))
}
+285
View File
@@ -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<NodeKind>),
VectorRef(u32),
$( $bvar(Box<$bty>), )*
$( $vvar($vty), )*
}
fn diff_table_fields(src: &Node, node: &Node, out: &mut Vec<FieldDelta>) {
$(
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<VectorNetwork>]) -> 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<Paint>) => fills via eq_paint_vec,
Strokes(Vec<Paint>) => strokes via eq_paint_vec,
Effects(Vec<Effect>) => effects via eq_vec_exact,
Corners(Corners) => corners via eq_exact,
Constraints(Constraints) => constraints via eq_plain,
Layout(Option<AutoLayout>) => 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<LayoutGrid>) => grids via eq_vec_exact,
Guides(Vec<Guide>) => guides via eq_vec_exact,
Exports(Vec<ExportSetting>) => exports via eq_vec_exact,
Interactions(Vec<Interaction>) => interactions via eq_vec_exact,
Overflow(Overflow) => overflow via eq_plain,
ScrollPosition(ScrollPosition) => scroll_position via eq_exact,
Bound(BTreeMap<String, VariableId>) => bound via eq_plain,
VarModes(BTreeMap<CollectionId, ModeId>) => var_modes via eq_plain,
ScaleFactor(f64) => scale_factor via eq_f64,
BoolOp(Option<BoolOp>) => 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<String, String>) => prop_refs via eq_plain,
PluginData(BTreeMap<String, String>) => plugin_data via eq_plain,
Annotations(Vec<Annotation>) => annotations via eq_vec_exact,
CodeLinks(Vec<CodeLink>) => code_links via eq_plain,
DevResources(Vec<DevResource>) => dev_resources via eq_plain,
Measurements(Vec<Measurement>) => measurements via eq_vec_exact,
Board(Option<BoardItem>) => 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<Vec<FieldDelta>, 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<T: PartialEq>(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<T: Serialize + ?Sized>(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<T: Serialize + PartialEq>(a: &T, b: &T) -> bool {
a == b && eq_json(a, b)
}
fn eq_vec_exact<T: Serialize + PartialEq>(a: &[T], b: &[T]) -> bool {
(a.is_empty() && b.is_empty()) || (a == b && eq_json(a, b))
}
fn eq_opt_exact<T: Serialize + PartialEq>(a: &Option<T>, b: &Option<T>) -> 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),
}
}
+146
View File
@@ -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<usize, Error> {
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<Node>,
#[serde(default, skip_serializing_if = "Option::is_none")]
vref: Option<u32>,
},
Mirror(Box<MirrorWire>),
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MirrorWire {
id: NodeId,
#[serde(default, skip_serializing_if = "Option::is_none")]
parent: Option<NodeId>,
pos: String,
source: NodeId,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
overrides: BTreeSet<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
deltas: Vec<FieldDelta>,
}
#[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<figcraft_doc::Style>,
#[serde(default)]
variables: figcraft_doc::Variables,
#[serde(default)]
current_page: Option<NodeId>,
#[serde(default)]
document_colors: Vec<Color>,
#[serde(default)]
comments: Vec<Comment>,
#[serde(default)]
libraries: Libraries,
#[serde(default)]
color_profile: ColorProfile,
#[serde(default)]
image_presets: Vec<ImagePreset>,
#[serde(default)]
design_review: DesignReview,
#[serde(default)]
annotation_categories: Option<Vec<AnnotationCategory>>,
#[serde(default)]
dev_snapshots: BTreeMap<NodeId, DevSnapshot>,
#[serde(default)]
timer: Option<BoardTimer>,
#[serde(default)]
vote: Option<Vote>,
#[serde(default)]
votes: Ballots,
#[serde(default)]
vote_history: Vec<VoteRecord>,
#[serde(default)]
images: Vec<WireImage>,
}
/// 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],
}
+408
View File
@@ -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<u32>) -> Vec<u8> {
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<NodeId>) {
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<Vec<NodeId>> = 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(_), .. }));
}
+50 -21
View File
@@ -290,27 +290,61 @@ fn image_of(key: &str, value: &Json) -> Result<ImageData, Error> {
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<ImageData, Error> {
/// 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<u8>, max_bytes: u64) -> Result<ImageData, Error> {
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<ImageData, Error> {
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<ImageData, Error> {
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<ImageData, Error> {
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<Change>) -> bool {
let mut clamped_any = false;
for c in changes {
if let Change::SetDoc { prop: DocProp::DesignReview, value } = c
&& let Ok(config) = value.read::<figcraft_doc::DesignReview>("design review")
&& !config.over_limits().is_empty()
&& let Ok(mut clamped) = value.read::<figcraft_doc::DesignReview>("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
+2 -2
View File
@@ -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.
+5
View File
@@ -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;
+33 -13
View File
@@ -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<Change>` (#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<u8>),
/// 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<u8>),
}
/// 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(())
}
+3 -1
View File
@@ -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()
}
+34 -4
View File
@@ -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());
}
+34 -1
View File
@@ -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<u8>)>,
}
/// 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<Vec<u8>, 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
+4 -4
View File
@@ -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();
+3 -1
View File
@@ -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()));
+3 -3
View File
@@ -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)];
+1 -1
View File
@@ -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)];
+12 -1
View File
@@ -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;
+3 -5
View File
@@ -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<String, PropDef>, 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<VectorNetwork>,
},
Text(TextData),
Text(Shared<TextData>),
BooleanOp {
op: BoolOp,
},
+105
View File
@@ -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<T>(Arc<T>);
impl<T> Shared<T> {
/// 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<T>) -> Self {
Self(arc)
}
/// Borrow the underlying [`Arc`].
pub fn as_arc(&self) -> &Arc<T> {
&self.0
}
/// Unwrap the underlying [`Arc`].
pub fn into_arc(self) -> Arc<T> {
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<T> Clone for Shared<T> {
fn clone(&self) -> Self {
Self(Arc::clone(&self.0))
}
}
impl<T> Deref for Shared<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: Clone> DerefMut for Shared<T> {
fn deref_mut(&mut self) -> &mut T {
Arc::make_mut(&mut self.0)
}
}
impl<T: PartialEq> PartialEq for Shared<T> {
fn eq(&self, other: &Self) -> bool {
*self.0 == *other.0
}
}
impl<T: Eq> Eq for Shared<T> {}
impl<T> From<T> for Shared<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T> From<Arc<T>> for Shared<T> {
fn from(arc: Arc<T>) -> Self {
Self(arc)
}
}
impl<T> AsRef<T> for Shared<T> {
fn as_ref(&self) -> &T {
&self.0
}
}
impl<T: Serialize> Serialize for Shared<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared<T> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
T::deserialize(deserializer).map(Self::new)
}
}
+195
View File
@@ -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<T>, NodeKind was 352 B
// and Node was 1608 B.
assert!(size_of::<NodeKind>() <= 144, "NodeKind grew unexpectedly: {} bytes", size_of::<NodeKind>());
assert!(size_of::<Node>() <= 1400, "Node grew unexpectedly: {} bytes", size_of::<Node>());
}
#[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<TextData> = 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<Point> = (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::<Vertex>()
+ icon.segments.len() * size_of::<Segment>()
+ icon.regions.len() * size_of::<Region>()
+ icon.regions.iter().map(|r| r.loops.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>()).sum::<usize>();
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::<Node>(),
size_of::<NodeKind>(),
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,
);
}
+5 -5
View File
@@ -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();
+2
View File
@@ -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 }
+269
View File
@@ -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<NodeId>, 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<NodeId> = 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<NodeId> = [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};
+1 -1
View File
@@ -76,7 +76,7 @@ fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) {
let kids: Vec<NodeId> =
(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]])
}
+2
View File
@@ -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<NodeId> = (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);
+2 -2
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
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<CommandSpec> {
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)?;
+1 -1
View File
@@ -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();
+18 -2
View File
@@ -40,6 +40,7 @@ pub enum Access {
pub struct Roots {
read: Vec<PathBuf>,
write: Vec<PathBuf>,
allowed_servers: Vec<String>,
}
impl Roots {
@@ -55,7 +56,18 @@ impl Roots {
})
.collect::<std::result::Result<Vec<_>, 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<String>) -> 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::<Vec<_>>();
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
})
}
}
+4 -4
View File
@@ -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:?}"),
}
}
+2 -2
View File
@@ -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:?}"),
}
}
+1 -1
View File
@@ -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;
+5 -3
View File
@@ -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::<Vec<_>>(), 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());
}
+1 -1
View File
@@ -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(())
+3 -3
View File
@@ -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<Value> {
})?;
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 {
+1 -1
View File
@@ -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();
+4 -4
View File
@@ -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<Node
region.paint_space = Some(figcraft_doc::RegionPaintSpace { width: paint_width, height: paint_height, transform: paint_transform });
}
let id = doc.alloc_id();
let mut v = Node::new(id, NodeKind::Vector { network: net }, src.name.clone(), bb.width(), bb.height());
let mut v = Node::new(id, NodeKind::Vector { network: net.into() }, src.name.clone(), bb.width(), bb.height());
v.transform = Affine::translate((bb.x0, bb.y0));
v.fills = src.fills;
v.strokes = src.strokes;
@@ -48,7 +48,7 @@ fn split_vector(s: &mut Session) -> 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);
+1 -1
View File
@@ -83,7 +83,7 @@ fn next_editing_session() -> u64 {
fn text_of(s: &Session, id: NodeId) -> Result<TextData> {
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"))),
}
}
+2 -2
View File
@@ -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;
+2 -2
View File
@@ -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));
+1 -1
View File
@@ -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;
@@ -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 }];
@@ -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();
+2 -2
View File
@@ -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}));
+4 -4
View File
@@ -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<Value> {
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<Value> {
}
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<Point> = 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);
@@ -106,7 +106,7 @@ fn clip_node(doc: &Document, id: NodeId, mut sub: VectorNetwork) -> Option<Node>
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<String> {
/// frames, groups, instances, …). `doc` is the file the layer was copied from.
fn outline_network(doc: &Document, n: &Node) -> Option<VectorNetwork> {
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);
+6 -6
View File
@@ -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");
+1 -1
View File
@@ -1271,7 +1271,7 @@ fn set_path(cmd: &str, doc: &mut Document, id: NodeId, v: &Value, props: &Map<St
let shape = super::create::path_network(cmd, d, size("width", "w")?, size("height", "h")?)?;
let n = doc.get_mut(id)?;
if let NodeKind::Vector { network } = &mut n.kind {
*network = shape.network;
*network = (shape.network).into();
}
n.width = shape.width;
n.height = shape.height;
+94 -18
View File
@@ -2,8 +2,8 @@
use figcraft_color::{Color, Paint};
use figcraft_doc::{
AutoLayout, BoolOp, Corners, Document, LayoutMode, Node, NodeId, NodeKind, Region, RegionPaintSpace, Segment, Sizing, StrokeAlign, StrokeJoin,
StrokeProps, VectorNetwork, WindingRule, proto,
AutoLayout, BoolOp, Corners, Document, LayoutMode, MainAlign, Node, NodeId, NodeKind, Region, RegionPaintSpace, Segment, Sizing, StrokeAlign,
StrokeJoin, StrokeProps, VectorNetwork, WindingRule, proto,
};
use figcraft_geom::{Affine, BezPath, Rect, Shape};
use serde_json::{Value, json};
@@ -445,7 +445,7 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<f64>,
/// 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<Rect> =
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<f64> =
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::<f64>() / 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<Value> {
@@ -725,29 +797,33 @@ fn layout_add(s: &mut Session, p: &Value) -> Result<Value> {
};
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<Value> {
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<Value> {
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<Value> {
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<Value> {
}
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();
+46 -4
View File
@@ -256,6 +256,48 @@ fn text_style_json(cmd: &str, v: &Value) -> Result<TextStyle> {
serde_json::from_value::<TextStyle>(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<StyleKind> {
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<String, VariableId>,
) -> 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<usize>) -> Option<TextStyle> {
let t = n.kind.text()?;
@@ -361,7 +403,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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());
}
}
}
+2 -1
View File
@@ -24,7 +24,8 @@ fn style(s: &mut Session, p: &Value, f: impl Fn(&mut TextStyle)) -> Result<Value
let bound = super::styles::bound_before(doc, &[id]);
if let NodeKind::Text(t) = &mut doc.get_mut(id)?.kind {
if a == b {
t.restyle(0, t.char_count(), &f);
let len = t.char_count();
t.restyle(0, len, &f);
} else {
t.restyle(a, b, &f);
}
+120 -6
View File
@@ -4,7 +4,7 @@
use std::collections::{BTreeMap, BTreeSet};
use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, Variable, VariableId, VariableValue, Variables, trim_num};
use figcraft_doc::{Collection, CollectionId, Document, Mode, ModeId, StyleKind, Variable, VariableId, VariableValue, Variables, trim_num};
use serde_json::{Value, json};
use super::CommandSpec;
@@ -18,14 +18,14 @@ pub fn specs() -> Vec<CommandSpec> {
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-<collection>=\"<mode>\"], 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-<collection>=\"<mode>\"], 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; the json format adds a top-level `textStyles` array (this file's text styles as style.list returns them, `bound` holding the ids `meta.variables` is keyed by), a FigCraft extension beside the REST-compatible `meta`",
false,
export
),
spec!(
"variable.import",
"Import variables",
"{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, warnings (also when it holds no variables, or fewer than its collections list)}",
"{variables (the local variables JSON, as variable.export writes it: an object, JSON text or a path to a regular file of at most 256 MiB; `variableCollections` and `variables` under `meta` or at the top level; a top-level `textStyles` array, a FigCraft extension, adds this file's text styles by name with their variable bindings re-pointed)} collections join this file's collection of the same name (values by mode name; new modes and variables are added, a variable of another type is skipped), others are added → {collections (added), variables (added), updated, styles {added, updated}, warnings (also when it holds no variables, or fewer than its collections list)}",
true,
import
),
@@ -44,8 +44,13 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(cmd, "collections: [collection ids or names]")),
};
let text = match string(p, "format").as_deref().unwrap_or("json") {
"json" => serde_json::to_string_pretty(&figcraft_format::rest::export_variables(&doc.variables, &colls))
.map_err(|e| EngineError::Other(e.to_string()))?,
"json" => {
let mut out = figcraft_format::rest::export_variables(&doc.variables, &colls);
if let Value::Object(m) = &mut out {
m.insert("textStyles".into(), text_styles(doc));
}
serde_json::to_string_pretty(&out).map_err(|e| EngineError::Other(e.to_string()))?
}
"css" => css(doc, &colls, false),
"tailwind" => css(doc, &colls, true),
"dart" => dart(&doc.variables, &colls),
@@ -60,6 +65,108 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
}
}
/// This file's own text styles as `style.list {type: "text"}` returns them (values and `bound`,
/// the variable ids being those `meta.variables` is keyed by): the `textStyles` of the variables
/// JSON, a FigCraft extension beside the REST-compatible `meta`.
fn text_styles(doc: &Document) -> Value {
let own = |st: &&figcraft_doc::Style| matches!(st.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &st.id);
Value::Array(doc.styles.iter().filter(own).filter_map(|st| serde_json::to_value(st).ok()).collect())
}
/// At most this many text styles are read from a variables JSON, this many bindings per style, and
/// this many chars of a description.
const MAX_TEXT_STYLES: usize = 10_000;
const MAX_STYLE_BINDINGS: usize = 32;
const MAX_STYLE_DESCRIPTION: usize = 10_000;
/// Read `entries` (the `textStyles` of a variables JSON) into this file: a style joins this file's
/// text style of the same name (the first one this import hasn't touched yet), others are added;
/// bindings follow `ids` (imported variable id to this file's). Returns (added, updated); what
/// can't be read is a warning.
fn import_text_styles(doc: &mut Document, entries: &Value, ids: &BTreeMap<VariableId, VariableId>, warnings: &mut Vec<String>) -> (usize, usize) {
let Value::Array(list) = entries else {
warnings.push("`textStyles` should be an array of text styles: skipped".to_string());
return (0, 0);
};
if list.len() > MAX_TEXT_STYLES {
warnings.push(format!("`textStyles` holds {} entries: only the first {MAX_TEXT_STYLES} are read", list.len()));
}
let (mut added, mut updated) = (0, 0);
let mut touched = Vec::new();
for (i, e) in list.iter().take(MAX_TEXT_STYLES).enumerate() {
let name = e.get("name").and_then(Value::as_str).and_then(super::variables::clean_name);
let (Some(name), Some(style)) = (name, e.get("style").filter(|x| x.is_object())) else {
warnings.push(format!("`textStyles` entry {i} needs a `name` and a `style` object: skipped"));
continue;
};
let description: String = e.get("description").and_then(Value::as_str).unwrap_or_default().chars().take(MAX_STYLE_DESCRIPTION).collect();
let wanted = e.get("bound");
let bind = |doc: &Document, kind: &StyleKind, current: Option<&figcraft_doc::Style>| {
text_style_bindings(&name, wanted, ids, doc, kind, current, warnings)
};
let id = e.get("id").and_then(Value::as_str);
match super::styles::upsert_text_style(doc, &name, id, &description, style, e.get("paragraph").unwrap_or(&Value::Null), &touched, bind) {
Ok((sid, was)) => {
touched.push(sid);
if was {
updated += 1;
} else {
added += 1;
}
}
Err(EngineError::BadParams { msg, .. }) => warnings.push(format!("text style `{name}`: {msg}")),
Err(err) => warnings.push(format!("text style `{name}`: {err}")),
}
}
crate::style_vars::settle(doc);
for sid in touched {
super::styles::propagate_style(doc, &sid);
}
(added, updated)
}
/// The bindings an imported text style `name` keeps, as this file's variable ids: a variable
/// follows `ids`, or stays when `current` (the style it replaces) already holds that same id for
/// the field (a file's own export names variables the import doesn't carry); a field the style
/// lacks or a variable of the wrong type is a warning, as are more than [`MAX_STYLE_BINDINGS`].
fn text_style_bindings(
name: &str,
wanted: Option<&Value>,
ids: &BTreeMap<VariableId, VariableId>,
doc: &Document,
kind: &StyleKind,
current: Option<&figcraft_doc::Style>,
warnings: &mut Vec<String>,
) -> BTreeMap<String, VariableId> {
let mut bound = BTreeMap::new();
let Some(Value::Object(m)) = wanted else { return bound };
if m.len() > MAX_STYLE_BINDINGS {
warnings.push(format!("text style `{name}`: {} bindings: only the first {MAX_STYLE_BINDINGS} are read", m.len()));
}
for (field, id) in m.iter().take(MAX_STYLE_BINDINGS) {
let held = current.and_then(|c| c.bound.get(field)).filter(|h| id.as_str() == Some(h.as_str()));
let local = id.as_str().and_then(|v| ids.get(v)).or(held);
match checked_binding(doc, kind, field, local) {
Ok(local) => {
bound.insert(field.clone(), local.clone());
}
Err(why) => warnings.push(format!("text style `{name}`: {why}: left unbound")),
}
}
bound
}
/// `local` when it is a variable of this file of the type a text style's `field` takes.
fn checked_binding<'a>(doc: &Document, kind: &StyleKind, field: &str, local: Option<&'a VariableId>) -> std::result::Result<&'a VariableId, String> {
let local = local.ok_or_else(|| format!("`{field}` is bound to a variable the JSON doesn't hold"))?;
let want = crate::style_vars::field_type(kind, field).ok_or_else(|| format!("no field `{field}` to bind"))?;
match doc.variables.get_by_id(local).map(|v| v.kind) {
Some(k) if k == want => Ok(local),
Some(k) => Err(format!("`{field}` takes a {} variable, not a {} one", want.id(), k.id())),
None => Err(format!("`{field}` is bound to a variable this file lacks")),
}
}
/// `text` as a CSS comment or quoted string body.
fn css_safe(text: &str) -> String {
text.replace("*/", "* /").replace(['"', '\\', '\n', '\r', '\u{c}'], " ")
@@ -362,5 +469,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
Ok(json!({"collections": added_colls, "variables": added, "updated": updated, "warnings": warnings}))
let (styles_added, styles_updated) = match v.get("textStyles") {
Some(entries) => import_text_styles(doc, entries, &ids, &mut warnings),
None => (0, 0),
};
Ok(json!({
"collections": added_colls, "variables": added, "updated": updated,
"styles": {"added": styles_added, "updated": styles_updated}, "warnings": warnings
}))
}
+1 -1
View File
@@ -15,7 +15,7 @@ pub const SCREEN_GAP: f64 = 80.0;
pub const PER_SCREEN: usize = 50;
fn text(content: &str) -> NodeKind {
NodeKind::Text(figcraft_doc::TextData::new(content))
NodeKind::Text(figcraft_doc::TextData::new(content).into())
}
fn ellipse() -> NodeKind {
+1 -1
View File
@@ -122,7 +122,7 @@ fn component() -> NodeKind {
}
fn text(chars: &str) -> NodeKind {
NodeKind::Text(TextData::new(chars))
NodeKind::Text(TextData::new(chars).into())
}
/// Pick a (capped) prefix of a value list.
+4 -4
View File
@@ -33,7 +33,7 @@ fn kind(s: &Session, n: NodeId) -> NodeKind {
fn adding_auto_layout_converts_a_single_group_and_arranges_its_children_directly() {
let mut s = Session::new();
let page = s.page().unwrap();
let (a, b) = (rect(&mut s, page, 10.0, 20.0), rect(&mut s, page, 90.0, 20.0));
let (a, b) = (rect(&mut s, page, 10.0, 20.0), rect(&mut s, page, 80.0, 20.0));
let group = id(ex(&mut s, "object.group", json!({"ids": [a, b], "name": "Actions"})));
let siblings = s.doc().unwrap().node(page).unwrap().children.clone();
let before = [page_box(&s, group), page_box(&s, a), page_box(&s, b)];
@@ -52,7 +52,7 @@ fn adding_auto_layout_converts_a_single_group_and_arranges_its_children_directly
// The second child now follows changes to the first through auto layout.
ex(&mut s, "node.set", json!({"id": a, "props": {"width": 60}}));
assert_eq!(page_box(&s, b), [110.0, 20.0, 150.0, 40.0]);
assert_eq!(page_box(&s, b), [100.0, 20.0, 140.0, 40.0]);
s.undo().unwrap();
s.undo().unwrap();
let restored = s.doc().unwrap().node(group).unwrap();
@@ -151,7 +151,7 @@ fn hidden_children_do_not_influence_inferred_direction_or_padding() {
ex(&mut s, "layout.add", json!({"ids": [frame]}));
let layout = s.doc().unwrap().node(frame).unwrap().layout.as_ref().unwrap();
assert_eq!(layout.mode, figcraft_doc::LayoutMode::Horizontal);
assert_eq!(layout.padding, [20.0, 170.0, 160.0, 10.0]);
assert_eq!(layout.padding, [20.0, 10.0, 20.0, 10.0]);
assert_eq!(layout.gap, 40.0);
assert_eq!([page_box(&s, a), page_box(&s, b)], before);
}
@@ -169,7 +169,7 @@ fn converting_a_group_preserves_fill_on_each_axis_in_its_parent() {
let before = [page_box(&s, group), page_box(&s, sibling)];
ex(&mut s, "layout.add", json!({"ids": [group]}));
let cl = &s.doc().unwrap().node(group).unwrap().child_layout;
assert_eq!(cl.sizing_h, if h == "fill" { Sizing::Fill } else { Sizing::Hug });
assert_eq!(cl.sizing_h, if h == "fill" { Sizing::Fill } else { Sizing::Fixed });
assert_eq!(cl.sizing_v, if v == "fill" { Sizing::Fill } else { Sizing::Hug });
assert_eq!([page_box(&s, group), page_box(&s, sibling)], before);
s.undo().unwrap();
+1 -1
View File
@@ -266,7 +266,7 @@ fn apply_radius(n: &mut Node, settings: &Settings) -> Option<bool> {
/// Run `f` over a text layer's base style and its runs; true when any style changed.
fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option<bool> {
let NodeKind::Text(t) = &mut n.kind else { return Some(false) };
let TextData { style, runs, .. } = t;
let TextData { style, runs, .. } = &mut **t;
let mut changed = f(style);
for run in runs {
changed |= f(&mut run.style);
+31 -11
View File
@@ -1,7 +1,7 @@
//! Code for a layer, as shown by the Inspect panel and returned by `inspect.code`: CSS for the
//! layer itself, HTML or React for its subtree, and SwiftUI, Jetpack Compose, ArkUI (HarmonyOS) or
//! Flutter (stacks for auto layout, absolute offsets otherwise). Components become components
//! whose properties are parameters and instances become calls passing their values (see
//! layer itself, HTML or React for its subtree, and SwiftUI, Jetpack Compose, ArkUI (HarmonyOS),
//! Flutter (stacks for auto layout, absolute offsets otherwise) or Uno Platform C# Markup.
//! Components become components whose properties are parameters and instances become calls passing their values (see
//! [`crate::component_codegen`]); variables bound to a layer become CSS custom properties, and
//! their iOS and Android code syntax in SwiftUI and Compose. The output is a starting point, not a
//! pixel-exact translation.
@@ -24,6 +24,7 @@ mod css;
mod flutter;
mod html;
mod swift;
mod uno;
pub(crate) use arkui::arkui;
pub(crate) use compose::{compose, kotlin_color};
@@ -36,19 +37,22 @@ pub(crate) use flutter::{FLUTTER_IMPORT, Place, flutter, flutter_indent};
use html::html;
pub(crate) use html::{Markup, Names, class_name};
pub(crate) use swift::swift;
pub(crate) use uno::uno;
#[cfg(test)]
pub(crate) use uno::{asset_name, cs_ident, cs_literal, cs_unique, path_data};
pub fn specs() -> Vec<CommandSpec> {
vec![spec!(
"inspect.code",
"Code for layer",
"{id?, language?: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter (default css; html, react, leptos and vue are the whole layer tree; components take their properties as parameters, instances pass their values; a component connected to code (codeConnect.set) gives its import and snippet instead; tailwind is React with Tailwind CSS v4 utilities for pages: fluid auto layout boxes, instances inlined with their overrides, bound variables as theme utilities), mobile? (tailwind: a mobile frame with the same layer names; the code is mobile first with the desktop layer's classes behind lg:), unit?: px|rem (CSS, HTML, React, Leptos and Vue; default px), rootFontSize? (rem: pixels per rem, default 16)} → {code, language, connected}",
"{id?, language?: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter|uno (default css; html, react, leptos and vue are the whole layer tree; components take their properties as parameters, instances pass their values; a component connected to code (codeConnect.set) gives its import and snippet instead; tailwind is React with Tailwind CSS v4 utilities for pages: fluid auto layout boxes, instances inlined with their overrides, bound variables as theme utilities), mobile? (tailwind: a mobile frame with the same layer names; the code is mobile first with the desktop layer's classes behind lg:), unit?: px|rem (CSS, HTML, React, Leptos and Vue; default px), rootFontSize? (rem: pixels per rem, default 16)} → {code, language, connected}",
false,
|s, p| {
let cmd = "inspect.code";
let id = targets(s, p).first().copied().ok_or_else(|| bad(cmd, "select a layer"))?;
let lang = match string(p, "language") {
Some(l) => {
CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter"))?
CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|tailwind|swiftui|compose|arkui|flutter|uno"))?
}
None => CodeLang::Css,
};
@@ -103,10 +107,12 @@ pub enum CodeLang {
ArkUi,
/// A Flutter `StatelessWidget` (Dart) with its widget tree.
Flutter,
/// Uno Platform C# Markup (.NET): a fluent C# expression tree of WinUI elements.
Uno,
}
impl CodeLang {
pub const ALL: [CodeLang; 10] = [
pub const ALL: [CodeLang; 11] = [
CodeLang::Css,
CodeLang::Html,
CodeLang::React,
@@ -117,6 +123,7 @@ impl CodeLang {
CodeLang::Compose,
CodeLang::ArkUi,
CodeLang::Flutter,
CodeLang::Uno,
];
pub fn id(self) -> &'static str {
match self {
@@ -130,6 +137,7 @@ impl CodeLang {
CodeLang::Compose => "compose",
CodeLang::ArkUi => "arkui",
CodeLang::Flutter => "flutter",
CodeLang::Uno => "uno",
}
}
pub fn label(self) -> &'static str {
@@ -144,6 +152,7 @@ impl CodeLang {
CodeLang::Compose => "Compose",
CodeLang::ArkUi => "ArkUI",
CodeLang::Flutter => "Flutter",
CodeLang::Uno => "Uno C# Markup",
}
}
/// Languages whose lengths are CSS pixels that can be shown in rem (not Tailwind: its lengths
@@ -169,6 +178,9 @@ impl CodeLang {
if s.eq_ignore_ascii_case("dart") {
return Some(CodeLang::Flutter);
}
if ["csharp-markup", "cs-markup"].iter().any(|a| s.eq_ignore_ascii_case(a)) {
return Some(CodeLang::Uno);
}
CodeLang::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(s) || l.label().eq_ignore_ascii_case(s))
}
}
@@ -284,9 +296,14 @@ pub fn code_for(doc: &Document, id: NodeId, lang: CodeLang) -> String {
CodeLang::Css => css(doc, id),
CodeLang::Html => html(doc, id),
CodeLang::Tailwind => crate::tailwind::code(doc, id, None),
CodeLang::React | CodeLang::Leptos | CodeLang::Vue | CodeLang::SwiftUi | CodeLang::Compose | CodeLang::ArkUi | CodeLang::Flutter => {
crate::component_codegen::code(doc, id, lang)
}
CodeLang::React
| CodeLang::Leptos
| CodeLang::Vue
| CodeLang::SwiftUi
| CodeLang::Compose
| CodeLang::ArkUi
| CodeLang::Flutter
| CodeLang::Uno => crate::component_codegen::code(doc, id, lang),
}
}
@@ -747,6 +764,8 @@ mod tests {
let mut s = Session::new();
let f = card(&mut s);
let doc = s.doc().unwrap();
// Add auto layout hugs the height: the taller of the 24 ellipse and the text line (30).
assert_eq!(doc.node(f).map(|n| n.height), Some(30.0));
let ark = code_for(doc, f, CodeLang::ArkUi);
for want in [
"Row({ space: ",
@@ -757,7 +776,7 @@ mod tests {
".backgroundColor('#FFFFFF')",
".borderRadius(12)",
".width(",
".height(100)",
".height(30)",
".clip(true)",
] {
assert!(ark.contains(want), "ArkUI has {want:?}:\n{ark}");
@@ -840,7 +859,8 @@ mod tests {
let dart = code_for(doc, f, CodeLang::Flutter);
// The card hugs its content, so its width is the layout's, not the 200 it was created with.
let w = doc.node(f).map(|n| n.width).unwrap_or_default();
assert!(dart.starts_with(&format!("Container(\n width: {},\n height: 100,\n", num(w))), "{dart}");
assert_eq!(doc.node(f).map(|n| n.height), Some(30.0), "hugs the taller of the ellipse and the text line");
assert!(dart.starts_with(&format!("Container(\n width: {},\n height: 30,\n", num(w))), "{dart}");
assert!(dart.contains("borderRadius: BorderRadius.circular(12)"), "{dart}");
assert!(dart.contains("child: Row(\n"), "{dart}");
assert!(dart.contains(" Text(\n \"Say \\\"hi\\\" \\$5\\nnow\",\n"), "escaped: {dart}");
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -12,7 +12,7 @@ use serde_json::{Value, json};
use crate::cmd::CommandSpec;
use crate::codegen::{
CodeLang, Ctx, FLUTTER_IMPORT, Markup, Names, Place, arkui, class_name, compose, flutter, flutter_indent, indent, literal, swift,
CodeLang, Ctx, FLUTTER_IMPORT, Markup, Names, Place, arkui, class_name, compose, flutter, flutter_indent, indent, literal, swift, uno,
};
use crate::components::{prop_default_value, slot_edited, slots_of, variant_options, variant_props, variant_set};
use crate::params::{id_of, string, targets};
@@ -119,7 +119,8 @@ pub fn code(doc: &Document, id: NodeId, lang: CodeLang) -> String {
if let Some(code) = crate::code_connect::link(doc, id, lang).and_then(|l| crate::code_connect::connected_code(doc, id, lang, l)) {
return code;
}
let comp = main_of(doc, id).and_then(|m| describe(doc, m));
// Uno C# Markup writes the layer tree only (instances and components are walked as frames).
let comp = main_of(doc, id).and_then(|m| describe(doc, m)).filter(|_| lang != CodeLang::Uno);
let code = match (&n.kind, comp) {
(NodeKind::Instance { .. }, Some(c)) => {
let call = usage(doc, id, lang, 0).unwrap_or_default();
@@ -155,6 +156,7 @@ pub fn code(doc: &Document, id: NodeId, lang: CodeLang) -> String {
flutter(&Ctx::new(doc, id), id, 0, &mut out, Place::Flow);
out
}
CodeLang::Uno => uno(doc, id),
_ => {
let mut out = String::new();
compose(&Ctx::new(doc, id), id, 0, &mut out);
+1 -1
View File
@@ -277,7 +277,7 @@ fn build(s: &mut Session, plugin: &str, w: NodeId, r: &WidgetRender) -> Result<(
fn add(doc: &mut Document, parent: NodeId, d: &WidgetNode, cmd: &str, pixels: &mut u64) -> Result<()> {
let (kind, name) = match d.kind {
WidgetKind::Frame => (NodeKind::Frame, "Frame"),
WidgetKind::Text => (NodeKind::Text(TextData { characters: d.text.clone(), ..TextData::default() }), "Text"),
WidgetKind::Text => (NodeKind::Text((TextData { characters: d.text.clone(), ..TextData::default() }).into()), "Text"),
WidgetKind::Rectangle => (NodeKind::Rectangle, "Rectangle"),
WidgetKind::Ellipse => (NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Ellipse"),
WidgetKind::Image => (NodeKind::Rectangle, "Image"),
+4
View File
@@ -562,6 +562,8 @@ mod proto_run_tests;
#[cfg(test)]
mod proto_tail_tests;
#[cfg(test)]
mod raw_tests;
#[cfg(test)]
mod reopen_tests;
#[cfg(test)]
mod responsive_tests;
@@ -664,6 +666,8 @@ mod transform_behaviour_tests;
#[cfg(test)]
mod unknown_params_tests;
#[cfg(test)]
mod uno_codegen_tests;
#[cfg(test)]
mod variable_props_tests;
#[cfg(test)]
mod variable_tests;
+25
View File
@@ -311,6 +311,31 @@ fn sharing_online_uses_a_separate_key_param() {
assert!(!r.to_string().contains("KeyKey"), "the server's key is nowhere in the summary");
}
#[test]
fn stopping_a_file_shared_with_a_separate_key_asks_with_that_key() {
// A file published with the server key has no owner token (#2495): Stop sharing must go as
// the server's operator, with the key it was published with, not an empty token. The key
// given replaces one the address carries, as it did for the publish.
for (server, asked_with) in [
("wss://share.example/", "wss://share.example/?key=Key%26Key%25Key1"),
("wss://share.example/?key=Old&team=1", "wss://share.example/?team=1&key=Key%26Key%25Key1"),
] {
let (mut s, script) = session();
ex(&mut s, "collab.share", json!({"server": server, "key": "Key&Key%Key1"}));
on_the_server(&mut s, &script, Some(("K7M2QX9TD", "4FHJ8R2WN")));
if let Some(p) = s.live_mut().and_then(|l| l.published.as_mut()) {
p.owner = None;
}
s.prefs.online_files.clear();
assert_eq!(ex(&mut s, "collab.stop", json!({}))["shared"], false);
let sc = script.lock().unwrap();
let [(asked, _, owner, revoke, false)] = sc.asked.as_slice() else { panic!("asked {:?}", sc.asked) };
// The address `collab.share {server: "…?key=…"}` would have given, the key escaped.
assert_eq!(asked, asked_with);
assert!(owner.is_empty() && !revoke.is_empty(), "the others' links go, with no owner token");
}
}
#[test]
fn a_server_without_join_codes_leaves_the_links() {
let (mut s, script) = session();
+44
View File
@@ -34,11 +34,17 @@ pub(crate) struct Script {
pub(crate) msgs_to: Vec<u64>,
/// The people removed: `(session, client)`.
pub(crate) removed: Vec<(u64, u32)>,
/// The scripted link's answer to an automation server allowlist check.
pub(crate) automation_join_allowed: bool,
}
pub(crate) struct Mock(pub(crate) Arc<Mutex<Script>>);
impl LiveLink for Mock {
fn automation_join_allowed(&self, link: &str, allowed_servers: &[String]) -> bool {
self.0.lock().unwrap().automation_join_allowed && allowed_servers.iter().any(|server| link.contains(server))
}
fn host(&mut self, session: u64, opts: HostOptions) -> Result<SessionInfo, String> {
let mut s = self.0.lock().unwrap();
s.session = session;
@@ -50,6 +56,7 @@ impl LiveLink for Mock {
i.url = format!("ws://{}/?file=f&token=t", i.address);
Ok(i)
}
fn join_resuming(&mut self, session: u64, link: &str, name: &str, resume: Option<crate::live::Resume>) -> Result<(), String> {
self.0.lock().unwrap().resumed = resume;
self.join(session, link, name)
@@ -103,6 +110,43 @@ impl LiveLink for Mock {
}
}
#[test]
fn confined_headless_session_may_join_only_an_explicitly_allowed_server() {
let dir = std::env::temp_dir().join(format!("figcraft-join-allow-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let roots = Arc::new(
crate::file_access::Roots::new(&[], &[dir.to_string_lossy().into_owned()])
.unwrap()
.with_allowed_servers(vec!["wss://figcraft.example.com/".into()]),
);
let script = Arc::new(Mutex::new(Script { automation_join_allowed: true, ..Script::default() }));
let mut s = Session::new();
s.live.install(Box::new(Mock(script.clone())));
crate::file_access::confined(Some(&roots), || {
assert!(
s.execute(
"collab.join",
&json!({"link": "figcraft://join?server=wss://figcraft.example.com/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv"})
)
.is_ok()
);
assert!(
s.execute(
"collab.join",
&json!({"link": "figcraft://join?server=wss://elsewhere.example.com/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv"})
)
.is_err()
);
assert!(s.execute("collab.publish", &json!({"server": "wss://figcraft.example.com/"})).is_err());
assert!(s.execute("collab.host", &json!({})).is_err());
assert!(s.execute("plugin.directory.list", &json!({"server": "wss://figcraft.example.com/"})).is_err());
});
assert_eq!(script.lock().unwrap().joined.len(), 1);
assert!(script.lock().unwrap().published.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// A session you are in as `role`, as client `me`, everyone in it editing.
pub(crate) fn info(role: Role, me: u32) -> SessionInfo {
SessionInfo {
+5 -5
View File
@@ -20,8 +20,8 @@ fn node_find_filters_are_literal_case_insensitive_and_anded() {
let mut s = Session::new();
let page = s.page().unwrap();
let frame = add(&mut s, page, NodeKind::Frame, "CAFÉ [Card]");
let title = add(&mut s, frame, NodeKind::Text(TextData::new("HÉLLO 世界")), "Café Title");
let other = add(&mut s, frame, NodeKind::Text(TextData::new("Other")), "Title");
let title = add(&mut s, frame, NodeKind::Text(TextData::new("HÉLLO 世界").into()), "Café Title");
let other = add(&mut s, frame, NodeKind::Text(TextData::new("Other").into()), "Title");
let rect = add(&mut s, page, NodeKind::Rectangle, "HÉLLO 世界");
found(&mut s, json!({"name": "CAFÉ"}), &[frame, title]);
found(&mut s, json!({"name": "[cArD]"}), &[frame]);
@@ -39,7 +39,7 @@ fn node_find_filters_are_literal_case_insensitive_and_anded() {
fn node_find_matches_a_greek_final_sigma_both_ways() {
let mut s = Session::new();
let page = s.page().unwrap();
let os = add(&mut s, page, NodeKind::Text(TextData::new("ΛΟΓΟΣ")), "ΟΣ");
let os = add(&mut s, page, NodeKind::Text(TextData::new("ΛΟΓΟΣ").into()), "ΟΣ");
found(&mut s, json!({"name": "Σ"}), &[os]);
found(&mut s, json!({"name": "ς"}), &[os]);
found(&mut s, json!({"text": "λογοσ"}), &[os]);
@@ -85,7 +85,7 @@ fn node_find_instances_match_main_name_and_visit_actual_children_only() {
let page = s.page().unwrap();
let main =
add(&mut s, page, NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "CAFÉ [Button]");
let original = add(&mut s, main, NodeKind::Text(TextData::new("Original")), "Original");
let original = add(&mut s, main, NodeKind::Text(TextData::new("Original").into()), "Original");
let inst = idv(&ex(&mut s, "instance.create", json!({"component": main})));
let child = s.doc().unwrap().get(inst).unwrap().children[0];
ex(&mut s, "node.set", json!({"ids": [inst], "props": {"name": "Copy"}}));
@@ -142,7 +142,7 @@ fn node_find_accepts_every_canonical_type() {
NodeKind::Star { count: 5, inner_ratio: 0.5 },
NodeKind::Line,
NodeKind::Vector { network: Default::default() },
NodeKind::Text(TextData::new("Text")),
NodeKind::Text(TextData::new("Text").into()),
NodeKind::BooleanOp { op: BoolOp::Union },
NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() },
NodeKind::ComponentSet { description: String::new() },
+1 -1
View File
@@ -98,7 +98,7 @@ fn missing_provider_fonts_stay_offline_and_text_stays_editable() {
let page = source.first_page().unwrap();
let mut text = figcraft_doc::TextData::new("Offline text");
text.style.font_family = "FigCraft Missing Provider Q7".into();
source.create(page, NodeKind::Text(text), "Label", 0.0, 0.0, 200.0, 30.0).unwrap();
source.create(page, NodeKind::Text(text.into()), "Label", 0.0, 0.0, 200.0, 30.0).unwrap();
let bytes = figcraft_format::penpot::export(&source).unwrap().0;
let data = base64::engine::general_purpose::STANDARD.encode(bytes);
for command in ["file.open", "file.import"] {
+138
View File
@@ -0,0 +1,138 @@
//! Camera raw files open, import and place as the picture they develop to; damaged ones are
//! errors. The raw files are DNGs written here from synthetic sensor data (craft-raw's writer).
use base64::Engine as _;
use craft_raw::opcodes::OpcodeLists;
use craft_raw::{BlackLevel, Cfa, ColorData, DngCompression, DngWriteOptions, Orientation, RawData, RawFormat, RawImage, Rect};
use serde_json::json;
use crate::Session;
/// Sensor columns a band of the scene covers.
const BAND: usize = 22;
const BLACK: f32 = 64.0;
const WHITE: f32 = 4095.0;
/// The camera's response to a neutral (`AsShotNeutral`): white balance multiplies red by 2 and blue by 1/0.7.
const NEUTRAL: [f64; 3] = [0.5, 1.0, 0.7];
/// A 3 × 22 by 48 RGGB raw, turned a quarter (Exif orientation 6), whose camera RGB is linear sRGB.
/// Its sensor columns hold three bands: a red, a mid grey, and a light that clips every channel.
fn dng() -> Vec<u8> {
let (w, h) = (3 * BAND, 48);
let cfa = Cfa::bayer("RGGB").unwrap();
let scene = |x: usize| match x / BAND {
0 => [0.40, 0.08, 0.06],
1 => [0.18, 0.18, 0.18],
_ => [4.0, 4.0, 4.0],
};
let data = (0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
let c = cfa.color_at(x, y) as usize;
let level = (scene(x)[c] * NEUTRAL[c] as f32).clamp(0.0, 1.0);
(BLACK + (WHITE - BLACK) * level).round() as u16
})
.collect();
// XYZ (D65) → linear sRGB (IEC 61966-2-1): this camera sees in sRGB primaries.
let xyz_to_camera = [[3.2404542, -1.5371385, -0.4985314], [-0.9692660, 1.8760108, 0.0415560], [0.0556434, -0.2040259, 1.0572252]];
let raw = RawImage {
format: RawFormat::Dng,
width: w,
height: h,
cpp: 1,
data: RawData::U16(data),
cfa: Some(cfa),
bits: 12,
black: BlackLevel::uniform(BLACK),
white: vec![WHITE],
active_area: Rect::new(0, 0, w, h),
crop: Rect::new(0, 0, w, h),
orientation: Orientation::Rotate90,
color: ColorData { illuminant: [21, 0], color_matrix: [Some(xyz_to_camera), None], as_shot_neutral: Some(NEUTRAL), ..Default::default() },
wb_multipliers: None,
linearized: true,
linearization_table: None,
pixel_aspect: 1.0,
opcodes: OpcodeLists::default(),
camera: Default::default(),
cinema: Default::default(),
lens_metadata: Default::default(),
level_sources: Default::default(),
notices: Default::default(),
};
let opts = DngWriteOptions { compression: DngCompression::Uncompressed, software: "figcraft tests".into(), ..Default::default() };
craft_raw::write_dng(&raw, &opts).unwrap()
}
fn import(s: &mut Session, bytes: &[u8], name: &str) -> crate::Result<serde_json::Value> {
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
s.execute("file.import", &json!({"data": b64, "name": name, "x": 0, "y": 0}))
}
/// The mean colour of the 5 × 5 pixels around (`x`, `y`) of the layer's image.
fn colour_at(s: &Session, id: figcraft_doc::NodeId, x: u32, y: u32) -> [i32; 3] {
let doc = s.doc().unwrap();
let hash = match &doc.node(id).unwrap().fills[0].kind {
figcraft_color::PaintKind::Image(paint) => paint.image.clone(),
other => panic!("not an image fill: {other:?}"),
};
let picture = image::load_from_memory(&doc.images[&hash].bytes).unwrap().to_rgb8();
let mut sum = [0i32; 3];
for dy in 0..5 {
for dx in 0..5 {
let p = picture.get_pixel(x + dx - 2, y + dy - 2);
for c in 0..3 {
sum[c] += i32::from(p[c]);
}
}
}
sum.map(|v| v / 25)
}
fn spread(c: [i32; 3]) -> i32 {
c.iter().max().unwrap() - c.iter().min().unwrap()
}
#[test]
fn camera_raw_files_import_and_open_as_their_developed_picture() {
let bytes = dng();
let mut s = Session::new();
let out = import(&mut s, &bytes, "shot.dng").unwrap();
let id = crate::params::id_of(&out["id"]).unwrap();
let n = s.doc().unwrap().node(id).unwrap();
// The orientation tag is applied: the sensor's columns run down the picture.
assert!(n.height > n.width, "{} x {}", n.width, n.height);
let x = n.width as u32 / 2;
let band = BAND as u32;
let (red, grey, light) = (colour_at(&s, id, x, band / 2), colour_at(&s, id, x, band * 3 / 2), colour_at(&s, id, x, band * 5 / 2));
// White balance and the colour matrix give back the scene: red stays red, grey stays neutral.
assert!(red[0] > red[1] + 60 && red[0] > red[2] + 60, "red band: {red:?}");
assert!(spread(grey) <= 8, "grey band: {grey:?}");
// Clipped channels are rebuilt: white balance alone would turn the clipped light magenta.
assert!(light.iter().all(|&c| c > grey[1]) && spread(light) <= 8, "clipped band: {light:?}, grey {grey:?}");
let path = std::env::temp_dir().join(format!("figcraft-raw-{}.dng", std::process::id()));
std::fs::write(&path, &bytes).unwrap();
let opened = s.execute("file.open", &json!({"path": path.to_string_lossy()}));
let _ = std::fs::remove_file(&path);
opened.unwrap();
assert_eq!(s.doc().unwrap().images.len(), 1);
}
#[test]
fn damaged_camera_raw_files_are_errors() {
let mut s = Session::new();
// A Panasonic RW2 header over junk: refused, saying why.
let mut junk = b"IIU\0\x08\0\0\0".to_vec();
junk.extend(std::iter::repeat_n(0x5a, 4096));
let err = import(&mut s, &junk, "shot.rw2").unwrap_err().to_string();
assert!(err.contains("camera raw"), "{err}");
// Cut short anywhere: refused or placed, never a panic, and the renderer copes with what was placed.
let bytes = dng();
for len in [12, 200, bytes.len() / 3, bytes.len() - 100] {
if let Ok(out) = import(&mut s, &bytes[..len], "shot.dng") {
let id = crate::params::id_of(&out["id"]).unwrap();
assert!(s.doc().unwrap().node(id).is_some());
}
}
}
+1 -1
View File
@@ -236,7 +236,7 @@ fn corner_smoothing_follows_the_documented_rules() {
(NodeKind::Star { count: 5, inner_ratio: 0.4 }, true, "stars"),
(
NodeKind::Vector {
network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true),
network: figcraft_doc::VectorNetwork::from_points(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true).into(),
},
true,
"vector networks that are closed shapes",
+11 -3
View File
@@ -345,10 +345,18 @@ impl Lives {
/// Start a session on the link for command `cmd`: `start` gets the link and the new
/// session's id, which comes back with what it returned.
fn start<T>(&mut self, cmd: &str, start: impl FnOnce(&mut dyn LiveLink, SessionId) -> Result<T>) -> Result<(SessionId, T)> {
fn start<T>(
&mut self,
cmd: &str,
join_link: Option<&str>,
start: impl FnOnce(&mut dyn LiveLink, SessionId) -> Result<T>,
) -> Result<(SessionId, T)> {
let link = self.link.as_deref_mut().ok_or_else(|| unavailable(cmd))?;
if let Some(why) = crate::file_access::network_refused() {
return Err(EngineError::Disabled(cmd.to_string(), why));
if let Some(roots) = crate::file_access::current() {
let allowed = cmd == "collab.join" && join_link.is_some_and(|invite| link.automation_join_allowed(invite, roots.allowed_servers()));
if !allowed {
return Err(EngineError::Disabled(cmd.to_string(), crate::file_access::NETWORK_REFUSED.into()));
}
}
let id = self.last.saturating_add(1);
let out = start(link, id)?;
+24 -3
View File
@@ -77,7 +77,8 @@ fn start_host(s: &mut Session, cmd: &str, p: &Value, bind: Bind, short: bool, vi
let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?;
check_sharable(cmd, &doc)?;
let opts = HostOptions { port, bind, name: display_name(&s.prefs), doc, short, view };
let (id, info) = s.live.start(cmd, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?;
let (id, info) =
s.live.start(cmd, None, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?;
s.live.open(Live { id, status: Status::Live, info: Some(info), doc_uid: Some(uid), tab: Some(uid), ..Live::default() });
Ok(id)
}
@@ -98,7 +99,7 @@ fn start_publish(s: &mut Session, cmd: &str, server: &str, p: &Value, share: boo
let name = string(p, "name").map(|n| n.trim().chars().filter(|c| !c.is_control()).take(256).collect::<String>()).filter(|n| !n.is_empty());
let me = display_name(&s.prefs);
let opts = PublishOptions { server: server.trim().to_string(), key, name: name.unwrap_or_else(|| doc.name.clone()), me, doc, share };
let (id, ()) = s.live.start(cmd, |l, id| l.publish(id, opts).map_err(|e| bad(cmd, e)))?;
let (id, ()) = s.live.start(cmd, None, |l, id| l.publish(id, opts).map_err(|e| bad(cmd, e)))?;
// This tab becomes the server file's synced document once it is there.
s.live.open(Live { id, status: Status::Connecting, doc_uid: Some(uid), tab: Some(uid), server: server.trim().to_string(), ..Live::default() });
Ok(id)
@@ -162,7 +163,13 @@ pub(super) fn share(s: &mut Session, p: &Value) -> Result<Value> {
if server.is_empty() {
return Err(EngineError::Disabled(CMD.into(), ONLINE_OFF.into()));
}
start_publish(s, CMD, &server, p, true)?
let id = start_publish(s, CMD, &server, p, true)?;
// A file published with the key has no owner token: stopping and sharing again go as
// the server's operator, with the key in the address as `collab.share {server}` takes it.
if let Some(key) = string(p, "key").map(|k| k.trim().to_string()).filter(|k| !k.is_empty()) {
server = with_key(&server, &key);
}
id
}
};
if let Some(live) = s.live.sessions.get_mut(&id) {
@@ -179,6 +186,20 @@ pub(super) fn share(s: &mut Session, p: &Value) -> Result<Value> {
Ok(s.live_summary())
}
/// `server` with `key` in its query (`?key=…`), escaped so any key reads back the same. It replaces
/// a key the address carries: the one given is the one the file was published with.
fn with_key(server: &str, key: &str) -> String {
let escaped: String = key
.bytes()
.map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { char::from(b).to_string() } else { format!("%{b:02X}") })
.collect();
let (base, query) = server.split_once('?').unwrap_or((server, ""));
let mut pairs: Vec<&str> = query.split('&').filter(|p| !p.is_empty() && p.split('=').next() != Some("key")).collect();
let key = format!("key={escaped}");
pairs.push(&key);
format!("{base}?{}", pairs.join("&"))
}
/// A way into a session this app hosts: its invite link and the join code that stands for it
/// (none when the link can't be put in one: a host without an IPv4 address).
fn local_link(link: &str) -> SharedLink {
+2 -2
View File
@@ -27,7 +27,7 @@ pub(crate) fn start_join(
resume: Option<Resume>,
) -> Result<SessionId> {
let (name, tab) = (display_name(&s.prefs), s.tab());
let (id, ()) = s.live.start(cmd, |l, id| l.join_resuming(id, link, &name, resume).map_err(|e| bad(cmd, e)))?;
let (id, ()) = s.live.start(cmd, Some(link), |l, id| l.join_resuming(id, link, &name, resume).map_err(|e| bad(cmd, e)))?;
let server = share.as_ref().map(|s| s.server.clone()).unwrap_or_default();
// The session's file opens in a tab of its own; until then the join shows on this one.
s.live.open(Live { id, status: Status::Connecting, tab, server, published, share, ..Live::default() });
@@ -201,7 +201,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"collab.share",
"Share with a join code",
"{via?: \"online\" (default: the open file is kept on the server in Preferences, `pref.publishServer`, and the server hands out the codes) | \"local\" (this app hosts it for people on the same network; no server), access?: \"edit\" (default) | \"comment\" (online only: view and comment, not edit) | \"view\" (look only: their edits are refused): which code `code` is, server? (online: another server's address, with ?key=… when it needs its key), key? (online: the server's key, when the address has none), name? (online: the file's name there), port?, bind?: \"lan\" (default) | \"local\" (this machine only) | an IP address (local)} → the open file's session as `collab.peers` gives it: `code` is what others type to join (`collab.join {code}`, the Join field), `link` the invite link to give with it and `url` its WebSocket URL (local: the ones that go with `code`, so a view-only code's link and URL let people look only; online: your own link to the file, which edits: `share` has the link that goes with each code). Local: at once, the code carries the host's IPv4 address, port and secret (K7M2Q-…, 20 symbols), and `share` is {via, access, shared, editCode, viewCode, editLink, viewLink}: the edit and view-only ways in, each with its own secret (commentCode and commentLink null). Online: status \"connecting\" first; once live `code` is the server's (K7M-2QX-9TD) and `share` is {via, access, shared, editCode, viewCode, commentCode, editLink, viewLink, commentLink}: links made for others (commentCode and commentLink null from a server older than comment links) (the file's own links in `published` stay yours); `code` stays null when the server is older than join codes (give `share.editLink` / `share.viewLink` instead). Called again while shared: only switches which code `code` is (`access`). Called after `collab.stop` on a file that is still on the server: new links and codes for that same file (nothing is published twice). `collab.stop` stops sharing",
"{via?: \"online\" (default: the open file is kept on the server in Preferences, `pref.publishServer`, and the server hands out the codes) | \"local\" (this app hosts it for people on the same network; no server), access?: \"edit\" (default) | \"comment\" (online only: view and comment, not edit) | \"view\" (look only: their edits are refused): which code `code` is, server? (online: another server's address, with ?key=… when it needs its key), key? (online: the server's key, when the address has none; Stop sharing and sharing again in this session use it too, since such a file has no owner token), name? (online: the file's name there), port?, bind?: \"lan\" (default) | \"local\" (this machine only) | an IP address (local)} → the open file's session as `collab.peers` gives it: `code` is what others type to join (`collab.join {code}`, the Join field), `link` the invite link to give with it and `url` its WebSocket URL (local: the ones that go with `code`, so a view-only code's link and URL let people look only; online: your own link to the file, which edits: `share` has the link that goes with each code). Local: at once, the code carries the host's IPv4 address, port and secret (K7M2Q-…, 20 symbols), and `share` is {via, access, shared, editCode, viewCode, editLink, viewLink}: the edit and view-only ways in, each with its own secret (commentCode and commentLink null). Online: status \"connecting\" first; once live `code` is the server's (K7M-2QX-9TD) and `share` is {via, access, shared, editCode, viewCode, commentCode, editLink, viewLink, commentLink}: links made for others (commentCode and commentLink null from a server older than comment links) (the file's own links in `published` stay yours); `code` stays null when the server is older than join codes (give `share.editLink` / `share.viewLink` instead). Called again while shared: only switches which code `code` is (`access`). Called after `collab.stop` on a file that is still on the server: new links and codes for that same file (nothing is published twice). `collab.stop` stops sharing",
false,
share
),
+7
View File
@@ -446,6 +446,13 @@ pub trait LiveLink: Send {
fn can_host(&self) -> bool {
true
}
/// Whether `link` names a collaboration server in the automation allowlist.
///
/// Implementations must parse the invite and compare its endpoint; a string-prefix check
/// would let a crafted invite bypass the file/network boundary.
fn automation_join_allowed(&self, _link: &str, _allowed_servers: &[String]) -> bool {
false
}
/// Start hosting session `session` for `opts.doc`.
fn host(&mut self, session: SessionId, opts: HostOptions) -> std::result::Result<SessionInfo, String>;
/// Start joining the session behind an invite link, as session `session`. Errors are for
@@ -46,7 +46,7 @@ fn local_samples_wrap_at_their_saved_line_breaks() {
continue;
}
wrapped += usize::from(!saved.starts.is_empty());
let plain = figcraft_doc::TextData { saved_breaks: None, ..t.clone() };
let plain = figcraft_doc::TextData { saved_breaks: None, ..(**t).clone() };
let (own, hinted) = (soft_starts(&plain, n.width), soft_starts(t, n.width));
differed_before += usize::from(own != saved.starts);
if t.saved_breaks_for(n.width).is_none() {
File diff suppressed because it is too large. Load diff
+160
View File
@@ -304,6 +304,166 @@ fn variables_import_checks_what_it_reads() {
healthy(&s);
}
#[test]
fn text_styles_in_a_variables_json_are_checked_and_capped() {
let mut s = Session::new();
let mode = json!([{"modeId": "m", "name": "Mode 1"}]);
// Junk `textStyles` entries are skipped with a warning, never an internal error.
let empty = json!({"variableCollections": {}, "variables": {}});
for junk in
[json!(5), json!([3]), json!([{"name": 3}]), json!([{"name": "x", "style": "nope"}]), json!([{"name": "x", "style": {"font_size": "big"}}])]
{
let mut file = empty.clone();
file["textStyles"] = junk.clone();
match s.execute("variable.import", &json!({"variables": file})) {
Ok(r) => assert!(r["warnings"].to_string().contains("text style") || r["warnings"].to_string().contains("textStyles"), "{junk}: {r}"),
Err(e) => assert!(!matches!(e, crate::EngineError::Internal { .. }), "{junk}: {e}"),
}
}
let mut file = empty.clone();
file["textStyles"] = json!([{"name": "x", "style": {"font_size": "big"}}]);
let r = ex(&mut s, "variable.import", json!({"variables": file}));
assert!(r["warnings"].to_string().contains("text style `x`"), "{r}");
assert!(s.doc().unwrap().styles.is_empty(), "no junk style got in");
// A name is cut to 500 chars, a description to 10,000, and only the first 10,000 entries are read.
let mut file = empty.clone();
file["textStyles"] = json!([{"name": "n".repeat(100_000), "description": "d".repeat(100_000), "style": {}}]);
ex(&mut s, "variable.import", json!({"variables": file}));
let styles = &s.doc().unwrap().styles;
assert_eq!(styles.len(), 1);
assert!(styles[0].name.chars().count() <= 500 && styles[0].description.chars().count() <= 10_000, "{}", styles[0].name.len());
let mut file = empty.clone();
file["textStyles"] = Value::Array((0..10_050).map(|i| json!({"name": format!("s{i}"), "style": {}})).collect());
let r = ex(&mut s, "variable.import", json!({"variables": file}));
assert_eq!(r["styles"]["added"], 10_000, "{}", r["styles"]);
assert!(r["warnings"].to_string().contains("10000") || r["warnings"].to_string().contains("10,000"), "{}", r["warnings"]);
// A binding to a field the style lacks, or to a variable of another type, is dropped with a warning.
let mut t = Session::new();
let file = json!({
"meta": {"variableCollections": {"c": {"id": "c", "name": "T", "modes": mode}},
"variables": {"s": {"id": "s", "name": "s", "variableCollectionId": "c", "resolvedType": "STRING", "valuesByMode": {"m": "x"}}}},
"textStyles": [{"name": "t", "style": {}, "bound": {"fontSize": "s", "nope": "s"}}]
});
let r = ex(&mut t, "variable.import", json!({"variables": file}));
assert_eq!(r["styles"]["added"], 1, "{r}");
assert!(t.doc().unwrap().styles[0].bound.is_empty(), "{r}");
let w = r["warnings"].as_array().unwrap().iter().filter_map(|x| x.as_str()).filter(|x| x.contains("text style `t`")).collect::<Vec<_>>();
assert!(w.len() == 2 && w.iter().any(|x| x.contains("fontSize")) && w.iter().any(|x| x.contains("nope")), "{r}");
}
/// A file with a "Body" text style whose size, line height and style name follow variables.
fn body_session() -> Session {
let mut s = Session::new();
ex(&mut s, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]}));
ex(&mut s, "variable.create", json!({"collection": "Type", "name": "size", "type": "number", "value": 16}));
ex(&mut s, "variable.create", json!({"collection": "Type", "name": "lh", "type": "number", "value": 24}));
ex(&mut s, "variable.create", json!({"collection": "Type", "name": "face", "type": "string", "value": "Bold"}));
ex(
&mut s,
"style.create",
json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 12, "lineHeight": "150%", "paragraphSpacing": 8, "listStyle": "bulleted"}}),
);
for (field, v) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] {
ex(&mut s, "style.bind", json!({"style": "Body", "field": field, "variable": v}));
}
s
}
#[test]
fn variables_export_carries_text_styles_with_their_bindings() {
let mut s = body_session();
let out = ex(&mut s, "variable.export", json!({}));
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
let styles = file["textStyles"].as_array().unwrap();
assert_eq!(styles.len(), 1, "{file}");
assert_eq!(styles[0]["name"], "Body");
assert_eq!(styles[0]["style"]["font_size"], 16.0);
assert_eq!(styles[0]["style"]["font_style"], "Bold");
assert_eq!(styles[0]["paragraph"]["paragraph_spacing"], 8.0, "{file}");
assert_eq!(styles[0]["paragraph"]["list"], "bulleted", "{file}");
let mut keys: Vec<&str> = styles[0].as_object().unwrap().keys().map(String::as_str).collect();
keys.sort_unstable();
assert_eq!(keys, ["bound", "description", "id", "name", "paragraph", "style", "type"], "the entry's shape is public: {file}");
assert_eq!(styles[0], ex(&mut s, "style.list", json!({"type": "text"}))[0], "what style.list returns");
for field in ["fontSize", "lineHeight", "fontStyle"] {
let id = styles[0]["bound"][field].as_str().unwrap();
assert!(file["meta"]["variables"].get(id).is_some(), "{field} -> {id}");
}
let css = ex(&mut s, "variable.export", json!({"format": "css"}));
assert!(!css["text"].as_str().unwrap().contains("Body"), "{css}");
}
#[test]
fn text_styles_round_trip_through_variables_import() {
let mut s = body_session();
let out = ex(&mut s, "variable.export", json!({}));
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
let mut t = Session::new();
ex(&mut t, "variable.createCollection", json!({"name": "Type", "modes": ["Base"]}));
for (name, v) in [("gap", 4), ("pad", 6), ("lh", 30)] {
ex(&mut t, "variable.create", json!({"collection": "Type", "name": name, "type": "number", "value": v}));
}
let r = ex(&mut t, "variable.import", json!({"variables": file}));
assert_eq!(r["styles"], json!({"added": 1, "updated": 0}), "{r}");
assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");
let doc = t.doc().unwrap();
let body = doc.styles.iter().find(|x| x.name == "Body").unwrap();
let ids: Vec<&str> = body.bound.values().map(|v| v.as_str()).collect();
assert_eq!(body.bound.len(), 3, "{body:?}");
assert!(ids.iter().all(|i| doc.variables.get(i).is_some()), "bindings point at this file's variables");
for (field, name) in [("fontSize", "size"), ("lineHeight", "lh"), ("fontStyle", "face")] {
assert_eq!(doc.variables.get(&body.bound[field]).unwrap().name, name, "{field}");
}
let StyleKind::Text { paragraph, .. } = &body.kind else { panic!("{body:?}") };
assert_eq!((paragraph.paragraph_spacing, paragraph.list), (8.0, ListStyle::Bulleted));
let StyleKind::Text { style, .. } = &body.kind else { panic!("{body:?}") };
assert_eq!((style.font_style.as_str(), style.font_size), ("Bold", 16.0));
// Again: the style is updated, not duplicated.
let r = ex(&mut t, "variable.import", json!({"variables": file}));
assert_eq!(r["styles"], json!({"added": 0, "updated": 1}), "{r}");
assert_eq!(t.doc().unwrap().styles.len(), 1);
assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");
assert_eq!(t.doc().unwrap().styles[0].bound.len(), 3);
// A binding to a variable the JSON lacks is dropped with a warning naming the style.
let mut u = Session::new();
let mut lone = file.clone();
lone["meta"] = json!({"variableCollections": {}, "variables": {}});
let r = ex(&mut u, "variable.import", json!({"variables": lone}));
assert_eq!(r["styles"]["added"], 1, "{r}");
assert!(u.doc().unwrap().styles[0].bound.is_empty());
assert!(r["warnings"].to_string().contains("Body"), "{r}");
}
#[test]
fn a_files_own_export_leaves_its_text_styles_alone() {
let mut s = body_session();
ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}}));
ex(&mut s, "variable.createCollection", json!({"name": "Other", "modes": ["Base"]}));
ex(&mut s, "variable.create", json!({"collection": "Other", "name": "o", "type": "number", "value": 1}));
let out = ex(&mut s, "variable.export", json!({"collections": ["Other"]}));
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
let before = s.doc().unwrap().styles.clone();
assert_eq!(before.len(), 2);
let r = ex(&mut s, "variable.import", json!({"variables": file}));
assert_eq!(s.doc().unwrap().styles, before, "{r}");
assert_eq!(r["styles"], json!({"added": 0, "updated": 2}), "{r}");
assert!(!r["warnings"].to_string().contains("left unbound"), "{r}");
}
/// Two text styles share a name and are reordered after the export: re-importing it gives each
/// style its own values back (matched by the exported id), not its namesake's.
#[test]
fn a_files_own_export_keeps_each_same_named_style_after_a_reorder() {
let mut s = body_session();
ex(&mut s, "style.create", json!({"type": "text", "name": "Body", "value": {"fontFamily": "Inter", "fontSize": 20}}));
let out = ex(&mut s, "variable.export", json!({}));
let file: Value = serde_json::from_str(out["text"].as_str().unwrap()).unwrap();
s.doc_mut().unwrap().styles.reverse();
let before = s.doc().unwrap().styles.clone();
let r = ex(&mut s, "variable.import", json!({"variables": file}));
assert_eq!(s.doc().unwrap().styles, before, "{r}");
}
#[test]
fn variables_import_caps_the_file_it_reads() {
let dir = std::env::temp_dir().join(format!("figcraft-vars-io-cap-{}", std::process::id()));
+2 -2
View File
@@ -323,7 +323,7 @@ fn ex_to_vector(doc: &mut figcraft_doc::Document, id: NodeId) {
let (path, _) = figcraft_render::node_outline(doc, n).unwrap();
let mut network = VectorNetwork::from_path(&path);
network.regions[0].fills = Some(vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]);
doc.get_mut(id).unwrap().kind = NodeKind::Vector { network };
doc.get_mut(id).unwrap().kind = NodeKind::Vector { network: network.into() };
}
/// How far `path` strays from `from`: the largest distance from a point sampled along `path` to
@@ -365,7 +365,7 @@ fn simplify_keeps_nearly_collinear_points_near_them() {
{
let n = s.doc_mut().unwrap().get_mut(id).unwrap();
n.transform = figcraft_geom::Affine::IDENTITY;
n.kind = NodeKind::Vector { network };
n.kind = NodeKind::Vector { network: network.into() };
}
let before = net(&s, id);
ex(&mut s, "vector.simplify", json!({"ids": [id], "tolerance": 0.75}));
+3 -3
View File
@@ -16,7 +16,7 @@ fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
fn net(s: &Session, id: NodeId) -> VectorNetwork {
match &s.doc().unwrap().node(id).unwrap().kind {
NodeKind::Vector { network } => network.clone(),
NodeKind::Vector { network } => (**network).clone(),
other => panic!("not a vector: {other:?}"),
}
}
@@ -46,7 +46,7 @@ fn vector_layer(s: &mut Session, network: VectorNetwork) -> NodeId {
{
let doc = s.doc_mut().unwrap();
match &mut doc.get_mut(id).unwrap().kind {
NodeKind::Vector { network: net } => *net = network,
NodeKind::Vector { network: net } => *net = network.into(),
other => panic!("not a vector: {other:?}"),
}
}
@@ -183,7 +183,7 @@ fn the_rule_switches_every_area_or_only_the_one_asked_for() {
{
let doc = s.doc_mut().unwrap();
match &mut doc.get_mut(id).unwrap().kind {
NodeKind::Vector { network } => *network = two,
NodeKind::Vector { network } => *network = two.into(),
other => panic!("not a vector: {other:?}"),
}
}
+4
View File
@@ -27,6 +27,10 @@ craft-figcraft-format = { workspace = true }
craft-figma-rest = { workspace = true }
craft-jpeg = { workspace = true }
craft-image-codecs = { workspace = true }
craft-raw = { workspace = true }
craft-develop = { workspace = true }
craft-color-transform = { workspace = true }
craft-geom = { workspace = true }
[dev-dependencies]
zip = { workspace = true }
+2
View File
@@ -23,6 +23,8 @@ mod deep_import_tests;
mod expansion_cost_tests;
mod export;
#[cfg(test)]
mod export_slot_tests;
#[cfg(test)]
mod export_tests;
#[cfg(test)]
mod guides_tests;
+8 -8
View File
@@ -136,7 +136,7 @@ fn themed() -> Document {
],
);
});
add(&mut doc, frame, NodeKind::Text(TextData::new("Hello")), "Title", (10.0, 80.0), (60.0, 20.0), &|n| {
add(&mut doc, frame, NodeKind::Text(TextData::new("Hello").into()), "Title", (10.0, 80.0), (60.0, 20.0), &|n| {
n.fills = vec![solid(0.0, 0.0, 0.0)];
bind(
n,
@@ -218,7 +218,7 @@ fn same_after_round_trip(doc: &Document, what: &str) -> Vec<String> {
let mut styles = d.styles.clone();
for s in &mut styles {
// Held the way a layer's paints and text are.
let mut n = Node::new(NodeId(0), NodeKind::Text(TextData::new("")), "", 0.0, 0.0);
let mut n = Node::new(NodeId(0), NodeKind::Text(TextData::new("").into()), "", 0.0, 0.0);
match &mut s.kind {
StyleKind::Paint { paints } => {
n.fills = std::mem::take(paints);
@@ -231,8 +231,8 @@ fn same_after_round_trip(doc: &Document, what: &str) -> Vec<String> {
}
n.fills.clear();
normalize(&mut n, &|i| i);
if let NodeKind::Text(td) = n.kind {
*style = td.style;
if let NodeKind::Text(td) = &n.kind {
*style = td.style.clone();
}
}
_ => {}
@@ -466,7 +466,7 @@ fn styled() -> Document {
});
let mut td = TextData::new("Title");
td.style = heading;
add(&mut doc, frame, NodeKind::Text(td), "Title", (10.0, 80.0), (100.0, 32.0), &|n| {
add(&mut doc, frame, NodeKind::Text(td.into()), "Title", (10.0, 80.0), (100.0, 32.0), &|n| {
n.fills = vec![solid(0.0, 0.0, 0.0)];
n.styles.text = Some("s-text".into());
});
@@ -568,7 +568,7 @@ fn sized() -> (Document, [NodeId; 3]) {
add(&mut doc, main, NodeKind::Rectangle, "Box", (10.0, 10.0), (40.0, 40.0), &|n| {
n.constraints = Constraints { horizontal: HConstraint::Scale, vertical: VConstraint::Scale };
});
add(&mut doc, main, NodeKind::Text(TextData::new("Card")), "Label", (56.0, 20.0), (32.0, 16.0), &|_| {});
add(&mut doc, main, NodeKind::Text(TextData::new("Card").into()), "Label", (56.0, 20.0), (32.0, 16.0), &|_| {});
let mut g = Gen { r: Lcg(1), doc, image: String::new(), frames: Vec::new(), layers: Vec::new() };
let insts = [(); 3].map(|_| g.instance(main, page, BTreeMap::new()));
let mut doc = g.doc;
@@ -671,7 +671,7 @@ fn layers_bound_like_their_mains_are_no_overrides_in_another_mode() {
n.bound.insert("fill".into(), "v-bg".into());
},
);
add(&mut doc, main, NodeKind::Text(TextData::new("Chip")), "Chip label", (8.0, 6.0), (40.0, 16.0), &|n| {
add(&mut doc, main, NodeKind::Text(TextData::new("Chip").into()), "Chip label", (8.0, 6.0), (40.0, 16.0), &|n| {
n.fills = vec![solid(0.0, 0.0, 0.0)];
n.bound.insert("fill".into(), "v-fg".into());
});
@@ -1266,7 +1266,7 @@ fn checkbox_variable_and_conditional_actions_round_trip() {
let frame = doc.create(page, NodeKind::Frame, "Checkbox demo", 0.0, 0.0, 320.0, 180.0).unwrap();
let toggle = doc.create(frame, NodeKind::Frame, "Toggle checkbox", 24.0, 24.0, 44.0, 44.0).unwrap();
let mark = doc.create(toggle, NodeKind::Rectangle, "Checked indicator", 12.0, 12.0, 20.0, 20.0).unwrap();
let label = doc.create(frame, NodeKind::Text(TextData::new("Unchecked")), "Status", 84.0, 36.0, 120.0, 20.0).unwrap();
let label = doc.create(frame, NodeKind::Text(TextData::new("Unchecked").into()), "Status", 84.0, 36.0, 120.0, 20.0).unwrap();
doc.node_mut(mark).unwrap().bound.insert("visible".into(), "checked".into());
doc.node_mut(label).unwrap().bound.insert("characters".into(), "status".into());
let set_status = |value| Action::SetVariable { variable: "status".into(), value: json!(value), expr: None };
+2 -2
View File
@@ -574,7 +574,7 @@ fn a_jam_diamond_is_a_native_shape_drawn_by_figcraft() {
assert_eq!(frame.children.len(), 2, "the outline and the text: {warnings:?}");
let outline = doc.node(frame.children[0]).unwrap();
let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) };
assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(240.0, 240.0)));
assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(240.0, 240.0)).into());
assert_eq!(outline.fills[0].solid_color().unwrap().to_rgba8(), [255, 191, 64, 255]);
assert!(outline.child_layout.absolute);
assert_eq!(outline.constraints.horizontal, figcraft_doc::HConstraint::Scale);
@@ -596,7 +596,7 @@ fn a_jam_shape_past_the_size_cap_draws_its_outline_at_the_cap() {
assert_eq!((frame.width, frame.height), (1e6, 1e6));
let outline = doc.node(frame.children[0]).unwrap();
let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) };
assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(1e6, 1e6)));
assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(1e6, 1e6)).into());
}
/// 23 of FigJam's 30 shape kinds have a FigCraft outline; the other 7 stay frames and say which.
+41 -8
View File
@@ -14,7 +14,7 @@
//! through our own importer are tested, and written files were opened in other software
//! (`docs/file-format-parity.md` says what was checked); other apps may not open every file.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use figcraft_doc::color::{BlendMode, Color, GradientKind, ImageScaleMode, Paint, PaintKind};
@@ -104,7 +104,7 @@ enum SourceDirectionality AUTO=0 LTR=1 RTL=2
enum DocumentColorProfile LEGACY=0 SRGB=1 DISPLAY_P3=2
enum EmojiImageSet APPLE=0 NOTO=1
enum MaskType ALPHA=0 OUTLINE=1 LUMINANCE=2
enum VariableResolvedDataType BOOLEAN=0 FLOAT=1 STRING=2 COLOR=4 SYMBOL_ID=6 TEXT_DATA=8
enum VariableResolvedDataType BOOLEAN=0 FLOAT=1 STRING=2 COLOR=4 SYMBOL_ID=6 TEXT_DATA=8 SLOT_CONTENT_ID=12
enum VectorMirror NONE=0 ANGLE=1 ANGLE_AND_LENGTH=2
enum BooleanOperation UNION=0 INTERSECT=1 SUBTRACT=2 XOR=3
enum LayoutGridType MIN=0 CENTER=1 STRETCH=2 MAX=3
@@ -112,9 +112,9 @@ enum LayoutGridPattern STRIPES=0 GRID=1
enum Axis X=0 Y=1
enum ImageType PNG=0 JPEG=1 SVG=2 PDF=3
enum ExportConstraintType CONTENT_SCALE=0 CONTENT_WIDTH=1 CONTENT_HEIGHT=2
enum ComponentPropType BOOL=0 TEXT=1 INSTANCE_SWAP=3 VARIANT=4
enum VariableField MISSING=0 CORNER_RADIUS=1 PARAGRAPH_SPACING=2 PARAGRAPH_INDENT=3 STROKE_WEIGHT=4 STACK_SPACING=5 STACK_PADDING_LEFT=6 STACK_PADDING_TOP=7 STACK_PADDING_RIGHT=8 STACK_PADDING_BOTTOM=9 VISIBLE=10 TEXT_DATA=11 WIDTH=12 HEIGHT=13 RECTANGLE_TOP_LEFT_CORNER_RADIUS=14 RECTANGLE_TOP_RIGHT_CORNER_RADIUS=15 RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS=16 RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS=17 BORDER_TOP_WEIGHT=18 BORDER_BOTTOM_WEIGHT=19 BORDER_LEFT_WEIGHT=20 BORDER_RIGHT_WEIGHT=21 STACK_COUNTER_SPACING=23 MIN_WIDTH=24 MAX_WIDTH=25 MIN_HEIGHT=26 MAX_HEIGHT=27 FONT_FAMILY=28 FONT_STYLE=29 OPACITY=31 FONT_SIZE=32 LETTER_SPACING=34 LINE_HEIGHT=36 OVERRIDDEN_SYMBOL_ID=37
enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 EXPRESSION=5 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13
enum ComponentPropType BOOL=0 TEXT=1 INSTANCE_SWAP=3 VARIANT=4 SLOT=7
enum VariableField MISSING=0 CORNER_RADIUS=1 PARAGRAPH_SPACING=2 PARAGRAPH_INDENT=3 STROKE_WEIGHT=4 STACK_SPACING=5 STACK_PADDING_LEFT=6 STACK_PADDING_TOP=7 STACK_PADDING_RIGHT=8 STACK_PADDING_BOTTOM=9 VISIBLE=10 TEXT_DATA=11 WIDTH=12 HEIGHT=13 RECTANGLE_TOP_LEFT_CORNER_RADIUS=14 RECTANGLE_TOP_RIGHT_CORNER_RADIUS=15 RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS=16 RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS=17 BORDER_TOP_WEIGHT=18 BORDER_BOTTOM_WEIGHT=19 BORDER_LEFT_WEIGHT=20 BORDER_RIGHT_WEIGHT=21 STACK_COUNTER_SPACING=23 MIN_WIDTH=24 MAX_WIDTH=25 MIN_HEIGHT=26 MAX_HEIGHT=27 FONT_FAMILY=28 FONT_STYLE=29 OPACITY=31 FONT_SIZE=32 LETTER_SPACING=34 LINE_HEIGHT=36 OVERRIDDEN_SYMBOL_ID=37 SLOT_CONTENT_ID=40
enum VariableDataType BOOLEAN=0 FLOAT=1 STRING=2 ALIAS=3 COLOR=4 EXPRESSION=5 SYMBOL_ID=7 TEXT_DATA=9 PROP_REF=13 SLOT_CONTENT_ID=18
enum VariableScope ALL_SCOPES=0 TEXT_CONTENT=1 CORNER_RADIUS=2 WIDTH_HEIGHT=3 GAP=4 ALL_FILLS=5 FRAME_FILL=6 SHAPE_FILL=7 TEXT_FILL=8 STROKE=9 STROKE_FLOAT=10 EFFECT_FLOAT=11 EFFECT_COLOR=12 OPACITY=13 FONT_STYLE=14 FONT_FAMILY=15 FONT_SIZE=16 LINE_HEIGHT=17 LETTER_SPACING=18 PARAGRAPH_SPACING=19 PARAGRAPH_INDENT=20
enum StyleType NONE=0 FILL=1 STROKE=2 TEXT=3 EFFECT=4 EXPORT=5 GRID=6
enum InteractionType ON_CLICK=0 DRAG=9 ON_HOVER=4 ON_PRESS=7 MOUSE_IN=2 MOUSE_OUT=3 MOUSE_DOWN=5 MOUSE_UP=6 AFTER_TIMEOUT=1 ON_KEY_DOWN=10
@@ -164,13 +164,14 @@ message ComponentPropValue bool boolValue=1, TextData textValue=2, GUID guidValu
message ComponentPropPreferredValues string[] stringValues=1
message ComponentPropDef GUID id=1, string name=2, ComponentPropValue initialValue=3, string sortPosition=4, GUID parentPropDefId=5, ComponentPropType type=6, ComponentPropPreferredValues preferredValues=8, VariableData varValue=9
message ComponentPropAssignment GUID defID=1, ComponentPropValue value=2, VariableData varValue=3
enum ComponentPropNodeField VISIBLE=0 TEXT_DATA=1 OVERRIDDEN_SYMBOL_ID=2
enum ComponentPropNodeField VISIBLE=0 TEXT_DATA=1 OVERRIDDEN_SYMBOL_ID=2 SLOT_CONTENT_ID=4
message ComponentPropRef GUID defID=2, ComponentPropNodeField componentPropNodeField=4
message VariantPropSpec GUID propDefId=1, string value=2
message StateGroupPropertyValueOrder string property=1, string[] values=2
message PropRefValue GUID defId=1
message SymbolId GUID guid=1
message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, Expression expressionValue=6, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13
message SlotContentId GUID guid=1
message VariableAnyValue bool boolValue=1, string textValue=2, float floatValue=3, VariableID alias=4, Color colorValue=5, Expression expressionValue=6, SymbolId symbolIdValue=8, TextData textDataValue=10, PropRefValue propRefValue=13, SlotContentId slotContentIdValue=18
enum ExpressionFunction ADDITION=0 SUBTRACTION=1 MULTIPLY=3 DIVIDE=4 EQUALS=5 NOT_EQUAL=6 LESS_THAN=7 LESS_THAN_OR_EQUAL=8 GREATER_THAN=9 GREATER_THAN_OR_EQUAL=10 AND=11 OR=12 NOT=13 VAR_MODE_LOOKUP=16 NEGATE=17
message Expression ExpressionFunction expressionFunction=1, VariableData[] expressionArguments=2
message VariableData VariableAnyValue value=1, VariableDataType dataType=2, VariableResolvedDataType resolvedDataType=3
@@ -196,7 +197,7 @@ message GridTrackSizingFunction GridTrackSizingType type=1, float value=2
message GridTrackSize GridTrackSizingFunction minSizing=1, GridTrackSizingFunction maxSizing=2
message GUIDGridTrackSizeMapEntry GUID id=1, GridTrackSize trackSize=2
message GUIDGridTrackSizeMap GUIDGridTrackSizeMapEntry[] entries=1
message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141, Guide[] guides=138
message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, TextPathStart textPathStart=432, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141, Guide[] guides=138, bool isSlotContent=495
struct Blob byte[] bytes
message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6
";
@@ -401,10 +402,31 @@ struct Overlay {
background: Option<Color>,
}
/// An instance's own slot content: a private `isSlotContent` frame on the hidden page, assigned
/// to the instance's SLOT property. Its layers are written below that frame instead of as
/// overrides of the main's layers.
#[derive(Clone)]
struct SlotContent {
/// Local id of the private frame's GUID (session [`LAYERS`]).
frame: u32,
/// The slot frame's own layers, in order.
content: Vec<NodeId>,
/// Local id of the SLOT definition's GUID (session [`AUX`]).
def: u32,
}
struct Exporter<'d> {
doc: &'d Document,
/// Layer → local id of its GUID (session [`LAYERS`]).
ids: BTreeMap<NodeId, u32>,
/// Highest local id handed out for a layer GUID, including private slot content.
next_layer: u32,
/// Slot frame of an instance whose content is its own → its private content frame.
slot_frames: BTreeMap<NodeId, SlotContent>,
/// Instance → the slot frames whose assignments it writes.
instance_slots: BTreeMap<NodeId, Vec<NodeId>>,
/// Layers written as private slot content (not as overrides of their main).
private_layers: BTreeSet<NodeId>,
nodes: Vec<Kv<'static>>,
/// Blob bytes → index (identical blobs are written once).
blobs: BTreeMap<Vec<u8>, u32>,
@@ -456,6 +478,10 @@ impl<'d> Exporter<'d> {
Self {
doc,
ids: BTreeMap::new(),
next_layer: 0,
slot_frames: BTreeMap::new(),
instance_slots: BTreeMap::new(),
private_layers: BTreeSet::new(),
nodes: Vec::new(),
blobs: BTreeMap::new(),
blob_bytes: 0,
@@ -505,6 +531,13 @@ impl<'d> Exporter<'d> {
self.aux
}
/// A fresh GUID for a layer written outside the document's tree (a private slot content frame
/// or one of the layers under it). `assign` hands out all of these before the asset nodes.
fn next_layer_local(&mut self) -> u32 {
self.next_layer = self.next_layer.saturating_add(1);
self.next_layer
}
fn guid_of(&self, id: NodeId) -> Option<Kv<'static>> {
self.ids.get(&id).map(|l| guid(LAYERS, *l))
}
+62 -7
View File
@@ -1,7 +1,7 @@
use super::common::{layout_grid, node_field, prop_type, resolved_type, scope_name, variant_pairs};
use super::{
AUX, Action, Affine, Bound, Color, Exporter, Fields, Kv, LAYERS, MAX_NODES, Node, NodeId, NodeKind, Overlay, OverlayPosition, Paint, StyleKind,
TextData, VariableValue, arr, b, color, e, fl, guid, matrix, o, position, root_fields, s, u, xy,
AUX, Action, Affine, Bound, Color, Exporter, Fields, Kv, LAYERS, MAX_NODES, Node, NodeId, NodeKind, Overlay, OverlayPosition, Paint, SlotContent,
StyleKind, TextData, VariableValue, arr, b, color, e, fl, guid, matrix, o, position, root_fields, s, u, xy,
};
impl<'d> Exporter<'d> {
@@ -73,8 +73,48 @@ impl<'d> Exporter<'d> {
}
}
}
// The page that holds styles and variables takes the next id, then their nodes.
let mut next = u32::try_from(self.ids.len() + 1).unwrap_or(u32::MAX);
self.next_layer = u32::try_from(self.ids.len()).unwrap_or(u32::MAX);
// An instance's own slot content is a private frame on the hidden page, named by the
// instance's SLOT property assignment. Reserve GUIDs for that frame and for the layers
// written under it: an instance's layers otherwise have none, since its main's stand in.
let slot_frames: Vec<NodeId> = doc
.ids()
.filter(|id| {
doc.node(*id).is_some_and(|n| {
n.overrides.contains("slot") && n.source.and_then(|s| doc.node(s)).and_then(|s| s.prop_refs.get("slot")).is_some()
})
})
.collect();
for id in slot_frames {
let Some(n) = doc.node(id) else { continue };
let Some(prop) = n.source.and_then(|s| doc.node(s)).and_then(|s| s.prop_refs.get("slot")).cloned() else { continue };
let Some(inst) = doc.ancestors(id).into_iter().find(|a| doc.node(*a).is_some_and(|x| matches!(x.kind, NodeKind::Instance { .. }))) else {
continue;
};
let Some(NodeKind::Instance { component, .. }) = doc.node(inst).map(|x| &x.kind) else { continue };
let Some(def) = self.def_for(*component, &prop, "SLOT") else {
self.warn("slot content without a matching slot property was left out");
continue;
};
let content: Vec<NodeId> = n.children.iter().copied().filter(|c| doc.node(*c).is_some_and(|x| x.source.is_none())).collect();
let mut pending = content.clone();
while let Some(c) = pending.pop() {
let Some(x) = doc.node(c) else { continue };
// Mirrored layers come from a main and are not written as private content.
if x.source.is_some() || !self.private_layers.insert(c) {
continue;
}
let local = self.next_layer_local();
self.ids.insert(c, local);
pending.extend(x.children.iter().copied());
}
let frame = self.next_layer_local();
self.slot_frames.insert(id, SlotContent { frame, content, def });
self.instance_slots.entry(inst).or_default().push(id);
}
// The page that holds styles, variables and private slot content takes the next id; its
// nodes start one after that page's own GUID.
let mut next = self.next_layer.saturating_add(1);
let mut node = || {
next = next.saturating_add(1);
next
@@ -104,10 +144,10 @@ impl<'d> Exporter<'d> {
/// collections and the variables, each a node of its own.
pub(super) fn assets(&mut self, pages: usize) {
let doc = self.doc;
if self.style_ids.is_empty() && self.set_ids.is_empty() {
if self.style_ids.is_empty() && self.set_ids.is_empty() && self.slot_frames.is_empty() {
return;
}
let page = u32::try_from(self.ids.len() + 1).unwrap_or(u32::MAX);
let page = self.next_layer.saturating_add(1);
let mut f: Fields = vec![
("guid", guid(LAYERS, page)),
("phase", e("CREATED")),
@@ -160,7 +200,7 @@ impl<'d> Exporter<'d> {
} else {
let mut sample = Node::new(NodeId(0), NodeKind::Rectangle, "", 0.0, 0.0);
if let StyleKind::Text { style, .. } = &st.kind {
sample.kind = NodeKind::Text(TextData { style: style.as_text_style(), ..TextData::new("Ag") });
sample.kind = NodeKind::Text((TextData { style: style.as_text_style(), ..TextData::new("Ag") }).into());
}
sample.bound.clone_from(&st.bound);
self.bound(&sample)
@@ -258,6 +298,21 @@ impl<'d> Exporter<'d> {
}
self.nodes.push(o(f));
}
// Private slot content frames, one per instance slot whose content is its own. Their layers
// are ordinary layers below the frame, using the GUIDs reserved in `assign`. A reader takes
// the frame's children through the instance's SLOT assignment, never as page layers.
let slots: Vec<_> = self.slot_frames.clone().into_iter().collect();
for (slot, info) in slots {
let mut f = head(info.frame, "FRAME", "Slot content");
f.extend(root_fields());
f.push(("isSlotContent", b(true)));
self.nodes.push(o(f));
let parent = doc.node(slot);
let frame_guid = guid(LAYERS, info.frame);
for (i, c) in info.content.iter().enumerate() {
self.emit(*c, frame_guid.clone(), i, parent, 1);
}
}
}
/// A reference to variable `var` (a stored id: no name stands in for it, #1613) as variable data.
+3 -2
View File
@@ -50,7 +50,7 @@ pub(super) fn outlined(n: &Node) -> Option<(Node, String)> {
r.winding = WindingRule::NonZero;
}
let mut v = n.clone();
v.kind = NodeKind::Vector { network };
v.kind = NodeKind::Vector { network: network.into() };
v.fills = std::mem::take(&mut v.strokes);
v.stroke = Default::default();
v.styles.fill = v.styles.stroke.take();
@@ -277,7 +277,8 @@ pub(super) fn prop_type(d: &PropDef) -> Option<&'static str> {
PropDef::Boolean { .. } => Some("BOOL"),
PropDef::Text { .. } => Some("TEXT"),
PropDef::InstanceSwap { .. } => Some("INSTANCE_SWAP"),
PropDef::Variant { .. } | PropDef::Slot { .. } => None,
PropDef::Slot { .. } => Some("SLOT"),
PropDef::Variant { .. } => None,
}
}
+46 -3
View File
@@ -2,7 +2,9 @@ use super::common::{
bool_data, changed, layout_grid, prop_type, resolved_alike, scaled, sort_position, symbol_data, text_data, text_value, var_data, variant_pairs,
};
use super::scale::main_equal_lengths;
use super::{AUX, BTreeMap, Bound, Exporter, Fields, Kv, MAX_NODES, Node, NodeId, NodeKind, PropDef, StyleKind, Value, arr, b, e, fl, guid, o, s};
use super::{
AUX, BTreeMap, Bound, Exporter, Fields, Kv, LAYERS, MAX_NODES, Node, NodeId, NodeKind, PropDef, StyleKind, Value, arr, b, e, fl, guid, o, s,
};
use super::{MAX_SCALE_FACTOR, MIN_SCALE_FACTOR};
/// A changed effect/grid style, and a payload only when it differs from that style's values.
@@ -47,7 +49,16 @@ impl<'d> Exporter<'d> {
let main = self.guid_of(*default)?;
(o(vec![("guidValue", main.clone())]), symbol_data(main))
}
PropDef::Variant { .. } | PropDef::Slot { .. } => return None,
// A slot has no scalar default: its content lives in a private frame assigned by each
// instance. `initialValue` and `varValue` stay empty, as readers of SLOT definitions do.
PropDef::Slot { preferred } => {
if !preferred.is_empty() {
self.warn("preferred components of slot properties were left out");
}
(o(Vec::new()), o(Vec::new()))
}
// A variant's definitions are written on its set (`set_props`), not on the variant.
PropDef::Variant { .. } => return None,
};
Some(o(vec![
("id", guid(AUX, id)),
@@ -134,6 +145,7 @@ impl<'d> Exporter<'d> {
"visible" => ("VISIBLE", "BOOL", "BOOLEAN"),
"characters" => ("TEXT_DATA", "TEXT", "TEXT_DATA"),
"mainComponent" => ("OVERRIDDEN_SYMBOL_ID", "INSTANCE_SWAP", "SYMBOL_ID"),
"slot" => ("SLOT_CONTENT_ID", "SLOT", "SLOT_CONTENT_ID"),
_ => {
self.warn("slot layers were written as plain layers");
return None;
@@ -189,6 +201,10 @@ impl<'d> Exporter<'d> {
let mut seen = 0usize;
while let Some((id, parent)) = stack.pop() {
let Some(d) = doc.node(id) else { continue };
// Layers written as private slot content are not overrides of the main's layers.
if self.private_layers.contains(&id) {
continue;
}
seen += 1;
if seen > MAX_NODES {
break;
@@ -203,6 +219,15 @@ impl<'d> Exporter<'d> {
let (mut mine, mut theirs) = (Vec::new(), Vec::new());
self.layer(d, doc.node(parent), &mut mine, true);
self.layer(src, src.parent.and_then(|p| doc.node(p)), &mut theirs, true);
// Property bindings belong to the main: an instance layer does not repeat them in the
// document. Inherit them for the diff, or `changed` writes an "unset" row for
// `parameterConsumptionMap` that clears the binding on import — including a slot's
// SLOT_CONTENT_ID reference, and with it the instance's own slot content.
for (k, v) in &theirs {
if matches!(*k, "parameterConsumptionMap" | "componentPropRefs") && !mine.iter().any(|(mk, _)| *mk == *k) {
mine.push((*k, v.clone()));
}
}
// A nested instance swapped for another component.
let swap = match (&d.kind, &src.kind) {
(NodeKind::Instance { component, .. }, NodeKind::Instance { component: was, .. }) if component == was => None,
@@ -296,10 +321,28 @@ impl<'d> Exporter<'d> {
assignments.push(o(vec![("defID", guid(AUX, id)), ("value", value), ("varValue", var)]));
}
}
// A slot whose content is this instance's own names the private frame that holds it. The
// frame's GUID was reserved in `assign`; the importer resolves the property definition
// (a variant's copy included) and expands the frame's layers into the instance's slot.
for slot in self.instance_slots.get(&n.id).cloned().unwrap_or_default() {
let Some(info) = self.slot_frames.get(&slot) else { continue };
assignments.push(o(vec![
("defID", guid(AUX, info.def)),
("value", o(Vec::new())),
(
"varValue",
o(vec![
("value", o(vec![("slotContentIdValue", o(vec![("guid", guid(LAYERS, info.frame))]))])),
("dataType", e("SLOT_CONTENT_ID")),
("resolvedDataType", e("SLOT_CONTENT_ID")),
]),
),
]));
}
if !assignments.is_empty() {
f.push(("componentPropAssignments", arr(assignments)));
}
if n.children.iter().filter_map(|c| doc.node(*c)).any(|c| c.source.is_none()) {
if n.children.iter().filter_map(|c| doc.node(*c)).any(|c| c.source.is_none() && !self.private_layers.contains(&c.id)) {
self.warn("instance layers that don't come from their main component were left out");
}
}
+9 -6
View File
@@ -1,8 +1,8 @@
use super::common::{export_setting, layout_grid, outlined, prop_type, variant_pairs};
use super::{
AUX, AutoLayout, BoolOp, Bound, ContentAlign, CrossAlign, Exporter, Fields, HConstraint, Kv, LAYERS, LayoutMode, MAX_DEPTH, MainAlign, MaskType,
Node, NodeId, NodeKind, PropDef, STASH, Sizing, TextData, TextStyle, VConstraint, WindingRule, arr, b, blend_name, color, e, fl, grid_sizing,
guid, int, matrix, o, position, root_fields, s, u, xy,
Node, NodeId, NodeKind, STASH, Sizing, VConstraint, WindingRule, arr, b, blend_name, color, e, fl, grid_sizing, guid, int, matrix, o, position,
root_fields, s, u, xy,
};
impl<'d> Exporter<'d> {
@@ -169,9 +169,6 @@ impl<'d> Exporter<'d> {
f.push(("componentPropDefs", arr(defs)));
}
}
if props.values().any(|d| matches!(d, PropDef::Slot { .. })) {
self.warn("slot properties were left out");
}
if !description.is_empty() {
f.push(("symbolDescription", s(description)));
}
@@ -222,7 +219,13 @@ impl<'d> Exporter<'d> {
// Text whose own style sets fills paints with them (the layer's fills only show through
// runs); a variable bound to the layer's fill colours the layer's.
let fills = match &n.kind {
NodeKind::Text(TextData { style: TextStyle { fills: Some(own), .. }, .. }) => self.paints(own, true, &Bound::default()),
NodeKind::Text(t) if t.style.fills.is_some() => {
if let Some(own) = &t.style.fills {
self.paints(own, true, &Bound::default())
} else {
self.paints(&n.fills, true, &bound)
}
}
_ => self.paints(&n.fills, true, &bound),
};
let strokes = self.paints(&n.strokes, false, &bound);
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more