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

This commit is contained in:
bflatastic committed 2026-11-28 17:03:08 +07:00
commit fd24ba3d55
156 files changed
+6225 -444

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]]
@@ -667,14 +682,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"
@@ -2560,6 +2673,7 @@ dependencies = [
"clap",
"clap_complete",
"clap_mangen",
"figcraft-collab-net",
"figcraft-doc",
"figcraft-engine",
"figcraft-format",
@@ -2642,6 +2756,7 @@ dependencies = [
"craft-docpath",
"craft-font-catalog",
"craft-font-store",
"craft-raw",
"deunicode",
"figcraft-collab",
"figcraft-color",
@@ -2672,12 +2787,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",
@@ -4100,6 +4219,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"
@@ -4334,6 +4629,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"
@@ -8084,7 +8389,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
@@ -380,6 +380,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. |
@@ -387,6 +388,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> {
+48 -10
View File
@@ -26,6 +26,12 @@ use crate::replica::{Positions, Replica};
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)
@@ -51,15 +57,14 @@ pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nod
return Err(Error::Decode(format!("delta snapshot truncated: header declared {declared} bytes, inflated {}", raw.len())));
}
let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR);
stream_decode_wire(&raw, max_nodes, max_materialized_bytes.min(cap))
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))
}
fn est_vector_bytes(net: &VectorNetwork) -> usize {
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>()));
@@ -83,7 +88,7 @@ fn est_kind_bytes(kind: &NodeKind) -> usize {
}
}
fn est_node_bytes(n: &Node) -> usize {
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())
@@ -101,11 +106,13 @@ fn est_node_bytes(n: &Node) -> usize {
.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))
}
fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize {
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(),
@@ -113,19 +120,51 @@ fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usiz
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::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m),
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<VectorNetwork>,
vectors: Vec<figcraft_doc::Shared<VectorNetwork>>,
vector_sizes: Vec<usize>,
node_sizes: HashMap<NodeId, usize>,
meta: Option<WireMeta>,
@@ -240,7 +279,7 @@ impl<'de> Visitor<'de> for VectorsSeed<'_> {
return Err(self.0.fail(err));
}
self.0.vector_sizes.push(size);
self.0.vectors.push(net);
self.0.vectors.push(figcraft_doc::Shared::new(net));
}
Ok(())
}
@@ -296,8 +335,7 @@ impl<'de> Visitor<'de> for DeltaWireSeed<'_> {
match key.as_str() {
"meta" => {
let meta: WireMeta = map.next_value()?;
let img_bytes = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.bytes.len()));
if let Err(err) = self.0.charge(img_bytes) {
if let Err(err) = self.0.charge(est_meta_bytes(&meta)) {
return Err(self.0.fail(err));
}
self.0.meta = Some(meta);
+46 -6
View File
@@ -6,8 +6,9 @@ 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::{DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord};
use super::{DEFAULT_MAX_MATERIALIZED_BYTES, DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord};
use crate::Error;
use crate::replica::Replica;
@@ -102,6 +103,9 @@ fn topo_order(doc: &Document) -> Vec<NodeId> {
}
/// 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);
@@ -118,8 +122,43 @@ pub fn encode_delta_snapshot(replica: &Replica) -> Result<Vec<u8>, Error> {
}
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 };
compress_wire(&wire)
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> {
@@ -143,7 +182,7 @@ fn encode_one_node(node: &Node, pos: String, seen: &HashMap<NodeId, &Node>, inte
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 = VectorNetwork::default();
*network = figcraft_doc::Shared::default();
Some(idx)
}
_ => None,
@@ -202,7 +241,7 @@ impl<W: Write> Write for CountingWriter<W> {
}
}
fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<Vec<u8>, Error> {
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);
@@ -213,10 +252,11 @@ fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<Vec<u8>, Error> {
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 len_u32 = u32::try_from(counting.written).map_err(|_| Error::TooLarge(u32::MAX as usize))?;
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)
Ok((out, written))
}
+4 -3
View File
@@ -11,7 +11,7 @@ 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, StrokeProps, StyleRefs, VariableId,
ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, Shared, StrokeProps, StyleRefs, VariableId,
VectorNetwork, Vertex,
};
use serde::{Deserialize, Serialize};
@@ -51,7 +51,7 @@ macro_rules! delta_fields {
)*
}
pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[VectorNetwork]) -> Result<(), Error> {
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) => {
@@ -278,7 +278,8 @@ fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool {
| (NodeKind::Group, NodeKind::Group)
| (NodeKind::Rectangle, NodeKind::Rectangle)
| (NodeKind::Line, NodeKind::Line) => true,
(NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => exact_vector_network_eq(na, nb),
(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),
}
}
+61 -3
View File
@@ -77,9 +77,9 @@ pub(crate) fn design_system_doc(num_instances: usize) -> (Document, NodeId, Vec<
let mut main_children = Vec::new();
for i in 0..6 {
let kind = match i {
0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}"))),
2 => NodeKind::Vector { network: icon_a.clone() },
3 => NodeKind::Vector { network: icon_b.clone() },
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();
@@ -348,3 +348,61 @@ fn delta_snapshot_never_panics_when_truncated_or_bit_flipped() {
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(_), .. }));
}
+9 -6
View File
@@ -427,12 +427,15 @@ impl Server {
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.
// If delta encoding ever fails, fall back to the legacy snapshot instead of refusing join.
_ if reads_delta && reads_design_review => match self.cached_delta_snapshot() {
Ok(bytes) => CatchUp::DeltaSnapshot(bytes),
Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
},
// 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
+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
@@ -28,3 +28,7 @@ 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 }
+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);
+265
View File
@@ -0,0 +1,265 @@
//! `.fig` export round trips of component properties, especially slots: the definitions on a
//! main, the property references on its layers, an instance's property values and the content its
//! slots hold. These are the fields a `.fig` written by the exporter is read back from.
use std::collections::BTreeMap;
use figcraft_doc::{Document, NodeId, NodeKind, PropDef, TextData};
use serde_json::Value;
use super::kiwi::Kv;
use super::{Archive, decode_canvas, export, import};
/// A copy of `src` below `parent`, linked back to it as an instance's expanded layer.
fn mirror(doc: &mut Document, src: NodeId, parent: NodeId) -> NodeId {
let mut n = doc.node(src).unwrap().clone();
let kids = std::mem::take(&mut n.children);
n.id = doc.alloc_id();
n.source = Some(src);
let id = doc.insert(n, parent, None).unwrap();
for k in kids {
mirror(doc, k, id);
}
id
}
/// A "Card" main with a text, a boolean and a slot property. Its slot has default content; the
/// instance overrides every property. With `own_slot`, it also puts its own content in the slot.
fn slots_document_with(own_slot: bool) -> Document {
let mut doc = Document::new("Slots");
let page = doc.first_page().unwrap();
let props = BTreeMap::from([
("Label".to_string(), PropDef::Text { default: "Title".into() }),
("Visible".to_string(), PropDef::Boolean { default: true }),
("Content".to_string(), PropDef::Slot { preferred: Vec::new() }),
]);
let main =
doc.create(page, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, "Card", 0.0, 0.0, 300.0, 160.0).unwrap();
let label = doc.create(main, NodeKind::Text(TextData::new("Title").into()), "Label", 0.0, 0.0, 200.0, 20.0).unwrap();
doc.node_mut(label).unwrap().prop_refs.insert("characters".into(), "Label".into());
let slot = doc.create(main, NodeKind::Frame, "Content", 0.0, 30.0, 280.0, 100.0).unwrap();
doc.node_mut(slot).unwrap().prop_refs.insert("slot".into(), "Content".into());
doc.create(slot, NodeKind::Rectangle, "Default", 0.0, 0.0, 40.0, 20.0).unwrap();
let id = doc.alloc_id();
let mut inst = doc.node(main).unwrap().clone();
let inst_props = BTreeMap::from([("Label".to_string(), Value::String("Hi".into())), ("Visible".to_string(), Value::Bool(false))]);
(inst.id, inst.kind, inst.name, inst.parent, inst.source) =
(id, NodeKind::Instance { component: main, props: inst_props }, "Card".into(), None, None);
inst.children.clear();
doc.insert(inst, page, None).unwrap();
let mirrored: Vec<_> = doc.node(main).unwrap().children.clone();
for k in mirrored {
let m = mirror(&mut doc, k, id);
let is_slot = doc.node(m).unwrap().prop_refs.contains_key("slot");
let is_text = matches!(doc.node(m).unwrap().kind, NodeKind::Text(_));
let n = doc.node_mut(m).unwrap();
if is_text {
if let NodeKind::Text(td) = &mut n.kind {
td.characters = "Hi".into();
}
n.overrides.insert("characters".into());
}
// The slot keeps its own content instead of the main's default.
if own_slot && is_slot {
n.prop_refs.clear();
n.overrides.insert("slot".into());
n.children.clear();
doc.create(m, NodeKind::Text(TextData::new("Own").into()), "Own", 0.0, 0.0, 100.0, 20.0).unwrap();
}
}
doc
}
fn slots_document() -> Document {
slots_document_with(true)
}
fn names(doc: &Document, id: NodeId) -> Vec<String> {
doc.node(id).unwrap().children.iter().map(|c| doc.node(*c).unwrap().name.clone()).collect()
}
fn instance_slot(doc: &Document) -> &figcraft_doc::Node {
let inst = doc.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap();
inst.children.iter().filter_map(|c| doc.node(*c)).find(|n| n.name == "Content").unwrap()
}
/// A component set whose variants share a slot property, with an instance of the large variant
/// putting its own content in that slot.
fn set_slots_document() -> Document {
let mut doc = Document::new("Set slots");
let page = doc.first_page().unwrap();
let set = doc.create(page, NodeKind::ComponentSet { description: String::new() }, "Panel", 0.0, 0.0, 300.0, 100.0).unwrap();
let mut variants = Vec::new();
for (i, name) in ["Size=Small", "Size=Large"].into_iter().enumerate() {
let props = BTreeMap::from([("Content".to_string(), PropDef::Slot { preferred: Vec::new() })]);
let v = doc
.create(set, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, name, 0.0, 60.0 * i as f64, 100.0, 100.0)
.unwrap();
let slot = doc.create(v, NodeKind::Frame, "Content", 0.0, 0.0, 90.0, 60.0).unwrap();
doc.node_mut(slot).unwrap().prop_refs.insert("slot".into(), "Content".into());
variants.push(v);
}
let large = variants[1];
let id = doc.alloc_id();
let mut inst = doc.node(large).unwrap().clone();
(inst.id, inst.kind, inst.name, inst.parent, inst.source) =
(id, NodeKind::Instance { component: large, props: BTreeMap::new() }, "Panel".into(), None, None);
inst.children.clear();
doc.insert(inst, page, None).unwrap();
for k in doc.node(large).unwrap().children.clone() {
mirror(&mut doc, k, id);
}
let slot = doc.node(id).unwrap().children[0];
let n = doc.node_mut(slot).unwrap();
n.prop_refs.clear();
n.overrides.insert("slot".into());
n.children.clear();
doc.create(slot, NodeKind::Text(TextData::new("Mine").into()), "Mine", 0.0, 0.0, 80.0, 20.0).unwrap();
doc
}
/// The written message carries the SLOT definition, the main layer's SLOT_CONTENT_ID reference,
/// the instance's assignment and its private slot content frame — with the field ids of the real
/// format. No override row may unset the main's bindings.
#[test]
fn slot_fields_are_written_to_the_kiwi_message() {
let doc = slots_document();
let (bytes, _) = export(&doc, None).unwrap();
let archive = Archive::open(&bytes).unwrap();
let (schema, message) = decode_canvas(&archive.canvas).unwrap();
let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap();
let changes = msg.get("nodeChanges").unwrap().list();
let main = changes.iter().find(|n| n.get("type").and_then(Kv::str) == Some("SYMBOL")).unwrap();
let defs = main.get("componentPropDefs").unwrap().list();
assert_eq!(defs.iter().filter(|d| d.get("type").and_then(Kv::str) == Some("SLOT")).count(), 1);
let slot_frame = changes.iter().find(|n| n.get("name").and_then(Kv::str) == Some("Content")).unwrap();
let entries = slot_frame.get("parameterConsumptionMap").unwrap().get("entries").unwrap().list();
assert!(entries.iter().any(|e| e.get("variableField").and_then(Kv::str) == Some("SLOT_CONTENT_ID")));
let inst = changes.iter().find(|n| n.get("type").and_then(Kv::str) == Some("INSTANCE")).unwrap();
let assignments = inst.get("componentPropAssignments").unwrap().list();
assert!(assignments.iter().any(|a| a.get("varValue").and_then(|v| v.get("dataType")).and_then(Kv::str) == Some("SLOT_CONTENT_ID")));
assert!(changes.iter().any(|n| n.get("isSlotContent").and_then(Kv::bool) == Some(true)));
// An "unset" row for parameterConsumptionMap would clear the main's binding on import.
let overrides = inst.get("symbolData").unwrap().get("symbolOverrides").unwrap().list();
assert!(!overrides.iter().any(|o| o.get("parameterConsumptionMap").is_some()), "instance rows must inherit the main's property bindings");
}
#[test]
fn component_properties_and_slot_content_round_trip() {
let doc = slots_document();
let (bytes, warnings) = export(&doc, None).unwrap();
let (back, _) = import(&bytes, "Slots").unwrap();
// The main keeps all three definitions, its text binding and its slot binding.
let main = back.nodes().find(|n| matches!(n.kind, NodeKind::Component { .. })).unwrap();
let NodeKind::Component { props, .. } = &main.kind else { panic!("not a component") };
assert_eq!(props.get("Label"), Some(&PropDef::Text { default: "Title".into() }), "{props:?}");
assert_eq!(props.get("Visible"), Some(&PropDef::Boolean { default: true }), "{props:?}");
assert!(matches!(props.get("Content"), Some(PropDef::Slot { .. })), "the slot definition came back: {props:?}");
let main_slot = main.children.iter().filter_map(|c| back.node(*c)).find(|n| n.prop_refs.contains_key("slot")).unwrap();
assert_eq!(main_slot.prop_refs.get("slot").map(String::as_str), Some("Content"));
assert_eq!(names(&back, main_slot.id), ["Default"]);
// The instance's own values, its slot override and the content it holds.
let inst = back.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap();
let NodeKind::Instance { props, .. } = &inst.kind else { panic!("not an instance") };
assert_eq!(props.get("Label"), Some(&Value::String("Hi".into())), "{props:?}");
assert_eq!(props.get("Visible"), Some(&Value::Bool(false)), "{props:?}");
let slot = inst.children.iter().filter_map(|c| back.node(*c)).find(|n| n.overrides.contains("slot")).unwrap();
assert_eq!(names(&back, slot.id), ["Own"], "the instance's slot content came back");
assert!(!warnings.iter().any(|w| w.contains("slot")), "slots should be written, not warned about: {warnings:?}");
}
/// A synced instance keeps no property references on its expanded layers at all. The exporter
/// must not turn that into "unset" rows, which used to clear every binding (slots included).
#[test]
fn instance_layers_inherit_their_mains_property_bindings() {
let mut doc = slots_document();
for id in doc.ids().collect::<Vec<_>>() {
if let Some(n) = doc.node_mut(id)
&& n.source.is_some()
{
n.prop_refs.clear();
}
}
let (bytes, warnings) = export(&doc, None).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
let (back, _) = import(&bytes, "Slots").unwrap();
let labels: Vec<_> = back.nodes().filter(|n| n.name == "Label").collect();
assert_eq!(labels.len(), 2, "the main's and the instance's label");
assert!(labels.iter().all(|n| n.prop_refs.get("characters").map(String::as_str) == Some("Label")), "both keep the text binding");
let inst = back.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap();
let slot = inst.children.iter().filter_map(|c| back.node(*c)).find(|n| n.overrides.contains("slot")).unwrap();
assert_eq!(names(&back, slot.id), ["Own"]);
}
/// An instance that doesn't assign its slot keeps the main's default content: no private frame,
/// no assignment, and no override of the slot.
#[test]
fn unassigned_slot_keeps_the_mains_default_content() {
let doc = slots_document_with(false);
let (bytes, warnings) = export(&doc, None).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
let archive = Archive::open(&bytes).unwrap();
let (schema, message) = decode_canvas(&archive.canvas).unwrap();
let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap();
let changes = msg.get("nodeChanges").unwrap().list();
let inst = changes.iter().find(|n| n.get("type").and_then(Kv::str) == Some("INSTANCE")).unwrap();
assert!(
!inst.get("componentPropAssignments").map(Kv::list).unwrap_or_default().iter().any(|a| a
.get("varValue")
.and_then(|v| v.get("dataType"))
.and_then(Kv::str)
== Some("SLOT_CONTENT_ID"))
);
assert!(!changes.iter().any(|n| n.get("isSlotContent").and_then(Kv::bool) == Some(true)));
let (back, _) = import(&bytes, "Slots").unwrap();
let slot = instance_slot(&back);
assert!(!slot.overrides.contains("slot"));
assert_eq!(names(&back, slot.id), ["Default"]);
}
/// Variants share their set's slot property: each variant's layer names its own copy of the
/// definition, and an instance of one variant still gets its own slot content.
#[test]
fn a_variants_slot_property_and_content_round_trip() {
let doc = set_slots_document();
let (bytes, warnings) = export(&doc, None).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
let (back, _) = import(&bytes, "Set slots").unwrap();
for name in ["Size=Small", "Size=Large"] {
let v = back.nodes().find(|n| n.name == name).unwrap();
let NodeKind::Component { props, .. } = &v.kind else { panic!("{name} is a component") };
assert!(matches!(props.get("Content"), Some(PropDef::Slot { .. })), "{name}: {props:?}");
let slot = v.children.iter().filter_map(|c| back.node(*c)).find(|n| n.prop_refs.contains_key("slot")).unwrap();
assert_eq!(slot.prop_refs.get("slot").map(String::as_str), Some("Content"), "{name}");
}
let inst = back.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap();
let slot = inst.children.iter().filter_map(|c| back.node(*c)).find(|n| n.overrides.contains("slot")).unwrap();
assert_eq!(names(&back, slot.id), ["Mine"]);
}
/// Preferred slot components have no public field in the format, so they are dropped — but not
/// silently: the exporter warns, the way it does for an instance swap's preferred values.
#[test]
fn preferred_slot_components_are_left_out_with_a_warning() {
const WARN: &str = "preferred components of slot properties were left out";
let plain = slots_document();
let (_, warnings) = export(&plain, None).unwrap();
assert!(!warnings.iter().any(|w| w == WARN), "no preferred components: {warnings:?}");
let mut doc = slots_document();
let main = doc.nodes().find(|n| matches!(n.kind, NodeKind::Component { .. })).unwrap().id;
let preferred = doc.alloc_id();
let NodeKind::Component { props, .. } = &mut doc.node_mut(main).unwrap().kind else { panic!("not a component") };
props.insert("Content".to_string(), PropDef::Slot { preferred: vec![preferred] });
let (_, warnings) = export(&doc, None).unwrap();
assert!(warnings.iter().any(|w| w == WARN), "preferred components were dropped without a warning: {warnings:?}");
}
+10 -10
View File
@@ -331,10 +331,10 @@ impl Gen {
id
}
8 => {
let id = self.node(parent, NodeKind::Vector { network: VectorNetwork::default() }, "Vector");
let id = self.node(parent, NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector");
let n = self.doc.node_mut(id).unwrap();
let net = network(&mut self.r, n.width, n.height);
n.kind = NodeKind::Vector { network: net };
n.kind = NodeKind::Vector { network: net.into() };
if self.r.chance(40) {
(n.stroke.cap_start, n.stroke.cap_end) = (StrokeCap::None, StrokeCap::LineArrow);
}
@@ -342,7 +342,7 @@ impl Gen {
}
9 => {
let td = text_data(&mut self.r);
self.node(parent, NodeKind::Text(td), "Text")
self.node(parent, NodeKind::Text(td.into()), "Text")
}
10 if on_page => {
let id = self.doc.alloc_id();
@@ -412,7 +412,7 @@ impl Gen {
fn components(&mut self, page: NodeId) {
let comp = self.node(page, NodeKind::Component { description: "A button".into(), props: BTreeMap::new(), prop_order: Vec::new() }, "Button");
let icon = self.node(comp, NodeKind::Rectangle, "Icon");
let label = self.node(comp, NodeKind::Text(TextData::new("Label")), "Label");
let label = self.node(comp, NodeKind::Text(TextData::new("Label").into()), "Label");
{
let n = self.doc.node_mut(comp).unwrap();
if let NodeKind::Component { props, .. } = &mut n.kind {
@@ -855,10 +855,10 @@ fn vector_region_paints_round_trip() {
let gradient = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }));
two.regions[0].fills = Some(vec![half, gradient]);
two.regions[1].fills = Some(Vec::new());
let id = doc.create(page, NodeKind::Vector { network: two }, "Painted", 0.0, 0.0, 100.0, 100.0).unwrap();
let id = doc.create(page, NodeKind::Vector { network: two.into() }, "Painted", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)];
let inherit = VectorNetwork::from_points(&square, true);
let id2 = doc.create(page, NodeKind::Vector { network: inherit }, "Inherits", 0.0, 0.0, 100.0, 100.0).unwrap();
let id2 = doc.create(page, NodeKind::Vector { network: inherit.into() }, "Inherits", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id2).unwrap().fills = vec![Paint::solid(Color::BLACK)];
let (back, warnings) = round_trip(&doc, "region paints");
@@ -956,7 +956,7 @@ fn closed_vector_geometry_is_written_with_its_corner_smoothing() {
for (v, r) in network.vertices.iter_mut().zip([20.0, 0.0, 10.0, 0.0]) {
v.radius = r;
}
let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
let id = doc.create(page, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id).unwrap().strokes = vec![Paint::solid(Color::BLACK)];
// The vector's written fill and stroke outlines.
let outlines = |doc: &Document| -> Vec<Vec<u8>> {
@@ -999,7 +999,7 @@ fn sharp_points_on_a_rounded_vector_stay_sharp() {
for (v, r) in network.vertices.iter_mut().zip([8.0, 0.0, 8.0, 0.0]) {
v.radius = r;
}
let id = doc.create(page, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
let id = doc.create(page, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.node_mut(id).unwrap().corners.radii = [8.0; 4];
let (back, _) = round_trip(&doc, "sharp point");
let v = back.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).unwrap();
@@ -1474,7 +1474,7 @@ fn set_with_properties() -> (Document, NodeId) {
let v = doc
.create(set, NodeKind::Component { description: String::new(), props, prop_order: Vec::new() }, name, 0.0, 60.0 * i as f64, 120.0, 40.0)
.unwrap();
let label = doc.create(v, NodeKind::Text(TextData::new("Button")), "Label", 0.0, 0.0, 60.0, 20.0).unwrap();
let label = doc.create(v, NodeKind::Text(TextData::new("Button").into()), "Label", 0.0, 0.0, 60.0, 20.0).unwrap();
doc.node_mut(label).unwrap().prop_refs.insert("characters".into(), "Label".into());
// The icon is an instance placed in the variant: like the editor's, its `source` is its
// main, which the binding doesn't belong to.
@@ -1736,7 +1736,7 @@ fn text_with_thousands_of_distinct_styles_exports_in_linear_time() {
td.runs = (0..20_000)
.map(|i| StyleRun { start: i, end: i + 1, style: TextStyle { font_size: 8.0 + i as f64 / 100.0, ..TextStyle::default() } })
.collect();
doc.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 100.0, 100.0).unwrap();
doc.create(p, NodeKind::Text(td.into()), "T", 0.0, 0.0, 100.0, 100.0).unwrap();
let start = std::time::Instant::now();
let (bytes, _) = export(&doc, None).unwrap();
assert!(!bytes.is_empty());
+1 -1
View File
@@ -34,7 +34,7 @@ fn sample() -> Document {
n.stroke.weight = 2.0;
n.stroke.align = StrokeAlign::Center;
});
add(&mut doc, frame, NodeKind::Text(TextData::new("One\nTwo")), "Text", 60.0, 40.0, &|_| {});
add(&mut doc, frame, NodeKind::Text(TextData::new("One\nTwo").into()), "Text", 60.0, 40.0, &|_| {});
doc
}
+1 -1
View File
@@ -77,7 +77,7 @@ fn the_export_writes_where_a_list_starts() {
let mut td = figcraft_doc::TextData::new("two\nthree\nplain\nsix\ndot");
let pl = |list, start_offset| ParaList { list, indent: 0, start_offset, ..ParaList::default() };
td.paragraphs = vec![pl(N, 1), pl(N, 0), pl(P, 0), pl(N, 5), pl(B, 4)];
doc.create(page, NodeKind::Text(td), "List", 0.0, 0.0, 200.0, 80.0).unwrap();
doc.create(page, NodeKind::Text(td.into()), "List", 0.0, 0.0, 200.0, 80.0).unwrap();
let (bytes, _) = super::super::export(&doc, None).unwrap();
let a = Archive::open(&bytes).unwrap();
let (schema, message) = decode_canvas(&a.canvas).unwrap();
+13 -5
View File
@@ -181,7 +181,7 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only
let mut skipped = text.style.clone();
skipped.set_look(|look| look.skip_ink = true);
text.runs = vec![StyleRun { start: 1, end: 3, style: skipped }];
doc.create(doc.first_page().unwrap(), NodeKind::Text(text), "Label", 0.0, 0.0, 100.0, 30.0).unwrap();
doc.create(doc.first_page().unwrap(), NodeKind::Text(text.into()), "Label", 0.0, 0.0, 100.0, 30.0).unwrap();
let (bytes, warnings) = export(&doc, None).unwrap();
assert!(warnings.is_empty(), "skip-ink is supported: {warnings:?}");
@@ -203,14 +203,14 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only
custom.style.set_look(|look| look.skip_ink = true);
custom.style.set_look(|look| look.thickness = figcraft_doc::DecorationLength::Pixels(2.0));
let mut custom_doc = Document::new("Unsupported decoration");
custom_doc.create(custom_doc.first_page().unwrap(), NodeKind::Text(custom), "Custom", 0.0, 0.0, 100.0, 30.0).unwrap();
custom_doc.create(custom_doc.first_page().unwrap(), NodeKind::Text(custom.into()), "Custom", 0.0, 0.0, 100.0, 30.0).unwrap();
let (_, warnings) = export(&custom_doc, None).unwrap();
assert!(warnings.iter().any(|w| w.contains("text decoration looks")), "custom look warning missing: {warnings:?}");
let mut variable = TextData::new("x");
variable.style.variations.insert("wght".into(), 400.0);
let mut variable_doc = Document::new("Variable font warning");
variable_doc.create(variable_doc.first_page().unwrap(), NodeKind::Text(variable), "Variable", 0.0, 0.0, 100.0, 30.0).unwrap();
variable_doc.create(variable_doc.first_page().unwrap(), NodeKind::Text(variable.into()), "Variable", 0.0, 0.0, 100.0, 30.0).unwrap();
let (_, warnings) = export(&variable_doc, None).unwrap();
assert!(warnings.iter().any(|w| w.contains("variable font settings")), "variation warning missing: {warnings:?}");
@@ -227,7 +227,15 @@ fn export_writes_one_actual_node_value_and_complete_run_values_without_skip_only
bound: Default::default(),
});
let id = linked_doc
.create(linked_doc.first_page().unwrap(), NodeKind::Text(TextData { style: local, ..TextData::new("x") }), "Label", 0.0, 0.0, 100.0, 30.0)
.create(
linked_doc.first_page().unwrap(),
NodeKind::Text((TextData { style: local, ..TextData::new("x") }).into()),
"Label",
0.0,
0.0,
100.0,
30.0,
)
.unwrap();
linked_doc.node_mut(id).unwrap().styles.text = Some("body".into());
let (bytes, warnings) = export(&linked_doc, None).unwrap();
@@ -259,7 +267,7 @@ fn skip_ink_without_an_underline_stays_out_of_the_look_and_exports_the_default()
// ...and default native text writes the default, which reads back as the default look.
let mut doc = Document::new("Plain");
doc.create(doc.first_page().unwrap(), NodeKind::Text(TextData::new("x")), "Label", 0.0, 0.0, 100.0, 30.0).unwrap();
doc.create(doc.first_page().unwrap(), NodeKind::Text(TextData::new("x").into()), "Label", 0.0, 0.0, 100.0, 30.0).unwrap();
let (bytes, _) = export(&doc, None).unwrap();
let archive = super::Archive::open(&bytes).unwrap();
let (schema, body) = super::decode_canvas(&archive.canvas).unwrap();
+4 -4
View File
@@ -26,7 +26,7 @@ fn large(screens: usize) -> Document {
32.0,
)
.unwrap();
let label = d.create(button, NodeKind::Text(TextData::new("OK")), "Label", 8.0, 8.0, 40.0, 16.0).unwrap();
let label = d.create(button, NodeKind::Text(TextData::new("OK").into()), "Label", 8.0, 8.0, 40.0, 16.0).unwrap();
d.get_mut(label).unwrap().plugin_data.insert("agent".into(), "note".into());
for s in 0..screens {
let screen = d.create(page, NodeKind::Frame, &format!("Screen {s}"), (s % 20) as f64 * 400.0, (s / 20) as f64 * 300.0, 360.0, 240.0).unwrap();
@@ -44,7 +44,7 @@ fn large(screens: usize) -> Document {
t.align_h = TextAlignH::Center;
t.paragraph_spacing = 4.0;
t.features.insert("liga".into(), false);
NodeKind::Text(t)
NodeKind::Text(t.into())
}
_ => NodeKind::Line,
};
@@ -86,7 +86,7 @@ fn large(screens: usize) -> Document {
n.source = Some(button);
n.overrides.insert("fills".into());
n.prop_refs.insert("visible".into(), "Show".into());
let l = d.create(inst, NodeKind::Text(TextData::new("Go")), "Label", 8.0, 8.0, 40.0, 16.0).unwrap();
let l = d.create(inst, NodeKind::Text(TextData::new("Go").into()), "Label", 8.0, 8.0, 40.0, 16.0).unwrap();
d.get_mut(l).unwrap().source = Some(label);
}
d
@@ -131,7 +131,7 @@ fn defaults_are_left_out_and_come_back() {
let mut d = Document::new("Defaults");
let p = d.first_page().unwrap();
let r = d.create(p, NodeKind::Rectangle, "Plain", 5.0, 0.0, 10.0, 10.0).unwrap();
let t = d.create(p, NodeKind::Text(TextData::new("Hi")), "Text", 0.0, 20.0, 10.0, 10.0).unwrap();
let t = d.create(p, NodeKind::Text(TextData::new("Hi").into()), "Text", 0.0, 20.0, 10.0, 10.0).unwrap();
let v = to_json(&d).unwrap();
let node = |id: figcraft_doc::NodeId| v["nodes"][id.0.to_string()].as_object().unwrap().clone();
let plain = node(r);
+18 -1
View File
@@ -21,6 +21,7 @@ pub mod fig;
pub mod jpeg;
pub mod library;
pub mod penpot;
pub mod raw;
pub mod rest;
pub mod sketch;
pub mod thumbnail;
@@ -174,14 +175,30 @@ fn stored_dimensions(bytes: &[u8]) -> Result<(u32, u32), craft_image_codecs::Cod
}
}
/// Register encoded image bytes with the document; returns the hash and pixel size.
/// Register encoded image bytes with the document; returns the hash and pixel size. A camera raw
/// file is developed first and the document keeps the developed picture (see [`raw`]).
pub fn add_image(doc: &mut Document, bytes: Vec<u8>) -> Result<(String, u32, u32), FormatError> {
let bytes = developed_if_raw(bytes)?;
let (w, h) = stored_dimensions(&bytes).map_err(|e| FormatError::Corrupt(format!("unsupported image: {e}")))?;
let hash = image_hash(&bytes);
doc.images.insert(hash.clone(), ImageData { bytes: Arc::new(bytes), width: w, height: h });
Ok((hash, w, h))
}
/// `bytes`, or the picture developed from them when they are a camera raw file. Camera makers
/// write raw files in TIFF containers, so a TIFF the raw reader claims but can't develop stays the
/// TIFF it is when it reads as one.
fn developed_if_raw(bytes: Vec<u8>) -> Result<Vec<u8>, FormatError> {
if !raw::is_camera_raw(&bytes) {
return Ok(bytes);
}
match raw::develop(&bytes) {
Ok(developed) => Ok(developed.bytes),
Err(_) if stored_dimensions(&bytes).is_ok() => Ok(bytes),
Err(e) => Err(e),
}
}
/// Image bytes with their pixel size (0×0 when they can't be decoded).
pub(crate) fn image_data(data: Vec<u8>) -> ImageData {
let (w, h) = stored_dimensions(&data).unwrap_or((0, 0));
+6 -4
View File
@@ -3015,7 +3015,9 @@ fn layer_kind(
// This parsing crate must not depend on the higher-level SVG/render crates.
"svg-raw" => NodeKind::Frame,
"circle" | "ellipse" => NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 },
"path" if v.get("content").and_then(Value::as_array).is_some_and(Vec::is_empty) => NodeKind::Vector { network: VectorNetwork::default() },
"path" if v.get("content").and_then(Value::as_array).is_some_and(Vec::is_empty) => {
NodeKind::Vector { network: VectorNetwork::default().into() }
}
"path" => match vector_bezpath(v, warnings) {
Some(path) => {
let local = shape_matrix(v, x, y, w, h).inverse() * Affine::translate((x, y)) * path;
@@ -3029,14 +3031,14 @@ fn layer_kind(
let local = Affine::translate(-origin.to_vec2()) * local;
let network = VectorNetwork::from_path(&local);
vector_source = Some(local);
NodeKind::Vector { network }
NodeKind::Vector { network: network.into() }
}
None => {
warn(warnings, "A Penpot path could not be decoded; kept as a frame".into());
NodeKind::Frame
}
},
"text" => NodeKind::Text(text_node(v)),
"text" => NodeKind::Text(text_node(v).into()),
other => {
warn(warnings, format!("Unsupported Penpot layer type '{other}': imported as frame"));
NodeKind::Frame
@@ -3363,7 +3365,7 @@ impl LayerImport<'_, '_> {
&& let Some(path) = vector_source
&& let Some(node) = self.doc.node_mut(created)
{
node.kind = NodeKind::Vector { network: filled_network(&path) };
node.kind = NodeKind::Vector { network: filled_network(&path).into() };
}
let svg = v.get("svgAttrs");
let fill_rule = svg.and_then(|a| a.get("style")).and_then(|s| string(s, "fillRule")).or_else(|| svg.and_then(|a| string(a, "fillRule")));
+4 -4
View File
@@ -153,7 +153,7 @@ fn rectangles_ellipses_and_paths_keep_their_geometry() {
add(&mut doc, p, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Circle", 0.0, 0.0, 30.0, 20.0);
add(&mut doc, p, NodeKind::Star { count: 5, inner_ratio: 0.4 }, "Star", 200.0, 0.0, 50.0, 50.0);
let network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(40.0, 30.0)], false);
let line = add(&mut doc, p, NodeKind::Vector { network }, "Open", 300.0, 0.0, 40.0, 30.0);
let line = add(&mut doc, p, NodeKind::Vector { network: network.into() }, "Open", 300.0, 0.0, 40.0, 30.0);
doc.node_mut(line).unwrap().strokes = vec![Paint::solid(Color::BLACK)];
let (back, e, _) = roundtrip(&doc);
@@ -185,7 +185,7 @@ fn stroked_closed_vectors_are_written_with_their_corner_smoothing() {
for v in &mut network.vertices {
v.radius = 20.0;
}
let id = add(&mut doc, p, NodeKind::Vector { network }, "Smoothed", 0.0, 0.0, 100.0, 100.0);
let id = add(&mut doc, p, NodeKind::Vector { network: network.into() }, "Smoothed", 0.0, 0.0, 100.0, 100.0);
{
let n = doc.node_mut(id).unwrap();
n.fills = vec![Paint::solid(Color::BLACK)];
@@ -266,7 +266,7 @@ fn open_path_caps_and_dotted_strokes_survive() {
let mut doc = Document::new("Caps");
let p = page(&doc);
let network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(50.0, 0.0)], false);
let id = add(&mut doc, p, NodeKind::Vector { network }, "Arrow", 0.0, 0.0, 50.0, 1.0);
let id = add(&mut doc, p, NodeKind::Vector { network: network.into() }, "Arrow", 0.0, 0.0, 50.0, 1.0);
{
let n = doc.node_mut(id).unwrap();
n.strokes = vec![Paint::solid(Color::BLACK)];
@@ -398,7 +398,7 @@ fn edited_text_is_rebuilt_with_runs_and_styles() {
bold.font_style = "Bold Italic".into();
bold.fills = Some(vec![Paint::solid(Color::from_hex("#ff0000").unwrap())]);
text.runs.push(StyleRun { start: 6, end: 10, style: bold });
let id = add(&mut doc, p, NodeKind::Text(text), "Copy", 0.0, 0.0, 200.0, 60.0);
let id = add(&mut doc, p, NodeKind::Text(text.into()), "Copy", 0.0, 0.0, 200.0, 60.0);
doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("#333333").unwrap())];
let (back, e, _) = roundtrip(&doc);
+158
View File
@@ -0,0 +1,158 @@
//! Camera raw files (Panasonic RW2, Canon CR2 / CR3, Nikon NEF, Sony ARW, Fujifilm RAF, Olympus
//! ORF, DNG and the other containers [`craft_raw`] decodes) as images.
//!
//! A raw file holds sensor samples, not a picture, so it is developed once, when it enters a
//! document, and the document keeps the result: a JPEG at quality 95 with full chroma resolution,
//! untagged and so read as sRGB. Drawing, export, collaboration and the browser build then see an
//! ordinary image; the raw file itself is not stored. (A PNG of the same picture is several times
//! larger, and every collaborator downloads the document's images.)
//!
//! The development is the camera's as-shot rendering at neutral settings, made of the shared
//! stages in `craft-develop`:
//!
//! 1. [`craft_raw::decode_with`]: black and white levels, the active area and default crop, the
//! file's own corrections as DNG opcodes (defect pixels, the in-camera distortion correction of
//! RW2 and NEF files).
//! 2. The demosaic (AHD) of the white-balanced mosaic, cropped and with the pixel aspect applied
//! ([`RawDevelopExt::develop_balanced_masked`]).
//! 3. Clipped highlights rebuilt from the channels that did not clip ([`highlight`]).
//! 4. The as-shot white balance and the camera's colour matrices to linear ITU-R BT.2020 (the DNG
//! colour model, DNG 1.7.1 chapter 6), raised by the file's baseline exposure.
//! 5. The generic tone curve on luminance ([`ToneMap::rolloff_hdr`] at neutral settings).
//! 6. BT.2020 to BT.709 primaries, colours outside them desaturated toward their luminance
//! ([`gamut_map`]), the sRGB transfer function (IEC 61966-2-1) and the file's orientation.
//!
//! Not applied: the look tables and tone curve of a camera profile that some DNGs carry, lens
//! corrections a file only records as metadata, noise reduction and sharpening.
use craft_color_transform::{Mat3, REC2020, SRGB};
use craft_develop::finish::gamut_map;
use craft_develop::raster::{Image, par_rows};
use craft_develop::sensor::{Method, RawDevelopExt, color, highlight};
use craft_develop::tone::ToneMap;
use crate::FormatError;
/// A normalised sensor sample (1 = the white level) at or above this counts as clipped.
const CLIP: f32 = 0.99;
/// The most samples a raw file may declare: the pixels of the largest image the renderer decodes
/// (512 MiB of RGBA), so a raw that develops is also one the canvas can draw.
const MAX_SAMPLES: usize = 1 << 27;
/// JPEG quality of the developed picture.
const QUALITY: u8 = 95;
/// Luminance weights of the BT.2020 primaries (ITU-R BT.2020, table 4).
const LUMA_2020: [f32; 3] = [0.2627, 0.6780, 0.0593];
/// Luminance weights of the BT.709 primaries (ITU-R BT.709, item 3.2).
const LUMA_709: [f32; 3] = [0.2126, 0.7152, 0.0722];
/// The file extensions of the raw containers [`craft_raw`] decodes, lower case. Opening goes by the
/// extension; whether the bytes are a raw file is still [`is_camera_raw`]'s to say.
pub const EXTENSIONS: [&str; 21] = [
"3fr", "arw", "cr2", "cr3", "crw", "dng", "erf", "fff", "mef", "mrw", "nef", "nrw", "orf", "pef", "raf", "raw", "rw2", "rwl", "sr2", "srf", "srw",
];
/// Whether `ext` (any case, without the dot) is one of [`EXTENSIONS`].
pub fn is_extension(ext: &str) -> bool {
EXTENSIONS.iter().any(|e| e.eq_ignore_ascii_case(ext))
}
/// Whether `bytes` are a camera raw file (decodable in this build or not).
pub fn is_camera_raw(bytes: &[u8]) -> bool {
craft_raw::probe(bytes).is_some()
}
/// A camera raw file developed into an image.
#[derive(Clone, Debug)]
pub struct Developed {
/// The picture, encoded.
pub bytes: Vec<u8>,
pub width: u32,
pub height: u32,
}
/// Develop the camera raw file `bytes` (see the module docs). An error names what stopped it: not
/// a raw file, a raw variant this build doesn't decode, or damaged data.
pub fn develop(bytes: &[u8]) -> Result<Developed, FormatError> {
let format = craft_raw::probe(bytes).ok_or_else(|| raw_error("not a camera raw file"))?;
if !format.is_supported() {
return Err(raw_error(format!("{format:?} files can't be read")));
}
let mut limits = craft_raw::Limits::default();
limits.max_samples = MAX_SAMPLES;
let raw = craft_raw::decode_with(bytes, &limits).map_err(|e| raw_error(e.to_string()))?;
let white = color::as_shot_white_xy(&raw);
let transform = color::camera_transform(&raw, white);
let wb = transform.wb;
let (mut picture, clipped) = raw.develop_balanced_masked(Method::Ahd, wb, CLIP).map_err(|e| raw_error(e.to_string()))?;
match clipped {
Some(mask) => highlight::reconstruct_masked(&mut picture, wb, CLIP, [1.0; 3], &mask),
None => highlight::reconstruct(&mut picture, wb, CLIP),
};
let gain = 2f64.powf(transform.baseline_exposure);
let gain = if gain.is_finite() { gain } else { 1.0 };
// White-balanced camera RGB → scene-linear BT.2020, the baseline exposure included.
let to_2020 = rows(&transform.matrix.mul(&Mat3::diag(f64::from(wb[0]) * gain, f64::from(wb[1]) * gain, f64::from(wb[2]) * gain)));
let to_709 = rows(&SRGB.from_xyz().mul(&REC2020.to_xyz()));
let tone = ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0);
let (width, height) = (picture.width, picture.height);
let mut rgb: Image<[u8; 3]> = Image::new(width, height);
let source = &picture.data;
par_rows(&mut rgb.data, width, |y, row| {
for (x, out) in row.iter_mut().enumerate() {
let scene = apply(&to_2020, source[y * width + x]);
let luminance = dot(LUMA_2020, scene);
let display = if luminance > 0.0 { scene.map(|c| c * tone.apply(luminance) / luminance) } else { [0.0; 3] };
let (linear, _) = gamut_map(apply(&to_709, display), LUMA_709);
*out = linear.map(encode_srgb);
}
});
drop(picture);
let rgb = rgb.into_oriented(craft_geom::Orientation::from_exif(raw.orientation.to_exif()));
let (width, height) = (u32::try_from(rgb.width).map_err(|_| too_large())?, u32::try_from(rgb.height).map_err(|_| too_large())?);
let image = craft_image_codecs::Image::from_u8(width, height, craft_image_codecs::ChannelLayout::Rgb, rgb.data.into_flattened())
.map_err(|e| raw_error(e.to_string()))?;
let options = craft_image_codecs::EncodeOptions {
jpeg_quality: QUALITY,
jpeg_chroma_subsampling: false,
embed_icc: false,
embed_metadata: false,
..Default::default()
};
let bytes = craft_image_codecs::encode(&image, craft_image_codecs::Format::Jpeg, &options).map_err(|e| raw_error(e.to_string()))?;
Ok(Developed { bytes, width, height })
}
fn raw_error(reason: impl std::fmt::Display) -> FormatError {
FormatError::Corrupt(format!("unsupported image: camera raw: {reason}"))
}
fn too_large() -> FormatError {
raw_error("the picture is too large")
}
fn rows(m: &Mat3) -> [[f32; 3]; 3] {
m.0.map(|row| row.map(|v| v as f32))
}
fn apply(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
m.map(|row| dot(row, v))
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
/// Linear `v` (0 to 1) as an 8-bit sRGB code (IEC 61966-2-1, the inverse of its equation 1).
fn encode_srgb(v: f32) -> u8 {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let e = if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
(e * 255.0 + 0.5) as u8
}
+6 -6
View File
@@ -628,13 +628,13 @@ impl<'a> Ctx<'a> {
}
}
// Point counts aren't part of the documented JSON: the outline is exact when present.
"REGULAR_POLYGON" | "STAR" if point_count().is_none() && has_geometry => NodeKind::Vector { network: VectorNetwork::default() },
"REGULAR_POLYGON" | "STAR" if point_count().is_none() && has_geometry => NodeKind::Vector { network: VectorNetwork::default().into() },
"REGULAR_POLYGON" => NodeKind::Polygon { count: point_count().unwrap_or_else(|| self.default_count(3)) },
"STAR" => NodeKind::Star {
count: point_count().unwrap_or_else(|| self.default_count(5)),
inner_ratio: num(j, "innerRadius").map_or(0.382, |r| r.clamp(0.01, 1.0)),
},
"VECTOR" => NodeKind::Vector { network: VectorNetwork::default() },
"VECTOR" => NodeKind::Vector { network: VectorNetwork::default().into() },
"BOOLEAN_OPERATION" => NodeKind::BooleanOp {
op: match text(j, "booleanOperation") {
Some("SUBTRACT") => BoolOp::Subtract,
@@ -643,7 +643,7 @@ impl<'a> Ctx<'a> {
_ => BoolOp::Union,
},
},
"TEXT" => NodeKind::Text(text::text_data(self, j)),
"TEXT" => NodeKind::Text(text::text_data(self, j).into()),
"COMPONENT" => NodeKind::Component { description: description(&self.component_meta, j), props: BTreeMap::new(), prop_order: Vec::new() },
"COMPONENT_SET" => NodeKind::ComponentSet { description: description(&self.set_meta, j) },
"SLICE" => NodeKind::Slice,
@@ -830,7 +830,7 @@ impl<'a> Ctx<'a> {
if let Some(net) = net {
match net {
Some(network) => {
n.kind = NodeKind::Vector { network };
n.kind = NodeKind::Vector { network: network.into() };
return false;
}
None => self.warn("invalid or oversized vector networks import as outlines"),
@@ -853,7 +853,7 @@ impl<'a> Ctx<'a> {
for r in &mut network.regions {
r.winding = winding;
}
n.kind = NodeKind::Vector { network };
n.kind = NodeKind::Vector { network: network.into() };
outline
}
@@ -963,7 +963,7 @@ impl<'a> Ctx<'a> {
"grid"
}
StyleKind::Text { .. } => {
sample.kind = NodeKind::Text(text::text_data(self, node));
sample.kind = NodeKind::Text(text::text_data(self, node).into());
"text"
}
};
@@ -17,11 +17,11 @@ fn cleared_range_hyperlink_round_trip() {
let mut text = TextData { characters: "AB".into(), ..Default::default() };
text.style.link = Some(url.clone());
text.restyle(1, 2, |style| style.link = None);
document.create(page, NodeKind::Text(text), "Cleared", 0.0, 0.0, 100.0, 30.0).unwrap();
document.create(page, NodeKind::Text(text.into()), "Cleared", 0.0, 0.0, 100.0, 30.0).unwrap();
let mut control = TextData { characters: "AB".into(), ..Default::default() };
control.restyle(1, 2, |style| style.link = Some(url.clone()));
document.create(page, NodeKind::Text(control), "Explicit", 0.0, 40.0, 100.0, 30.0).unwrap();
document.create(page, NodeKind::Text(control.into()), "Explicit", 0.0, 40.0, 100.0, 30.0).unwrap();
let expected = vec![Some(url.clone()), None];
assert_eq!(links(&document, "Cleared"), expected);
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more