diff --git a/Cargo.lock b/Cargo.lock index 7e10bf096..35d34b470 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -138,19 +138,34 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + [[package]] name = "alloc-no-stdlib" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib 2.0.4", +] + [[package]] name = "alloc-stdlib" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -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", ] diff --git a/Cargo.toml b/Cargo.toml index 74bdafcca..9fd9a8e06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,6 +76,12 @@ craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# Camera raw files (craft-libs): the container decoders, and the shared develop stages that turn +# sensor data into a picture (demosaic, white balance, colour matrices, tone). +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-geom = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["frames"] } # foundation diff --git a/README.md b/README.md index 9fae6ff68..aaef0a360 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ exposes to agents, and exported at 2x by FigCraft's own renderer. The source fil

Prototype and hand off

- Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like count + 1), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF. + Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like count + 1), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter, Uno C# Markup) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF. diff --git a/ROADMAP.md b/ROADMAP.md index 08827c069..a63ecbd4a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below; CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (Uno C# Markup code generation for layers, with auto layout and vectors as paths; M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; the object a stamp will stick to is outlined while the stamp tool is over it or a stamp is dragged over it, and board objects take no drops (gap 24); a server can list the files shared from it now for everyone who reaches it, Home ▸ Online shows them and their links carry no secret (`team_files`, part of #742); team library analytics count detached instances per component and file (gap 10); skipping the Open link notice by command is saved with the preferences at once (gap 15); a selected connector's bar on a board sets its start and end points, solid or dashed, its weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; a long layer name stays on one line in the Export button and the Dev Mode header, ending with an ellipsis, and no longer covers the Design panel (#1650); with hundreds of layers selected, the Design panel and the selection overlays stop going over the whole selection on every frame, so dragging 648 layers averages about 1.1 ms of UI per frame (#1571); plugin panels show pictures: an `image` control, base64 within 256 KB and 4,096 px a side, named by its label (gap 6); `.fig` connector labels without a saved snapshot are kept, centred on their line (gap 1); a drag moving many layers re-runs only what sits around them, not each layer's bindings, sizing, text and instance checks, on every move (#1571); damaged font tracking table offsets are checked instead of wrapping on 32-bit targets, and font indexing makes its existing offset bounds explicit (#1125); Bosnian (`bs`) draft catalog; text style dedupe is O(spans) via a last-two cache and fingerprint buckets (#1102); pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); progress docs cleaned of what merges left twice: rows merged into one, repeated status items removed, and `cargo xtask docs` (in `ci`) fails on a repeated table row or status item; a name typed for a variable or collection finds the one with that exact id before one named like it, and stored mode ids, font family variables and the panels' labels read exact ids (#1613); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); `.fig` elbowed and curved connectors without a saved path are routed like board connectors instead of drawn straight (gap 1); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; `figcraft-cli connect publish` publishes a code repository's code connect mappings to a design file (gap 16); while a drag only moves a large selection, its outlines, box, slots, spacing and Design panel values are worked out once and shifted, not rebuilt on every move (#1571); Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); an imported or pasted file finds an installed family under the other names its fonts give it, and with other case and spacing, instead of reporting it missing (#1292); a development example generates figcraft-cli's shell completions and man pages from its clap definitions (part of #1396); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); German terminology corrections (M10): gradient stops, OpenType stylistic sets and the Home-screen preference; a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; the server key is checked by comparing SHA-256 hashes of the presented and the kept key, as the deployment guide says (#1130); opening a file contacts no team library server it names until you check it (#1097); a hostile server can no longer grow a client's memory with made-up people, and a session remembers a bounded number of deleted layer ids (#1121); `doc.list` gives AI agents and plugins the open files' names, not their paths (#1117); with a large selection, frames where nothing changed reuse the selection's outlines, box and slots and the Design panel's instance and position values instead of working them out again (#1571); team libraries and plugins larger than the 16 MiB download burst can be downloaded again, more slowly (#1089); a batch keeps one undo snapshot, not one per step (#1099); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); joining and leaving a file nobody is editing reads and writes nothing on the server: it stays loaded a minute after everyone leaves (#1074); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); hovering the canvas hit-tests once per pointer move, not on every frame, and moving an auto layout frame no longer lays out its contents again on every move (#1571); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); `comment.people` lists names that were only @mentioned, and `comment.next` and `comment.prompt` carry the mentions too (#1415); grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); a recovery copy made while a version is previewed holds the file, not the version shown; a FigJam `.jam` file opens as a board (#1342); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); share links can comment: a third access level beside edit and view, whose holder sees the file live and adds, replies to, reacts to and resolves comments but can't change the design; Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); `comment.list {mentions}` lists only the threads that @mention a name (#1415); in the browser an internal error that stops the page keeps its unsaved files, which open again on reload (#1123); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); figcraft-cli parses its arguments with clap, following RFC-0012 (#1396); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); the browser build publishes files to a server, so Share ▸ Online and Publish to server work there (#917); the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); the portable Windows zip keeps its settings, recovery copies and plugins in `config\` beside the executable, starting with an installed copy's preferences; the window starts on other graphics when its first ones fail before the first frame: Direct3D 12 compiles with FXC and no device compiles wgpu's indirect-validation shaders, then Vulkan, OpenGL and lower requirements on the power-saving GPU (#965, #1438); Thai, Lao, Khmer and Burmese lines break between words (#1219); an AI agent attached over MCP shows where it works (#1416); a manual overlay's position can be dragged on the canvas (#405); one name for live sessions and comments: Preferences ▸ Your name, in the Join dialog too, kept in the browser, and a rename shows at once in the sessions you are in (#1380); requests that change a server's files have a budget per address, the server key's too, and join codes are found by their hash (#1075); the Join dialog shows a join from the click until its file is ready, with Cancel, and a failed join with Try again (#1381); SVG import draws each pattern tile once per scale, within the layer budget (#1080); Vietnamese letters typed with combining marks (decomposed) take one font that has every mark, instead of missing-glyph boxes beside the letter (#1478); comment.list reports each message's @mentions (#1415); mask groups draw only over the area they can paint, and nested isolated layers share one memory budget (#1061); components can't contain their own instances, directly or through other components; `edit.duplicate` returns an id map with `map: true` (#995); the batches kept for reconnecting apps are bounded in bytes by default, and `figcraft-server` takes `max_log_mb` (#1069); MCP and control calls name their document (#998); sibling placement in live sessions searches instead of counting (#1065); an AI agent attached over MCP comments under its own name, with an Agent label (#1414); the instance-swap menus have a search field (#1338); a refused batch's fixes take time linear in the batch (#1063); the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); large images on the canvas draw from a smaller copy, so two 16k images no longer lag (#1483); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); the web build's wasm back under its 24 MiB gate (#1472); shadows of images with transparent pixels follow their alpha (#1289); Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); offline Penpot 2.x import/export (#1143); optional batch continue-on-error with per-step outcomes (#1386); the Design panel's sections on one grid (#858); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); images placed at their own size, 2x screenshots in points (#1360); the toolbar on one 32 pt grid, without its Resources button (#1210); M4: zero-length round-capped dashes draw dots; dash expansion uses the existing safety budget; extracted from #1143; Arabic draft catalog; scaled instances keep their scale when their main is rebuilt (#922); .fig embedded images are copied once per blob, not once per hash (#1059); page ruler guides survive save and reopen (#1476); colour picker LCH and OKLCH models; non-ASCII layer names transliterate in code export (#1235); branches in live sessions and branch history entries, gap 17; plugin widgets take text input and a property menu (plugin API 4); boards: templates and tables; boards: a shared timer and voting sessions; boards: the dot grid, connector ends dragged to re-attach, curved connectors; Installed weights of an embedded font family (#1246); `.sketch` import, best effort (Sketch 48 and newer); CJK line breaking: JIS X 4051's line-start and line-end sets completed with the halfwidth small kana, the halfwidth and spacing (semi-)voiced sound marks, the iteration marks 〱–〵 and the halfwidth parentheses, with behaviour cases for each; Adobe Fonts found on macOS (#298); egui 0.37 hidden-capture deadline contract; Dev Mode measurements kept on the canvas and a read-only layers panel; boards: a board area row and progress entry; community fixes in #507, #510, #529 and #530: auto-save, a text box by dragging, batch step references, removing someone from a live session, Russian and Turkish catalogs reviewed, Czech and Indonesian drafts, the Japanese draft completed, zoom previews, the web clipboard, Alt-drag snapping and Cmd+D repeat, recovery copies, crash and rollback fixes, colour emoji, `.fig` import fixes; earlier changes are in the revision history below; CLI scales reject repeated x suffixes; CLI help and docs name the first non-divider page as the default for export and render; invalid browser-page server endpoints are ignored before they replace the sharing default; the browser crate docs no longer repeat an obsolete same-computer-only live-session restriction; document HTTP(S) links without a host are refused before opening; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7) FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow, native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through @@ -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/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | | 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. | diff --git a/apps/figcraft-cli/Cargo.toml b/apps/figcraft-cli/Cargo.toml index f0c28add4..b37642bfd 100644 --- a/apps/figcraft-cli/Cargo.toml +++ b/apps/figcraft-cli/Cargo.toml @@ -19,6 +19,7 @@ workspace = true [dependencies] figcraft-engine = { workspace = true } +figcraft-collab-net = { workspace = true } figcraft-doc = { workspace = true } figcraft-render = { workspace = true } figcraft-text = { workspace = true } diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index 601800ae3..04cfcd508 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -14,7 +14,8 @@ use figcraft_doc::{PrintSettings, VdCompat}; /// /// Files: .figcraft (native), .penpot (Penpot 2.x), .json (FigCraft or REST API file JSON), .fig /// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort), -/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer). +/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer), camera raw files such as .rw2, .cr2, +/// .cr3, .nef, .arw, .raf, .orf and .dng (developed as shot into an image layer). #[derive(Parser)] #[command( name = "figcraft-cli", @@ -225,6 +226,9 @@ pub struct McpArgs { /// How long the attached app may take over each request, in seconds (1–600; default 60) #[arg(long, value_name = "SECONDS", requires = "attach", value_parser = clap::value_parser!(u64).range(1..=600))] pub timeout: Option, + /// Allow a confined headless MCP session to join collaboration links from this server (repeatable) + #[arg(long = "automation-allow-server", value_name = "URL", conflicts_with = "attach")] + pub automation_allow_servers: Vec, #[command(flatten)] pub roots: RootArgs, } @@ -570,6 +574,7 @@ mod tests { (&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation), (&["mcp", "--timeout", "300"], MissingRequiredArgument), (&["mcp", "--attach", "7979", "--automation-read-root", "."], ArgumentConflict), + (&["mcp", "--attach", "7979", "--automation-allow-server", "wss://figcraft.example.com/"], ArgumentConflict), (&["mcp", "--automation-write-root"], InvalidValue), (&["mcp", "stray"], UnknownArgument), (&["convert", "a"], MissingRequiredArgument), @@ -603,6 +608,7 @@ mod tests { assert_eq!(e.as_ref().map(clap::Error::kind), Some(ErrorKind::DisplayHelp), "{args:?}"); assert_eq!(e.map(|e| e.exit_code()), Some(0), "{args:?}"); } + // The help is the subcommand's, even after a mistake. let help = try_parse(&["plugin", "publish", "--bogus", "--help"]).err().map(|e| e.to_string()).unwrap_or_default(); assert!(help.contains("Usage: figcraft-cli plugin publish"), "{help}"); @@ -611,6 +617,23 @@ mod tests { assert_eq!(a.file, "-h"); } + #[test] + fn mcp_accepts_repeated_server_allowlists() { + let Command::Mcp(a) = ok(&[ + "mcp", + "--automation-read-root", + "in", + "--automation-write-root", + "out", + "--automation-allow-server", + "wss://figcraft.example.com/", + "--automation-allow-server=wss://team.example.com/design/", + ]) else { + panic!("mcp") + }; + assert_eq!(a.automation_allow_servers, ["wss://figcraft.example.com/", "wss://team.example.com/design/"]); + } + /// Every subcommand's help renders and documents each of its options. #[test] fn every_subcommand_has_help() { diff --git a/apps/figcraft-cli/src/lib.rs b/apps/figcraft-cli/src/lib.rs index c555c6cac..0cb6baaf4 100644 --- a/apps/figcraft-cli/src/lib.rs +++ b/apps/figcraft-cli/src/lib.rs @@ -76,6 +76,12 @@ pub type CliResult = Result; fn dispatch(cli: Cli, io: &mut Io) -> CliResult { check(&cli.command)?; + // Headless MCP is always confined (AGENTS.md: agent entry points refuse to start without both + // roots); checked before the fonts are scanned, so a usage error comes back at once. + let mcp_roots = match &cli.command { + Command::Mcp(a) if a.attach.is_none() => Some(mcp_roots(&a.roots, &a.automation_allow_servers)?), + _ => None, + }; if !cli.no_system_fonts { // Text lays out with the installed fonts, like the desktop app, so headless renders and // auto layout sizes match what users see. @@ -99,7 +105,7 @@ fn dispatch(cli: Cli, io: &mut Io) -> CliResult { Ok(0) } // `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them. - Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, roots_of(&a.roots)?, io), + Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, mcp_roots, io), Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server, a.key.as_deref(), io), Command::Connect { command: ConnectCommand::Publish(a) } => { confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run, io)) @@ -180,6 +186,29 @@ fn mcp(attach: Option<&str>, timeout: Option, roots: Option CliResult { + if roots.automation_read_root.is_empty() || roots.automation_write_root.is_empty() { + return Err(CliError::Usage("headless mcp requires both --automation-read-root and --automation-write-root".into())); + } + let roots = figcraft_engine::file_access::Roots::new(&roots.automation_read_root, &roots.automation_write_root).map_err(CliError::Failed)?; + let mut servers = Vec::with_capacity(allowed_servers.len()); + for server in allowed_servers { + if server.contains('?') { + return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into())); + } + let (endpoint, query) = figcraft_collab_net::Endpoint::parse(server) + .map_err(|_| CliError::Usage("--automation-allow-server must be a ws:// or wss:// server URL".into()))?; + if !query.is_empty() { + return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into())); + } + servers.push(endpoint.url()); + } + Ok(roots.with_allowed_servers(servers)) +} + /// What the arguments can't say alone: an output that would replace its input needs `--in-place`. fn check(command: &Command) -> CliResult<()> { let refuse = |flag: &str, path: &str, input: &str, allowed: bool| -> CliResult<()> { @@ -255,3 +284,33 @@ where } } } + +#[cfg(test)] +mod mcp_roots_tests { + use super::{CliError, mcp_roots}; + use crate::args::RootArgs; + + #[test] + fn headless_mcp_requires_both_roots_and_allowlist_cannot_carry_a_key() { + let server = "wss://figcraft.example.com/".to_string(); + let no_roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: Vec::new() }; + assert!(matches!(mcp_roots(&no_roots, &[]), Err(CliError::Usage(_)))); + assert!(matches!(mcp_roots(&no_roots, std::slice::from_ref(&server)), Err(CliError::Usage(_)))); + + let path = std::env::temp_dir().join(format!("figcraft-cli-roots-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + let root = path.to_string_lossy().into_owned(); + let read_only = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: Vec::new() }; + assert!(matches!(mcp_roots(&read_only, &[]), Err(CliError::Usage(_)))); + let roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: vec![path.to_string_lossy().into_owned()] }; + assert!(matches!(mcp_roots(&roots, &[]), Err(CliError::Usage(_)))); + + let roots = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: vec![root] }; + let allowed = mcp_roots(&roots, &[server]).unwrap(); + assert_eq!(allowed.allowed_servers(), ["wss://figcraft.example.com:443/"]); + + let with_key = "wss://figcraft.example.com/?key=secret".to_string(); + assert!(matches!(mcp_roots(&roots, &[with_key]), Err(CliError::Usage(message)) if !message.contains("secret"))); + let _ = std::fs::remove_dir_all(path); + } +} diff --git a/apps/figcraft-cli/tests/it/cli.rs b/apps/figcraft-cli/tests/it/cli.rs index efc1f0e29..eb0be8aa8 100644 --- a/apps/figcraft-cli/tests/it/cli.rs +++ b/apps/figcraft-cli/tests/it/cli.rs @@ -244,7 +244,18 @@ fn run_takes_the_documented_gradient_shorthand() { #[test] fn mcp_over_stdio() { - let mut child = bin().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); + let d = tmp("mcp-over-stdio"); + let mut child = bin() + .arg("mcp") + .arg("--automation-read-root") + .arg(&d) + .arg("--automation-write-root") + .arg(&d) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); { let stdin = child.stdin.as_mut().unwrap(); writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap(); @@ -261,6 +272,7 @@ fn mcp_over_stdio() { assert_eq!(lines[0]["result"]["protocolVersion"], "2025-06-18"); assert_eq!(lines[1]["error"]["code"], -32700); assert_eq!(lines[2]["result"]["isError"], false); + let _ = std::fs::remove_dir_all(d); } #[test] @@ -270,8 +282,18 @@ fn mcp_over_stdio_confined_to_automation_roots() { std::fs::create_dir_all(d.join(sub)).unwrap(); } let p = |rel: &str| d.join(rel).to_string_lossy().into_owned(); - // A root that isn't a folder stops the server before it serves. - let out = bin().args(["mcp", "--automation-read-root", &p("missing")]).output().unwrap(); + for args in [ + vec!["mcp".to_owned()], + vec!["mcp".to_owned(), "--automation-read-root".to_owned(), p("in")], + vec!["mcp".to_owned(), "--automation-write-root".to_owned(), p("out")], + ] { + let out = bin().args(args).output().unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&out.stderr).contains("requires both --automation-read-root and --automation-write-root")); + } + + // Both roots are required; a root that isn't a folder stops the server before it serves. + let out = bin().args(["mcp", "--automation-read-root", &p("missing"), "--automation-write-root", &p("out")]).output().unwrap(); assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("--automation-read-root")); let mut child = bin() diff --git a/contributors/people.toml b/contributors/people.toml index 6629165ad..8db486ad1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -141,3 +141,7 @@ real_name = "Ibuchukwu Umeano" [people.Terra854] display_name = "Terra854" + +[people.andrejskvorc] +real_name = "Andrej Skvorc" +sync_github_name = true diff --git a/crates/collab-net/src/invite.rs b/crates/collab-net/src/invite.rs index ace18d299..4f41051ef 100644 --- a/crates/collab-net/src/invite.rs +++ b/crates/collab-net/src/invite.rs @@ -84,6 +84,15 @@ impl Endpoint { } } + /// Whether this endpoint is within an explicitly allowed server origin and path prefix. + pub fn is_within(&self, allowed: &Endpoint) -> bool { + self.secure == allowed.secure + && self.host.eq_ignore_ascii_case(&allowed.host) + && safe_path(&self.path) + && safe_path(&allowed.path) + && (allowed.path == "/" || self.path.starts_with(&allowed.path)) + } + /// Read `ws(s)://host[:port][/path][?query]` (a missing port is the scheme's: 80 or 443): the /// endpoint and the query's decoded pairs. Errors say what's wrong without echoing `url`. pub fn parse(url: &str) -> Result<(Endpoint, Vec<(String, String)>), String> { @@ -261,6 +270,10 @@ fn valid_path(p: &str) -> bool { p.starts_with('/') && p.len() <= 256 && p.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~')) } +fn safe_path(p: &str) -> bool { + !p.split('/').any(|part| matches!(part, "." | "..")) +} + /// `%XX` escapes decoded (UTF-8); `None` for broken escapes. fn percent_decode(s: &str) -> Option { let bytes = s.as_bytes(); diff --git a/crates/collab-net/src/invite_tests.rs b/crates/collab-net/src/invite_tests.rs index b7618dc28..1bb2730dc 100644 --- a/crates/collab-net/src/invite_tests.rs +++ b/crates/collab-net/src/invite_tests.rs @@ -3,6 +3,8 @@ use proptest::prelude::*; +use figcraft_engine::live::LiveLink; + use crate::invite::{Endpoint, Invite}; const TOKEN: &str = "AbCdEfGhIjKlMnOpQrStUv"; @@ -58,6 +60,28 @@ fn server_links_carry_tls_and_a_path() { assert!(plain.link().starts_with("figcraft://join?host=10.0.0.5:47900&")); } +#[test] +fn an_automation_server_allowlist_matches_the_parsed_origin_and_path_prefix() { + let net = crate::NetLink::new(std::sync::Arc::new(|| {})); + let allowed = vec!["wss://figcraft.example.com/team/".to_string()]; + let invite = |server: &str| Invite { server: Endpoint::parse(server).unwrap().0, ..invite() }.link(); + + assert!(net.automation_join_allowed(&invite("wss://FIGCRAFT.example.com/team/live/"), &allowed)); + assert!(net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/teams/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/../outside/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/live/"), &["wss://figcraft.example.com/team/../".to_string()])); + assert!(!net.automation_join_allowed(&invite("ws://figcraft.example.com/team/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com:444/team/"), &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://other.example.com/team/"), &allowed)); + assert!(!net.automation_join_allowed( + "figcraft://join?server=wss://other.example.com/team/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv", + &allowed + )); + assert!(!net.automation_join_allowed("figcraft://join?host=192.168.1.20:47900&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv", &allowed)); + assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &["wss://figcraft.example.com/team/?key=secret".to_string()])); +} + #[test] fn server_addresses_with_a_key() { let (e, q) = Endpoint::parse("ws://127.0.0.1:47900/?key=KeyKeyKeyKeyKeyKeyKey0").unwrap(); diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs index 198022a09..1145be6ff 100644 --- a/crates/collab-net/src/link.rs +++ b/crates/collab-net/src/link.rs @@ -151,6 +151,15 @@ pub(crate) fn reachable(addr: SocketAddr) -> SocketAddr { } impl LiveLink for NetLink { + fn automation_join_allowed(&self, link: &str, allowed_servers: &[String]) -> bool { + let Ok((invite, _)) = Invite::parse_join(link) else { + return false; + }; + allowed_servers + .iter() + .any(|allowed| Endpoint::parse(allowed).is_ok_and(|(endpoint, query)| query.is_empty() && invite.server.is_within(&endpoint))) + } + /// Host the open file on `o.bind`: a join code's short secret when `o.short`, and a second, /// view-only secret with its invite link when `o.view`. fn host(&mut self, session: SessionId, o: HostOptions) -> Result { diff --git a/crates/collab/src/delta_snapshot/decode.rs b/crates/collab/src/delta_snapshot/decode.rs index 2579a12dc..512cde16e 100644 --- a/crates/collab/src/delta_snapshot/decode.rs +++ b/crates/collab/src/delta_snapshot/decode.rs @@ -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 { 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) -> 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::()))); let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::())); @@ -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::() .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::())) .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::()), FieldDelta::Effects(v) => v.len().saturating_mul(size_of::()), - 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::()), + FieldDelta::CodeLinks(v) => v.len().saturating_mul(size_of::()), _ => 0, }; acc.saturating_add(extra) }) } +pub(super) fn est_meta_bytes(meta: &WireMeta) -> usize { + let images = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.key.len()).saturating_add(i.bytes.len())); + let comments = meta.comments.iter().fold(0usize, |a, c| { + let replies = c.replies.iter().fold(0usize, |r, m| r.saturating_add(m.author.len()).saturating_add(m.text.len()).saturating_add(64)); + a.saturating_add(c.first.author.len()).saturating_add(c.first.text.len()).saturating_add(replies).saturating_add(128) + }); + let styles = meta.styles.iter().fold(0usize, |a, s| a.saturating_add(s.id.len()).saturating_add(s.name.len()).saturating_add(128)); + let dev_snaps = meta.dev_snapshots.values().fold(0usize, |a, s| s.nodes.iter().fold(a, |b, n| b.saturating_add(est_node_bytes(n)))); + let vars = meta.variables.collections.len().saturating_mul(128).saturating_add(meta.variables.variables.len().saturating_mul(128)); + let libs = meta.libraries.components.len().saturating_mul(128).saturating_add(meta.libraries.styles.len().saturating_mul(128)); + let votes = meta.votes.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len().saturating_mul(size_of::()))); + let categories = meta + .annotation_categories + .iter() + .flatten() + .fold(0usize, |a, c| a.saturating_add(c.id.len()).saturating_add(c.name.len()).saturating_add(128)); + meta.name + .len() + .saturating_add(images) + .saturating_add(comments) + .saturating_add(styles) + .saturating_add(dev_snaps) + .saturating_add(vars) + .saturating_add(libs) + .saturating_add(votes) + .saturating_add(categories) + .saturating_add(meta.vote_history.len().saturating_mul(128)) + .saturating_add(meta.image_presets.len().saturating_mul(64)) + .saturating_add(meta.document_colors.len().saturating_mul(32)) +} + struct DecodeState { doc: Document, positions: Positions, touched: BTreeSet, - vectors: Vec, + vectors: Vec>, vector_sizes: Vec, node_sizes: HashMap, meta: Option, @@ -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); diff --git a/crates/collab/src/delta_snapshot/encode.rs b/crates/collab/src/delta_snapshot/encode.rs index 474cea954..bcee23a11 100644 --- a/crates/collab/src/delta_snapshot/encode.rs +++ b/crates/collab/src/delta_snapshot/encode.rs @@ -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 { } /// Encode `replica` as a compressed `CatchUp::DeltaSnapshot` payload. +/// +/// Returns `Error::TooLarge` if the payload would exceed the client decoder's materialized-memory +/// budget, allowing callers such as `Server::join_as` to fall back to `CatchUp::Snapshot`. pub fn encode_delta_snapshot(replica: &Replica) -> Result, Error> { let doc = replica.document(); let order = topo_order(doc); @@ -118,8 +122,43 @@ pub fn encode_delta_snapshot(replica: &Replica) -> Result, 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 = vectors.iter().map(est_vector_bytes).collect(); + let mut total = est_meta_bytes(meta); + for &vs in &vector_sizes { + total = total.saturating_add(vs); + } + let mut node_sizes: HashMap = HashMap::with_capacity(records.len()); + for rec in records { + match rec { + WireRecord::Full { pos, node, vref } => { + let vsize = vref.and_then(|idx| usize::try_from(idx).ok()).and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0); + let est = est_node_bytes(node).saturating_add(pos.len()).saturating_add(vsize); + total = total.saturating_add(est); + node_sizes.insert(node.id, est); + } + WireRecord::Mirror(m) => { + let src_size = node_sizes.get(&m.source).copied().unwrap_or(0); + let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &vector_sizes)).saturating_add(m.pos.len()); + let overrides = m.overrides.iter().fold(0usize, |a, s| a.saturating_add(s.len()).saturating_add(24)); + total = total.saturating_add(est); + node_sizes.insert(m.id, est.saturating_add(overrides)); + } + } + } + total } fn encode_one_node(node: &Node, pos: String, seen: &HashMap, interner: &mut VectorInterner) -> Result { @@ -143,7 +182,7 @@ fn encode_one_node(node: &Node, pos: String, seen: &HashMap, 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 Write for CountingWriter { } } -fn compress_wire(wire: &DeltaWireRef<'_>) -> Result, Error> { +fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<(Vec, usize), Error> { let mut out = Vec::with_capacity(4096); out.extend_from_slice(DELTA_MAGIC); out.push(DELTA_VERSION); @@ -213,10 +252,11 @@ fn compress_wire(wire: &DeltaWireRef<'_>) -> Result, 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)) } diff --git a/crates/collab/src/delta_snapshot/fields.rs b/crates/collab/src/delta_snapshot/fields.rs index e3ebe097b..240242d6e 100644 --- a/crates/collab/src/delta_snapshot/fields.rs +++ b/crates/collab/src/delta_snapshot/fields.rs @@ -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]) -> 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), } } diff --git a/crates/collab/src/delta_snapshot_tests.rs b/crates/collab/src/delta_snapshot_tests.rs index ff6a369fc..fb3a0a075 100644 --- a/crates/collab/src/delta_snapshot_tests.rs +++ b/crates/collab/src/delta_snapshot_tests.rs @@ -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(_), .. })); +} diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 785650625..0f2a648c8 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -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 diff --git a/crates/doc/src/boolean_hit_tests.rs b/crates/doc/src/boolean_hit_tests.rs index 5a8a01128..158eed55d 100644 --- a/crates/doc/src/boolean_hit_tests.rs +++ b/crates/doc/src/boolean_hit_tests.rs @@ -57,7 +57,7 @@ fn ordinary_hit_uses_region_paints_without_layer_fill() { Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(Vec::new()), ..Default::default() }, ], }; - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); d.get_mut(id).unwrap().fills.clear(); assert!(d.node(id).unwrap().fills.is_empty()); assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), Some(id)); @@ -71,7 +71,7 @@ fn inherited_paint_frames_use_per_region_hit_testing() { let mut network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true); network.regions[0].winding = WindingRule::EvenOdd; network.regions.push(network.regions[0].clone()); - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap(); assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), None, "legacy even-odd loops cancel"); let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind else { panic!("expected vector") }; network.regions[0].paint_space = Some(crate::RegionPaintSpace { width: 10.0, height: 10.0, transform: figcraft_geom::Affine::IDENTITY }); @@ -87,7 +87,7 @@ fn explicitly_unfilled_regions_keep_the_stroke_only_selection_band() { let mut network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)], true); network.regions[0].fills = Some(Vec::new()); - let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap(); let n = d.get_mut(id).unwrap(); n.fills.clear(); n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]; diff --git a/crates/doc/src/colors_tests.rs b/crates/doc/src/colors_tests.rs index ebf659594..84bb21659 100644 --- a/crates/doc/src/colors_tests.rs +++ b/crates/doc/src/colors_tests.rs @@ -13,7 +13,7 @@ fn colourful() -> (Document, NodeId) { let mut d = Document::new("c"); let p = d.first_page().unwrap(); let r = d.create(p, NodeKind::Rectangle, "R", 0.0, 0.0, 10.0, 10.0).unwrap(); - let t = d.create(p, NodeKind::Text(TextData::default()), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); + let t = d.create(p, NodeKind::Text(TextData::default().into()), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); { let n = d.node_mut(r).unwrap(); n.fills = vec![Paint::solid(RED)]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c83c7eb85..ea546fffa 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -23,6 +23,7 @@ pub mod library; pub mod node; pub mod props; pub mod proto; +pub mod shared; pub mod styles; pub mod text; pub mod vector; @@ -43,6 +44,7 @@ pub use handoff::*; pub use library::*; pub use node::*; pub use props::*; +pub use shared::Shared; pub use styles::*; pub use text::*; pub use vector::*; @@ -978,7 +980,14 @@ impl Document { pt.source = m.0; } } - if let NodeKind::Vector { network } = &mut c.kind { + if let NodeKind::Vector { network } = &mut c.kind + && network + .regions + .iter() + .filter_map(|r| r.fills.as_deref()) + .flatten() + .any(|p| matches!(&p.kind, figcraft_color::PaintKind::Pattern(pt) if map.contains_key(&NodeId(pt.source)))) + { for p in network.regions.iter_mut().filter_map(|r| r.fills.as_mut()).flatten() { if let figcraft_color::PaintKind::Pattern(pt) = &mut p.kind && let Some(m) = map.get(&NodeId(pt.source)) @@ -1379,6 +1388,8 @@ mod proto_expr_tests; #[cfg(test)] mod proto_overlay_anchor_tests; #[cfg(test)] +mod shared_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod vector_radius_tests; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index fad9d1a90..0514ffa5c 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -6,6 +6,7 @@ use crate::props::{ StrokeProps, }; use crate::proto::{Interaction, Overflow, ScrollPosition}; +use crate::shared::Shared; use crate::styles::{CollectionId, ModeId, StyleRefs, VariableId}; use crate::text::TextData; use crate::vector::VectorNetwork; @@ -78,9 +79,6 @@ pub fn ordered_props<'a>(props: &'a BTreeMap, order: &[String]) } /// What a node is, with per-type data. -// Text sets the size; the lint counts the gap to the next largest variant, which grew only because -// Page's guides moved to the node (#1476). -#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum NodeKind { @@ -120,9 +118,9 @@ pub enum NodeKind { }, Line, Vector { - network: VectorNetwork, + network: Shared, }, - Text(TextData), + Text(Shared), BooleanOp { op: BoolOp, }, diff --git a/crates/doc/src/shared.rs b/crates/doc/src/shared.rs new file mode 100644 index 000000000..fc5ab039a --- /dev/null +++ b/crates/doc/src/shared.rs @@ -0,0 +1,105 @@ +//! Copy-on-write `Arc` wrapper for shared layer payloads (`TextData`, `VectorNetwork`). +//! +//! Cloning a [`Shared`] payload is an O(1) atomic reference-count bump, so mirrored layers inside +//! component instances and duplicated subtrees share identical vector networks and text data in +//! memory. Mutating through [`DerefMut`] detaches via [`Arc::make_mut`], leaving every other +//! holder unchanged. Serialization and deserialization are transparent. + +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// Copy-on-write reference-counted wrapper around `T`. +#[derive(Debug, Default)] +pub struct Shared(Arc); + +impl Shared { + /// Wrap `value` in a new shared allocation. + pub fn new(value: T) -> Self { + Self(Arc::new(value)) + } + + /// Wrap an existing [`Arc`]. + pub fn from_arc(arc: Arc) -> Self { + Self(arc) + } + + /// Borrow the underlying [`Arc`]. + pub fn as_arc(&self) -> &Arc { + &self.0 + } + + /// Unwrap the underlying [`Arc`]. + pub fn into_arc(self) -> Arc { + self.0 + } + + /// Whether `self` and `other` point to the exact same allocation. + pub fn ptr_eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + /// Current strong reference count of the underlying allocation. + pub fn strong_count(&self) -> usize { + Arc::strong_count(&self.0) + } +} + +impl Clone for Shared { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl Deref for Shared { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl DerefMut for Shared { + fn deref_mut(&mut self) -> &mut T { + Arc::make_mut(&mut self.0) + } +} + +impl PartialEq for Shared { + fn eq(&self, other: &Self) -> bool { + *self.0 == *other.0 + } +} + +impl Eq for Shared {} + +impl From for Shared { + fn from(value: T) -> Self { + Self::new(value) + } +} + +impl From> for Shared { + fn from(arc: Arc) -> Self { + Self(arc) + } +} + +impl AsRef for Shared { + fn as_ref(&self) -> &T { + &self.0 + } +} + +impl Serialize for Shared { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } +} + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared { + fn deserialize>(deserializer: D) -> Result { + T::deserialize(deserializer).map(Self::new) + } +} diff --git a/crates/doc/src/shared_tests.rs b/crates/doc/src/shared_tests.rs new file mode 100644 index 000000000..b2b8d7f34 --- /dev/null +++ b/crates/doc/src/shared_tests.rs @@ -0,0 +1,195 @@ +//! Copy-on-write structural sharing tests for [`Shared`] and `NodeKind` payloads. + +use figcraft_geom::Point; + +use crate::*; + +#[test] +fn node_kind_stays_compact_with_shared_text_and_vector_payloads() { + use std::mem::size_of; + // Before wrapping TextData (352 B) and VectorNetwork (72 B) in Shared, NodeKind was 352 B + // and Node was 1608 B. + assert!(size_of::() <= 144, "NodeKind grew unexpectedly: {} bytes", size_of::()); + assert!(size_of::() <= 1400, "Node grew unexpectedly: {} bytes", size_of::()); +} + +#[test] +fn shared_clone_shares_pointer_and_deref_mut_detaches_without_mutating_source() { + let mut net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true); + let a = Shared::new(net.clone()); + let mut b = a.clone(); + assert!(a.ptr_eq(&b)); + assert_eq!(a.strong_count(), 2); + + // Mutating through DerefMut detaches b and leaves a untouched. + b.vertices[0].x = 42.0; + assert!(!a.ptr_eq(&b)); + assert_eq!(a.strong_count(), 1); + assert_eq!(b.strong_count(), 1); + assert_eq!(a.vertices[0].x, 0.0); + assert_eq!(b.vertices[0].x, 42.0); + + // Non-mutating reads never detach. + net.vertices[0].x = 42.0; + assert_eq!(*b, net); + let c = b.clone(); + let _len = c.vertices.len(); + assert!(b.ptr_eq(&c)); +} + +#[test] +fn duplicated_text_and_vector_layers_share_payloads_until_edited() { + let mut doc = Document::new("CoW"); + let page = doc.first_page().unwrap(); + let group = doc.create(page, NodeKind::Frame, "Card", 0.0, 0.0, 200.0, 100.0).unwrap(); + let net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(24.0, 0.0), Point::new(12.0, 24.0)], true); + let vec_id = doc.create(group, NodeKind::Vector { network: net.into() }, "Icon", 0.0, 0.0, 24.0, 24.0).unwrap(); + let txt_id = doc.create(group, NodeKind::Text(TextData::new("Hello").into()), "Title", 32.0, 0.0, 100.0, 20.0).unwrap(); + + let copy = doc.duplicate_into(group, page, None).unwrap(); + let copy_children = doc.node(copy).unwrap().children.clone(); + let (copy_vec, copy_txt) = (copy_children[0], copy_children[1]); + + // Both vector and text payloads share the exact same Arc right after duplication. + match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) { + (NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)), + _ => panic!("expected vector nodes"), + } + match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) { + (NodeKind::Text(a), NodeKind::Text(b)) => assert!(a.ptr_eq(b)), + _ => panic!("expected text nodes"), + } + + // Editing the copy's text detaches only the copy's TextData; the vector stays shared. + if let Some(NodeKind::Text(t)) = doc.node_mut(copy_txt).map(|n| &mut n.kind) { + t.characters = "Edited".into(); + } + match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) { + (NodeKind::Text(a), NodeKind::Text(b)) => { + assert!(!a.ptr_eq(b)); + assert_eq!(a.characters, "Hello"); + assert_eq!(b.characters, "Edited"); + } + _ => panic!("expected text nodes"), + } + match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) { + (NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)), + _ => panic!("expected vector nodes"), + } +} + +#[test] +fn shared_serialization_is_transparent_in_json() { + let td = TextData::new("Transparent"); + let raw = serde_json::to_string(&td).unwrap(); + let wrapped = serde_json::to_string(&Shared::new(td.clone())).unwrap(); + assert_eq!(raw, wrapped); + let back: Shared = serde_json::from_str(&wrapped).unwrap(); + assert_eq!(*back, td); +} + +#[test] +#[ignore = "benchmark: run with cargo test --release -p figcraft-doc bench_cow_sharing -- --ignored --nocapture"] +fn bench_cow_sharing() { + use std::collections::HashSet; + use std::mem::size_of; + use std::time::Instant; + + let pts: Vec = (0..64) + .map(|i| { + let a = (i as f64) * std::f64::consts::TAU / 64.0; + let r = if i % 2 == 0 { 16.0 } else { 8.0 }; + Point::new(a.cos() * r, a.sin() * r) + }) + .collect(); + let icon = VectorNetwork::from_points(&pts, true); + + let mut doc = Document::new("BenchCoW"); + let page = doc.first_page().unwrap(); + let comp = doc + .create( + page, + NodeKind::Component { description: "Card".into(), props: Default::default(), prop_order: Vec::new() }, + "Card", + 0.0, + 0.0, + 400.0, + 300.0, + ) + .unwrap(); + let mut kids = Vec::new(); + for i in 0..40 { + let kind = match i % 4 { + 0 => NodeKind::Text(TextData::new(format!("Label {i}")).into()), + 1 => NodeKind::Vector { network: icon.clone().into() }, + _ => NodeKind::Rectangle, + }; + kids.push(doc.create(comp, kind, &format!("L{i}"), (i % 8) as f64 * 48.0, (i / 8) as f64 * 56.0, 40.0, 40.0).unwrap()); + } + + let t0 = Instant::now(); + for k in 0..1024 { + let inst = doc + .create( + page, + NodeKind::Instance { component: comp, props: Default::default() }, + "Card", + (k % 32) as f64 * 420.0, + (k / 32) as f64 * 320.0, + 400.0, + 300.0, + ) + .unwrap(); + doc.get_mut(inst).unwrap().source = Some(comp); + for &src_id in &kids { + let mut c = doc.node(src_id).unwrap().clone(); + c.id = doc.alloc_id(); + c.parent = None; + c.children.clear(); + c.source = Some(src_id); + doc.insert(c, inst, None).unwrap(); + } + } + let build_ms = t0.elapsed().as_secs_f64() * 1000.0; + + let mut unique_vec_ptrs = HashSet::new(); + let mut unique_txt_ptrs = HashSet::new(); + let mut total_vecs = 0usize; + let mut total_txts = 0usize; + for n in doc.nodes() { + match &n.kind { + NodeKind::Vector { network } => { + total_vecs += 1; + unique_vec_ptrs.insert(std::sync::Arc::as_ptr(network.as_arc()) as usize); + } + NodeKind::Text(t) => { + total_txts += 1; + unique_txt_ptrs.insert(std::sync::Arc::as_ptr(t.as_arc()) as usize); + } + _ => {} + } + } + + let vec_heap_one = icon.vertices.len() * size_of::() + + icon.segments.len() * size_of::() + + icon.regions.len() * size_of::() + + icon.regions.iter().map(|r| r.loops.iter().map(|l| l.len() * size_of::()).sum::()).sum::(); + let vec_heap_naive = total_vecs * vec_heap_one; + let vec_heap_shared = unique_vec_ptrs.len() * vec_heap_one; + + eprintln!( + "Node={} B (was 1608 B), NodeKind={} B (was 352 B)\n42k build: {:.1} ms, nodes={}\nVectors: {} total -> {} unique Arcs (heap {:.2} MB -> {:.3} MB, {:.1}x)\nTexts: {} total -> {} unique Arcs ({:.1}x)", + size_of::(), + size_of::(), + build_ms, + doc.node_count(), + total_vecs, + unique_vec_ptrs.len(), + vec_heap_naive as f64 / 1_048_576.0, + vec_heap_shared as f64 / 1_048_576.0, + vec_heap_naive as f64 / vec_heap_shared.max(1) as f64, + total_txts, + unique_txt_ptrs.len(), + total_txts as f64 / unique_txt_ptrs.len().max(1) as f64, + ); +} diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 9d922d6c8..7ff7e0524 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -137,7 +137,7 @@ fn region_paints_participate_in_colors_images_and_pattern_remapping() { figcraft_color::Paint::image("region-image", figcraft_color::ImageScaleMode::Fill), figcraft_color::Paint::pattern(source.0), ]); - let vector = d.create(group, NodeKind::Vector { network }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap(); + let vector = d.create(group, NodeKind::Vector { network: network.into() }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap(); assert!(used_images(&d).contains("region-image")); let dup = d.duplicate_into(group, p, None).unwrap(); let copied_children = d.node(dup).unwrap().children.clone(); @@ -311,7 +311,7 @@ fn serde_roundtrip_and_repair() { let p = page(&d); let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 100.0, 100.0).unwrap(); d.get_mut(f).unwrap().layout = Some(AutoLayout::default()); - d.create(f, NodeKind::Text(TextData::new("Hi")), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap(); + d.create(f, NodeKind::Text(TextData::new("Hi").into()), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap(); d.create(f, NodeKind::Star { count: 5, inner_ratio: 0.4 }, "S", 0.0, 0.0, 10.0, 10.0).unwrap(); let j = serde_json::to_string(&d).unwrap(); let back: Document = serde_json::from_str(&j).unwrap(); @@ -576,12 +576,12 @@ fn hit_test_even_odd_vector_hole_misses() { }; let mut d = Document::new("x"); let p = page(&d); - let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); + let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); assert_eq!(d.hit_test(p, Point::new(20.0, 100.0), 0.0, None), Some(eo)); assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), None, "the hole is not filled"); let mut d = Document::new("x"); let p = page(&d); - let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); + let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap(); assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), Some(nz)); } @@ -832,7 +832,7 @@ fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() { let smoothed = net.rounded_smoothed(1.0).unwrap(); let mut d = Document::new("x"); let p = page(&d); - let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); + let v = d.create(p, NodeKind::Vector { network: net.clone().into() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap(); let n = d.node_mut(v).unwrap(); n.corners.smoothing = 1.0; n.strokes.clear(); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 11fb7f2fa..f587f4138 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -43,3 +43,5 @@ craft-font-catalog = { workspace = true } zip = { workspace = true } wat = { workspace = true } image = { workspace = true } +# Writes the DNG files the camera raw tests open. +craft-raw = { workspace = true } diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index 2e1f01b4e..e07fc3db7 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -458,6 +458,275 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() { assert!(s.doc().unwrap().node(f).unwrap().layout.is_none()); } +// ---- Add auto layout (Shift+A) defaults, measured in Figma's web app with synthetic rectangles ---- + +fn rect_at(s: &mut Session, parent: Option, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let mut p = json!({"x": x, "y": y, "width": w, "height": h}); + if let (Some(parent), Some(o)) = (parent, p.as_object_mut()) { + o.insert("parent".into(), json!(parent)); + } + id(s.execute("shape.rectangle", &p).unwrap()) +} + +fn add_layout(s: &mut Session, ids: &[NodeId]) -> NodeId { + let r = s.execute("layout.add", &json!({"ids": ids})).unwrap(); + id_of(&r["ids"][0]).unwrap() +} + +fn canvas(s: &Session, node: NodeId) -> (f64, f64) { + let c = s.doc().unwrap().world_transform(node).as_coeffs(); + (c[4], c[5]) +} + +#[test] +fn shift_a_on_two_rects_far_apart_spaces_them_between_at_a_fixed_width() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.main_align, l.padding), (LayoutMode::Horizontal, MainAlign::SpaceBetween, [0.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (140.0, 40.0)); + assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0)); +} + +#[test] +fn shift_a_gap_auto_needs_a_gap_at_least_the_narrower_child() { + // (first size, second x, second width, second height, Auto?) + for (w, x2, w2, h2, auto) in [ + (40.0, 72.0, 40.0, 40.0, false), + (40.0, 80.0, 40.0, 40.0, true), + (20.0, 52.0, 20.0, 20.0, true), + (100.0, 160.0, 100.0, 100.0, false), + (40.0, 100.0, 80.0, 60.0, true), + ] { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, w, w); + let b = rect_at(&mut s, None, x2, 0.0, w2, h2); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!(l.gap, x2 - w, "{w} {x2}"); + if auto { + assert_eq!((l.main_align, n.child_layout.sizing_h, n.width), (MainAlign::SpaceBetween, Sizing::Fixed, x2 + w2), "{w} {x2}"); + } else { + assert_eq!(l.main_align, MainAlign::Min, "{w} {x2}"); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug, "{w} {x2}"); + } + } +} + +#[test] +fn shift_a_on_three_rects_in_a_row_uses_the_mean_gap_and_hugs() { + for (xs, gap, width) in [([0.0, 100.0, 200.0], 60.0, 240.0), ([0.0, 100.0, 180.0], 50.0, 220.0)] { + let mut s = Session::new(); + let ids: Vec = xs.iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect(); + let f = add_layout(&mut s, &ids); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!(l.gap, gap); + assert_eq!(l.main_align, MainAlign::Min); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Hug, Sizing::Hug, width)); + } +} + +#[test] +fn shift_a_on_stacked_rects_fixes_the_width_and_hugs_the_height() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 60.0)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (80.0, 160.0)); + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 0.0, 240.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 200.0)); + assert_eq!(l.main_align, MainAlign::Min); + assert_eq!((n.child_layout.sizing_h, n.width), (Sizing::Fixed, 40.0)); +} + +#[test] +fn shift_a_on_one_rect_pads_ten_and_keeps_it_in_place() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 10.0, [10.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); + assert_eq!((n.width, n.height), (60.0, 60.0)); + assert_eq!(canvas(&s, f), (-10.0, -10.0)); + assert_eq!(canvas(&s, a), (0.0, 0.0)); + assert_eq!(size(&s, a), (40.0, 40.0)); +} + +fn filled_frame(s: &mut Session) -> NodeId { + id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#ff0000"}})).unwrap()) +} + +#[test] +fn shift_a_on_a_frame_mirrors_its_left_and_top_offsets() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0); + rect_at(&mut s, Some(f), 120.0, 30.0, 40.0, 40.0); + let fills = s.doc().unwrap().node(f).unwrap().fills.len(); + let clip = s.doc().unwrap().node(f).unwrap().clip; + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 60.0, [30.0, 20.0, 30.0, 20.0])); + assert_eq!(l.main_align, MainAlign::Min); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); + assert_eq!((n.width, n.height), (180.0, 100.0)); + assert_eq!((n.fills.len(), n.clip), (fills, clip)); +} + +#[test] +fn shift_a_on_a_frame_with_centred_content_spaces_it_between() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 49.0, 49.0, 40.0, 40.0); + rect_at(&mut s, Some(f), 211.0, 49.0, 40.0, 40.0); + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.main_align, l.padding), (MainAlign::SpaceBetween, [49.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (300.0, 138.0)); +} + +#[test] +fn shift_a_on_a_frame_with_stacked_content_fixes_the_content_width() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.0, 20.0, 40.0, 40.0); + rect_at(&mut s, Some(f), 20.0, 100.0, 40.0, 40.0); + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Vertical, 40.0, [20.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (80.0, 160.0)); +} + +#[test] +fn shift_a_on_a_group_follows_the_wrap_rule() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + let f = add_layout(&mut s, &[g]); + assert_eq!(f, g); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!(l.main_align, MainAlign::SpaceBetween); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert_eq!((n.width, n.height), (140.0, 40.0)); + assert!(n.fills.is_empty() && !n.clip); + assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0)); +} + +#[test] +fn shift_a_on_a_one_child_group_follows_the_group_rule_not_the_one_child_frame_exception() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let g = id(s.execute("object.group", &json!({"ids": [a]})).unwrap()); + let r = s.execute("layout.add", &json!({"ids": [g], "direction": "vertical"})).unwrap(); + assert_eq!(id_of(&r["ids"][0]), Some(g)); + let n = s.doc().unwrap().node(g).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [0.0; 4])); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug)); + assert!(n.fills.is_empty() && !n.clip); +} + +fn add_layout_dir(s: &mut Session, ids: &[NodeId], direction: &str) -> NodeId { + let r = s.execute("layout.add", &json!({"ids": ids, "direction": direction})).unwrap(); + id_of(&r["ids"][0]).unwrap() +} + +#[test] +fn shift_a_gap_auto_compares_the_narrower_width_not_the_mean() { + // Widths 40 and 100, gap 60: at least the narrower (40), below the mean (70). + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 100.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.gap, l.main_align, n.child_layout.sizing_h, n.width), (60.0, MainAlign::SpaceBetween, Sizing::Fixed, 200.0)); +} + +#[test] +fn shift_a_direction_vertical_on_a_horizontal_pair_stacks_with_a_fixed_width_and_no_space_between() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0); + let f = add_layout_dir(&mut s, &[a, b], "vertical"); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + // Measured along y the two overlap, so the gap clamps to 0. + assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Vertical, 0.0, MainAlign::Min)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Fixed, Sizing::Hug, 140.0)); +} + +#[test] +fn shift_a_direction_horizontal_on_a_stacked_pair_hugs_the_width() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0); + let f = add_layout_dir(&mut s, &[a, b], "horizontal"); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Horizontal, 0.0, MainAlign::Min)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); +} + +#[test] +fn shift_a_overlapping_children_clamp_the_gap_to_zero_and_fractions_round() { + let mut s = Session::new(); + let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0); + let b = rect_at(&mut s, None, 30.0, 0.0, 40.0, 40.0); + let f = add_layout(&mut s, &[a, b]); + let l = s.doc().unwrap().node(f).unwrap().layout.clone().unwrap(); + assert_eq!((l.gap, l.main_align), (0.0, MainAlign::Min)); + // Gaps 5 and 6 average 5.5, which rounds to 6. + let mut s = Session::new(); + let ids: Vec = [0.0, 45.0, 91.0].iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect(); + let f = add_layout(&mut s, &ids); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().gap, 6.0); + // Fractional left and top offsets round to whole padding. + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.4, 30.6, 40.0, 40.0); + rect_at(&mut s, Some(f), 120.0, 30.6, 40.0, 40.0); + add_layout(&mut s, &[f]); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().padding, [31.0, 20.0, 31.0, 20.0]); +} + +#[test] +fn shift_a_on_a_frame_with_one_child_keeps_the_inferred_layout() { + let mut s = Session::new(); + let f = filled_frame(&mut s); + rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0); + add_layout(&mut s, &[f]); + let n = s.doc().unwrap().node(f).unwrap(); + let l = n.layout.clone().unwrap(); + assert_eq!((l.mode, l.gap, l.padding, l.main_align), (LayoutMode::Horizontal, 10.0, [30.0, 240.0, 130.0, 20.0], MainAlign::Min)); + assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug)); + assert_eq!((n.width, n.height), (300.0, 200.0)); +} + #[test] fn align_is_unavailable_for_a_child_in_an_auto_layout_flow() { use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align}; diff --git a/crates/engine/src/al_drag_tests.rs b/crates/engine/src/al_drag_tests.rs index 0c5119fc5..33793ea5f 100644 --- a/crates/engine/src/al_drag_tests.rs +++ b/crates/engine/src/al_drag_tests.rs @@ -76,7 +76,7 @@ fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) { let kids: Vec = (0..3).map(|_| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 60, "parent": f})).unwrap())).collect(); s.execute("layout.add", &json!({"ids": [f]})).unwrap(); - s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed"}})).unwrap(); + s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed", "width": 300, "height": 300}})).unwrap(); s.execute("select.none", &json!({})).unwrap(); (f, [kids[0], kids[1], kids[2]]) } diff --git a/crates/engine/src/al_nesting_tests.rs b/crates/engine/src/al_nesting_tests.rs index f3ab62a06..cf7733927 100644 --- a/crates/engine/src/al_nesting_tests.rs +++ b/crates/engine/src/al_nesting_tests.rs @@ -170,6 +170,8 @@ fn the_dragged_frame_never_receives_itself_and_plain_frames_in_a_flow_are_items( let list = frame(&mut s, None, 500.0, 0.0, 200.0, 400.0); let cards: Vec = (0..3).map(|i| frame(&mut s, Some(list), 0.0, i as f64 * 70.0, 150.0, 60.0)).collect(); s.execute("layout.add", &json!({"ids": [list], "direction": "vertical"})).unwrap(); + // The list now hugs its cards; padding gives it room around them to drop into. + s.execute("node.set", &json!({"id": list, "props": {"padding": 20, "sizingH": "hug"}})).unwrap(); s.execute("select.none", &json!({})).unwrap(); let card0 = bounds(&s, cards[0]); let grab = Point::new(bounds(&s, cards[2]).x0 + 3.0, bounds(&s, cards[2]).y0 + 3.0); diff --git a/crates/engine/src/assets/playground.rs b/crates/engine/src/assets/playground.rs index ddb969c25..d9186556e 100644 --- a/crates/engine/src/assets/playground.rs +++ b/crates/engine/src/assets/playground.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { vec![spec!( "component.playground", "Component playground", - "{id? (an instance, a component or a component set; default the selection), properties? {name: value} (variant, boolean, text and instance-swap properties, as instance.setProperties takes them), language? css|html|react|leptos|vue|swiftui|compose|arkui|flutter (default react), path? (write the preview there as a PNG), scale? (the PNG's, default 2)} → {component, properties: [{name, type, options?, value}], language, code, width, height, path?} the component with those property values, tried on a copy: its code and its look. Nothing in the document changes", + "{id? (an instance, a component or a component set; default the selection), properties? {name: value} (variant, boolean, text and instance-swap properties, as instance.setProperties takes them), language? css|html|react|leptos|vue|swiftui|compose|arkui|flutter|uno (default react), path? (write the preview there as a PNG), scale? (the PNG's, default 2)} → {component, properties: [{name, type, options?, value}], language, code, width, height, path?} the component with those property values, tried on a copy: its code and its look. Nothing in the document changes", false, |s, p| { let cmd = "component.playground"; @@ -63,7 +63,7 @@ pub fn specs() -> Vec { Some(_) => return Err(bad(cmd, "properties: {name: value}")), }; let lang = match string(p, "language") { - Some(l) => CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|swiftui|compose|arkui|flutter"))?, + Some(l) => CodeLang::from_id(&l).ok_or_else(|| bad(cmd, "language: css|html|react|leptos|vue|swiftui|compose|arkui|flutter|uno"))?, None => CodeLang::React, }; let (copy, inst) = build(s.doc()?, target, &values)?; diff --git a/crates/engine/src/auto_layout_move_tests.rs b/crates/engine/src/auto_layout_move_tests.rs index 49256dc64..9cc02d92a 100644 --- a/crates/engine/src/auto_layout_move_tests.rs +++ b/crates/engine/src/auto_layout_move_tests.rs @@ -47,7 +47,7 @@ fn a_frame_moved_inside_auto_layout_still_moves_its_siblings() { // A stack and a rectangle side by side in an outer auto layout frame: the outer layout still // follows when the stack grows. let (mut s, inner, [first, _]) = stack(); - let other = id_of(&s.execute("shape.rectangle", &json!({"x": 300, "y": 0, "width": 100, "height": 40})).unwrap()["id"]).unwrap(); + let other = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 0, "width": 100, "height": 40})).unwrap()["id"]).unwrap(); s.execute("select.set", &json!({"ids": [inner.0, other.0]})).unwrap(); s.execute("layout.add", &json!({})).unwrap(); let outer = s.doc().unwrap().node(inner).and_then(|n| n.parent).unwrap(); diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 5eba5a506..1d5bfebcd 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -40,6 +40,7 @@ pub enum Access { pub struct Roots { read: Vec, write: Vec, + allowed_servers: Vec, } impl Roots { @@ -55,7 +56,18 @@ impl Roots { }) .collect::, String>>() }; - Ok(Self { read: resolve("--automation-read-root", read)?, write: resolve("--automation-write-root", write)? }) + Ok(Self { read: resolve("--automation-read-root", read)?, write: resolve("--automation-write-root", write)?, allowed_servers: Vec::new() }) + } + + /// Also allow headless collaboration joins to explicitly approved servers. + pub fn with_allowed_servers(mut self, servers: Vec) -> Self { + self.allowed_servers = servers; + self + } + + /// Servers an automation session may join through its collaboration link. + pub fn allowed_servers(&self) -> &[String] { + &self.allowed_servers } /// The resolved path to use for `access` to `path`, or why it is refused. @@ -91,7 +103,11 @@ impl Roots { /// The folders as JSON, resolved: `{read: [every folder that may be read], write: [the write roots]}`. pub fn to_json(&self) -> serde_json::Value { let list = |v: &[PathBuf]| v.iter().map(|p| shown(p)).collect::>(); - serde_json::json!({"read": list(&[self.read.as_slice(), self.write.as_slice()].concat()), "write": list(&self.write)}) + serde_json::json!({ + "read": list(&[self.read.as_slice(), self.write.as_slice()].concat()), + "write": list(&self.write), + "allowedServers": self.allowed_servers + }) } } diff --git a/crates/engine/src/board_code_tests.rs b/crates/engine/src/board_code_tests.rs index 64f734f0b..666111e93 100644 --- a/crates/engine/src/board_code_tests.rs +++ b/crates/engine/src/board_code_tests.rs @@ -21,8 +21,8 @@ fn bx(s: &Session, id: NodeId) -> Rect { fn td(s: &Session, block: NodeId) -> TextData { let t = text_of(s.doc().unwrap(), block).unwrap(); - match node(s, t).kind { - NodeKind::Text(td) => td, + match &node(s, t).kind { + NodeKind::Text(td) => (**td).clone(), other => panic!("not text: {other:?}"), } } @@ -392,8 +392,8 @@ fn key(s: &mut Session, key: &str, shift: bool) { } fn characters(s: &Session, t: NodeId) -> String { - match node(s, t).kind { - NodeKind::Text(td) => td.characters, + match &node(s, t).kind { + NodeKind::Text(td) => td.characters.clone(), other => panic!("not text: {other:?}"), } } diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs index c83fddc22..0bb67a044 100644 --- a/crates/engine/src/board_mindmap_tests.rs +++ b/crates/engine/src/board_mindmap_tests.rs @@ -30,8 +30,8 @@ fn map(s: &mut Session) -> (NodeId, [NodeId; 3], [NodeId; 3]) { fn text_data(s: &Session, n: NodeId) -> figcraft_doc::TextData { let t = text_of(s.doc().unwrap(), n).unwrap(); - match node(s, t).kind { - NodeKind::Text(td) => td, + match &node(s, t).kind { + NodeKind::Text(td) => (**td).clone(), other => panic!("not text: {other:?}"), } } diff --git a/crates/engine/src/boards/board/connectors.rs b/crates/engine/src/boards/board/connectors.rs index 408de045a..7e285f679 100644 --- a/crates/engine/src/boards/board/connectors.rs +++ b/crates/engine/src/boards/board/connectors.rs @@ -85,7 +85,7 @@ pub(super) fn make(doc: &mut Document, page: NodeId, c: Connector, caps: (Stroke if pts.windows(2).all(|w| w.first() == w.get(1)) { return Err(bad(cmd, "the ends are in the same place")); } - let id = add(doc, page, NodeKind::Vector { network: VectorNetwork::default() }, "Connector", (0.0, 0.0), (0.0, 0.0), |n| { + let id = add(doc, page, NodeKind::Vector { network: VectorNetwork::default().into() }, "Connector", (0.0, 0.0), (0.0, 0.0), |n| { n.fills.clear(); n.strokes = vec![Paint::solid(LINE)]; n.stroke.weight = LINE_WEIGHT; diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs index e62d41973..7b230cabc 100644 --- a/crates/engine/src/boards/board/derived.rs +++ b/crates/engine/src/boards/board/derived.rs @@ -263,13 +263,15 @@ pub(super) fn place_route(doc: &mut Document, id: NodeId, pts: &[Point], routing _ => VectorNetwork::from_points(&rel.elements().iter().filter_map(PathEl::end_point).collect::>(), false), }; let t = Affine::translate((b.x0, b.y0)); - let same = - n.transform == t && n.width == b.width() && n.height == b.height() && matches!(&n.kind, NodeKind::Vector { network: old } if *old == network); + let same = n.transform == t + && n.width == b.width() + && n.height == b.height() + && matches!(&n.kind, NodeKind::Vector { network: old } if **old == network); if same { return; } if let Some(n) = doc.node_mut(id) { - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; n.transform = t; (n.width, n.height) = (b.width(), b.height()); } diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 410699560..c6f8c33c4 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -178,7 +178,7 @@ fn reshape(doc: &mut Document, id: NodeId, new: BoardShape) -> Result<()> { if let Some(o) = doc.get(id)?.children.first().copied() && let Some(on) = doc.node_mut(o) { - on.kind = NodeKind::Vector { network: VectorNetwork::from_path(&new.path(w, h)) }; + on.kind = NodeKind::Vector { network: VectorNetwork::from_path(&new.path(w, h)).into() }; (on.width, on.height, on.transform) = (w, h, Affine::IDENTITY); } Ok(()) diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 5cc660b84..6fa1bf0fb 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -44,7 +44,7 @@ pub(crate) fn add_text(doc: &mut Document, parent: NodeId, text: &str, size: f64 ..TextData::default() }; td.style.font_size = size; - let id = add(doc, parent, NodeKind::Text(td), name, (0.0, 0.0), (width.max(1.0), size * 1.4), |n| { + let id = add(doc, parent, NodeKind::Text(td.into()), name, (0.0, 0.0), (width.max(1.0), size * 1.4), |n| { n.fills = vec![Paint::solid(color)]; n.child_layout.sizing_h = Sizing::Fill; })?; @@ -297,7 +297,7 @@ fn make_shape( }); n.board = Some(BoardItem::Shape { shape }); })?; - add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&shape.path(w, h)) }, "Outline", (0.0, 0.0), size, |n| { + add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&shape.path(w, h)).into() }, "Outline", (0.0, 0.0), size, |n| { n.fills = vec![Paint::solid(color)]; n.strokes = vec![Paint::solid(line_shade(color))]; n.stroke.weight = 1.5; @@ -359,7 +359,7 @@ pub(super) fn stamp_cmd(s: &mut Session, p: &Value) -> Result { })?; for part in stamp.mark() { let path = figcraft_geom::BezPath::from_svg(part.d).map_err(|e| EngineError::Other(format!("stamp mark: {e}")))?; - add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&path) }, "Mark", (0.0, 0.0), (STAMP_SIZE, STAMP_SIZE), |n| { + add(doc, id, NodeKind::Vector { network: VectorNetwork::from_path(&path).into() }, "Mark", (0.0, 0.0), (STAMP_SIZE, STAMP_SIZE), |n| { if part.filled { n.fills = vec![Paint::solid(Color::WHITE)]; } else { diff --git a/crates/engine/src/boolean_cap_tests.rs b/crates/engine/src/boolean_cap_tests.rs index b9d40e349..5f6e6b71b 100644 --- a/crates/engine/src/boolean_cap_tests.rs +++ b/crates/engine/src/boolean_cap_tests.rs @@ -27,7 +27,7 @@ fn flattening_a_boolean_past_the_caps_is_refused() { .into_iter() .map(|across| { let network = VectorNetwork::from_path(&bars(750, across)); - s.doc_mut().unwrap().create(page, NodeKind::Vector { network }, "Bars", 0.0, 0.0, 3000.0, 3000.0).unwrap() + s.doc_mut().unwrap().create(page, NodeKind::Vector { network: network.into() }, "Bars", 0.0, 0.0, 3000.0, 3000.0).unwrap() }) .collect(); let g = id_of(&s.execute("bool.union", &json!({"ids": ids})).unwrap()["id"]).unwrap(); diff --git a/crates/engine/src/canvas/shapebuilder.rs b/crates/engine/src/canvas/shapebuilder.rs index fea91db25..bb2b8cbb2 100644 --- a/crates/engine/src/canvas/shapebuilder.rs +++ b/crates/engine/src/canvas/shapebuilder.rs @@ -323,12 +323,12 @@ fn reshape_vector_regions(doc: &mut Document, id: NodeId, areas: &[(usize, BezPa } let Some(bounds) = rebuilt.bounds() else { let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: rebuilt }; + n.kind = NodeKind::Vector { network: rebuilt.into() }; return Ok(()); }; rebuilt.translate(-bounds.x0, -bounds.y0); let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: rebuilt }; + n.kind = NodeKind::Vector { network: rebuilt.into() }; n.children.clear(); n.corners = Corners::default(); n.transform *= Affine::translate((bounds.x0, bounds.y0)); @@ -351,7 +351,7 @@ fn reshape(doc: &mut Document, id: NodeId, area: &BezPath) -> Result<()> { } } let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: net }; + n.kind = NodeKind::Vector { network: net.into() }; n.children.clear(); n.corners = Corners::default(); crate::vectoredit::refit(doc, id) @@ -388,7 +388,7 @@ fn create_merged(doc: &mut Document, style: Part, area: &BezPath) -> Result NodeId { append(&mut network, box_path(50.0, 0.0, 100.0, 100.0)); network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("#ff0000").unwrap())]); network.regions[1].fills = Some(vec![Paint::solid(Color::from_hex("#0000ff").unwrap())]); - s.doc_mut().unwrap().get_mut(id).unwrap().kind = NodeKind::Vector { network }; + s.doc_mut().unwrap().get_mut(id).unwrap().kind = NodeKind::Vector { network: network.into() }; id } @@ -104,7 +104,7 @@ fn legacy_unstyled_nested_evenodd_regions_keep_the_hole_unpainted() { region.fills = None; region.paint_space = None; } - s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net }; + s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.into() }; let crossing = rect(&mut s, -5.0, 45.0, 15.0, 10.0, "#ffffff"); s.set_selection(vec![vector, crossing]); let a = arrangement(&mut s, &[vector, crossing]).unwrap(); @@ -168,7 +168,7 @@ fn exceeding_arrangement_capacity_never_drops_unprocessed_regions() { part.regions[0].fills = Some(vec![Paint::solid(Color::BLACK)]); append(&mut net, part); } - s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.clone() }; + s.doc_mut().unwrap().get_mut(vector).unwrap().kind = NodeKind::Vector { network: net.clone().into() }; s.set_selection(vec![vector]); let error = s.execute("shapeBuilder.remove", &json!({"points": [[5, 5]]})).unwrap_err(); assert!(error.to_string().contains("too many fill regions")); @@ -269,7 +269,7 @@ fn removal_preserves_holes_and_transformed_gradient_frames() { { let doc = s.doc_mut().unwrap(); let node = doc.get_mut(vector).unwrap(); - node.kind = NodeKind::Vector { network: outer }; + node.kind = NodeKind::Vector { network: outer.into() }; node.transform = transform; } let before = normalized_paint_world(&s, vector, 0); diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 9508bfcb8..2c41c7d13 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -83,7 +83,7 @@ fn next_editing_session() -> u64 { fn text_of(s: &Session, id: NodeId) -> Result { match &s.doc()?.get(id)?.kind { - NodeKind::Text(t) => Ok(t.clone()), + NodeKind::Text(t) => Ok((**t).clone()), _ => Err(EngineError::Other(format!("{id} is not a text layer"))), } } diff --git a/crates/engine/src/canvas/tools/click.rs b/crates/engine/src/canvas/tools/click.rs index 1e7a9f902..59100ce8d 100644 --- a/crates/engine/src/canvas/tools/click.rs +++ b/crates/engine/src/canvas/tools/click.rs @@ -231,7 +231,7 @@ impl Session { let ds = self.ds_mut()?; let d = ds.doc_mut(); let id = d.alloc_id(); - let mut n = Node::new(id, NodeKind::Text(TextData::default()), "Text", 1.0, 14.0); + let mut n = Node::new(id, NodeKind::Text(TextData::default().into()), "Text", 1.0, 14.0); let pw = d.world_transform(parent); let at = Point::new(ev.x.round(), (ev.y - 7.0).round()); n.transform = pw.inverse() * Affine::translate(at.to_vec2()); @@ -329,7 +329,7 @@ impl Session { let ds = self.ds_mut()?; let d = ds.doc_mut(); let id = d.alloc_id(); - let mut n = Node::new(id, NodeKind::Text(TextData::default()), "Text", pn.width, pn.height); + let mut n = Node::new(id, NodeKind::Text(TextData::default().into()), "Text", pn.width, pn.height); n.name = String::new(); n.transform = pn.transform; n.constraints = pn.constraints; diff --git a/crates/engine/src/canvas/tools/pen.rs b/crates/engine/src/canvas/tools/pen.rs index 097a2bf04..8df275a65 100644 --- a/crates/engine/src/canvas/tools/pen.rs +++ b/crates/engine/src/canvas/tools/pen.rs @@ -218,7 +218,7 @@ impl Session { Some(id) if doc.contains(id) => id, _ => { let id = doc.alloc_id(); - let mut n = Node::new(id, NodeKind::Vector { network: VectorNetwork::default() }, "Vector", 0.0, 0.0); + let mut n = Node::new(id, NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector", 0.0, 0.0); n.fills.clear(); n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)]; n.stroke.align = StrokeAlign::Center; @@ -227,7 +227,7 @@ impl Session { } }; let n = doc.get_mut(id)?; - n.kind = NodeKind::Vector { network: net }; + n.kind = NodeKind::Vector { network: net.into() }; n.width = bb.width(); n.height = bb.height(); n.transform = Affine::translate((bb.x0, bb.y0)); diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index cf00a06de..99d58679a 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -341,7 +341,7 @@ pub fn ensure_vector(doc: &mut Document, id: NodeId) -> Result<()> { } } let node = doc.get_mut(id)?; - node.kind = NodeKind::Vector { network: net }; + node.kind = NodeKind::Vector { network: net.into() }; node.children.clear(); if matches!(n.kind, NodeKind::Line) { node.stroke.align = StrokeAlign::Center; diff --git a/crates/engine/src/canvas/vectoredit/pointer.rs b/crates/engine/src/canvas/vectoredit/pointer.rs index dadb1e3e8..2f32f5aef 100644 --- a/crates/engine/src/canvas/vectoredit/pointer.rs +++ b/crates/engine/src/canvas/vectoredit/pointer.rs @@ -1171,7 +1171,7 @@ impl Session { // The preview starts again from the document before the drag: bring the moved layer. self.preview(|doc, _| { *doc.get_mut(id)? = moved; - edit(doc, id, |net| *net = merged) + edit(doc, id, |net| *net = (*merged).clone()) })?; set_state(self, |e| { e.vertices = vec![if keep > v { keep - 1 } else { keep }]; diff --git a/crates/engine/src/canvas/vectoredit/regions_tests.rs b/crates/engine/src/canvas/vectoredit/regions_tests.rs index a12fc0f84..fa57e02b5 100644 --- a/crates/engine/src/canvas/vectoredit/regions_tests.rs +++ b/crates/engine/src/canvas/vectoredit/regions_tests.rs @@ -51,7 +51,7 @@ fn editing_vector(s: &mut Session, n: VectorNetwork) -> NodeId { let id = crate::params::id_of(&r["id"]).unwrap(); let doc = s.doc_mut().unwrap(); let node = doc.get_mut(id).unwrap(); - node.kind = figcraft_doc::NodeKind::Vector { network: n }; + node.kind = figcraft_doc::NodeKind::Vector { network: n.into() }; node.transform = Affine::IDENTITY; node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)]; super::refit(doc, id).unwrap(); diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs index c5f02d122..636368ee7 100644 --- a/crates/engine/src/canvas/vectoredit/tests.rs +++ b/crates/engine/src/canvas/vectoredit/tests.rs @@ -188,7 +188,7 @@ fn a_handle_and_a_point_are_compared_on_the_page() { let mut seg = figcraft_doc::Segment::line(0, 1); seg.ta = (0.5, -0.9); n.segments.push(seg); - node.kind = figcraft_doc::NodeKind::Vector { network: n }; + node.kind = figcraft_doc::NodeKind::Vector { network: n.into() }; node.transform = figcraft_geom::Affine::scale_non_uniform(10.0, 1.0); } ex(&mut s, "vector.edit.begin", json!({"id": id})); @@ -215,7 +215,7 @@ fn a_handle_on_another_point_is_still_the_handles() { let mut seg = figcraft_doc::Segment::line(0, 1); seg.ta = (10.0, 0.0); n.segments.push(seg); - node.kind = figcraft_doc::NodeKind::Vector { network: n }; + node.kind = figcraft_doc::NodeKind::Vector { network: n.into() }; node.transform = figcraft_geom::Affine::IDENTITY; } ex(&mut s, "vector.edit.begin", json!({"id": id})); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 48fa80638..b96340c2f 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -173,8 +173,8 @@ pub fn kind_for(t: &str) -> Option<(NodeKind, &'static str)> { "star" => (NodeKind::Star { count: 5, inner_ratio: 0.38 }, "Star"), "line" => (NodeKind::Line, "Line"), "arrow" => (NodeKind::Line, "Arrow"), - "vector" | "path" => (NodeKind::Vector { network: VectorNetwork::default() }, "Vector"), - "text" => (NodeKind::Text(TextData::default()), "Text"), + "vector" | "path" => (NodeKind::Vector { network: VectorNetwork::default().into() }, "Vector"), + "text" => (NodeKind::Text(TextData::default().into()), "Text"), "frame" => (NodeKind::Frame, "Frame"), "section" => (NodeKind::Section { contents_hidden: false }, "Section"), "component" => (NodeKind::Component { description: String::new(), props: Default::default(), prop_order: Vec::new() }, "Component"), @@ -332,7 +332,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result { if let NodeKind::Vector { network } = &mut kind { if let Some(d) = string(p, "path") { let shape = path_network(cmd, &d, asked.0, asked.1)?; - *network = shape.network; + *network = (shape.network).into(); if boolean(p, "closed") == Some(false) { network.regions.clear(); } @@ -355,7 +355,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result { } let (sx, sy) = vector_scale(asked.0, asked.1, bb.width(), bb.height(), "a point set").map_err(|e| bad(cmd, e))?; let local: Vec = pts.iter().map(|q| Point::new((q.x - bb.x0) * sx, (q.y - bb.y0) * sy)).collect(); - *network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false)); + *network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false)).into(); w = bb.width() * sx; h = bb.height() * sy; offset = (bb.x0, bb.y0); diff --git a/crates/engine/src/cmd/edit/vector_clipboard.rs b/crates/engine/src/cmd/edit/vector_clipboard.rs index f52916ee8..107f60aaf 100644 --- a/crates/engine/src/cmd/edit/vector_clipboard.rs +++ b/crates/engine/src/cmd/edit/vector_clipboard.rs @@ -106,7 +106,7 @@ fn clip_node(doc: &Document, id: NodeId, mut sub: VectorNetwork) -> Option n.transform = doc.world_transform(id) * Affine::translate((b.x0, b.y0)); n.width = b.width(); n.height = b.height(); - n.kind = NodeKind::Vector { network: sub }; + n.kind = NodeKind::Vector { network: sub.into() }; n.parent = None; n.children.clear(); n.name = "Vector".into(); @@ -181,7 +181,7 @@ pub fn clipboard_svg(s: &Session) -> Option { /// frames, groups, instances, …). `doc` is the file the layer was copied from. fn outline_network(doc: &Document, n: &Node) -> Option { let net = match &n.kind { - NodeKind::Vector { network } => network.clone(), + NodeKind::Vector { network } => (**network).clone(), k if k.is_shape() || matches!(k, NodeKind::BooleanOp { .. }) => { let (path, rule) = figcraft_render::node_outline(doc, n)?; let mut net = VectorNetwork::from_path(&path); diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs index d204931ac..d3242a340 100644 --- a/crates/engine/src/cmd/file/load.rs +++ b/crates/engine/src/cmd/file/load.rs @@ -124,7 +124,7 @@ fn load_any( font_notes.append(&mut notes); // Show missing-font details first in the UI toast. Ok((figcraft_format::Loaded { issues: font_notes, ..doc.into() }, true)) } - "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" => { + e if matches!(e, "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff") || figcraft_format::raw::is_extension(e) => { let mut doc = Document::new(file_stem(name_hint)); let page = doc.first_page().ok_or(EngineError::NoDocument)?; let (hash, w, h) = crate::cmd::create::add_readable_image(&mut doc, bytes.to_vec()).map_err(EngineError::Other)?; @@ -787,7 +787,7 @@ mod penpot_font_warning_tests { let mut doc = Document::new("External font refs"); let page = doc.first_page().unwrap(); let text = TextData::new("Playball"); - let id = doc.create(page, NodeKind::Text(text), "Custom caption", 0., 0., 120., 30.).unwrap(); + let id = doc.create(page, NodeKind::Text(text.into()), "Custom caption", 0., 0., 120., 30.).unwrap(); doc.node_mut(id).unwrap().plugin_data.insert( "penpot.customFontRefs".into(), r#"[{"id":"custom-123abc","family":"Playball","variants":[{"weight":400,"italic":false}]}]"#.into(), @@ -805,7 +805,7 @@ mod penpot_font_warning_tests { let page = doc.first_page().unwrap(); let mut text = TextData::new("hello world"); text.style.font_family = "Rare Licensed Family".into(); - doc.create(page, NodeKind::Text(text), "Headline", 0.0, 0.0, 200.0, 30.0).unwrap(); + doc.create(page, NodeKind::Text(text.into()), "Headline", 0.0, 0.0, 200.0, 30.0).unwrap(); let warnings = missing_penpot_font_warnings(&doc, &["Inter".into(), "Source Sans Pro".into()]); assert_eq!(warnings.len(), 1); assert!(warnings[0].contains("Rare Licensed Family")); @@ -830,7 +830,7 @@ mod penpot_font_warning_tests { let mut run = t.style.clone(); run.font_family = "Available Font".into(); t.runs.push(StyleRun { start: 0, end: 2, style: run }); - doc.create(page, NodeKind::Text(t), "Full run", 0.0, 0.0, 100.0, 30.0).unwrap(); + doc.create(page, NodeKind::Text(t.into()), "Full run", 0.0, 0.0, 100.0, 30.0).unwrap(); assert!(missing_penpot_font_warnings(&doc, &["Available Font".into()]).is_empty()); } } @@ -875,7 +875,7 @@ mod penpot_svg_v10_tests { let mut run = t.style.clone(); run.font_family = "Run Font".into(); t.runs = (0..50_000).map(|_| StyleRun { start: 0, end: 100_000, style: run.clone() }).collect(); - doc.create(page, NodeKind::Text(t), "Long", 0.0, 0.0, 100.0, 30.0).unwrap(); + doc.create(page, NodeKind::Text(t.into()), "Long", 0.0, 0.0, 100.0, 30.0).unwrap(); let report = font_report_with_families(&doc, &[]); assert_eq!(report["fonts"].as_array().map(Vec::len), Some(1), "{report}"); assert_eq!(report["fonts"][0]["family"], "Run Font"); @@ -921,7 +921,7 @@ mod penpot_svg_v10_tests { let page = doc.first_page().unwrap(); let mut text = TextData::new("Example"); text.style.font_family = "Definitely Never Installed V10 Font Q7".into(); - doc.create(page, NodeKind::Text(text), "Caption", 0.0, 0.0, 100.0, 24.0).unwrap(); + doc.create(page, NodeKind::Text(text.into()), "Caption", 0.0, 0.0, 100.0, 24.0).unwrap(); let report = font_report_with_families(&doc, &["Inter".into()]); assert_eq!(report["missing"], 1); assert_eq!(report["fonts"][0]["family"], "Definitely Never Installed V10 Font Q7"); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 79310056d..10291c20a 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1271,7 +1271,7 @@ fn set_path(cmd: &str, doc: &mut Document, id: NodeId, v: &Value, props: &Map Result { net.translate(-bb.x0, -bb.y0); let vid = doc.alloc_id(); let name = first.as_ref().map(|f| f.name.clone()).unwrap_or_else(|| "Vector".into()); - let mut v = Node::new(vid, NodeKind::Vector { network: net }, name, bb.width(), bb.height()); + let mut v = Node::new(vid, NodeKind::Vector { network: net.into() }, name, bb.width(), bb.height()); v.transform = Affine::translate((bb.x0, bb.y0)); if let Some(f) = first { v.fills = output_fills; @@ -620,7 +620,7 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result { let parent = n.parent.ok_or_else(|| bad("vector.outlineStroke", "page"))?; let idx = doc.index_in_parent(i); let vid = doc.alloc_id(); - let mut v = Node::new(vid, NodeKind::Vector { network: net }, n.name.clone(), bb.width(), bb.height()); + let mut v = Node::new(vid, NodeKind::Vector { network: net.into() }, n.name.clone(), bb.width(), bb.height()); v.transform = n.transform * Affine::translate((bb.x0, bb.y0)); // The stroke's paints (and its colour style) fill the outline. v.fills = n.strokes.clone(); @@ -698,6 +698,78 @@ fn sort_layout_children(doc: &Document, kids: &mut [NodeId], vertical: bool) { } } +/// What "Add auto layout" settled on for one frame, beyond the layout itself. +struct AddPlan { + layout: AutoLayout, + /// Width stays fixed (Figma fixes it in a vertical flow and with an Auto gap); otherwise it hugs. + fixed_width: bool, + /// A converted frame in a vertical flow shrinks to its content plus padding. + set_width: Option, + /// A wrap of one layer: the frame grows by this much around the layer and stays put on the canvas. + grow: f64, +} + +/// The layout "Add auto layout" gives a frame (measured in Figma's web app with synthetic +/// rectangles, 2026-11-09): height hugs; the width is fixed in a vertical flow and with an Auto +/// gap (main align Space between: two children, a gap at least the narrower child, and for a +/// converted frame equal left and right offsets), and hugs otherwise; a converted frame takes its +/// left and top offsets as padding, a wrap of several layers has none, a wrap of one layer pads 10. +fn add_layout(doc: &Document, frame: NodeId, new_wrap: bool, group: bool, dir: Option<&str>) -> AddPlan { + let wrapped = new_wrap || group; + let flow = figcraft_layout::flow_children(doc, frame); + let mut al = infer_layout(doc, frame); + let mut plan = AddPlan { layout: AutoLayout::default(), fixed_width: false, set_width: None, grow: 0.0 }; + if let Some(d) = dir { + al.mode = match d.to_ascii_lowercase().as_str() { + "vertical" | "column" => LayoutMode::Vertical, + "grid" => LayoutMode::Grid, + _ => LayoutMode::Horizontal, + }; + } + let Some(f) = doc.node(frame) else { + plan.layout = al; + return plan; + }; + if flow.is_empty() || (!wrapped && flow.len() == 1) { + plan.layout = al; + return plan; + } + if new_wrap && flow.len() == 1 { + al.padding = [10.0; 4]; + al.gap = 10.0; + plan.grow = 10.0; + plan.layout = al; + return plan; + } + let mut boxes: Vec = + flow.iter().filter_map(|c| doc.node(*c)).map(|c| figcraft_geom::transform_rect_bbox(c.transform, c.local_rect())).collect(); + let vertical = al.mode == LayoutMode::Vertical; + boxes.sort_by(|a, b| if vertical { a.y0.total_cmp(&b.y0) } else { a.x0.total_cmp(&b.x0) }); + let gaps: Vec = + boxes.windows(2).filter_map(|w| Some(if vertical { w.get(1)?.y0 - w.first()?.y1 } else { w.get(1)?.x0 - w.first()?.x1 })).collect(); + al.gap = if gaps.is_empty() { 10.0 } else { (gaps.iter().sum::() / gaps.len() as f64).max(0.0).round() }; + let all = boxes.iter().copied().reduce(|a, b| a.union(b)).unwrap_or_default(); + let (left, top) = (all.x0.max(0.0).round(), all.y0.max(0.0).round()); + al.padding = if wrapped { [0.0; 4] } else { [top, left, top, left] }; + let content_w = all.x1 - all.x0; + if vertical { + plan.fixed_width = true; + if !wrapped { + plan.set_width = Some(content_w + 2.0 * left); + } + } else if al.mode == LayoutMode::Horizontal && boxes.len() == 2 { + let narrower = boxes.iter().map(Rect::width).fold(f64::MAX, f64::min); + let gap = gaps.first().copied().unwrap_or(0.0); + let centred = wrapped || ((all.x0) - (f.width - all.x1)).abs() <= 0.5; + if gap > 0.0 && gap >= narrower && centred { + al.main_align = MainAlign::SpaceBetween; + plan.fixed_width = true; + } + } + plan.layout = al; + plan +} + /// Add inferred auto layout to existing frames or one group converted in place; wrap other /// selections. Preserve mask boundaries and a converted group's Fill sizing in its parent. fn layout_add(s: &mut Session, p: &Value) -> Result { @@ -725,29 +797,33 @@ fn layout_add(s: &mut Session, p: &Value) -> Result { }; let doc = s.doc_mut()?; for f in &targets { - let mut al = infer_layout(doc, *f); - if let Some(d) = &dir { - al.mode = match d.to_ascii_lowercase().as_str() { - "vertical" | "column" => LayoutMode::Vertical, - "grid" => LayoutMode::Grid, - _ => LayoutMode::Horizontal, - }; - } + let plan = add_layout(doc, *f, !in_place, single_group, dir.as_deref()); + let al = plan.layout; let mut kids = doc.get(*f)?.children.clone(); sort_layout_children(doc, &mut kids, al.mode == LayoutMode::Vertical); let empty = doc.node(*f).is_some_and(|n| n.children.iter().filter_map(|c| doc.node(*c)).all(|c| !c.visible || c.child_layout.absolute)); let n = doc.get_mut(*f)?; n.children = kids; n.layout = Some(al); + if single_group { + n.fills.clear(); + n.clip = false; + } + if plan.grow > 0.0 { + n.transform = Affine::translate((-plan.grow, -plan.grow)) * n.transform; + } if !in_place || !empty { // A frame wrapped around the selection hugs it; an existing frame with no flow // children keeps its size instead of collapsing to its padding. if !single_group || n.child_layout.sizing_h != Sizing::Fill { - n.child_layout.sizing_h = Sizing::Hug; + n.child_layout.sizing_h = if plan.fixed_width { Sizing::Fixed } else { Sizing::Hug }; } if !single_group || n.child_layout.sizing_v != Sizing::Fill { n.child_layout.sizing_v = Sizing::Hug; } + if let Some(w) = plan.set_width { + n.width = w; + } } } s.set_selection(targets.clone()); @@ -856,7 +932,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result { net = VectorNetwork::from_path(&simplified); net.regions.clear(); } - *network = net; + *network = net.into(); } } ok() @@ -888,7 +964,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let bounds = result.bounding_box(); result.apply_affine(Affine::translate((-bounds.x0, -bounds.y0))); let node = doc.get_mut(i)?; - node.kind = NodeKind::Vector { network: VectorNetwork::from_path(&result) }; + node.kind = NodeKind::Vector { network: VectorNetwork::from_path(&result).into() }; node.transform *= Affine::translate((bounds.x0, bounds.y0)); node.width = bounds.width(); node.height = bounds.height(); @@ -908,7 +984,7 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let bb = res.bounding_box(); res.apply_affine(Affine::translate((-bb.x0, -bb.y0))); let nm = doc.get_mut(i)?; - nm.kind = NodeKind::Vector { network: VectorNetwork::from_path(&res) }; + nm.kind = NodeKind::Vector { network: VectorNetwork::from_path(&res).into() }; nm.transform *= Affine::translate((bb.x0, bb.y0)); nm.width = bb.width(); nm.height = bb.height(); @@ -959,14 +1035,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { } let Some(bb) = net.bounds() else { let nm = doc.get_mut(i)?; - nm.kind = NodeKind::Vector { network: net }; + nm.kind = NodeKind::Vector { network: net.into() }; nm.width = 0.0; nm.height = 0.0; continue; }; net.translate(-bb.x0, -bb.y0); let nm = doc.get_mut(i)?; - nm.kind = NodeKind::Vector { network: net }; + nm.kind = NodeKind::Vector { network: net.into() }; nm.transform *= Affine::translate((bb.x0, bb.y0)); nm.width = bb.width(); nm.height = bb.height(); diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 64252c97a..0c81717b5 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -256,6 +256,48 @@ fn text_style_json(cmd: &str, v: &Value) -> Result { serde_json::from_value::(v).map(|t| t.as_text_style()).map_err(|e| bad(cmd, e.to_string())) } +/// A text style value from JSON: the character values from `style`, the paragraph values from +/// `paragraph` (the same object for the flat `value` of `style.create`). +fn text_kind(cmd: &str, style: &Value, paragraph: &Value) -> Result { + Ok(StyleKind::Text { style: text_style_json(cmd, style)?, paragraph: Box::new(paragraph_style_json(cmd, paragraph)?) }) +} + +/// Make or redefine this file's text style `name` from JSON (see [`text_kind`]). `bind` gives its +/// variable bindings from the document, the new value and the style it replaces. The style +/// redefined is the local text style of that name with the exported `id` (so a file re-importing +/// its own export keeps each style's identity when two share a name), else the first of that +/// name; never one in `touched`. True when one existed (with the style's id); the caller settles +/// and propagates. +pub(crate) fn upsert_text_style( + doc: &mut Document, + name: &str, + id: Option<&str>, + description: &str, + style: &Value, + paragraph: &Value, + touched: &[StyleId], + bind: impl FnOnce(&Document, &StyleKind, Option<&Style>) -> BTreeMap, +) -> Result<(StyleId, bool)> { + let kind = text_kind("variable.import", style, paragraph)?; + let eligible = |x: &Style| { + x.name == name && matches!(x.kind, StyleKind::Text { .. }) && !crate::library::is_remote_style(doc, &x.id) && !touched.contains(&x.id) + }; + let same = id.and_then(|id| doc.styles.iter().position(|x| x.id == id && eligible(x))).or_else(|| doc.styles.iter().position(&eligible)); + let updated = same.is_some(); + let bound = bind(doc, &kind, same.and_then(|i| doc.styles.get(i))); + let mut st = match same.and_then(|i| doc.styles.get(i)) { + Some(x) => Style { kind, bound, ..x.clone() }, + None => Style { id: doc.new_style_id(), name: name.to_string(), description: description.to_string(), kind, bound }, + }; + crate::style_vars::prune(&mut st); + let sid = st.id.clone(); + match same.and_then(|i| doc.styles.get_mut(i)) { + Some(slot) => *slot = st, + None => doc.styles.push(st), + } + Ok((sid, updated)) +} + /// The text style definition a layer's chars from `at` (None = its base style) show. fn text_style_of(n: &Node, at: Option) -> Option { let t = n.kind.text()?; @@ -361,7 +403,7 @@ fn create(s: &mut Session, p: &Value) -> Result { let kind = if let Some(v) = get(p, "value") { match t.as_str() { "paint" | "color" | "fill" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, + "text" => text_kind(cmd, v, v)?, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, "grid" => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => return Err(bad(cmd, "type: paint|text|effect|grid")), @@ -567,7 +609,7 @@ fn update(s: &mut Session, p: &Value) -> Result { let cur = doc.styles.get(idx).map(|x| x.kind.type_name()).unwrap_or("paint"); Some(match cur { "paint" => StyleKind::Paint { paints: paints_of(v).ok_or_else(|| bad(cmd, "value: paints"))? }, - "text" => StyleKind::Text { style: text_style_json(cmd, v)?, paragraph: Box::new(paragraph_style_json(cmd, v)?) }, + "text" => text_kind(cmd, v, v)?, "effect" => StyleKind::Effect { effects: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, _ => StyleKind::Grid { grids: serde_json::from_value(v.clone()).map_err(|e| bad(cmd, e.to_string()))? }, }) @@ -812,13 +854,13 @@ pub fn sync_text_styles(doc: &mut Document, ids: &[NodeId]) { } let link = t2.text_style_link().flatten().map(str::to_string); if t2 != *t || link != n.styles.text { - updates.push((id, link, t2)); + updates.push((id, link, (*t2).clone())); } } for (id, link, t2) in updates { if let Ok(n) = doc.get_mut(id) { n.styles.text = link; - n.kind = NodeKind::Text(t2); + n.kind = NodeKind::Text(t2.into()); } } } diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c4f4eaffd..f959ec12b 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -24,7 +24,8 @@ fn style(s: &mut Session, p: &Value, f: impl Fn(&mut TextStyle)) -> Result Vec { spec!( "variable.export", "Export variables", - "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], colour calculations as the colour they show in that mode with other collections in their default modes; numbers in px unless layers or scopes use them as opacity or font weight | tailwind: a Tailwind CSS v4 stylesheet, the default mode as an @theme block named the way inspect.code's tailwind utilities read them: --color-*, --radius-*, --text-*, --spacing-*, --font-*, unique per file; each other mode as in css; colour calculations as the colour they show in that mode, other collections in their default modes) | dart: a Dart file for Flutter, a class of constants per collection and mode (Color, double, String, bool), aliases and colour calculations resolved), path? (write it there)} → {text}, or {path} when written", + "{collections? [ids or names; default every collection of this file, not library copies], format? (json (default): the local variables JSON that variable.import reads, colour calculations as the colour they show in each mode with other collections in their default modes | css: custom properties, the default mode on :root and each other mode on [data-=\"\"], 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 { 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 { } } +/// 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, warnings: &mut Vec) -> (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, + doc: &Document, + kind: &StyleKind, + current: Option<&figcraft_doc::Style>, + warnings: &mut Vec, +) -> BTreeMap { + 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 { } } } - 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 + })) } diff --git a/crates/engine/src/content/synthetic.rs b/crates/engine/src/content/synthetic.rs index 589c5ab72..fc6b34d8e 100644 --- a/crates/engine/src/content/synthetic.rs +++ b/crates/engine/src/content/synthetic.rs @@ -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 { diff --git a/crates/engine/src/content/synthetic_ds.rs b/crates/engine/src/content/synthetic_ds.rs index be5268355..a16b2446e 100644 --- a/crates/engine/src/content/synthetic_ds.rs +++ b/crates/engine/src/content/synthetic_ds.rs @@ -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. diff --git a/crates/engine/src/convert_container_tests.rs b/crates/engine/src/convert_container_tests.rs index db1282932..2bb4180d7 100644 --- a/crates/engine/src/convert_container_tests.rs +++ b/crates/engine/src/convert_container_tests.rs @@ -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(); diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index 7e890cdb6..7b53a2d74 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -266,7 +266,7 @@ fn apply_radius(n: &mut Node, settings: &Settings) -> Option { /// 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 { 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); diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 700c1bec3..7e6369bdb 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -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 { 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}"); diff --git a/crates/engine/src/dev/codegen/uno.rs b/crates/engine/src/dev/codegen/uno.rs new file mode 100644 index 000000000..7d90f8482 --- /dev/null +++ b/crates/engine/src/dev/codegen/uno.rs @@ -0,0 +1,1322 @@ +//! Uno Platform C# Markup: a layer and its subtree as a fluent C# expression tree of WinUI +//! elements (`Uno.Extensions.Markup`), inside a small `UserControl` class. Lengths are fixed and +//! children sit at their offsets in a `Canvas`, as in the Flutter target before its auto layout +//! code. Whatever has no counterpart is left as a `// not mapped: …` comment in the chain. + +use std::collections::BTreeSet; + +use figcraft_color::{BlendMode, Color, ImageScaleMode, PaintKind}; +use figcraft_doc::{ + AutoLayout, CellAlign, CrossAlign, Document, EffectKind, HConstraint, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, + Sizing, StrokeAlign, TextAlignH, TextAlignV, TextAutoResize, TextCase, TextData, TextDecoration, TextStyle, VConstraint, +}; + +use super::swift::one_line; +use super::{Ctx, MAX_CHILDREN, first_fill, num, stroke_color}; + +/// Longest string literal written (characters); the rest is cut. +const MAX_LITERAL: usize = 10_000; +/// Longest layer name written into a comment (characters). +const MAX_COMMENT: usize = 80; +/// Longest identifier or asset name written (characters). +const MAX_IDENT: usize = 40; +/// Most style runs of one text written as `Run`s. +const MAX_RUNS: usize = 200; +/// Where the app keeps the images and vectors the code refers to. +const ASSETS: &str = "ms-appx:///Assets"; + +/// C# indents by four spaces. +pub(crate) fn uno_indent(depth: usize) -> String { + " ".repeat(depth) +} + +/// A C# string literal: `"` and `\` escaped, control and line separator characters as escapes, +/// never an interpolated string. Cut at [`MAX_LITERAL`] characters. +pub(crate) fn cs_literal(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars().take(MAX_LITERAL) { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + // Other control characters and the line and paragraph separators end a C# line. + c if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') => out.push_str(&format!("\\u{:04X}", u32::from(c))), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// C# reserved words, which an identifier may not be (all lowercase, so only camelCase meets them). +const CS_KEYWORDS: &[&str] = &[ + "abstract", + "as", + "base", + "bool", + "break", + "byte", + "case", + "catch", + "char", + "checked", + "class", + "const", + "continue", + "decimal", + "default", + "delegate", + "do", + "double", + "else", + "enum", + "event", + "explicit", + "extern", + "false", + "finally", + "fixed", + "float", + "for", + "foreach", + "goto", + "if", + "implicit", + "in", + "int", + "interface", + "internal", + "is", + "lock", + "long", + "namespace", + "new", + "null", + "object", + "operator", + "out", + "override", + "params", + "private", + "protected", + "public", + "readonly", + "ref", + "return", + "sbyte", + "sealed", + "short", + "sizeof", + "stackalloc", + "static", + "string", + "struct", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "uint", + "ulong", + "unchecked", + "unsafe", + "ushort", + "using", + "virtual", + "void", + "volatile", + "while", +]; + +/// The ASCII alphanumeric words of `name` after transliteration (so non-Latin names stay +/// readable), kept whole up to [`MAX_IDENT`] characters; the first word is kept even when it alone +/// is too long (the caller cuts it). +fn ascii_words(name: &str) -> Vec { + let mut kept: Vec = Vec::new(); + let mut len = 0; + for w in deunicode::deunicode(name).split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) { + if !kept.is_empty() && len + w.len() > MAX_IDENT { + break; + } + len += w.len(); + kept.push(w.to_string()); + } + kept +} + +/// A C# identifier from a layer name: words joined as PascalCase (`pascal`) or camelCase, cut at +/// [`MAX_IDENT`] characters on a word boundary. A name left with nothing takes `kind`; a leading +/// digit gets a `_` prefix and a reserved word a `_` suffix (never `@`). +pub(crate) fn cs_ident(name: &str, pascal: bool, kind: &str) -> String { + let mut out = String::new(); + for (i, w) in ascii_words(name).iter().enumerate() { + let mut cs = w.chars(); + let Some(first) = cs.next() else { continue }; + // The first letter of each word is upper-case (the first word of camelCase lower-case); + // the rest keeps its case, so `mainCard` stays recognisable. + if i == 0 && !pascal { + out.extend(first.to_lowercase()); + } else { + out.extend(first.to_uppercase()); + } + out.push_str(cs.as_str()); + } + let mut out: String = out.chars().take(MAX_IDENT).collect(); + if out.is_empty() { + let k: String = kind.chars().filter(char::is_ascii_alphanumeric).collect(); + let mut cs = k.chars(); + out = match cs.next() { + Some(f) if pascal => f.to_uppercase().chain(cs).collect(), + Some(f) => f.to_lowercase().chain(cs).collect(), + None => "Layer".into(), + }; + } + if out.starts_with(|c: char| c.is_ascii_digit()) { + out.insert(0, '_'); + } + if CS_KEYWORDS.contains(&out.as_str()) { + out.push('_'); + } + out +} + +/// `base` made unique among `used` (C# names are case-sensitive): `Card`, `Card2`, `Card3`, …. +pub(crate) fn cs_unique(base: &str, used: &mut BTreeSet) -> String { + let name = (1usize..) + .map(|k| if k == 1 { base.to_string() } else { format!("{base}{k}") }) + .find(|n| !used.contains(n)) + .unwrap_or_else(|| base.to_string()); + used.insert(name.clone()); + name +} + +/// The file name (without extension) of the image or vector asset of a layer: lowercase +/// `[a-z0-9_]`, starting with a letter, at most [`MAX_IDENT`] characters, unique among `used` +/// (`logo`, `logo_2`, `logo_3`, …). A name left with nothing takes `kind`. +pub(crate) fn asset_name(name: &str, kind: &str, used: &mut BTreeSet) -> String { + let mut base = ascii_words(name).iter().map(|w| w.to_ascii_lowercase()).collect::>().join("_"); + base = base.chars().take(MAX_IDENT).collect(); + let base = base.trim_end_matches('_').to_string(); + let base = if base.is_empty() { + let k: String = kind.to_ascii_lowercase().chars().filter(char::is_ascii_alphanumeric).collect(); + if k.is_empty() { "image".into() } else { k } + } else { + base + }; + let base = if base.starts_with(|c: char| c.is_ascii_digit()) { format!("img_{base}") } else { base }; + let name = + (1usize..).map(|k| if k == 1 { base.clone() } else { format!("{base}_{k}") }).find(|n| !used.contains(n)).unwrap_or_else(|| base.clone()); + used.insert(name.clone()); + name +} + +/// `Color.FromArgb(0xAA, 0xRR, 0xGG, 0xBB)` (needs `using Windows.UI;`). +pub(crate) fn cs_color(c: Color) -> String { + let [r, g, b, a] = c.to_rgba8(); + format!("Color.FromArgb(0x{a:02X}, 0x{r:02X}, 0x{g:02X}, 0x{b:02X})") +} + +/// A layer name for a comment line: one line, cut. +fn comment_name(name: &str) -> String { + let one = one_line(name); + let cut: String = one.chars().take(MAX_COMMENT).collect(); + if cut.chars().count() < one.chars().count() { format!("{cut}…") } else { cut } +} + +/// One element of the tree before it is written: comment lines above it, the local it is held +/// in, its constructor, the chain of property calls (a call starting with `//` is a comment +/// line) and its children. Children are added with `Children.Add(x)` or `Child = x`, never with +/// the fluent `.Children(…)` / `.Child(…)`, whose load time doubles with every level of nesting. +struct Element { + lead: Vec, + var: String, + ctor: String, + calls: Vec, + /// `Child` (a single child, assigned) or `Children` (added one by one), and the children. + adds: &'static str, + kids: Vec, +} + +impl Element { + fn new(ctor: &str) -> Self { + Element { lead: Vec::new(), var: String::new(), ctor: ctor.to_string(), calls: Vec::new(), adds: "Children", kids: Vec::new() } + } + + fn call(&mut self, c: impl Into) { + self.calls.push(c.into()); + } + + fn note(&mut self, what: &str) { + self.calls.push(format!("// not mapped: {what}")); + } + + /// The constructor and the chain at `depth`, as an expression without a trailing newline. + fn expr(&self, depth: usize) -> String { + let (pad, inner) = (uno_indent(depth), uno_indent(depth + 1)); + let mut out = format!("{pad}{}", self.ctor); + for c in &self.calls { + // A call of several lines is indented relative to its first. + out.push_str(&format!("\n{inner}{}", c.replace('\n', &format!("\n{inner}")))); + } + out + } + + /// The statements for this element and its subtree at `depth`: its comment lines, the + /// declaration of its local, then each child's statements followed by the line that adds it. + fn write(&self, depth: usize, out: &mut String) { + let (pad, inner) = (uno_indent(depth), uno_indent(depth + 1)); + for l in &self.lead { + out.push_str(&format!("{pad}{l}\n")); + } + out.push_str(&format!("{pad}var {} = {}", self.var, self.ctor)); + // The semicolon ends the last call, not a `// not mapped` comment after it. + let last = self.calls.iter().rposition(|c| !c.starts_with("//")); + if last.is_none() { + out.push(';'); + } + for (i, c) in self.calls.iter().enumerate() { + out.push_str(&format!("\n{inner}{}", c.replace('\n', &format!("\n{inner}")))); + if last == Some(i) { + out.push(';'); + } + } + out.push('\n'); + for k in &self.kids { + k.write(depth, out); + if self.adds == "Child" { + out.push_str(&format!("{pad}{}.Child = {};\n", self.var, k.var)); + } else { + out.push_str(&format!("{pad}{}.Children.Add({});\n", self.var, k.var)); + } + } + } +} + +/// Where a child sits in its parent: nowhere in particular (the root), at an offset in a +/// `Canvas`, in the flow of an `AutoLayout` (`z` is its paint order when the parent paints the first +/// child on top), over an `AutoLayout` at an offset that ignores it, or in a cell of a `Grid`. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Place { + Flow, + /// The layer the code is generated for: placed like `Flow`, but an auto layout frame that hugs + /// its content keeps hugging (its size then follows the content, as FigCraft's layout does). + Root, + At(f64, f64), + Line { + vertical: bool, + z: Option, + }, + Independent { + x: f64, + y: f64, + z: Option, + }, + /// In a cell of a `Grid`: row, column, spans and the alignment in the cell. + Cell { + row: usize, + column: usize, + row_span: usize, + column_span: usize, + align: (CellAlign, CellAlign), + }, + /// Over a `Grid`, across all its cells, at an offset that ignores it. + Overlay { + x: f64, + y: f64, + rows: usize, + columns: usize, + }, +} + +/// What a tree walk keeps between layers. +struct Gen<'a> { + ctx: &'a Ctx<'a>, + /// Asset names given out, so no two layers share a file. + assets: BTreeSet, + /// Frames written as a `Canvas` for lack of auto layout (one warning per view says how many). + free_frames: usize, + /// The names of the locals given out. + names: BTreeSet, +} + +/// Uno C# Markup for layer `id` and its subtree: a `UserControl` class whose content is the tree. +pub(crate) fn uno(doc: &Document, id: NodeId) -> String { + let Some(root) = doc.node(id) else { return String::new() }; + let ctx = Ctx::new(doc, id); + let mut g = Gen { ctx: &ctx, assets: BTreeSet::new(), free_frames: 0, names: BTreeSet::new() }; + let mut top = match g.layer(root, 0, Place::Root) { + Some(e) => e, + None => { + let mut e = Element::new("new Border()"); + e.var = "root".into(); + e + } + }; + if g.free_frames > 0 { + // One warning per view, above everything else written for the root layer. + let (count, verb) = if g.free_frames == 1 { + ("1 frame has".to_string(), "its children are") + } else { + (format!("{} frames have", g.free_frames), "children are") + }; + top.lead.insert(0, format!("// warning: {count} no auto layout: {verb} positioned absolutely and do not adapt to size.")); + } + // The statements sit two levels in: namespace member, constructor body. + let mut body = String::new(); + top.write(2, &mut body); + body.push_str(&format!("{}Content = {};\n", uno_indent(2), top.var)); + let mut out = String::new(); + let usings: Vec<&str> = [ + ("using Microsoft.UI.Text;", "FontWeights."), + ("using Windows.Foundation;", "new Rect("), + ("using Windows.UI;", "Color.FromArgb("), + ("using Windows.UI.Text;", "FontStyle."), + ("using Uno.Toolkit.UI;", "new AutoLayout("), + ] + .into_iter() + .filter(|(_, marker)| body.contains(marker)) + .map(|(u, _)| u) + .collect(); + for u in &usings { + out.push_str(u); + out.push('\n'); + } + if !usings.is_empty() { + out.push('\n'); + } + // A view named like a WinUI type (`Button`, `Border`) would hide it in the tree below. + let mut name = cs_ident(&root.name, true, "Layer"); + if !name.ends_with("View") { + name.push_str("View"); + } + out.push_str(&format!("// {}\nnamespace MyApp;\n\n", comment_name(&root.name))); + out.push_str(&format!("internal sealed partial class {name} : UserControl\n{{\n")); + out.push_str(&format!(" public {name}()\n {{\n{body} }}\n}}\n")); + out +} + +impl Gen<'_> { + /// A local name from a layer name, unique in the view (`card`, `card2`, …). + fn fresh(&mut self, name: &str, kind: &str) -> String { + let base = cs_ident(name, false, kind); + cs_unique(&base, &mut self.names) + } + + /// A layer and its subtree at `depth` (levels of nesting), placed in its parent as `at` says. + /// `None` for a layer that draws nothing. + fn layer(&mut self, n: &Node, depth: usize, at: Place) -> Option { + if matches!(n.kind, NodeKind::Slice) { + return None; + } + // The parent's name comes before its children's. + let var = self.fresh(&n.name, n.kind.label()); + if self.ctx.too_deep(depth) { + let mut e = Element::new("new Border()"); + e.lead.push(format!("// {} …", comment_name(&n.name))); + e.var = var; + return Some(e); + } + let mut e = match &n.kind { + NodeKind::Text(t) => self.text(n, t, at), + NodeKind::Ellipse { start, sweep, inner } => self.ellipse(n, (*start, *sweep, *inner), at), + NodeKind::Rectangle | NodeKind::Group | NodeKind::Section { .. } => self.boxed(n, depth, at), + k if k.is_frame_like() => self.boxed(n, depth, at), + _ => self.asset(n, at), + }; + e.var = var; + // The layer's name is the last comment line above the statement that creates its outermost + // element, below any `// warning:` line: the plugin that post-processes the code pairs + // elements with layers by it. `// not mapped:` lines sit in the chain, below the constructor. + e.lead.push(format!("// {}", comment_name(&n.name))); + Some(e) + } + + /// A frame-like layer, group or rectangle. Auto layout is an `AutoLayout` (horizontal, + /// vertical) or a `Grid` (grid mode); anything else is a `Border` holding a `Canvas` with the + /// children at their offsets. + fn boxed(&mut self, n: &Node, depth: usize, at: Place) -> Element { + match n.layout.as_ref() { + Some(l) if !matches!(n.kind, NodeKind::Rectangle) => self.auto_layout(n, l, depth, at), + _ => self.canvas_box(n, depth, at), + } + } + + /// A frame with auto layout: an `AutoLayout` (or, in grid mode, a `Grid`) that takes the box + /// (fill, border, corners) itself. A `Border` pushes its content in by its thickness, so + /// the padding is written less the stroke weight, as FigCraft's layout ignores strokes (unless + /// they are included). Where that would be negative the border sits behind the layout in a + /// `Grid`, as for a frame without auto layout. + fn auto_layout(&mut self, n: &Node, l: &AutoLayout, depth: usize, at: Place) -> Element { + let [pt, pr, pb, pl] = l.padding; + let weights = match (stroke_color(n), n.stroke.sides) { + (None, _) => [0.0; 4], + (Some(_), Some(s)) => s, + (Some(_), None) => [n.stroke.weight; 4], + }; + let weights = if l.strokes_included { [0.0; 4] } else { weights }; + let pad = [pt - weights[0], pr - weights[1], pb - weights[2], pl - weights[3]]; + let behind = pad.iter().any(|p| *p < 0.0); + let grid = l.mode == LayoutMode::Grid; + let mut line = Element::new(if grid { "new Grid()" } else { "new AutoLayout()" }); + let kids = self.ctx.kids(n); + let vertical = l.mode == LayoutMode::Vertical; + let mut absolute = false; + // Grid mode: where FigCraft's own layout puts each child. + let (cells, rows) = + if grid { figcraft_layout::grid_place(self.ctx.doc, l, &figcraft_layout::flow_children(self.ctx.doc, n.id)) } else { (Vec::new(), 0) }; + let tracks = GridTracks::new(l, rows); + let frame_align = ( + match l.main_align { + MainAlign::Center => CellAlign::Center, + MainAlign::Max => CellAlign::Max, + _ => CellAlign::Min, + }, + match l.cross_align { + CrossAlign::Center => CellAlign::Center, + CrossAlign::Max => CellAlign::Max, + _ => CellAlign::Min, + }, + ); + for (i, k) in kids.iter().enumerate().take(MAX_CHILDREN) { + let Some(c) = self.ctx.doc.node(*k) else { continue }; + // "First on top": the paint order descends, the order of the children stays. + let z = (l.reverse_z && !grid).then_some(kids.len() - i); + let place = if c.child_layout.absolute { + absolute = true; + let [_, _, _, _, x, y] = c.transform.as_coeffs(); + if grid { + // Against the grid's padded box, the offsets are the frame's less the padding. + Place::Overlay { + x: x - if behind { pl } else { pad[3] }, + y: y - if behind { pt } else { pad[0] }, + rows: tracks.rows, + columns: tracks.columns, + } + } else { + Place::Independent { x, y, z } + } + } else if grid { + match cells.iter().find(|cell| cell.id == *k) { + Some(cell) => { + let (cl, cr) = (cell.column.min(tracks.columns - 1), cell.row.min(tracks.rows - 1)); + Place::Cell { + row: cr, + column: cl, + row_span: cell.row_span.min(tracks.rows - cr), + column_span: cell.column_span.min(tracks.columns - cl), + align: (c.child_layout.grid_align_h.unwrap_or(frame_align.0), c.child_layout.grid_align_v.unwrap_or(frame_align.1)), + } + } + None => Place::Flow, + } + } else { + Place::Line { vertical, z } + }; + line.kids.extend(self.layer(c, depth + 1, place)); + } + // The Toolkit grows a hugging layout to cover a child that ignores it; FigCraft's does not. + let (aw, ah) = axes(n, at); + let force = (absolute && aw == Sizing::Hug, absolute && ah == Sizing::Hug); + let size = |e: &mut Element| { + dims(e, n, if force.0 { Sizing::Fixed } else { aw }, if force.1 { Sizing::Fixed } else { ah }); + if force.0 || force.1 { + e.note("hug size fixed: an absolute child would enlarge it"); + } + }; + let mut outer; + if behind { + // The layout inside keeps the whole padding; the border is drawn behind it. + let mut border = Element::new("new Border()"); + self.paint_box(&mut border, n, false, at); + if grid { + grid_calls(&mut line, l, &tracks, [pt, pr, pb, pl]); + } else { + layout_calls(&mut line, l, [pt, pr, pb, pl]); + } + outer = Element::new("new Grid()"); + place(&mut outer, n, at); + size(&mut outer); + border.var = self.fresh(&format!("{} border", n.name), "border"); + line.var = self.fresh(&format!("{} layout", n.name), "layout"); + outer.kids = vec![border, line]; + common(&mut outer, n); + } else { + outer = line; + place(&mut outer, n, at); + size(&mut outer); + self.paint_box(&mut outer, n, false, at); + if grid { + grid_calls(&mut outer, l, &tracks, pad); + } else { + layout_calls(&mut outer, l, pad); + } + common(&mut outer, n); + } + if n.clip && n.corners.radii.iter().all(|r| *r <= 0.0) && !n.children.is_empty() { + clip(&mut outer, n, at); + } + outer + } + + /// A frame-like layer, group or rectangle without a layout of its own to map: a `Border` + /// with its fill, stroke and corners holding a `Canvas` with the children at their offsets. + /// With a stroke and children the border sits behind the canvas in a `Grid`, since a `Border` + /// pushes its content in by its thickness. + fn canvas_box(&mut self, n: &Node, depth: usize, at: Place) -> Element { + let mut border = Element::new("new Border()"); + let sized = !matches!(n.kind, NodeKind::Group | NodeKind::Section { .. }); + self.paint_box(&mut border, n, sized, at); + let mut canvas = Element::new("new Canvas()"); + for k in self.ctx.kids(n).iter().take(MAX_CHILDREN) { + let Some(c) = self.ctx.doc.node(*k) else { continue }; + let [_, _, _, _, x, y] = c.transform.as_coeffs(); + canvas.kids.extend(self.layer(c, depth + 1, Place::At(x, y))); + } + let has_kids = !canvas.kids.is_empty(); + if has_kids { + canvas.var = self.fresh(&format!("{} canvas", n.name), "canvas"); + if n.layout.is_none() { + self.free_frames += 1; + } + } + let mut outer; + if has_kids && stroke_color(n).is_some() { + outer = Element::new("new Grid()"); + place(&mut outer, n, at); + size(&mut outer, n, at); + border.calls.retain(|c| !c.starts_with(".Width(") && !c.starts_with(".Height(")); + border.var = self.fresh(&format!("{} border", n.name), "border"); + outer.kids = vec![border, canvas]; + common(&mut outer, n); + } else { + outer = border; + place(&mut outer, n, at); + if has_kids { + outer.adds = "Child"; + outer.kids = vec![canvas]; + } + common(&mut outer, n); + } + if n.clip && has_kids && n.corners.radii.iter().all(|r| *r <= 0.0) { + clip(&mut outer, n, at); + } + outer + } + + /// The fill, stroke and corners of a `Border`. + fn paint_box(&mut self, e: &mut Element, n: &Node, sized: bool, at: Place) { + if sized { + size(e, n, at); + } + let visible: Vec<_> = n.fills.iter().filter(|p| p.visible).collect(); + match visible.first().map(|p| &p.kind) { + Some(PaintKind::Image(img)) => { + let name = asset_name(&n.name, "image", &mut self.assets); + let stretch = match img.scale_mode { + ImageScaleMode::Fit => "Uniform", + ImageScaleMode::Fill | ImageScaleMode::Crop | ImageScaleMode::Tile => "UniformToFill", + }; + e.call(format!(".Background(new ImageBrush().ImageSource(\"{ASSETS}/{name}.png\").Stretch(Stretch.{stretch}))")); + match img.scale_mode { + ImageScaleMode::Crop => e.note("image crop (drawn as fill)"), + ImageScaleMode::Tile => e.note("tiled image (drawn as fill)"), + ImageScaleMode::Fill | ImageScaleMode::Fit => {} + } + } + Some(PaintKind::Gradient(_)) => { + if let Some(c) = first_fill(n) { + e.call(format!(".Background({})", cs_color(c))); + } + e.note("gradient fill (its first stop colour is used)"); + } + Some(PaintKind::Pattern(_)) => e.note("pattern fill"), + Some(PaintKind::Solid { .. }) => { + if let Some(c) = first_fill(n) { + e.call(format!(".Background({})", cs_color(c))); + } + } + None => {} + } + if visible.len() > 1 { + e.note(&format!("{} more fills (only the first is drawn)", visible.len() - 1)); + } + if let Some(c) = stroke_color(n) { + e.call(format!(".BorderBrush({})", cs_color(c))); + match n.stroke.sides { + // Per-side weights are top, right, bottom, left; `Thickness` takes left first. + Some([t, r, b, l]) => e.call(format!(".BorderThickness(new Thickness({}, {}, {}, {}))", num(l), num(t), num(r), num(b))), + None => e.call(format!(".BorderThickness({})", num(n.stroke.weight))), + } + if n.stroke.align != StrokeAlign::Inside { + e.note("stroke outside or centred (a border is drawn inside)"); + } + } + let [tl, tr, br, bl] = n.corners.radii; + if n.corners.uniform().is_some() { + if tl > 0.0 { + e.call(format!(".CornerRadius({})", num(tl))); + } + } else { + e.call(format!(".CornerRadius(new CornerRadius({}, {}, {}, {}))", num(tl), num(tr), num(br), num(bl))); + } + if n.corners.smoothing > 0.0 && n.corners.radii.iter().any(|r| *r > 0.0) { + e.note("corner smoothing"); + } + } + + /// An ellipse: `Ellipse` with `Fill` and a centred `Stroke`. + fn ellipse(&mut self, n: &Node, (start, sweep, inner): (f64, f64, f64), at: Place) -> Element { + let mut e = Element::new("new Ellipse()"); + place(&mut e, n, at); + size(&mut e, n, at); + if let Some(c) = first_fill(n) { + e.call(format!(".Fill({})", cs_color(c))); + } + if let Some(c) = stroke_color(n) { + e.call(format!(".Stroke({})", cs_color(c))); + e.call(format!(".StrokeThickness({})", num(n.stroke.weight))); + if n.stroke.align != StrokeAlign::Center { + e.note("stroke inside or outside (an ellipse stroke is centred)"); + } + } + if start != 0.0 || (sweep - std::f64::consts::TAU).abs() > 1e-6 || inner > 0.0 { + e.note("arc or ring (drawn as a full ellipse)"); + } + common(&mut e, n); + e + } + + /// A vector, shape or other layer without a counterpart: a `Path` with the outline as path + /// data, which takes the theme's colours; or, when the layer is more than one plain fill and + /// one plain stroke, the image the app is to hold. + fn asset(&mut self, n: &Node, at: Place) -> Element { + if let Some(e) = self.path(n, at) { + return e; + } + let name = asset_name(&n.name, n.kind.label(), &mut self.assets); + let mut e = Element::new("new Image()"); + e.lead.push(format!("// {} \"{}\": export it as a PNG to Assets/{name}.png", n.kind.label(), comment_name(&n.name))); + place(&mut e, n, at); + e.call(format!(".Source(\"{ASSETS}/{name}.png\")")); + size(&mut e, n, at); + e.call(".Stretch(Stretch.Uniform)"); + common(&mut e, n); + e + } + + /// The layer's outline as a `Microsoft.UI.Xaml.Shapes.Path` (written in full: the implicit + /// usings bring in `System.IO`, whose `Path` clashes), with at most one solid fill and one solid + /// stroke. `None` when the layer needs the image: a gradient, image or pattern paint, several + /// fills or strokes, effects, no outline, or an outline past [`MAX_PATH_ELEMENTS`]. + fn path(&mut self, n: &Node, at: Place) -> Option { + let fills: Vec<_> = n.fills.iter().filter(|p| p.visible).collect(); + let strokes: Vec<_> = n.strokes.iter().filter(|p| p.visible).collect(); + let plain = |ps: &[&figcraft_color::Paint]| ps.iter().all(|p| matches!(p.kind, PaintKind::Solid { .. })); + if fills.len() > 1 || strokes.len() > 1 || !plain(&fills) || !plain(&strokes) || n.effects.iter().any(|f| f.visible) { + return None; + } + let (outline, rule) = figcraft_render::node_outline(self.ctx.doc, n)?; + let data = path_data(&outline, rule)?; + let mut e = Element::new("new Microsoft.UI.Xaml.Shapes.Path()"); + place(&mut e, n, at); + e.call(format!(".Data({})", cs_literal(&data))); + if let Some(c) = first_fill(n) { + e.call(format!(".Fill({})", cs_color(c))); + } + if let Some(c) = stroke_color(n) { + e.call(format!(".Stroke({})", cs_color(c))); + e.call(format!(".StrokeThickness({})", num(n.stroke.weight))); + if n.stroke.align != StrokeAlign::Center { + // A `Path` stroke is centred on the outline. + e.note("stroke inside or outside (drawn centred)"); + } + } + size(&mut e, n, at); + common(&mut e, n); + Some(e) + } + + /// Text: a `TextBlock`, in a `Grid` of the box's height when it is aligned to the middle or + /// bottom of a fixed box. An explicit line height puts half the leading above the first line in + /// FigCraft and all of it below in Uno, so the text is moved down by the half-leading. + fn text(&mut self, n: &Node, t: &TextData, at: Place) -> Element { + let fixed = matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate); + let framed = fixed && t.align_v != TextAlignV::Top; + let mut tb = text_block(n, t, !framed, line_axes(n, at)); + let leading = leading(&t.style); + // In a `Canvas` the offset takes the shift; anywhere else the recipe below does. + let at_text = match (leading, at) { + (Leading::Shift(h), Place::At(x, y)) if !framed => Place::At(x, y + h), + _ => at, + }; + if !framed { + place(&mut tb, n, at_text); + leading_calls(&mut tb, leading, !matches!(at_text, Place::At(..))); + common(&mut tb, n); + return tb; + } + leading_calls(&mut tb, leading, true); + tb.call(format!(".VerticalAlignment(VerticalAlignment.{})", if t.align_v == TextAlignV::Middle { "Center" } else { "Bottom" })); + let mut g = Element::new("new Grid()"); + place(&mut g, n, at); + size(&mut g, n, at); + tb.var = self.fresh(&format!("{} text", n.name), "text"); + g.kids = vec![tb]; + common(&mut g, n); + g + } +} + +/// The calls that address a child in its parent, first in its chain: the `Canvas` offsets, or +/// the attached `AutoLayout` call (fill on an axis, or independent of the layout), the paint +/// order and the size limits. +fn place(e: &mut Element, n: &Node, at: Place) { + let mut lead: Vec = Vec::new(); + let z = |z: Option, lead: &mut Vec| { + if let Some(z) = z { + lead.push(format!(".Canvas(zIndex: {z})")); + } + }; + match at { + Place::Flow | Place::Root => {} + // The offsets read as the element's address. + Place::At(x, y) => lead.push(format!(".Canvas(left: {}, top: {})", num(x), num(y))), + Place::Line { vertical, z: order } => { + let cl = &n.child_layout; + let (primary, counter) = if vertical { (cl.sizing_v, cl.sizing_h) } else { (cl.sizing_h, cl.sizing_v) }; + let mut args: Vec<&str> = Vec::new(); + if primary == Sizing::Fill { + args.push("primaryAlignment: AutoLayoutPrimaryAlignment.Stretch"); + } + if counter == Sizing::Fill { + args.push("counterAlignment: AutoLayoutAlignment.Stretch"); + } + if !args.is_empty() { + lead.push(format!(".AutoLayout({})", args.join(", "))); + } + z(order, &mut lead); + for (name, v) in [("MinWidth", cl.min_w), ("MaxWidth", cl.max_w), ("MinHeight", cl.min_h), ("MaxHeight", cl.max_h)] { + if let Some(v) = v.filter(|v| v.is_finite()) { + lead.push(format!(".{name}({})", num(v))); + } + } + } + Place::Cell { row, column, row_span, column_span, align } => { + let mut args = format!("row: {row}, column: {column}"); + if row_span > 1 { + args.push_str(&format!(", rowSpan: {row_span}")); + } + if column_span > 1 { + args.push_str(&format!(", columnSpan: {column_span}")); + } + lead.push(format!(".Grid({args})")); + cell_alignment(n, align, &mut lead); + let cl = &n.child_layout; + for (name, v) in [("MinWidth", cl.min_w), ("MaxWidth", cl.max_w), ("MinHeight", cl.min_h), ("MaxHeight", cl.max_h)] { + if let Some(v) = v.filter(|v| v.is_finite()) { + lead.push(format!(".{name}({})", num(v))); + } + } + } + Place::Overlay { x, y, rows, columns } => { + lead.push(format!(".Grid(row: 0, column: 0, rowSpan: {rows}, columnSpan: {columns})")); + lead.push(".HorizontalAlignment(HorizontalAlignment.Left)".into()); + lead.push(".VerticalAlignment(VerticalAlignment.Top)".into()); + lead.push(format!(".Margin({}, {}, 0, 0)", num(x), num(y))); + if n.constraints.horizontal != HConstraint::Left || n.constraints.vertical != VConstraint::Top { + e.note("constraints (the child stays at its top-left offset)"); + } + } + Place::Independent { x, y, z: order } => { + lead.push(".AutoLayout(isIndependentLayout: true)".into()); + z(order, &mut lead); + lead.push(".HorizontalAlignment(HorizontalAlignment.Left)".into()); + lead.push(".VerticalAlignment(VerticalAlignment.Top)".into()); + lead.push(format!(".Margin({}, {}, 0, 0)", num(x), num(y))); + if n.constraints.horizontal != HConstraint::Left || n.constraints.vertical != VConstraint::Top { + e.note("constraints (the child stays at its top-left offset)"); + } + } + } + e.calls.splice(0..0, lead); +} + +/// The sizes of a cell child's alignment: a filling axis stretches (the cell's default), any +/// other aligns in its cell. +fn cell_alignment(n: &Node, align: (CellAlign, CellAlign), lead: &mut Vec) { + let cl = &n.child_layout; + if cl.sizing_h != Sizing::Fill { + let a = match align.0 { + CellAlign::Min => "Left", + CellAlign::Center => "Center", + CellAlign::Max => "Right", + }; + lead.push(format!(".HorizontalAlignment(HorizontalAlignment.{a})")); + } + if cl.sizing_v != Sizing::Fill { + let a = match align.1 { + CellAlign::Min => "Top", + CellAlign::Center => "Center", + CellAlign::Max => "Bottom", + }; + lead.push(format!(".VerticalAlignment(VerticalAlignment.{a})")); + } +} + +/// Clip content to the layer's box. The clip is a fixed rectangle, so it is written only for a +/// layer that is fixed on both axes; one that hugs or fills would cut its content at the size it has +/// in the design once it grows. +fn clip(e: &mut Element, n: &Node, at: Place) { + if axes(n, at) == (Sizing::Fixed, Sizing::Fixed) { + e.call(format!(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, {}, {})))", num(n.width), num(n.height))); + } else { + e.note("clip content on a frame that hugs or fills"); + } +} + +/// How a layer sizes on each axis: in an auto layout flow as its parent lays it out, as the root by its +/// own hug, and fixed everywhere else. +fn axes(n: &Node, at: Place) -> (Sizing, Sizing) { + match at { + Place::Line { .. } | Place::Cell { .. } => (n.child_layout.sizing_h, n.child_layout.sizing_v), + // With no parent to fill, only a hug of the root's own auto layout is kept. + Place::Root if n.layout.is_some() && n.kind.is_frame_like() => { + let own = |s: Sizing| if s == Sizing::Hug { Sizing::Hug } else { Sizing::Fixed }; + (own(n.child_layout.sizing_h), own(n.child_layout.sizing_v)) + } + _ => (Sizing::Fixed, Sizing::Fixed), + } +} + +/// [`axes`] for a text in a flow (outside one a text sizes itself from its resize mode). +fn line_axes(n: &Node, at: Place) -> Option<(Sizing, Sizing)> { + matches!(at, Place::Line { .. } | Place::Cell { .. }).then(|| axes(n, at)) +} + +/// The tracks a grid frame is written with: how many of each, and what had to be cut or rounded. +struct GridTracks { + columns: usize, + rows: usize, + cut: bool, +} + +/// Most tracks written per axis. +const MAX_WRITTEN_TRACKS: usize = 64; + +impl GridTracks { + fn new(l: &AutoLayout, rows: usize) -> Self { + let (columns, rows) = ((l.grid_columns as usize).max(1), rows.max(1)); + GridTracks { + columns: columns.min(MAX_WRITTEN_TRACKS), + rows: rows.min(MAX_WRITTEN_TRACKS), + cut: columns > MAX_WRITTEN_TRACKS || rows > MAX_WRITTEN_TRACKS, + } + } +} + +/// A `ColumnDefinitions` / `RowDefinitions` string for `count` tracks: fixed ones in pixels, hugging +/// ones `Auto`, filling ones as stars. Uno ignores fractional stars, so the shares of an axis are +/// scaled by the smallest factor up to 100 that makes them whole; the flag says they could not be +/// and were rounded. A track missing from `specs` fills one share. +fn track_string(specs: &[figcraft_doc::GridTrack], count: usize) -> (String, bool) { + let spec = |i: usize| specs.get(i).copied().unwrap_or_default(); + let share = |t: figcraft_doc::GridTrack| if t.value.is_finite() { t.value.clamp(0.0, 1e6) } else { 0.0 }; + let shares: Vec = (0..count).map(&spec).filter(|t| t.sizing == Sizing::Fill).map(share).collect(); + let whole = |k: f64| shares.iter().all(|f| (f * k - (f * k).round()).abs() < 1e-6); + let factor = (1..=100).map(f64::from).find(|k| whole(*k)); + let k = factor.unwrap_or(1.0); + let out: Vec = (0..count) + .map(|i| { + let t = spec(i); + match t.sizing { + Sizing::Fixed => num(share(t)), + Sizing::Hug => "Auto".to_string(), + Sizing::Fill => format!("{}*", num((share(t) * k).round().max(if factor.is_some() { 0.0 } else { 1.0 }))), + } + }) + .collect(); + (out.join(","), factor.is_none()) +} + +/// The calls a `Grid` takes for its tracks, spacing and padding. In grid mode FigCraft's `gap` is +/// the space between columns and `cross_gap` between rows (`layout_grid` reads them as `gx`, `gy`), +/// and the main and cross alignment are the children's default alignment in their cell. +fn grid_calls(e: &mut Element, l: &AutoLayout, t: &GridTracks, pad: [f64; 4]) { + let (columns, rounded_c) = track_string(&l.column_tracks, t.columns); + let (rows, rounded_r) = track_string(&l.row_tracks, t.rows); + e.call(format!(".ColumnDefinitions({})", cs_literal(&columns))); + e.call(format!(".RowDefinitions({})", cs_literal(&rows))); + if l.gap > 0.0 { + e.call(format!(".ColumnSpacing({})", num(l.gap))); + } + if l.cross_gap > 0.0 { + e.call(format!(".RowSpacing({})", num(l.cross_gap))); + } + padding_call(e, pad); + if rounded_c || rounded_r { + e.note("fractional grid track sizes (rounded to whole stars)"); + } + if t.cut { + e.note(&format!("more than {MAX_WRITTEN_TRACKS} grid tracks (only {MAX_WRITTEN_TRACKS} per axis are written)")); + } + if l.reverse_z { + e.note("first child on top (a grid paints its children in order)"); + } +} + +/// `Padding` from top, right, bottom, left: one number when equal, nothing when zero. +fn padding_call(e: &mut Element, pad: [f64; 4]) { + let [t, r, b, lf] = pad; + if pad.iter().any(|p| *p != 0.0) { + if t == r && r == b && b == lf { + e.call(format!(".Padding({})", num(t))); + } else { + e.call(format!(".Padding({}, {}, {}, {})", num(lf), num(t), num(r), num(b))); + } + } +} + +/// What an explicit line height asks of a text. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Leading { + /// An automatic line height, or one so close to the font's own that there is nothing to move. + None, + /// The text moves down by the half-leading (pixels). + Shift(f64), + /// The line height is below the font's natural height: block line stacking draws it as written. + Tight, + /// The font family is not installed where the code is written, so its metrics are unknown. + NoFont, +} + +/// The half-leading of a text style: `h = (L - (ascent + descent) / upem * size) / 2` for the +/// explicit line height `L`, from the face FigCraft itself draws with. The number depends on the +/// fonts installed where `inspect.code` runs. `find_face` falls back to the default face, so +/// `has_family` tells whether the family is really here. +fn leading(s: &TextStyle) -> Leading { + let size = s.font_size; + if !size.is_finite() || size <= 0.0 { + return Leading::None; + } + let l = match s.line_height { + LineHeight::Pixels(v) if v > 0.0 && v.is_finite() => v, + LineHeight::Percent(p) if p > 0.0 && p.is_finite() => p / 100.0 * size, + _ => return Leading::None, + }; + if !figcraft_text::has_family(&s.font_family) { + return Leading::NoFont; + } + let Some(face) = figcraft_text::find_face(&s.font_family, &s.font_style) else { return Leading::NoFont }; + if face.upem <= 0.0 || !face.upem.is_finite() { + return Leading::NoFont; + } + let h = (l - (face.ascent + face.descent) / face.upem * size) / 2.0; + if !h.is_finite() || h.abs() < 0.5 { + Leading::None + } else if h < 0.0 { + // Uno's default stacking never draws a line closer than the font's natural height; + // `BlockLineHeight` does (measured), so the lines keep `LineHeight` as written. + Leading::Tight + } else { + Leading::Shift(h) + } +} + +/// The calls (or note) a [`Leading`] needs. A tight line height needs no shift, only the stacking +/// strategy (the `LineHeight` call itself comes with the text style). `flow`: the text sits in a panel, where the shift is a +/// top padding with a negative bottom margin that gives the room back (the box keeps its height +/// and the last line is not cut); an existing margin (an independent child's offsets) is merged. +fn leading_calls(e: &mut Element, leading: Leading, flow: bool) { + match leading { + Leading::None => {} + Leading::Tight => e.call(".LineStackingStrategy(LineStackingStrategy.BlockLineHeight)"), + Leading::NoFont => e.note("line height shift (the font is not installed here, so its metrics are unknown)"), + Leading::Shift(h) if flow => { + e.call(format!(".Padding(0, {}, 0, 0)", num(h))); + match e.calls.iter().position(|c| c.starts_with(".Margin(") && c.ends_with(", 0, 0)")) { + Some(i) => { + if let Some(c) = e.calls.get_mut(i) { + let head = c.trim_end_matches(", 0, 0)").to_string(); + *c = format!("{head}, 0, {})", num(-h)); + } + } + None => e.call(format!(".Margin(0, 0, 0, {})", num(-h))), + } + } + Leading::Shift(_) => {} + } +} + +/// Most elements (moves, lines, curves, closes) of an outline written as path data. +const MAX_PATH_ELEMENTS: usize = 5_000; + +/// An outline as the path mini-language of `Path.Data`: a fill rule (`F1` non-zero, `F0` even-odd) +/// then `M x y`, `L x y`, `Q cx cy x y`, `C c1x c1y c2x c2y x y` and `Z`, numbers through [`num`]. +/// `None` for an empty outline, one with a coordinate that is not finite, one past +/// [`MAX_PATH_ELEMENTS`], or one whose text is longer than [`MAX_LITERAL`] (which [`cs_literal`] +/// would cut, leaving broken geometry): the layer is then exported as an image. +pub(crate) fn path_data(path: &figcraft_geom::BezPath, rule: figcraft_render::FillRule) -> Option { + use figcraft_geom::kurbo::PathEl; + let els = path.elements(); + if els.is_empty() || els.len() > MAX_PATH_ELEMENTS { + return None; + } + let pt = |p: figcraft_geom::Point| (p.x.is_finite() && p.y.is_finite()).then(|| format!("{} {}", num(p.x), num(p.y))); + let mut out = String::from(if rule == figcraft_render::FillRule::EvenOdd { "F0" } else { "F1" }); + for el in els { + let part = match *el { + PathEl::MoveTo(p) => format!("M {}", pt(p)?), + PathEl::LineTo(p) => format!("L {}", pt(p)?), + PathEl::QuadTo(c, p) => format!("Q {} {}", pt(c)?, pt(p)?), + PathEl::CurveTo(c1, c2, p) => format!("C {} {} {}", pt(c1)?, pt(c2)?, pt(p)?), + PathEl::ClosePath => "Z".to_string(), + }; + out.push(' '); + out.push_str(&part); + if out.len() > MAX_LITERAL { + return None; + } + } + Some(out) +} + +/// The calls an `AutoLayout` takes for its orientation, gap, padding (`pad` is top, right, +/// bottom, left as written) and alignment. +fn layout_calls(e: &mut Element, l: &AutoLayout, pad: [f64; 4]) { + e.call(format!(".Orientation(Orientation.{})", if l.mode == LayoutMode::Vertical { "Vertical" } else { "Horizontal" })); + // The space distributions make the gaps themselves. + if l.gap != 0.0 && !l.main_align.is_auto_gap() { + e.call(format!(".Spacing({})", num(l.gap))); + } + padding_call(e, pad); + if l.wrap { + e.note("wrap (FlexPanel needs Uno.Toolkit 10; one line written)"); + } + match l.main_align { + MainAlign::Min => {} + MainAlign::Center => e.call(".PrimaryAxisAlignment(AutoLayoutAlignment.Center)"), + MainAlign::Max => e.call(".PrimaryAxisAlignment(AutoLayoutAlignment.End)"), + MainAlign::SpaceBetween => e.call(".Justify(AutoLayoutJustify.SpaceBetween)"), + MainAlign::SpaceAround | MainAlign::SpaceEvenly => { + e.call(".Justify(AutoLayoutJustify.SpaceBetween)"); + e.note("space around/evenly exported as space between"); + } + } + match l.cross_align { + CrossAlign::Min => {} + CrossAlign::Center => e.call(".CounterAxisAlignment(AutoLayoutAlignment.Center)"), + CrossAlign::Max => e.call(".CounterAxisAlignment(AutoLayoutAlignment.End)"), + CrossAlign::Baseline => e.note("baseline alignment (children are aligned to the start)"), + } +} + +/// The layer's width and height on the axes where it is fixed (a hugging axis takes its size +/// from the content, a filling one from the parent). +fn size(e: &mut Element, n: &Node, at: Place) { + let (w, h) = axes(n, at); + dims(e, n, w, h); +} + +fn dims(e: &mut Element, n: &Node, w: Sizing, h: Sizing) { + if w == Sizing::Fixed { + e.call(format!(".Width({})", num(n.width))); + } + if h == Sizing::Fixed { + e.call(format!(".Height({})", num(n.height))); + } +} + +/// What every layer shares: opacity, rotation, and the notes for what has no counterpart. +fn common(e: &mut Element, n: &Node) { + if n.opacity < 1.0 { + e.call(format!(".Opacity({})", num(f64::from(n.opacity)))); + } + // Rotation turns counter-clockwise about the top-left corner (the offsets given); a WinUI + // `RotateTransform` turns clockwise about the element's own origin. + let rot = figcraft_geom::rotation_degrees(n.transform); + if rot.abs() > 0.01 && rot.is_finite() { + e.call(format!(".RenderTransform(new RotateTransform().Angle({}))", num(-rot))); + } + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) { + e.note(&format!("blend mode {}", n.blend.css())); + } + for fx in n.effects.iter().filter(|f| f.visible) { + e.note(match fx.kind { + EffectKind::DropShadow(_) => "drop shadow (needs Uno.Toolkit ShadowContainer)", + EffectKind::InnerShadow(_) => "inner shadow (needs Uno.Toolkit ShadowContainer)", + EffectKind::LayerBlur(_) => "layer blur", + EffectKind::BackgroundBlur(_) => "background blur", + EffectKind::Noise(_) => "noise", + EffectKind::Texture(_) => "texture", + EffectKind::Glass(_) => "glass", + }); + } + if n.is_mask { + e.note("mask"); + } +} + +/// `FontWeights.SemiBold` for a weight in hundreds (the nearest). +fn cs_weight(w: u16) -> &'static str { + match w { + 0..=150 => "Thin", + 151..=250 => "ExtraLight", + 251..=350 => "Light", + 351..=450 => "Normal", + 451..=550 => "Medium", + 551..=650 => "SemiBold", + 651..=750 => "Bold", + 751..=850 => "ExtraBold", + 851..=950 => "Black", + _ => "ExtraBlack", + } +} + +/// The colour of the first visible solid or gradient paint (a gradient's first stop). +fn paints_color(paints: &[figcraft_color::Paint]) -> Option { + paints.iter().filter(|p| p.visible).find_map(|p| match &p.kind { + PaintKind::Solid { color } => Some(color.with_alpha(color.a * p.opacity)), + PaintKind::Gradient(g) => g.sorted_stops().first().map(|s| s.color), + PaintKind::Image(_) | PaintKind::Pattern(_) => None, + }) +} + +/// `characters` as a string expression in `case`: the case is applied when the code runs, so the +/// string keeps the original text (and the app can translate it). +fn text_expr(characters: &str, case: TextCase) -> String { + let lit = cs_literal(characters); + match case { + TextCase::Original | TextCase::SmallCaps => lit, + TextCase::Upper => format!("{lit}.ToUpperInvariant()"), + TextCase::Lower => format!("{lit}.ToLowerInvariant()"), + TextCase::Title => format!("System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase({lit})"), + } +} + +/// The calls a `TextBlock` or `Run` takes for the parts of `s` that differ from `base` (all of +/// them without a base). `fill` is the colour the text is drawn in. +fn style_calls(e: &mut Element, s: &TextStyle, fill: Option, base: Option<(&TextStyle, Option)>) { + if !s.font_family.is_empty() && base.is_none_or(|(b, _)| b.font_family != s.font_family) { + e.call(format!(".FontFamily({})", cs_literal(&s.font_family))); + } + if base.is_none_or(|(b, _)| b.font_size != s.font_size) { + e.call(format!(".FontSize({})", num(s.font_size))); + } + if (base.is_none() && s.weight() != 400) || base.is_some_and(|(b, _)| b.weight() != s.weight()) { + e.call(format!(".FontWeight(FontWeights.{})", cs_weight(s.weight()))); + } + if (base.is_none() && s.italic()) || base.is_some_and(|(b, _)| b.italic() != s.italic()) { + e.call(format!(".FontStyle(FontStyle.{})", if s.italic() { "Italic" } else { "Normal" })); + } + if let Some(c) = fill + && base.is_none_or(|(_, f)| f != fill) + { + e.call(format!(".Foreground({})", cs_color(c))); + } + if base.is_none() { + match s.line_height { + LineHeight::Pixels(v) if v > 0.0 && v.is_finite() => e.call(format!(".LineHeight({})", num(v))), + LineHeight::Percent(p) if p > 0.0 && p.is_finite() && s.font_size > 0.0 => { + e.call(format!(".LineHeight({})", num(p / 100.0 * s.font_size))) + } + _ => {} + } + } + // `CharacterSpacing` is in thousandths of an em. + let spacing = |x: &TextStyle| match x.letter_spacing { + LetterSpacing::Pixels(v) if v.is_finite() && x.font_size > 0.0 => (v / x.font_size * 1000.0).round(), + LetterSpacing::Percent(p) if p.is_finite() => (p * 10.0).round(), + _ => 0.0, + }; + if base.is_none_or(|(b, _)| spacing(b) != spacing(s)) && (base.is_some() || spacing(s) != 0.0) { + e.call(format!(".CharacterSpacing({})", num(spacing(s)))); + } + if base.is_none_or(|(b, _)| b.decoration != s.decoration) { + match s.decoration { + TextDecoration::None if base.is_some() => e.call(".TextDecorations(Windows.UI.Text.TextDecorations.None)"), + TextDecoration::None => {} + TextDecoration::Underline => e.call(".TextDecorations(Windows.UI.Text.TextDecorations.Underline)"), + TextDecoration::Strikethrough => e.call(".TextDecorations(Windows.UI.Text.TextDecorations.Strikethrough)"), + } + } +} + +/// A `TextBlock` for a text layer. `with_height` sets the box's height when the text has a fixed +/// box (a text in a `Grid` of that height leaves it to the grid). +fn text_block(n: &Node, t: &TextData, with_height: bool, axes: Option<(Sizing, Sizing)>) -> Element { + let mut e = Element::new("new TextBlock()"); + let s = &t.style; + let fill = first_fill(n); + // Text in one style is a `Text`; style runs make `Inlines` of `Run`s. + let runs: Vec<_> = t.runs.iter().filter(|r| r.start < r.end).collect(); + let chars: Vec = t.characters.chars().take(MAX_LITERAL * 10).collect(); + if runs.is_empty() || runs.len() > MAX_RUNS { + e.call(format!(".Text({})", text_expr(&t.characters, s.case))); + if !runs.is_empty() { + e.note("style runs (too many)"); + } + } else { + let mut pieces: Vec = Vec::new(); + let mut at = 0; + let mut run = |from: usize, to: usize, style: &TextStyle, fills: Option, plain: bool| { + let part: String = chars.get(from..to.min(chars.len())).unwrap_or_default().iter().collect(); + if part.is_empty() { + return; + } + let mut r = Element::new("new Run()"); + r.call(format!(".Text({})", text_expr(&part, style.case))); + if !plain { + style_calls(&mut r, style, fills, Some((s, fill))); + } + pieces.push(r.expr(1)); + }; + for r in &runs { + let (start, end) = (r.start.max(at), r.end.min(chars.len())); + if start >= end { + continue; + } + run(at, start, s, fill, true); + let run_fill = r.style.fills.as_deref().and_then(paints_color).or(fill); + run(start, end, &r.style, run_fill, false); + at = end; + } + run(at, chars.len(), s, fill, true); + e.call(format!(".Inlines(\n{})", pieces.join(",\n"))); + } + style_calls(&mut e, s, fill, None); + match t.align_h { + TextAlignH::Left => {} + TextAlignH::Center => e.call(".TextAlignment(TextAlignment.Center)"), + TextAlignH::Right => e.call(".TextAlignment(TextAlignment.Right)"), + TextAlignH::Justified => e.call(".TextAlignment(TextAlignment.Justify)"), + } + // In a flow the text takes its width from the sizing: hugging is one line, filling wraps at + // the parent's width, fixed is the box's width. + let one_line = t.auto_resize == TextAutoResize::WidthAndHeight; + // Outside a flow the resize mode says it. + let (width, tall) = axes.unwrap_or((if one_line { Sizing::Hug } else { Sizing::Fixed }, Sizing::Fixed)); + match width { + Sizing::Hug => e.call(".TextWrapping(TextWrapping.NoWrap)"), + Sizing::Fill => e.call(".TextWrapping(TextWrapping.Wrap)"), + Sizing::Fixed => { + e.call(format!(".Width({})", num(n.width))); + e.call(format!(".TextWrapping(TextWrapping.{})", if one_line { "NoWrap" } else { "Wrap" })); + } + } + if tall == Sizing::Fixed && with_height && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Truncate) { + e.call(format!(".Height({})", num(n.height))); + } + if t.auto_resize == TextAutoResize::Truncate || (t.max_lines > 0 && t.auto_resize != TextAutoResize::WidthAndHeight) { + e.call(".TextTrimming(TextTrimming.CharacterEllipsis)"); + if t.max_lines > 0 { + e.call(format!(".MaxLines({})", t.max_lines)); + } + } + if s.case == TextCase::SmallCaps { + e.note("small caps"); + } + e +} diff --git a/crates/engine/src/dev/component_codegen.rs b/crates/engine/src/dev/component_codegen.rs index 11b380b73..4884a9627 100644 --- a/crates/engine/src/dev/component_codegen.rs +++ b/crates/engine/src/dev/component_codegen.rs @@ -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); diff --git a/crates/engine/src/extensions/widgets.rs b/crates/engine/src/extensions/widgets.rs index efdd21414..09d3ee9a7 100644 --- a/crates/engine/src/extensions/widgets.rs +++ b/crates/engine/src/extensions/widgets.rs @@ -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"), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9f033cc7b..ced6a49c4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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; diff --git a/crates/engine/src/live_share_tests.rs b/crates/engine/src/live_share_tests.rs index 9581dc3fa..bce853df8 100644 --- a/crates/engine/src/live_share_tests.rs +++ b/crates/engine/src/live_share_tests.rs @@ -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(); diff --git a/crates/engine/src/live_tests.rs b/crates/engine/src/live_tests.rs index 4d19617ce..268b17603 100644 --- a/crates/engine/src/live_tests.rs +++ b/crates/engine/src/live_tests.rs @@ -34,11 +34,17 @@ pub(crate) struct Script { pub(crate) msgs_to: Vec, /// 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>); 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 { 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) -> 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 { diff --git a/crates/engine/src/node_find_tests.rs b/crates/engine/src/node_find_tests.rs index cb56d8139..f93757149 100644 --- a/crates/engine/src/node_find_tests.rs +++ b/crates/engine/src/node_find_tests.rs @@ -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() }, diff --git a/crates/engine/src/penpot_export_tests.rs b/crates/engine/src/penpot_export_tests.rs index 0e4b15c73..f19eb1d6f 100644 --- a/crates/engine/src/penpot_export_tests.rs +++ b/crates/engine/src/penpot_export_tests.rs @@ -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"] { diff --git a/crates/engine/src/raw_tests.rs b/crates/engine/src/raw_tests.rs new file mode 100644 index 000000000..06fb2697a --- /dev/null +++ b/crates/engine/src/raw_tests.rs @@ -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 { + 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 { + 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()); + } + } +} diff --git a/crates/engine/src/shapes_behaviour_tests.rs b/crates/engine/src/shapes_behaviour_tests.rs index d7d35be27..8a10aa3de 100644 --- a/crates/engine/src/shapes_behaviour_tests.rs +++ b/crates/engine/src/shapes_behaviour_tests.rs @@ -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", diff --git a/crates/engine/src/sharing/live.rs b/crates/engine/src/sharing/live.rs index 341031142..cee0f15a9 100644 --- a/crates/engine/src/sharing/live.rs +++ b/crates/engine/src/sharing/live.rs @@ -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(&mut self, cmd: &str, start: impl FnOnce(&mut dyn LiveLink, SessionId) -> Result) -> Result<(SessionId, T)> { + fn start( + &mut self, + cmd: &str, + join_link: Option<&str>, + start: impl FnOnce(&mut dyn LiveLink, SessionId) -> Result, + ) -> 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)?; diff --git a/crates/engine/src/sharing/live/host.rs b/crates/engine/src/sharing/live/host.rs index 417667abe..00e4f034b 100644 --- a/crates/engine/src/sharing/live/host.rs +++ b/crates/engine/src/sharing/live/host.rs @@ -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::()).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 { 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 { 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 { diff --git a/crates/engine/src/sharing/live/join.rs b/crates/engine/src/sharing/live/join.rs index badc1fd91..11e618395 100644 --- a/crates/engine/src/sharing/live/join.rs +++ b/crates/engine/src/sharing/live/join.rs @@ -27,7 +27,7 @@ pub(crate) fn start_join( resume: Option, ) -> Result { 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 { 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 ), diff --git a/crates/engine/src/sharing/live/types.rs b/crates/engine/src/sharing/live/types.rs index 07c2dd242..7c02364a8 100644 --- a/crates/engine/src/sharing/live/types.rs +++ b/crates/engine/src/sharing/live/types.rs @@ -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; /// Start joining the session behind an invite link, as session `session`. Errors are for diff --git a/crates/engine/src/text_metrics_local_tests.rs b/crates/engine/src/text_metrics_local_tests.rs index 34f25fac6..77d47e317 100644 --- a/crates/engine/src/text_metrics_local_tests.rs +++ b/crates/engine/src/text_metrics_local_tests.rs @@ -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() { diff --git a/crates/engine/src/uno_codegen_tests.rs b/crates/engine/src/uno_codegen_tests.rs new file mode 100644 index 000000000..9f29e04f1 --- /dev/null +++ b/crates/engine/src/uno_codegen_tests.rs @@ -0,0 +1,1116 @@ +//! Uno C# Markup code: `inspect.code {language: "uno"}` writes a fluent C# expression tree of +//! WinUI elements for a layer and its subtree. + +use crate::Session; +use crate::codegen::{CodeLang, asset_name, cs_ident, cs_literal, cs_unique}; +use crate::components::tests::{ex, idv}; +use figcraft_doc::*; +use serde_json::json; +use std::collections::BTreeSet; + +fn uno(s: &mut Session, id: NodeId) -> String { + ex(s, "inspect.code", json!({"id": id, "language": "uno"}))["code"].as_str().unwrap_or_default().to_string() +} + +#[test] +fn uno_is_a_code_language() { + assert!(CodeLang::ALL.contains(&CodeLang::Uno)); + assert_eq!(CodeLang::Uno.id(), "uno"); + assert_eq!(CodeLang::Uno.label(), "Uno C# Markup"); + for alias in ["uno", "UNO", "csharp-markup", "cs-markup", "Uno C# Markup"] { + assert_eq!(CodeLang::from_id(alias), Some(CodeLang::Uno), "{alias}"); + } + assert!(!CodeLang::Uno.is_web() && !CodeLang::Uno.escapes_dollar()); + // Not connectable to code until components are mapped. + assert!(crate::code_connect::language("uno").is_none()); +} + +#[test] +fn inspect_code_answers_in_uno() { + let mut s = Session::new(); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Box"}))); + let r = ex(&mut s, "inspect.code", json!({"id": f, "language": "uno"})); + assert_eq!(r["language"], "uno"); + assert!(!uno(&mut s, f).is_empty()); +} + +fn frame(s: &mut Session, name: &str, w: f64, h: f64) -> NodeId { + idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": w, "height": h, "name": name}))) +} + +fn set(s: &mut Session, id: NodeId, props: serde_json::Value) { + ex(s, "node.set", json!({"id": id, "props": props})); +} + +/// The statements of the generated constructor, as written (eight spaces of indent): what sits +/// between `public XView()` `{` and its closing brace. +fn tree(code: &str) -> String { + let start = code.find(" {\n").map_or(0, |i| i + " {\n".len()); + let end = code.rfind(" }\n}").unwrap_or(code.len()); + code.get(start..end).unwrap_or_default().to_string() +} + +/// [`tree`] with the indent taken off. +fn body(code: &str) -> String { + tree(code).lines().map(|l| format!("{}\n", l.get(8..).unwrap_or(l))).collect::().trim_end().to_string() +} + +/// Whether `block` (lines, indent and a closing `;` ignored) appears in `code` as consecutive lines. +fn has_block(code: &str, block: &str) -> bool { + let norm = |t: &str| t.lines().map(|l| l.trim().trim_end_matches(';').to_string()).collect::>(); + let (c, b) = (norm(code), norm(block)); + !b.is_empty() && c.windows(b.len()).any(|w| w == b.as_slice()) +} + +/// Whether one line of `code` is exactly `call` (a closing `;` ignored). +fn has_call(code: &str, call: &str) -> bool { + has_block(code, call) +} + +#[test] +fn an_empty_frame_is_a_view_class_with_a_sized_border() { + let mut s = Session::new(); + let f = frame(&mut s, "Empty", 100.0, 50.0); + let expected = "using Windows.UI; + +// Empty +namespace MyApp; + +internal sealed partial class EmptyView : UserControl +{ + public EmptyView() + { + // Empty + var empty = new Border() + .Width(100) + .Height(50) + .Background(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF)); + Content = empty; + } +} +"; + assert_eq!(uno(&mut s, f), expected); + // Deterministic: the same document gives the same code. + assert_eq!(uno(&mut s, f), uno(&mut s, f)); +} + +#[test] +fn a_frame_with_a_stroke_and_children_keeps_the_children_out_of_the_border() { + let mut s = Session::new(); + let f = frame(&mut s, "Login Screen", 200.0, 100.0); + set(&mut s, f, json!({"fill": "#112233", "stroke": "#FF0000", "strokeWeight": 3, "opacity": 0.5, "cornerRadius": 8})); + ex(&mut s, "shape.rectangle", json!({"x": 5, "y": 5, "width": 20, "height": 20, "parent": f, "props": {"name": "Box"}})); + let expected = "// warning: 1 frame has no auto layout: its children are positioned absolutely and do not adapt to size. +// Login Screen +var loginScreen = new Grid() + .Width(200) + .Height(100) + .Opacity(0.5); +var loginScreenBorder = new Border() + .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) + .BorderBrush(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) + .BorderThickness(3) + .CornerRadius(8); +loginScreen.Children.Add(loginScreenBorder); +var loginScreenCanvas = new Canvas(); +// Box +var box = new Border() + .Canvas(left: 5, top: 5) + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xD9, 0xD9, 0xD9)); +loginScreenCanvas.Children.Add(box); +loginScreen.Children.Add(loginScreenCanvas); +Content = loginScreen;"; + let code = uno(&mut s, f); + assert!(code.contains("internal sealed partial class LoginScreenView : UserControl"), "{code}"); + assert_eq!(body(&code), expected, "{code}"); +} + +#[test] +fn a_box_maps_its_stroke_sides_corners_opacity_rotation_and_what_it_cannot() { + let mut s = Session::new(); + let f = frame(&mut s, "Frame", 120.0, 80.0); + let r = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 30, "parent": f, "props": {"name": "Box"}}))); + set(&mut s, r, json!({"fill": "#336699", "topLeftRadius": 4, "topRightRadius": 8, "bottomRightRadius": 12, "bottomLeftRadius": 16})); + let code = uno(&mut s, f); + assert!(code.contains(".CornerRadius(new CornerRadius(4, 8, 12, 16))"), "{code}"); + // Per-side stroke weights are top, right, bottom, left; a Thickness takes left first. + set(&mut s, r, json!({"stroke": "#000000", "strokeWeight": 1})); + set(&mut s, r, json!({"strokeTopWeight": 1, "strokeRightWeight": 2, "strokeBottomWeight": 3, "strokeLeftWeight": 4})); + let code = uno(&mut s, f); + assert!(code.contains(".BorderThickness(new Thickness(4, 1, 2, 3))"), "{code}"); + set(&mut s, r, json!({"opacity": 0.25, "rotation": 90, "strokeAlign": "outside"})); + let code = uno(&mut s, f); + assert!(code.contains(".Opacity(0.25)"), "{code}"); + assert!(code.contains(".RenderTransform(new RotateTransform().Angle(-90))"), "{code}"); + assert!(code.contains("// not mapped: stroke outside or centred"), "{code}"); +} + +#[test] +fn a_shadow_is_left_as_a_not_mapped_comment() { + let mut s = Session::new(); + let f = frame(&mut s, "Fx", 100.0, 100.0); + set(&mut s, f, json!({"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 4], "radius": 8}]})); + let code = uno(&mut s, f); + assert!(code.contains("// not mapped: drop shadow (needs Uno.Toolkit ShadowContainer)"), "{code}"); +} + +#[test] +fn an_ellipse_is_an_ellipse_with_a_centred_stroke() { + let mut s = Session::new(); + let f = frame(&mut s, "Dots", 100.0, 100.0); + ex( + &mut s, + "shape.ellipse", + json!({"x": 10, "y": 20, "width": 40, "height": 40, "parent": f, "props": {"name": "Dot", "fill": "#FF0000", "stroke": "#000000", "strokeWeight": 2, "strokeAlign": "center"}}), + ); + let code = uno(&mut s, f); + let expected = "var dot = new Ellipse() + .Canvas(left: 10, top: 20) + .Width(40) + .Height(40) + .Fill(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)) + .Stroke(Color.FromArgb(0xFF, 0x00, 0x00, 0x00)) + .StrokeThickness(2);"; + assert!(has_block(&code, expected), "{code}"); +} + +#[test] +fn text_maps_its_style_and_box() { + let mut s = Session::new(); + let f = frame(&mut s, "Texts", 300.0, 200.0); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Say \"hi\"\n\\", "x": 10, "y": 12, "parent": f, "props": {"name": "T"}}))); + set( + &mut s, + t, + json!({"fontFamily": "Zzyzx Test Family", "fontSize": 16, "fontWeight": 600, "fontStyle": "Semi Bold Italic", "letterSpacing": 2, "lineHeight": "150%", "textDecoration": "underline", "textAlign": "center", "width": 150, "textAutoResize": "height", "fill": "#112233"}), + ); + let code = uno(&mut s, f); + assert!(code.contains("using Microsoft.UI.Text;"), "{code}"); + for line in [ + ".Canvas(left: 10, top: 12)", + ".Text(\"Say \\\"hi\\\"\\n\\\\\")", + ".FontFamily(\"Zzyzx Test Family\")", + ".FontSize(16)", + ".FontWeight(FontWeights.SemiBold)", + ".FontStyle(FontStyle.Italic)", + ".Foreground(Color.FromArgb(0xFF, 0x11, 0x22, 0x33))", + ".LineHeight(24)", + ".CharacterSpacing(125)", + ".TextDecorations(Windows.UI.Text.TextDecorations.Underline)", + ".TextAlignment(TextAlignment.Center)", + ".Width(150)", + ".TextWrapping(TextWrapping.Wrap)", + ] { + assert!(has_call(&code, line) || code.contains(&format!("{line})")), "{line} in {code}"); + } + // Auto height has a width but no height of its own. + assert!(!code.contains(".Height(") || code.matches(".Height(").count() == 1, "{code}"); + // A fixed box aligned to the middle sits in a grid of its height. + set(&mut s, t, json!({"textAutoResize": "none", "height": 60, "textAlignVertical": "middle"})); + let code = uno(&mut s, f); + assert!(code.contains("new Grid()") && code.contains(".VerticalAlignment(VerticalAlignment.Center)"), "{code}"); + // Truncation ends in an ellipsis. + set(&mut s, t, json!({"textAutoResize": "truncate", "textAlignVertical": "top"})); + assert!(uno(&mut s, f).contains(".TextTrimming(TextTrimming.CharacterEllipsis)")); +} + +#[test] +fn text_case_is_applied_when_the_code_runs() { + let mut s = Session::new(); + let f = frame(&mut s, "Cases", 300.0, 100.0); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hello", "x": 0, "y": 0, "parent": f, "props": {"name": "T"}}))); + for (case, expr) in [("upper", ".Text(\"Hello\".ToUpperInvariant())"), ("lower", ".Text(\"Hello\".ToLowerInvariant())")] { + set(&mut s, t, json!({"textCase": case})); + let code = uno(&mut s, f); + assert!(code.contains(expr), "{code}"); + } + set(&mut s, t, json!({"textCase": "title"})); + assert!(uno(&mut s, f).contains("TextInfo.ToTitleCase(\"Hello\")")); + set(&mut s, t, json!({"textCase": "smallCaps"})); + assert!(uno(&mut s, f).contains("// not mapped: small caps")); +} + +#[test] +fn mixed_styles_become_runs() { + let mut s = Session::new(); + let f = frame(&mut s, "Runs", 300.0, 100.0); + let t = idv(&ex( + &mut s, + "text.create", + json!({"text": "Plain bold end", "x": 0, "y": 0, "parent": f, "props": {"name": "T", "fontFamily": "Inter", "fontSize": 18}}), + )); + set(&mut s, t, json!({"fontWeight": 700, "start": 6, "end": 10})); + let code = uno(&mut s, f); + let expected = ".Inlines( + new Run() + .Text(\"Plain \"), + new Run() + .Text(\"bold\") + .FontWeight(FontWeights.Bold), + new Run() + .Text(\" end\"))"; + assert!(has_block(&code, expected), "{code}"); + assert!(!code.contains(".Text(\"Plain bold end\")"), "{code}"); +} + +#[test] +fn an_image_fill_is_an_image_brush_on_a_png_asset() { + use base64::Engine as _; + let mut s = Session::new(); + let image = image::RgbaImage::from_fn(8, 4, |x, y| image::Rgba([x as u8, y as u8, 120, 255])); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(bytes.into_inner()); + let img = idv(&ex(&mut s, "file.import", json!({"data": data, "name": "Foto Größe.png", "x": 0, "y": 0}))); + set(&mut s, img, json!({"name": "Foto Größe"})); + let code = uno(&mut s, img); + assert!( + code.contains(".Background(new ImageBrush().ImageSource(\"ms-appx:///Assets/foto_grosse.png\").Stretch(Stretch.UniformToFill))"), + "{code}" + ); +} + +#[test] +fn hidden_layers_and_deep_trees_are_left_out_or_summarised() { + let mut s = Session::new(); + let f = frame(&mut s, "Tree", 100.0, 100.0); + let hidden = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10, "parent": f, "props": {"name": "Hidden"}}))); + set(&mut s, hidden, json!({"visible": false})); + assert!(!uno(&mut s, f).contains("Hidden")); + let mut parent = f; + for i in 0..20 { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": parent, "name": format!("Level {i}")}))); + } + let code = uno(&mut s, f); + assert!(code.contains("// Level ") && code.contains(" …\n"), "{code}"); + assert!(code.lines().all(|l| l.len() < 400), "{code}"); +} + +#[test] +fn literals_are_escaped_never_interpolated() { + assert_eq!(cs_literal("a\"b\\c"), "\"a\\\"b\\\\c\""); + assert_eq!(cs_literal("line\r\n\ttab"), "\"line\\r\\n\\ttab\""); + assert_eq!(cs_literal("{x} $y\u{0}\u{2028}\u{85}"), "\"{x} $y\\u0000\\u2028\\u0085\""); + assert_eq!(cs_literal("é日本"), "\"é日本\""); + // Cut, not crashed, at 10,000 characters. + assert_eq!(cs_literal(&"x".repeat(20_000)).chars().count(), 10_002); +} + +#[test] +fn identifiers_are_c_sharp_names() { + assert_eq!(cs_ident("Login Screen", true, "Frame"), "LoginScreen"); + assert_eq!(cs_ident("main card", false, "Frame"), "mainCard"); + assert_eq!(cs_ident("mainCard / title-1", true, "Frame"), "MainCardTitle1"); + assert_eq!(cs_ident("кнопка", true, "Frame"), "Knopka"); + assert_eq!(cs_ident("3 cards", true, "Frame"), "_3Cards"); + assert_eq!(cs_ident("class", false, "Frame"), "class_"); + assert_eq!(cs_ident("???", true, "frame"), "Frame"); + assert_eq!(cs_ident("", false, "Text"), "text"); + assert!(cs_ident(&"word ".repeat(40), true, "Frame").chars().count() <= 40); + let mut used = BTreeSet::new(); + assert_eq!(cs_unique("Card", &mut used), "Card"); + assert_eq!(cs_unique("Card", &mut used), "Card2"); + assert_eq!(cs_unique("Card", &mut used), "Card3"); + assert_eq!(cs_unique("card", &mut used), "card"); +} + +#[test] +fn asset_names_are_lowercase_ascii_starting_with_a_letter_and_unique() { + let mut used = BTreeSet::new(); + assert_eq!(asset_name("Hero Image", "Rectangle", &mut used), "hero_image"); + assert_eq!(asset_name("hero image", "Rectangle", &mut used), "hero_image_2"); + assert_eq!(asset_name("HERO-IMAGE", "Rectangle", &mut used), "hero_image_3"); + assert_eq!(asset_name("Größe über Äpfel", "Vector", &mut used), "grosse_uber_apfel"); + assert_eq!(asset_name("로그인 화면", "Vector", &mut used), "rogeuin_hwamyeon"); + assert_eq!(asset_name("2x icon", "Vector", &mut used), "img_2x_icon"); + assert_eq!(asset_name("***", "Star", &mut used), "star"); + assert_eq!(asset_name("", "", &mut used), "image"); + let long = asset_name(&"segment ".repeat(20), "Vector", &mut used); + assert!(long.len() <= 40 && !long.ends_with('_') && long.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'), "{long}"); +} + +#[test] +fn instances_and_components_are_walked_as_frames() { + let mut s = Session::new(); + let f = frame(&mut s, "Card", 100.0, 50.0); + let c = idv(&ex(&mut s, "component.create", json!({"ids": [f]}))); + let code = uno(&mut s, c); + assert!(code.contains("internal sealed partial class CardView : UserControl"), "{code}"); + assert!(!code.contains("export default") && !code.contains("function "), "{code}"); +} + +fn rect(s: &mut Session, parent: NodeId, w: f64, h: f64, name: &str) -> NodeId { + idv(&ex(s, "shape.rectangle", json!({"parent": parent, "x": 0, "y": 0, "width": w, "height": h, "props": {"name": name, "fill": "#FF0000"}}))) +} + +/// A frame with auto layout and one rectangle child. +fn row(s: &mut Session, props: serde_json::Value) -> NodeId { + let f = frame(s, "Row", 200.0, 100.0); + let mut all = json!({"layout": "horizontal", "padding": 0, "gap": 0, "fills": [], "sizingH": "fixed", "sizingV": "fixed"}); + if let (Some(all), serde_json::Value::Object(extra)) = (all.as_object_mut(), props) { + all.extend(extra); + } + set(s, f, all); + rect(s, f, 20.0, 20.0, "A"); + f +} + +#[test] +fn a_row_is_an_auto_layout_with_its_box_gap_padding_and_alignment() { + let mut s = Session::new(); + let f = row( + &mut s, + json!({"fills": ["#112233"], "gap": 12, "padding": [7, 15, 7, 15], "mainAlign": "center", "crossAlign": "center", "cornerRadius": 8}), + ); + rect(&mut s, f, 20.0, 20.0, "B"); + let code = uno(&mut s, f); + assert!(code.starts_with("using Windows.UI;\nusing Uno.Toolkit.UI;\n") || code.contains("using Uno.Toolkit.UI;"), "{code}"); + let expected = "// Row +var row = new AutoLayout() + .Width(200) + .Height(100) + .Background(Color.FromArgb(0xFF, 0x11, 0x22, 0x33)) + .CornerRadius(8) + .Orientation(Orientation.Horizontal) + .Spacing(12) + .Padding(15, 7, 15, 7) + .PrimaryAxisAlignment(AutoLayoutAlignment.Center) + .CounterAxisAlignment(AutoLayoutAlignment.Center); +// A +var a = new Border() + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)); +row.Children.Add(a); +// B +var b = new Border() + .Width(20) + .Height(20) + .Background(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00)); +row.Children.Add(b); +Content = row;"; + assert_eq!(body(&code), expected, "{code}"); + // A frame with auto layout is not a frame without one: no warning. + assert!(!code.contains("// warning"), "{code}"); +} + +#[test] +fn a_column_has_a_vertical_orientation_and_a_uniform_padding_is_one_number() { + let mut s = Session::new(); + let f = row(&mut s, json!({"layout": "vertical", "padding": 8, "gap": 0})); + let code = uno(&mut s, f); + assert!(has_call(&code, ".Orientation(Orientation.Vertical)"), "{code}"); + assert!(has_call(&code, ".Padding(8)"), "{code}"); + assert!(!code.contains(".Spacing("), "no gap, no spacing: {code}"); + set(&mut s, f, json!({"padding": 0})); + assert!(!uno(&mut s, f).contains(".Padding(")); +} + +#[test] +fn main_and_cross_alignment_map_with_notes_for_what_the_toolkit_lacks() { + let mut s = Session::new(); + let f = row(&mut s, json!({"gap": 5})); + for (main, line) in [("max", ".PrimaryAxisAlignment(AutoLayoutAlignment.End)"), ("spaceBetween", ".Justify(AutoLayoutJustify.SpaceBetween)")] { + set(&mut s, f, json!({"mainAlign": main})); + let code = uno(&mut s, f); + assert!(code.contains(line), "{main}: {code}"); + assert!(!code.contains("// not mapped"), "{main}: {code}"); + } + // The distributions make the gaps: the gap value is not written. + assert!(!uno(&mut s, f).contains(".Spacing(")); + for main in ["spaceAround", "spaceEvenly"] { + set(&mut s, f, json!({"mainAlign": main})); + let code = uno(&mut s, f); + assert!( + code.contains(".Justify(AutoLayoutJustify.SpaceBetween)") + && code.contains("// not mapped: space around/evenly exported as space between"), + "{code}" + ); + } + set(&mut s, f, json!({"mainAlign": "min", "crossAlign": "max"})); + assert!(uno(&mut s, f).contains(".CounterAxisAlignment(AutoLayoutAlignment.End)")); + set(&mut s, f, json!({"crossAlign": "baseline"})); + let code = uno(&mut s, f); + assert!(!code.contains("CounterAxisAlignment") && code.contains("// not mapped: baseline alignment"), "{code}"); +} + +#[test] +fn the_stroke_weight_comes_off_the_padding_unless_strokes_are_included() { + let mut s = Session::new(); + let f = row(&mut s, json!({"padding": 10, "stroke": "#0000FF", "strokeWeight": 4, "strokeAlign": "inside", "strokesIncluded": false})); + let code = uno(&mut s, f); + assert!(code.contains(".BorderThickness(4)") && has_call(&code, ".Padding(6)"), "{code}"); + assert!(!code.contains("new Grid()"), "{code}"); + set(&mut s, f, json!({"strokesIncluded": true})); + assert!(has_call(&uno(&mut s, f), ".Padding(10)")); + // A stroke thicker than the padding on a side: the border sits behind the layout. + set(&mut s, f, json!({"strokesIncluded": false, "padding": 2})); + let code = uno(&mut s, f); + assert!(code.contains("new Grid()") && code.contains("new Border()") && has_call(&code, ".Padding(2)"), "{code}"); + let (grid, layout) = (code.find("new Grid()"), code.find("new AutoLayout()")); + assert!(grid < layout, "{code}"); + assert!(!code[layout.unwrap_or(0)..].contains(".BorderThickness("), "{code}"); +} + +#[test] +fn frames_without_auto_layout_get_one_warning_per_view_with_their_count() { + let mut s = Session::new(); + let outer = frame(&mut s, "Free", 200.0, 200.0); + for name in ["One", "Two"] { + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": name}))); + rect(&mut s, inner, 10.0, 10.0, "R"); + } + let code = uno(&mut s, outer); + assert_eq!(code.matches("// warning:").count(), 1, "{code}"); + assert!(code.contains("// warning: 3 frames have no auto layout: children are positioned absolutely and do not adapt to size."), "{code}"); + // An empty frame has no children to place: nothing to warn about. + let empty = frame(&mut s, "Empty2", 10.0, 10.0); + assert!(!uno(&mut s, empty).contains("// warning")); +} + +#[test] +fn nested_auto_layouts_carry_no_canvas_offsets() { + let mut s = Session::new(); + let outer = row(&mut s, json!({"layout": "vertical"})); + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": "Inner"}))); + set(&mut s, inner, json!({"layout": "horizontal", "padding": 3, "gap": 2})); + rect(&mut s, inner, 5.0, 5.0, "C"); + let code = uno(&mut s, outer); + assert_eq!(code.matches("new AutoLayout()").count(), 2, "{code}"); + assert!(!code.contains(".Canvas("), "{code}"); +} + +#[test] +fn children_are_added_never_chained() { + // Fluent `.Children(…)` / `.Child(…)` doubles the load time with every level of nesting, so + // containers are locals and their children are added one by one. + let mut s = Session::new(); + let outer = frame(&mut s, "Outer", 300.0, 300.0); + set(&mut s, outer, json!({"stroke": "#000000", "strokeWeight": 2})); + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 5, "y": 5, "width": 100, "height": 100, "parent": outer, "name": "Inner"}))); + set(&mut s, inner, json!({"layout": "vertical", "padding": 4, "gap": 3, "stroke": "#FF0000", "strokeWeight": 9, "strokesIncluded": false})); + rect(&mut s, inner, 10.0, 10.0, "R"); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hi", "x": 0, "y": 0, "parent": outer, "props": {"name": "T"}}))); + set(&mut s, t, json!({"textAutoResize": "none", "width": 50, "height": 40, "textAlignVertical": "middle"})); + let mut parent = outer; + for i in 0..6 { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": parent, "name": format!("Level {i}")}))); + } + let code = uno(&mut s, outer); + assert!(!code.contains(".Children(") && !code.contains(".Child("), "{code}"); + assert!(code.contains(".Children.Add(") && code.contains(".Child = "), "{code}"); + // A single child of a border is assigned. + let lone = frame(&mut s, "Lone", 20.0, 20.0); + rect(&mut s, lone, 5.0, 5.0, "X"); + let code = uno(&mut s, lone); + assert!(!code.contains(".Child(") && !code.contains(".Children("), "{code}"); + // Names of locals are unique C# identifiers, the parent's before its children's. + let twins = frame(&mut s, "Card", 50.0, 50.0); + rect(&mut s, twins, 5.0, 5.0, "Card"); + rect(&mut s, twins, 5.0, 5.0, "class"); + let code = uno(&mut s, twins); + for decl in ["var card = ", "var card2 = ", "var class_ = "] { + assert_eq!(code.matches(decl).count(), 1, "{decl} in {code}"); + } +} + +/// The calls of the local `var`, in order, without indent or the closing `;`. +fn chain(code: &str, var: &str) -> Vec { + let head = format!("var {var} = "); + let mut out = Vec::new(); + let mut lines = code.lines().skip_while(|l| !l.trim_start().starts_with(&head)); + let Some(first) = lines.next() else { return out }; + let mut done = first.trim_end().ends_with(';'); + for l in lines { + // A `// not mapped` comment may follow the call that ends the statement. + if done && !l.trim_start().starts_with("//") { + break; + } + done = done || l.trim_end().ends_with(';'); + out.push(l.trim().trim_end_matches(';').to_string()); + } + out +} + +fn first_child(s: &Session, f: NodeId) -> NodeId { + s.doc().ok().and_then(|d| d.node(f)).and_then(|n| n.children.first().copied()).unwrap_or(f) +} + +#[test] +fn fill_stretches_on_the_axis_it_fills_and_fixed_keeps_its_size() { + let mut s = Session::new(); + let f = row(&mut s, json!({})); + let a = first_child(&s, f); + let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); + // Horizontal parent: width is the primary axis, height the counter axis. + set(&mut s, a, json!({"sizingH": "fill"})); + let code = uno(&mut s, f); + let kid = chain(&code, "a"); + assert_eq!(kid[0], ".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch)", "{code}"); + assert!(!has(&kid, ".Width(") && has(&kid, ".Height("), "{code}"); + set(&mut s, a, json!({"sizingV": "fill"})); + let kid = chain(&uno(&mut s, f), "a"); + assert_eq!(kid[0], ".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch, counterAlignment: AutoLayoutAlignment.Stretch)"); + assert!(!has(&kid, ".Width(") && !has(&kid, ".Height(")); + // In a column the axes swap. + set(&mut s, f, json!({"layout": "vertical"})); + set(&mut s, a, json!({"sizingH": "fixed"})); + let kid = chain(&uno(&mut s, f), "a"); + assert_eq!(kid[0], ".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch)"); + assert!(has(&kid, ".Width(")); + set(&mut s, a, json!({"sizingH": "fill", "sizingV": "fixed"})); + assert_eq!(chain(&uno(&mut s, f), "a")[0], ".AutoLayout(counterAlignment: AutoLayoutAlignment.Stretch)"); +} + +#[test] +fn a_hugging_frame_has_no_size_of_its_own_the_root_included() { + let mut s = Session::new(); + let outer = row(&mut s, json!({"layout": "vertical", "sizingH": "hug", "sizingV": "hug"})); + let inner = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": outer, "name": "Inner"}))); + set(&mut s, inner, json!({"layout": "horizontal", "padding": 3, "gap": 2, "sizingH": "hug", "sizingV": "hug"})); + rect(&mut s, inner, 5.0, 5.0, "C"); + let code = uno(&mut s, outer); + let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); + let root = chain(&code, "row"); + // The root hugs too: its size follows its content, as FigCraft lays it out. + assert!(!has(&root, ".Width(") && !has(&root, ".Height("), "{code}"); + let nested = chain(&code, "inner"); + assert!(!has(&nested, ".Width(") && !has(&nested, ".Height("), "{code}"); +} + +#[test] +fn min_and_max_sizes_go_on_the_child() { + let mut s = Session::new(); + let f = row(&mut s, json!({})); + let a = first_child(&s, f); + set(&mut s, a, json!({"sizingH": "fill", "minWidth": 40, "maxWidth": 120, "minHeight": 10, "maxHeight": 30})); + let code = uno(&mut s, f); + for line in [".MinWidth(40)", ".MaxWidth(120)", ".MinHeight(10)", ".MaxHeight(30)"] { + assert!(chain(&code, "a").contains(&line.to_string()), "{line} in {code}"); + } +} + +#[test] +fn text_in_a_flow_hugs_fills_or_is_fixed() { + let mut s = Session::new(); + let f = row(&mut s, json!({})); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hello", "x": 0, "y": 0, "parent": f, "props": {"name": "T"}}))); + let calls = |s: &mut Session| chain(&uno(s, f), "t"); + let has = |c: &[String], p: &str| c.iter().any(|l| l.starts_with(p)); + set(&mut s, t, json!({"textAutoResize": "widthAndHeight", "sizingH": "hug", "sizingV": "hug"})); + let c = calls(&mut s); + assert!(c.contains(&".TextWrapping(TextWrapping.NoWrap)".to_string()), "{c:?}"); + assert!(!has(&c, ".Width(") && !has(&c, ".Height("), "{c:?}"); + set(&mut s, t, json!({"textAutoResize": "height", "sizingH": "fill"})); + let c = calls(&mut s); + assert_eq!(c.first().map(String::as_str), Some(".AutoLayout(primaryAlignment: AutoLayoutPrimaryAlignment.Stretch)"), "{c:?}"); + assert!(c.contains(&".TextWrapping(TextWrapping.Wrap)".to_string()) && !has(&c, ".Width("), "{c:?}"); + set(&mut s, t, json!({"textAutoResize": "height", "sizingH": "fixed", "width": 90})); + let c = calls(&mut s); + assert!(c.contains(&".Width(90)".to_string()) && c.contains(&".TextWrapping(TextWrapping.Wrap)".to_string()), "{c:?}"); +} + +#[test] +fn an_absolute_child_ignores_the_layout_and_keeps_its_offsets() { + let mut s = Session::new(); + let f = row(&mut s, json!({"padding": 10})); + let b = rect(&mut s, f, 12.0, 12.0, "Badge"); + set(&mut s, b, json!({"absolute": true, "x": 30, "y": 40})); + let code = uno(&mut s, f); + let expected = [ + ".AutoLayout(isIndependentLayout: true)", + ".HorizontalAlignment(HorizontalAlignment.Left)", + ".VerticalAlignment(VerticalAlignment.Top)", + ".Margin(30, 40, 0, 0)", + ".Width(12)", + ".Height(12)", + ]; + assert_eq!(chain(&code, "badge")[..6], expected, "{code}"); + // A top-left child needs no note; another constraint does, and the offsets stay. + assert!(!code.contains("// not mapped: constraints"), "{code}"); + set(&mut s, b, json!({"constraints": {"horizontal": "right"}})); + let code = uno(&mut s, f); + assert!(chain(&code, "badge").iter().any(|l| l == "// not mapped: constraints (the child stays at its top-left offset)"), "{code}"); + assert!(chain(&code, "badge").contains(&".Margin(30, 40, 0, 0)".to_string()), "{code}"); +} + +#[test] +fn a_hugging_parent_with_an_absolute_child_is_written_at_its_size() { + let mut s = Session::new(); + let outer = row(&mut s, json!({"layout": "vertical"})); + let hug = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 60, "height": 40, "parent": outer, "name": "Hug"}))); + set(&mut s, hug, json!({"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"})); + rect(&mut s, hug, 60.0, 40.0, "Body"); + let code = uno(&mut s, outer); + assert!(!code.contains("hug size fixed"), "{code}"); + let badge = rect(&mut s, hug, 8.0, 8.0, "Badge"); + set(&mut s, badge, json!({"absolute": true, "x": 50, "y": -4})); + let code = uno(&mut s, outer); + let c = chain(&code, "hug"); + assert!(c.contains(&"// not mapped: hug size fixed: an absolute child would enlarge it".to_string()), "{code}"); + assert!(c.contains(&".Width(60)".to_string()) && c.contains(&".Height(40)".to_string()), "{code}"); +} + +#[test] +fn first_on_top_paints_in_descending_order_without_reordering() { + let mut s = Session::new(); + let f = row(&mut s, json!({"gap": -10})); + rect(&mut s, f, 20.0, 20.0, "B"); + rect(&mut s, f, 20.0, 20.0, "C"); + let plain = uno(&mut s, f); + assert!(!plain.contains("zIndex") && !plain.contains("IsReverseZIndex"), "{plain}"); + set(&mut s, f, json!({"reverseZ": true})); + let code = uno(&mut s, f); + for (var, z) in [("a", 3), ("b", 2), ("c", 1)] { + assert!(chain(&code, var).contains(&format!(".Canvas(zIndex: {z})")), "{var} in {code}"); + } + // The order of the children is unchanged. + assert!(code.find("var a = ") < code.find("var b = ") && code.find("var b = ") < code.find("var c = "), "{code}"); + assert!(!code.contains("IsReverseZIndex"), "{code}"); +} + +/// A grid frame of 300 × 200 with no padding and no fill. +fn grid(s: &mut Session, props: serde_json::Value) -> NodeId { + let f = frame(s, "Table", 300.0, 200.0); + let mut all = json!({"layout": "grid", "padding": 0, "gap": 0, "crossGap": 0, "fills": [], "sizingH": "fixed", "sizingV": "fixed"}); + if let (Some(all), serde_json::Value::Object(extra)) = (all.as_object_mut(), props) { + all.extend(extra); + } + set(s, f, all); + f +} + +#[test] +fn a_grid_frame_is_a_grid_with_tracks_spacing_and_cells_from_the_layout_crate() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": [120, "auto", "1fr", "2fr"], "rowTracks": ["auto", "1fr"], "gap": 16, "crossGap": 8, "padding": 4})); + let kids: Vec = ["A", "B", "C", "D", "E"].iter().map(|n| rect(&mut s, g, 20.0, 20.0, n)).collect(); + set(&mut s, kids[1], json!({"gridColumnSpan": 2})); + set(&mut s, kids[4], json!({"gridColumn": 3, "gridRow": 1})); + let code = uno(&mut s, g); + let root = chain(&code, "table"); + for call in [".ColumnDefinitions(\"120,Auto,1*,2*\")", ".RowDefinitions(\"Auto,1*\")", ".ColumnSpacing(16)", ".RowSpacing(8)", ".Padding(4)"] { + assert!(root.contains(&call.to_string()), "{call} in {code}"); + } + assert!(!code.contains("new AutoLayout()") && !code.contains("// not mapped"), "{code}"); + // Every child sits in the cell FigCraft's own layout gives it. + let doc = s.doc().unwrap(); + let (cells, _) = figcraft_layout::grid_place(doc, doc.node(g).unwrap().layout.as_ref().unwrap(), &kids); + for (cell, name) in cells.iter().zip(["a", "b", "c", "d", "e"]) { + let mut want = format!(".Grid(row: {}, column: {}", cell.row, cell.column); + if cell.row_span > 1 { + want.push_str(&format!(", rowSpan: {}", cell.row_span)); + } + if cell.column_span > 1 { + want.push_str(&format!(", columnSpan: {}", cell.column_span)); + } + want.push(')'); + assert_eq!(chain(&code, name)[0], want, "{name} in {code}"); + } + assert!(chain(&code, "b")[0].contains("columnSpan: 2"), "{code}"); + assert_eq!(chain(&code, "e")[0], ".Grid(row: 1, column: 3)", "{code}"); + // The cell alignment is written, since a fixed size would otherwise be centred. + assert!(chain(&code, "a").contains(&".HorizontalAlignment(HorizontalAlignment.Left)".to_string()), "{code}"); +} + +#[test] +fn fractional_stars_are_scaled_to_whole_numbers_or_rounded_with_a_note() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": ["1.5fr", "1fr", "0.5fr"], "rowTracks": ["fill"]})); + rect(&mut s, g, 20.0, 20.0, "A"); + let code = uno(&mut s, g); + assert!(chain(&code, "table").contains(&".ColumnDefinitions(\"3*,2*,1*\")".to_string()), "{code}"); + assert!(!code.contains("// not mapped"), "{code}"); + set(&mut s, g, json!({"columnTracks": ["1.3333fr", "1fr"]})); + let code = uno(&mut s, g); + assert!(chain(&code, "table").contains(&".ColumnDefinitions(\"1*,1*\")".to_string()), "{code}"); + assert!(code.contains("// not mapped: fractional grid track sizes"), "{code}"); +} + +#[test] +fn a_grid_writes_at_most_sixty_four_tracks_per_axis() { + let mut s = Session::new(); + let tracks: Vec = (0..70).map(|_| json!("1fr")).collect(); + let g = grid(&mut s, json!({ "columnTracks": tracks })); + for i in 0..3 { + rect(&mut s, g, 5.0, 5.0, &format!("R{i}")); + } + let code = uno(&mut s, g); + let defs = chain(&code, "table").into_iter().find(|l| l.starts_with(".ColumnDefinitions(")).unwrap_or_default(); + assert_eq!(defs.matches('*').count(), 64, "{defs}"); + assert!(code.contains("// not mapped: more than 64 grid tracks"), "{code}"); +} + +#[test] +fn grid_children_align_in_their_cell_and_a_filling_one_stretches() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": ["1fr", "1fr"], "rowTracks": ["1fr"], "mainAlign": "center", "crossAlign": "max"})); + let a = rect(&mut s, g, 20.0, 20.0, "A"); + let b = rect(&mut s, g, 20.0, 20.0, "B"); + set(&mut s, a, json!({"gridAlignH": "max", "gridAlignV": "min"})); + set(&mut s, b, json!({"sizingH": "fill", "sizingV": "fill"})); + let code = uno(&mut s, g); + let (ka, kb) = (chain(&code, "a"), chain(&code, "b")); + assert!(ka.contains(&".HorizontalAlignment(HorizontalAlignment.Right)".to_string()), "{code}"); + assert!(ka.contains(&".VerticalAlignment(VerticalAlignment.Top)".to_string()), "{code}"); + assert!(!kb.iter().any(|l| l.starts_with(".HorizontalAlignment") || l.starts_with(".VerticalAlignment") || l.starts_with(".Width(")), "{code}"); + // With no alignment of its own a child takes the frame's. + let c = rect(&mut s, g, 20.0, 20.0, "C"); + let _ = c; + let code = uno(&mut s, g); + assert!(chain(&code, "c").contains(&".HorizontalAlignment(HorizontalAlignment.Center)".to_string()), "{code}"); + assert!(chain(&code, "c").contains(&".VerticalAlignment(VerticalAlignment.Bottom)".to_string()), "{code}"); +} + +#[test] +fn an_absolute_child_of_a_grid_spans_all_cells_at_its_offset_inside_the_padding() { + let mut s = Session::new(); + let g = grid(&mut s, json!({"columnTracks": ["1fr", "1fr"], "rowTracks": ["1fr"], "padding": 10})); + rect(&mut s, g, 20.0, 20.0, "A"); + let badge = rect(&mut s, g, 12.0, 12.0, "Badge"); + set(&mut s, badge, json!({"absolute": true, "x": 30, "y": 40})); + let code = uno(&mut s, g); + let c = chain(&code, "badge"); + assert_eq!(c[0], ".Grid(row: 0, column: 0, rowSpan: 1, columnSpan: 2)", "{code}"); + assert!(c.contains(&".Margin(20, 30, 0, 0)".to_string()), "{code}"); +} + +#[test] +fn wrapping_is_one_line_and_a_note() { + let mut s = Session::new(); + let f = row(&mut s, json!({"wrap": true})); + let code = uno(&mut s, f); + assert!(code.contains("// not mapped: wrap (FlexPanel needs Uno.Toolkit 10; one line written)"), "{code}"); + assert!(code.contains("new AutoLayout()"), "{code}"); + set(&mut s, f, json!({"wrap": false})); + assert!(!uno(&mut s, f).contains("wrap (FlexPanel")); +} + +/// A text in `parent` with an explicit pixel line height, in the first installed family (any, as the +/// formula is checked against the face the code itself asks for). `None` when no font is installed. +fn spaced_text(s: &mut Session, parent: NodeId, line_height: f64) -> Option<(NodeId, f64)> { + // The fonts of the machine; a face that exists nearly everywhere is preferred. + figcraft_text::scan_system_fonts(); + let family = ["DejaVu Sans", "Liberation Sans", "Arial"].into_iter().find(|f| figcraft_text::has_family(f)).map(str::to_string); + let family = family.or_else(|| figcraft_text::family_names().into_iter().next())?; + let t = idv(&ex(s, "text.create", json!({"text": "One\nTwo\nThree", "x": 7, "y": 9, "parent": parent, "props": {"name": "Para"}}))); + set(s, t, json!({"fontFamily": family, "fontSize": 20, "lineHeight": line_height, "textAutoResize": "widthAndHeight"})); + let style = match &s.doc().ok()?.node(t)?.kind { + NodeKind::Text(td) => td.style.clone(), + _ => return None, + }; + let face = figcraft_text::find_face(&style.font_family, &style.font_style)?; + Some((t, (line_height - (face.ascent + face.descent) / face.upem * 20.0) / 2.0)) +} + +#[test] +fn half_leading_moves_text_down_with_padding_in_a_flow_and_the_offset_in_a_canvas() { + use crate::codegen::num; + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let Some((_, h)) = spaced_text(&mut s, col, 60.0) else { return }; + assert!(h > 0.5, "60 px lines are looser than any 20 px font"); + let code = uno(&mut s, col); + let c = chain(&code, "para"); + assert!(c.contains(&".LineHeight(60)".to_string()), "{code}"); + assert!(c.contains(&format!(".Padding(0, {}, 0, 0)", num(h))), "{c:?}"); + assert!(c.contains(&format!(".Margin(0, 0, 0, {})", num(-h))), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Height(")), "never a height of n lines: {c:?}"); + // In a canvas the offset takes the shift and there is no padding. + let free = frame(&mut s, "Free", 200.0, 200.0); + let (_, h) = spaced_text(&mut s, free, 60.0).unwrap_or((free, 0.0)); + let code = uno(&mut s, free); + let c = chain(&code, "para"); + assert_eq!(c[0], format!(".Canvas(left: 7, top: {})", num(9.0 + h)), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); +} + +#[test] +fn half_leading_merges_with_the_margin_of_an_independent_child() { + use crate::codegen::num; + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let Some((t, h)) = spaced_text(&mut s, col, 60.0) else { return }; + set(&mut s, t, json!({"absolute": true, "x": 30, "y": 40})); + let c = chain(&uno(&mut s, col), "para"); + assert!(c.contains(&format!(".Margin(30, 40, 0, {})", num(-h))), "{c:?}"); + assert_eq!(c.iter().filter(|l| l.starts_with(".Margin(")).count(), 1, "{c:?}"); +} + +#[test] +fn a_line_height_below_the_font_uses_block_line_stacking_and_an_automatic_one_needs_nothing() { + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let Some((t, _)) = spaced_text(&mut s, col, 1.0) else { return }; + let c = chain(&uno(&mut s, col), "para"); + assert!(c.contains(&".LineHeight(1)".to_string()), "{c:?}"); + assert!(c.contains(&".LineStackingStrategy(LineStackingStrategy.BlockLineHeight)".to_string()), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(") || l.starts_with("//")), "{c:?}"); + set(&mut s, t, json!({"lineHeight": "auto"})); + let c = chain(&uno(&mut s, col), "para"); + assert!( + !c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(") || l.starts_with("//") || l.starts_with(".LineStacking")), + "{c:?}" + ); + // A looser line height than the font's keeps the half-leading shift and no block stacking. + set(&mut s, t, json!({"lineHeight": 60})); + let c = chain(&uno(&mut s, col), "para"); + assert!(c.iter().any(|l| l.starts_with(".Padding(0, ")) && !c.iter().any(|l| l.starts_with(".LineStacking")), "{c:?}"); +} + +#[test] +fn a_font_that_is_not_installed_gets_no_shift_and_a_note() { + let mut s = Session::new(); + let col = row(&mut s, json!({"layout": "vertical"})); + let t = idv(&ex(&mut s, "text.create", json!({"text": "Hi", "x": 0, "y": 0, "parent": col, "props": {"name": "Para"}}))); + set(&mut s, t, json!({"fontFamily": "Nonexistent Family Zzyzx", "fontSize": 20, "lineHeight": 60})); + let c = chain(&uno(&mut s, col), "para"); + assert!(c.iter().any(|l| l.starts_with("// not mapped: line height shift")), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with(".Padding(") || l.starts_with(".Margin(")), "{c:?}"); +} + +#[test] +fn path_data_writes_moves_lines_curves_and_closes_with_the_fill_rule() { + use crate::codegen::path_data; + use figcraft_geom::BezPath; + use figcraft_render::FillRule; + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((24.0, 0.0)); + p.quad_to((30.5, 6.25), (24.0, 12.0)); + p.curve_to((20.0, 20.0), (4.0, 20.125), (0.0, 12.0)); + p.close_path(); + assert_eq!(path_data(&p, FillRule::Winding).as_deref(), Some("F1 M 0 0 L 24 0 Q 30.5 6.25 24 12 C 20 20 4 20.13 0 12 Z")); + assert!(path_data(&p, FillRule::EvenOdd).is_some_and(|d| d.starts_with("F0 M 0 0"))); + // An open path has no Z; a second subpath starts with its own M. + let mut open = BezPath::new(); + open.move_to((1.0, 2.0)); + open.line_to((3.0, 4.0)); + open.move_to((5.0, 6.0)); + open.line_to((7.0, 8.0)); + assert_eq!(path_data(&open, FillRule::Winding).as_deref(), Some("F1 M 1 2 L 3 4 M 5 6 L 7 8")); +} + +#[test] +fn path_data_refuses_empty_non_finite_and_huge_outlines() { + use crate::codegen::path_data; + use figcraft_geom::BezPath; + use figcraft_render::FillRule; + assert!(path_data(&BezPath::new(), FillRule::Winding).is_none()); + let mut bad = BezPath::new(); + bad.move_to((0.0, 0.0)); + bad.line_to((f64::NAN, 1.0)); + assert!(path_data(&bad, FillRule::Winding).is_none()); + let mut inf = BezPath::new(); + inf.move_to((0.0, f64::INFINITY)); + assert!(path_data(&inf, FillRule::Winding).is_none()); + let mut huge = BezPath::new(); + huge.move_to((0.0, 0.0)); + for i in 0..5_000 { + huge.line_to((f64::from(i), 1.0)); + } + assert!(path_data(&huge, FillRule::Winding).is_none(), "5,001 elements are past the cap"); + // Under the element cap but longer than one C# literal (10,000 characters): refused too. + let mut long = BezPath::new(); + long.move_to((0.0, 0.0)); + for i in 0..2_000 { + long.line_to((f64::from(i), 1.0)); + } + assert!(path_data(&long, FillRule::Winding).is_none(), "about 16,000 characters"); + let mut ok = BezPath::new(); + ok.move_to((0.0, 0.0)); + for i in 0..999 { + ok.line_to((f64::from(i), 1.0)); + } + let data = path_data(&ok, FillRule::Winding); + assert!(data.as_ref().is_some_and(|d| d.len() <= 10_000 && d.ends_with("L 998 1")), "{data:?}"); +} + +#[test] +fn a_star_is_a_path_with_its_fill_and_size_and_no_asset() { + let mut s = Session::new(); + let f = frame(&mut s, "Icons", 100.0, 100.0); + let star = + idv(&ex(&mut s, "node.create", json!({"type": "star", "parent": f, "name": "Star Icon", "x": 10, "y": 20, "width": 40, "height": 40}))); + set(&mut s, star, json!({"fill": "#141414"})); + let code = uno(&mut s, f); + let c = chain(&code, "starIcon"); + assert_eq!(c.first().map(String::as_str), Some(".Canvas(left: 10, top: 20)"), "{code}"); + let data = c.iter().find(|l| l.starts_with(".Data(\"F1 M ")).cloned().unwrap_or_default(); + assert!(data.ends_with(" Z\")") && data.contains(" L "), "{c:?}"); + assert!(c.contains(&".Fill(Color.FromArgb(0xFF, 0x14, 0x14, 0x14))".to_string()), "{c:?}"); + assert!(c.contains(&".Width(40)".to_string()) && c.contains(&".Height(40)".to_string()), "{c:?}"); + assert!(code.contains("var starIcon = new Microsoft.UI.Xaml.Shapes.Path()"), "{code}"); + assert!(!code.contains("Assets/") && !code.contains(".svg") && !code.contains("new Image()"), "{code}"); +} + +#[test] +fn a_boolean_result_and_an_even_odd_outline_are_paths_too() { + let mut s = Session::new(); + let f = frame(&mut s, "Shapes", 200.0, 100.0); + let a = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40, "parent": f, "props": {"name": "A"}}))); + let b = idv(&ex(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40, "parent": f, "props": {"name": "B"}}))); + let u = idv(&ex(&mut s, "bool.union", json!({"ids": [a, b]}))); + set(&mut s, u, json!({"name": "Union", "fill": "#00FF00"})); + let code = uno(&mut s, f); + let c = chain(&code, "union"); + assert!(c.iter().any(|l| l.starts_with(".Data(\"F") && l.contains(" M ")), "{code}"); + // A boolean's result is even-odd; a star is non-zero. + assert!(c.iter().any(|l| l.starts_with(".Data(\"F0 ")), "{c:?}"); + assert!(!code.contains("export it as"), "{code}"); +} + +#[test] +fn a_stroked_vector_has_a_centred_stroke_and_a_note_for_inside_or_outside() { + let mut s = Session::new(); + let f = frame(&mut s, "Strokes", 100.0, 100.0); + let v = idv(&ex(&mut s, "node.create", json!({"type": "star", "parent": f, "name": "Line Star", "x": 0, "y": 0, "width": 30, "height": 30}))); + set(&mut s, v, json!({"fill": "#FF0000", "stroke": "#0000FF", "strokeWeight": 2, "strokeAlign": "center"})); + let c = chain(&uno(&mut s, f), "lineStar"); + assert!(c.contains(&".Stroke(Color.FromArgb(0xFF, 0x00, 0x00, 0xFF))".to_string()) && c.contains(&".StrokeThickness(2)".to_string()), "{c:?}"); + assert!(!c.iter().any(|l| l.starts_with("//")), "{c:?}"); + set(&mut s, v, json!({"strokeAlign": "inside"})); + let c = chain(&uno(&mut s, f), "lineStar"); + assert!(c.contains(&"// not mapped: stroke inside or outside (drawn centred)".to_string()), "{c:?}"); +} + +#[test] +fn vectors_that_a_path_cannot_draw_are_png_assets_with_unique_lowercase_names() { + let mut s = Session::new(); + let f = frame(&mut s, "Icons", 300.0, 100.0); + let gradient = json!({"type": "gradient", "kind": "linear", + "stops": [{"position": 0, "color": {"r": 1, "g": 0, "b": 0, "a": 1}}, {"position": 1, "color": {"r": 0, "g": 0, "b": 1, "a": 1}}], + "from": [0, 0.5], "to": [1, 0.5]}); + let mut ids = Vec::new(); + for x in [0, 50, 100, 150] { + ids.push(idv(&ex( + &mut s, + "node.create", + json!({"type": "star", "parent": f, "name": "Star Icon", "x": x, "y": 0, "width": 40, "height": 40}), + ))); + } + set(&mut s, ids[0], json!({"fills": [gradient]})); + set(&mut s, ids[1], json!({"fills": ["#FF0000", "#00FF00"]})); + set(&mut s, ids[2], json!({"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 4], "radius": 8}]})); + let code = uno(&mut s, f); + for n in ["star_icon", "star_icon_2", "star_icon_3"] { + assert!(code.contains(&format!(".Source(\"ms-appx:///Assets/{n}.png\")")), "{n} in {code}"); + assert!(code.contains(&format!("// Star \"Star Icon\": export it as a PNG to Assets/{n}.png")), "{code}"); + } + assert!(code.contains(".Stretch(Stretch.Uniform)"), "{code}"); + // The fourth is plain: a path, and it takes no asset name. + assert_eq!(code.matches("new Microsoft.UI.Xaml.Shapes.Path()").count(), 1, "{code}"); + assert!(!code.contains("star_icon_4") && !code.contains(".svg"), "{code}"); +} + +#[test] +fn a_path_too_long_for_one_literal_is_an_image_not_cut_geometry() { + let mut s = Session::new(); + let f = frame(&mut s, "Long", 2000.0, 2000.0); + // 2,001 elements (under the element cap) but about 24,000 characters of path data. + let mut d = String::from("M0 0"); + for i in 0..2000 { + d.push_str(&format!(" L{}.25 {}.75", 1000 + i % 997, 1000 + (i * 7) % 991)); + } + d.push_str(" Z"); + let v = idv(&ex(&mut s, "node.create", json!({"type": "vector", "path": d, "closed": true, "parent": f, "name": "Long Line"}))); + set(&mut s, v, json!({"fills": ["#000000"]})); + let code = uno(&mut s, f); + assert!(!code.contains(".Data("), "{code}"); + assert!(code.contains(".Source(\"ms-appx:///Assets/long_line.png\")"), "{code}"); + // A short outline is still a path. + let short = idv(&ex(&mut s, "node.create", json!({"type": "vector", "path": "M0 0 L10 0 L10 10 Z", "closed": true, "parent": f}))); + set(&mut s, short, json!({"fills": ["#000000"]})); + assert_eq!(uno(&mut s, f).matches(".Data(").count(), 1); +} + +#[test] +fn the_last_comment_line_above_a_layer_is_its_name_and_notes_and_warnings_cannot_be_taken_for_it() { + // The plugin that post-processes the code pairs elements with layers by this rule. + let mut s = Session::new(); + let root = frame(&mut s, "Root", 200.0, 200.0); + let warn = rect(&mut s, root, 10.0, 10.0, "warning: x"); + set(&mut s, warn, json!({"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 4], "radius": 8}]})); + rect(&mut s, root, 10.0, 10.0, "line one\nline two\u{2028}three"); + rect(&mut s, root, 10.0, 10.0, &"long ".repeat(40)); + let hidden = rect(&mut s, root, 10.0, 10.0, "Hidden Layer"); + set(&mut s, hidden, json!({"visible": false})); + let code = uno(&mut s, root); + let tree_text = tree(&code); + let lines: Vec<&str> = tree_text.lines().map(str::trim).collect(); + // For every statement that creates a layer's element (not the helpers a layer needs), the line + // above it is `// `; `// warning:` lines come before that line. + let decl = |l: &str| l.starts_with("var "); + let anchors: Vec<(&str, &str)> = lines + .iter() + .enumerate() + .filter(|(_, l)| decl(l)) + .map(|(i, l)| (*l, i.checked_sub(1).and_then(|j| lines.get(j)).copied().unwrap_or(""))) + .collect(); + let name_of = |var: &str| anchors.iter().find(|(l, _)| l.starts_with(&format!("var {var} = "))).map(|(_, a)| *a); + assert_eq!(name_of("root"), Some("// Root"), "{code}"); + assert_eq!(name_of("warningX"), Some("// warning: x"), "{code}"); + assert_eq!(name_of("lineOneLineTwoThree"), Some("// line one line two three"), "{code}"); + assert!(anchors.iter().any(|(_, a)| a.starts_with("// long long ") && a.ends_with('…') && a.chars().count() <= 84), "{code}"); + // The root's warning is above its name, never between the name and the statement. + let at = lines.iter().position(|l| l.starts_with("var root = ")).unwrap_or(0); + assert!(lines.get(at.wrapping_sub(2)).is_some_and(|l| l.starts_with("// warning: 1 frame has no auto layout")), "{code}"); + // A note is below the constructor, in the chain, and the layer's name still comes first. + let shadow = chain(&code, "warningX"); + assert!(shadow.iter().any(|l| l.starts_with("// not mapped: drop shadow")), "{code}"); + assert!(!anchors.iter().any(|(_, a)| a.starts_with("// not mapped:")), "{code}"); + // Hidden layers write nothing. + assert!(!code.contains("Hidden Layer") && !code.contains("hiddenLayer"), "{code}"); +} + +#[test] +fn a_slice_writes_nothing_and_a_cut_subtree_keeps_its_name() { + let mut s = Session::new(); + let f = frame(&mut s, "Cut", 100.0, 100.0); + ex(&mut s, "node.create", json!({"type": "slice", "parent": f, "name": "Export Area", "x": 0, "y": 0, "width": 10, "height": 10})); + let mut parent = f; + for i in 0..20 { + parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50, "parent": parent, "name": format!("Level {i}")}))); + } + let code = uno(&mut s, f); + assert!(!code.contains("Export Area") && !code.contains("exportArea"), "{code}"); + // The placeholder where the depth cap cuts keeps its layer's name above its statement. + let tree_text = tree(&code); + let lines: Vec<&str> = tree_text.lines().map(str::trim).collect(); + let cut = lines.iter().position(|l| l.ends_with(" …")).unwrap_or(0); + assert!(lines.get(cut + 1).is_some_and(|l| l.starts_with("var ") && l.ends_with("new Border();")), "{code}"); +} + +#[test] +fn a_root_that_hugs_its_content_keeps_hugging() { + let mut s = Session::new(); + let f = frame(&mut s, "Card", 240.0, 200.0); + set(&mut s, f, json!({"layout": "vertical", "padding": 16, "gap": 8, "sizingH": "fixed", "sizingV": "hug", "fills": []})); + idv(&ex(&mut s, "text.create", json!({"parent": f, "text": "Hello", "x": 0, "y": 0}))); + let code = uno(&mut s, f); + let root = tree(&code).split("// ").nth(1).unwrap_or_default().to_string(); + // The width is fixed; the height follows the content, so a longer text or a larger gap grows it. + assert!(root.contains(".Width(240)"), "{code}"); + assert!(!root.contains(".Height("), "{code}"); + // A root fixed on both axes keeps both sizes. + set(&mut s, f, json!({"sizingV": "fixed"})); + let fixed = uno(&mut s, f); + assert!(fixed.contains(".Width(240)") && fixed.contains(".Height("), "{fixed}"); +} + +#[test] +fn a_frame_that_hugs_or_fills_is_not_clipped_at_its_design_size() { + let mut s = Session::new(); + let f = frame(&mut s, "Card", 240.0, 120.0); + set(&mut s, f, json!({"layout": "vertical", "sizingV": "hug", "clip": true, "fills": []})); + idv(&ex(&mut s, "text.create", json!({"parent": f, "text": "Hello", "x": 0, "y": 0}))); + let code = uno(&mut s, f); + assert!(!code.contains(".Clip("), "{code}"); + assert!(code.contains("// not mapped: clip content on a frame that hugs or fills"), "{code}"); + // Fixed on both axes, the clip is the frame's box. + set(&mut s, f, json!({"sizingV": "fixed"})); + let fixed = uno(&mut s, f); + assert!(fixed.contains(".Clip(new RectangleGeometry().Rect(new Rect(0, 0, 240, "), "{fixed}"); +} diff --git a/crates/engine/src/variables_io_tests.rs b/crates/engine/src/variables_io_tests.rs index fc032d007..b8d99805b 100644 --- a/crates/engine/src/variables_io_tests.rs +++ b/crates/engine/src/variables_io_tests.rs @@ -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::>(); + 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())); diff --git a/crates/engine/src/vector_behaviour_tests.rs b/crates/engine/src/vector_behaviour_tests.rs index 48fab9c6e..7ab1f08a9 100644 --- a/crates/engine/src/vector_behaviour_tests.rs +++ b/crates/engine/src/vector_behaviour_tests.rs @@ -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})); diff --git a/crates/engine/src/vector_fill_rule_tests.rs b/crates/engine/src/vector_fill_rule_tests.rs index eb462ab22..90df92159 100644 --- a/crates/engine/src/vector_fill_rule_tests.rs +++ b/crates/engine/src/vector_fill_rule_tests.rs @@ -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:?}"), } } diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 2a0101b04..3d11dd37c 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -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 } diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index db799ca70..ecfd862a9 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -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; diff --git a/crates/format/src/fig/assets_tests.rs b/crates/format/src/fig/assets_tests.rs index 7fffa15cd..f2b7e5dfa 100644 --- a/crates/format/src/fig/assets_tests.rs +++ b/crates/format/src/fig/assets_tests.rs @@ -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 { 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 { } 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 }; diff --git a/crates/format/src/fig/board_import_tests.rs b/crates/format/src/fig/board_import_tests.rs index fb4d4ba30..bff5ad32f 100644 --- a/crates/format/src/fig/board_import_tests.rs +++ b/crates/format/src/fig/board_import_tests.rs @@ -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. diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index 5c6e9fc24..357b1f51e 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -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, } +/// 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, + /// 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, + /// 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, + /// Instance → the slot frames whose assignments it writes. + instance_slots: BTreeMap>, + /// Layers written as private slot content (not as overrides of their main). + private_layers: BTreeSet, nodes: Vec>, /// Blob bytes → index (identical blobs are written once). blobs: BTreeMap, 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> { self.ids.get(&id).map(|l| guid(LAYERS, *l)) } diff --git a/crates/format/src/fig/export/assets.rs b/crates/format/src/fig/export/assets.rs index f1df1874d..65b5d2083 100644 --- a/crates/format/src/fig/export/assets.rs +++ b/crates/format/src/fig/export/assets.rs @@ -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 = 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 = 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. diff --git a/crates/format/src/fig/export/common.rs b/crates/format/src/fig/export/common.rs index 3ca682682..3feee81b7 100644 --- a/crates/format/src/fig/export/common.rs +++ b/crates/format/src/fig/export/common.rs @@ -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, } } diff --git a/crates/format/src/fig/export/component.rs b/crates/format/src/fig/export/component.rs index 0247fd43d..a464e9ee6 100644 --- a/crates/format/src/fig/export/component.rs +++ b/crates/format/src/fig/export/component.rs @@ -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"); } } diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index 3b718cfc2..1dcb77f03 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -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); diff --git a/crates/format/src/fig/export_slot_tests.rs b/crates/format/src/fig/export_slot_tests.rs new file mode 100644 index 000000000..46d9e9a71 --- /dev/null +++ b/crates/format/src/fig/export_slot_tests.rs @@ -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 { + 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::>() { + 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:?}"); +} diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 9cb417078..c91866a53 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -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> { @@ -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()); diff --git a/crates/format/src/fig/interop_tests.rs b/crates/format/src/fig/interop_tests.rs index 4ad81cebc..95967392e 100644 --- a/crates/format/src/fig/interop_tests.rs +++ b/crates/format/src/fig/interop_tests.rs @@ -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 } diff --git a/crates/format/src/fig/text_list_tests.rs b/crates/format/src/fig/text_list_tests.rs index ef0439694..5fa9bfe02 100644 --- a/crates/format/src/fig/text_list_tests.rs +++ b/crates/format/src/fig/text_list_tests.rs @@ -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(); diff --git a/crates/format/src/fig/text_skip_ink_tests.rs b/crates/format/src/fig/text_skip_ink_tests.rs index b5285e1b6..5c8b24c5e 100644 --- a/crates/format/src/fig/text_skip_ink_tests.rs +++ b/crates/format/src/fig/text_skip_ink_tests.rs @@ -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(); diff --git a/crates/format/src/large_tests.rs b/crates/format/src/large_tests.rs index 4934b7e2e..07586a8d2 100644 --- a/crates/format/src/large_tests.rs +++ b/crates/format/src/large_tests.rs @@ -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); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 58353e67b..3ec35d42e 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -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) -> 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) -> Result, 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) -> ImageData { let (w, h) = stored_dimensions(&data).unwrap_or((0, 0)); diff --git a/crates/format/src/penpot.rs b/crates/format/src/penpot.rs index c47b55b18..22a8237c7 100644 --- a/crates/format/src/penpot.rs +++ b/crates/format/src/penpot.rs @@ -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"))); diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index e3ad744ef..6388085c6 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -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); diff --git a/crates/format/src/raw.rs b/crates/format/src/raw.rs new file mode 100644 index 000000000..80e20e370 --- /dev/null +++ b/crates/format/src/raw.rs @@ -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, + 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 { + 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 +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index c2a8c962c..7e7c80422 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -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" } }; diff --git a/crates/format/tests/it/range_hyperlink_round_trip.rs b/crates/format/tests/it/range_hyperlink_round_trip.rs index f47e22ae8..2b0935977 100644 --- a/crates/format/tests/it/range_hyperlink_round_trip.rs +++ b/crates/format/tests/it/range_hyperlink_round_trip.rs @@ -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); diff --git a/crates/layout/src/behaviour_tests.rs b/crates/layout/src/behaviour_tests.rs index a17a563df..0869497d4 100644 --- a/crates/layout/src/behaviour_tests.rs +++ b/crates/layout/src/behaviour_tests.rs @@ -142,7 +142,7 @@ fn build(c: &Case<'_>) -> (Document, NodeId, Vec, FakeMeasure) { let mut texts = HashMap::new(); let mut ids = Vec::new(); for k in c.kids { - let kind = if k.text.is_some() { NodeKind::Text(TextData::new("T")) } else { NodeKind::Rectangle }; + let kind = if k.text.is_some() { NodeKind::Text(TextData::new("T").into()) } else { NodeKind::Rectangle }; let kid = d.create(id, kind, "K", k.at.0, k.at.1, k.size.0, k.size.1).unwrap(); let n = d.get_mut(kid).unwrap(); if let (Some(t), NodeKind::Text(td)) = (k.text, &mut n.kind) { diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 1d77afe0d..2328e8cf1 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -134,7 +134,11 @@ pub fn set_size(doc: &mut Document, id: NodeId, w: f64, h: f64) { let sy = if oh > 1e-9 { h / oh } else { 1.0 }; match &mut n.kind { NodeKind::Vector { network } => network.scale(sx, sy), - NodeKind::Text(figcraft_doc::TextData { path: Some(tp), .. }) => tp.scale(sx, sy), + NodeKind::Text(t) if t.path.is_some() => { + if let Some(tp) = &mut t.path { + tp.scale(sx, sy); + } + } _ => {} } n.width = w; diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index df9dd73e5..332a28b42 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -181,7 +181,7 @@ impl Measure for FakeMeasure { } pub(super) fn text(d: &mut Document, parent: NodeId, name: &str) -> NodeId { - d.create(parent, NodeKind::Text(figcraft_doc::TextData::new(name)), name, 0.0, 0.0, 10.0, 10.0).unwrap() + d.create(parent, NodeKind::Text(figcraft_doc::TextData::new(name).into()), name, 0.0, 0.0, 10.0, 10.0).unwrap() } #[test] diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 08c4e9d08..9331f5fdb 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -241,7 +241,12 @@ impl Server { fn roots_note(&self) -> String { let Some(r) = &self.roots else { return String::new() }; let j = r.to_json(); - format!(" Files: only these folders may be read: {}; written: {} (any other path is refused).", j["read"], j["write"]) + let files = format!(" Files: only these folders may be read: {}; written: {} (any other path is refused).", j["read"], j["write"]); + if r.allowed_servers().is_empty() { + files + } else { + format!("{files} Collaboration: may join only links on {}; other network requests are refused.", j["allowedServers"]) + } } fn notification(&mut self, method: &str) { diff --git a/crates/pdf/src/export_tests.rs b/crates/pdf/src/export_tests.rs index d41f11379..adb3e06d7 100644 --- a/crates/pdf/src/export_tests.rs +++ b/crates/pdf/src/export_tests.rs @@ -147,7 +147,7 @@ fn text_hyperlinks_become_link_annotations() { linked.link = Some(URL.into()); // "docs" (chars 9..13) links. td.runs = vec![StyleRun { start: 9, end: 13, style: linked }]; - let t = d.create(f, NodeKind::Text(td), "T", 10.0, 10.0, 280.0, 40.0).unwrap(); + let t = d.create(f, NodeKind::Text(td.into()), "T", 10.0, 10.0, 280.0, 40.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let Some((layout, _)) = figcraft_text::layout_node(d.node(t).unwrap()) else { return }; if layout.glyphs.is_empty() { @@ -183,7 +183,7 @@ fn hostile_links_are_skipped() { td.style.link = Some(url.to_string()); // One off the page entirely. let x = if i == 2 { 500.0 } else { 0.0 }; - d.create(f, NodeKind::Text(td), "T", x, 0.0, 80.0, 20.0).unwrap(); + d.create(f, NodeKind::Text(td.into()), "T", x, 0.0, 80.0, 20.0).unwrap(); } let pdf = export_pdf(&d, &[f], &PdfOptions::default()).unwrap(); assert_eq!(text(&pdf).matches("/Subtype/Link").count(), 0); @@ -296,7 +296,7 @@ fn an_oversized_link_is_dropped_before_it_is_copied_per_line() { let mut td = TextData::new(words.trim_end()); td.style.font_size = 20.0; td.style.link = Some("https://example.com/".to_string() + &"a".repeat(1 << 20)); - let t = d.create(f, NodeKind::Text(td), "T", 10.0, 10.0, 280.0, 3980.0).unwrap(); + let t = d.create(f, NodeKind::Text(td.into()), "T", 10.0, 10.0, 280.0, 3980.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let pdf = export_pdf(&d, &[f], &PdfOptions::default()).unwrap(); assert_eq!(text(&pdf).matches("/Subtype/Link").count(), 0); diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 110bfa736..c2e9f2568 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -77,7 +77,7 @@ fn pdf_vector_region_paints_emit_independent_colors() { 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, 20.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 20.0, 10.0).unwrap(); let content = inflated(&export_pdf(&d, &[id], &PdfOptions::default()).unwrap()); assert!(content.contains("1 0 0 rg") && content.contains("0 0 1 rg"), "{content}"); } @@ -94,7 +94,7 @@ fn pdf_vector_region_paints_draw_smoothed_corners() { network.regions[0].fills = Some(vec![Paint::solid(Color::from_hex("FF0000").unwrap())]); let mut d = Document::new("smoothing"); let p = d.first_page().unwrap(); - 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 content = |d: &Document| inflated(&export_pdf(d, &[id], &PdfOptions::default()).unwrap()); let plain = content(&d); d.get_mut(id).unwrap().corners.smoothing = 0.6; @@ -145,7 +145,7 @@ pub(crate) fn sample_doc() -> (Document, Vec) { // Text. let mut td = TextData::new("Hello PDF"); td.style.font_size = 24.0; - let t = d.create(f1, NodeKind::Text(td), "T", 16.0, 200.0, 280.0, 32.0).unwrap(); + let t = d.create(f1, NodeKind::Text(td.into()), "T", 16.0, 200.0, 280.0, 32.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::from_hex("111111").unwrap())]; // A child sticking out of the frame (clipped). d.create(f1, NodeKind::Rectangle, "Out", 280.0, 200.0, 100.0, 100.0).unwrap(); @@ -288,7 +288,7 @@ fn hostile_inputs_error_or_skip() { visible: true, }]; } - let t = d.create(f, NodeKind::Text(TextData::new("x")), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); + let t = d.create(f, NodeKind::Text(TextData::new("x").into()), "T", 0.0, 0.0, 10.0, 10.0).unwrap(); if let NodeKind::Text(td) = &mut d.get_mut(t).unwrap().kind { td.style.font_size = f64::NAN; } diff --git a/crates/render/src/boolean_budget_tests.rs b/crates/render/src/boolean_budget_tests.rs index f13190678..0dcae7e6c 100644 --- a/crates/render/src/boolean_budget_tests.rs +++ b/crates/render/src/boolean_budget_tests.rs @@ -28,7 +28,7 @@ fn union_of_bars(n: usize) -> (Document, NodeId, NodeId) { for across in [true, false] { let network = VectorNetwork::from_path(&bars(n, across)); let len = n as f64 * 4.0; - d.create(b, NodeKind::Vector { network }, "Bars", 0.0, 0.0, len, len).unwrap(); + d.create(b, NodeKind::Vector { network: network.into() }, "Bars", 0.0, 0.0, len, len).unwrap(); } d.fit_to_children(b).unwrap(); (d, page, b) diff --git a/crates/render/src/boolean_cache_tests.rs b/crates/render/src/boolean_cache_tests.rs index 51e422425..a3e35a837 100644 --- a/crates/render/src/boolean_cache_tests.rs +++ b/crates/render/src/boolean_cache_tests.rs @@ -233,7 +233,7 @@ fn stroke_only_text_operands_use_glyphs_instead_of_the_text_box() { let b = d.create(page, NodeKind::BooleanOp { op: BoolOp::Union }, "B", 0.0, 0.0, 400.0, 100.0).unwrap(); let mut text = TextData::new("Hi"); text.style.font_size = 32.0; - let id = d.create(b, NodeKind::Text(text), "text", 0.0, 0.0, 400.0, 100.0).unwrap(); + let id = d.create(b, NodeKind::Text(text.into()), "text", 0.0, 0.0, 400.0, 100.0).unwrap(); let n = d.get_mut(id).unwrap(); n.fills.clear(); n.strokes = vec![Paint::solid(Color::BLACK)]; diff --git a/crates/render/src/downscaled_image_tests.rs b/crates/render/src/downscaled_image_tests.rs new file mode 100644 index 000000000..fb5f12792 --- /dev/null +++ b/crates/render/src/downscaled_image_tests.rs @@ -0,0 +1,140 @@ +//! Downscaled images (#2664): an image shown at half its pixels or fewer is drawn from a copy +//! averaged down to under twice that size, so one-pixel detail blends into an even grey instead of +//! aliasing into moiré bands, on the canvas and in exports alike. + +use std::sync::Arc; + +use figcraft_color::{ImageScaleMode, Paint, PaintKind}; +use figcraft_doc::{Document, ImageData, NodeId, NodeKind}; +use figcraft_geom::Affine; + +use crate::{Options, Pixmap, View, encode_png, render_view}; + +/// The image's side: smaller than every canvas copy, so the canvas draws it from itself too. +const SIDE: u32 = 200; + +/// A `SIDE` × `SIDE` checkerboard of one-pixel black and white squares filling a box its size: the +/// document, its page and the box. +fn checkerboard_doc() -> (Document, NodeId, NodeId) { + let mut img = Pixmap::new(SIDE, SIDE).unwrap(); + for (i, c) in (0u32..).zip(img.data_mut().chunks_exact_mut(4)) { + let black = (i % SIDE + i / SIDE).is_multiple_of(2); + c.copy_from_slice(if black { &[0, 0, 0, 255] } else { &[255, 255, 255, 255] }); + } + let mut d = Document::new("downscaled"); + let page = d.first_page().unwrap(); + d.images.insert("fine".into(), ImageData { bytes: Arc::new(encode_png(&img).unwrap()), width: SIDE, height: SIDE }); + let r = d.create(page, NodeKind::Rectangle, "Image", 0.0, 0.0, f64::from(SIDE), f64::from(SIDE)).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image("fine", ImageScaleMode::Fill)]; + (d, page, r) +} + +/// The darkest and lightest red over the image's pixels (but a 2-pixel rim, where it meets the +/// background) drawn at `scale` from `origin`. +fn red_range(d: &Document, page: NodeId, scale: f64, origin: (f64, f64), opts: &Options) -> (u8, u8) { + let side = (f64::from(SIDE) * scale).floor() as u32; + let pix = render_view(d, page, &View { origin, scale, width: side, height: side }, opts).unwrap(); + let inner = 2..side - 2; + inner + .clone() + .flat_map(|y| inner.clone().map(move |x| (x, y))) + .map(|(x, y)| pix.pixel(x, y).unwrap().red()) + .fold((255, 0), |(lo, hi), r| (lo.min(r), hi.max(r))) +} + +#[test] +fn an_image_shown_at_half_its_size_or_less_blends_its_fine_detail_evenly() { + let (d, page, _) = checkerboard_doc(); + let canvas = Options { lod: true, magnified_image_pixels: true, ..Default::default() }; + for (name, opts) in [("export", Options::default()), ("canvas", canvas)] { + for scale in [0.5, 0.37, 0.23] { + for origin in [(0.0, 0.0), (0.3, 0.7)] { + let (lo, hi) = red_range(&d, page, scale, origin, &opts); + assert!(lo >= 104 && hi <= 151, "{name} at {scale} from {origin:?}: reds {lo}..={hi}, not an even mid-grey"); + } + } + } +} + +#[test] +fn an_adjusted_image_shown_smaller_averages_its_adjusted_pixels() { + let (mut d, page, r) = checkerboard_doc(); + // Exposure brightens grey but leaves black black and white white. + if let PaintKind::Image(img) = &mut d.get_mut(r).unwrap().fills[0].kind { + img.filters.exposure = 1.0; + } + let canvas = Options { lod: true, magnified_image_pixels: true, ..Default::default() }; + for (name, opts) in [("export", Options::default()), ("canvas", canvas)] { + let (lo, hi) = red_range(&d, page, 0.37, (0.3, 0.7), &opts); + assert!(lo >= 104 && hi <= 151, "{name}: reds {lo}..={hi}, not the even mid-grey of black and white"); + } +} + +#[test] +fn a_crop_stretching_one_axis_keeps_the_pixels_that_axis_shows() { + // The whole image in a 400 × 2 box: each column two device pixels wide, the rows squeezed 100 + // to 1, so the view's row (at row 50's centre) shows every column black or white in turn. + let (mut d, page, r) = checkerboard_doc(); + let node = d.get_mut(r).unwrap(); + node.width = f64::from(2 * SIDE); + node.height = 2.0; + if let PaintKind::Image(img) = &mut node.fills[0].kind { + img.scale_mode = ImageScaleMode::Crop; + img.crop = Some([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + } + let pix = render_view(&d, page, &View { origin: (0.0, 0.005), scale: 1.0, width: 2 * SIDE, height: 1 }, &Options::default()).unwrap(); + let reds: Vec = (0..2 * SIDE).map(|x| pix.pixel(x, 0).unwrap().red()).collect(); + let (lo, hi) = reds[4..reds.len() - 4].iter().fold((255, 0), |(lo, hi), &r| (lo.min(r), hi.max(r))); + assert!(hi - lo > 64, "columns {lo}..={hi}: blended away, though each shows two device pixels wide"); +} + +/// A one-image document: `img` (`w` × `h`, under `key`: the cache is shared by every test) in a box +/// its size, scaled as `mode`. +fn image_doc(key: &str, img: &Pixmap, mode: ImageScaleMode) -> (Document, NodeId) { + let (w, h) = (img.width(), img.height()); + let mut d = Document::new("downscaled"); + let page = d.first_page().unwrap(); + d.images.insert(key.into(), ImageData { bytes: Arc::new(encode_png(img).unwrap()), width: w, height: h }); + let r = d.create(page, NodeKind::Rectangle, "Image", 0.0, 0.0, f64::from(w), f64::from(h)).unwrap(); + d.get_mut(r).unwrap().fills = vec![Paint::image(key, mode)]; + (d, page) +} + +#[test] +fn a_thin_image_shown_smaller_still_fills_its_box() { + // 200 × 3 at 0.5x: its copy is 100 × 2, proportions a third off from the image's. + let mut img = Pixmap::new(200, 3).unwrap(); + img.fill(tiny_skia::Color::BLACK); + let (d, page) = image_doc("thin", &img, ImageScaleMode::Fit); + let pix = render_view(&d, page, &View { origin: (0.0, 0.0), scale: 0.5, width: 100, height: 1 }, &Options::default()).unwrap(); + let reds: Vec = (0..100).map(|x| pix.pixel(x, 0).unwrap().red()).collect(); + assert!(reds[1..99].iter().all(|&r| r < 8), "the box's row isn't all image (black): {reds:?}"); +} + +#[test] +fn a_transparent_image_shown_smaller_keeps_its_colour() { + // Opaque red columns between transparent ones: averaged, a half-transparent pure red (light red + // over the page's white). + let mut img = Pixmap::new(200, 8).unwrap(); + for (i, c) in (0u32..).zip(img.data_mut().chunks_exact_mut(4)) { + c.copy_from_slice(if (i % 200).is_multiple_of(2) { &[255, 0, 0, 255] } else { &[0, 0, 0, 0] }); + } + let (d, page) = image_doc("half-clear", &img, ImageScaleMode::Fill); + let pix = render_view(&d, page, &View { origin: (0.0, 0.0), scale: 0.37, width: 74, height: 2 }, &Options::default()).unwrap(); + for x in 2..72 { + let c = pix.pixel(x, 1).unwrap(); + assert!(c.red() >= 245 && (100..=155).contains(&c.green()) && c.green().abs_diff(c.blue()) <= 4, "x {x}: {c:?}, not half red over white"); + } +} + +#[test] +fn a_layer_squeezed_on_one_axis_keeps_the_pixels_its_other_axis_shows() { + // The checkerboard's layer squeezed 100 to 1 vertically: each column one device pixel wide, so + // the view's row (at row 50's centre) shows every column black or white in turn. + let (mut d, page, r) = checkerboard_doc(); + d.get_mut(r).unwrap().transform = Affine::scale_non_uniform(1.0, 0.01); + let pix = render_view(&d, page, &View { origin: (0.0, 0.005), scale: 1.0, width: SIDE, height: 1 }, &Options::default()).unwrap(); + let reds: Vec = (0..SIDE).map(|x| pix.pixel(x, 0).unwrap().red()).collect(); + let (lo, hi) = reds[4..reds.len() - 4].iter().fold((255, 0), |(lo, hi), &r| (lo.min(r), hi.max(r))); + assert!(hi - lo > 64, "columns {lo}..={hi}: blended away, though each shows a device pixel wide"); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index d7bd63dd1..94fbbbeaf 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -153,8 +153,12 @@ fn pixels_when_magnified(prep: Prepared, device_scale: f64) -> Prepared { fn fill_with(pix: &mut Pixmap, path: &tiny_skia::Path, paints: &[Paint], w: f64, h: f64, xf: Affine, rule: FillRule, ctx: &Ctx, mask: Option<&Mask>) { let scale = xf.determinant().abs().sqrt(); + // An image picks its copy by the direction shown the most device pixels (a layer can be squeezed). + let [a, b, c, d, ..] = xf.as_coeffs(); + let stretch = crate::paint::max_stretch(a, b, c, d); for p in paints { - let Some(prep) = prepare_at(p, w, h, scale, ctx.doc, ctx.time, ctx.preview) else { continue }; + let k = if matches!(p.kind, PaintKind::Image(_)) { stretch } else { scale }; + let Some(prep) = prepare_at(p, w, h, k, ctx.doc, ctx.time, ctx.preview) else { continue }; let prep = if ctx.magnified_image_pixels && matches!(p.kind, PaintKind::Image(_)) { pixels_when_magnified(prep, scale) } else { prep }; let paint = tiny_skia::Paint { shader: prep.shader(), anti_alias: true, blend_mode: ts_blend(p.blend), ..Default::default() }; if p.blend == BlendMode::PlusDarker { diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 0c68f3b12..78a766fb1 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -4,7 +4,9 @@ //! //! The canvas draws a large image shown smaller than its pixels from a copy scaled down to one of //! [`DISPLAY_SIDES`] (see [`shown`]), so several of them stay decoded within the cache's budget -//! (#1483); exports and every other render draw from the image itself ([`get`]). +//! (#1483); exports draw from the image itself ([`get`]). Wherever an image shows at half its +//! pixels or fewer, it is drawn from a copy averaged down to under twice that size ([`filtered`]), +//! so fine detail blends instead of aliasing into moiré (#2664). //! //! Animated GIFs keep their original bytes like any image; their first frame is the image //! everywhere (canvas, exports). The presenter plays them: [`frame_at`] decodes every frame on @@ -345,8 +347,29 @@ pub fn get(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile /// [`get`] for the canvas, where the image shows `side` device pixels on its longer side: an image /// larger than one of [`DISPLAY_SIDES`] that holds `side` comes scaled down to that side (cached /// apart), else as [`get`] gives it. The image's size is the one `data` records (none: the image). +/// Either is halved further while at least twice `side` ([`filtered_side`]). pub fn shown(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile: ColorProfile, side: f64) -> Option> { - get_within(hash, data, filters, profile, display_side(data.map_or(0, |d| d.width.max(d.height)), side)) + let long = data.map_or(0, |d| d.width.max(d.height)); + get_within(hash, data, filters, profile, filtered_side(long, display_side(long, side), side)) +} + +/// [`get`] for an image showing `side` device pixels on its longer side: scaled down (cached apart) +/// while it is at least twice that long ([`filtered_side`]), else the image itself. +pub fn filtered(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, profile: ColorProfile, side: f64) -> Option> { + get_within(hash, data, filters, profile, filtered_side(data.map_or(0, |d| d.width.max(d.height)), MAX_SIDE, side)) +} + +/// The largest side to decode an image `long` pixels on its longer side at, decoded at most +/// `max_side` long, to show `side` device pixels long: halved while at least twice `side`, so it is +/// never sampled at half its size or less (each pixel an average of the pixels it covers, not a few +/// samples of them, which turns fine detail into moiré); else `max_side`. +pub(crate) fn filtered_side(long: u32, max_side: u32, side: f64) -> u32 { + let start = long.min(max_side); + let mut s = start; + while s > 1 && f64::from(s) >= 2.0 * side { + s = s.div_ceil(2); + } + if s < start { s } else { max_side } } /// The largest side to decode an image `long` pixels on its longer side at, to show `side` device @@ -362,14 +385,33 @@ fn get_within(hash: &str, data: Option<&ImageData>, filters: &ImageFilters, prof if let Some(p) = cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { return Some(p); } - let (mut p, srgb) = decode_within(&data?.bytes, profile, max_side, MAX_DECODED_BYTES)?; + let (mut p, srgb) = decode_within(&data?.bytes, profile, MAX_SIDE, MAX_DECODED_BYTES)?; // Images with their own profile are in `profile` already (sRGB → sRGB is the identity). finish(&mut p, filters, if srgb { profile } else { ColorProfile::Srgb }); - let p = Arc::new(p); + // A copy averages the finished pixels, as drawing the image smaller does: adjustments clamp, + // and premultiplied colour keeps transparent pixels from darkening their neighbours. + let p = Arc::new(shrink(p, max_side)?); cache().lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone(), MAX_CACHED_BYTES); Some(p) } +/// The size to place `pm`, image `data` or a copy of it, as: the size `data` records when `pm` is +/// that size decoded and scaled to `pm`'s longer side as [`get_within`] does (each side of a copy +/// rounds apart, so its own proportions are off by up to a pixel), else `pm`'s own. +pub(crate) fn source_size(data: Option<&ImageData>, pm: &Pixmap) -> (f64, f64) { + let own = (pm.width(), pm.height()); + let made = |(w, h)| thumbnail_size(w, h, MAX_SIDE).and_then(|(w, h)| thumbnail_size(w, h, own.0.max(own.1))); + let (w, h) = data.map(|d| (d.width, d.height)).filter(|&size| made(size) == Some(own)).unwrap_or(own); + (f64::from(w), f64::from(h)) +} + +/// `p` averaged down to at most `max_side` wide and tall. +fn shrink(p: Pixmap, max_side: u32) -> Option { + let (w, h) = (p.width(), p.height()); + let (nw, nh) = thumbnail_size(w, h, max_side)?; + Pixmap::from_vec(thumbnail_u8((w, h), (nw, nh), false, p.take())?, tiny_skia::IntSize::from_wh(nw, nh)?) +} + /// The filters, then the conversion into the document's colour space. fn finish(p: &mut Pixmap, filters: &ImageFilters, profile: ColorProfile) { if !filters.is_identity() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6779fe776..fb635509d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -679,6 +679,8 @@ mod clip_cover_tests; #[cfg(test)] mod dots_tests; #[cfg(test)] +mod downscaled_image_tests; +#[cfg(test)] mod effect_order_tests; #[cfg(test)] mod effects_behaviour_tests; diff --git a/crates/render/src/lod_tests.rs b/crates/render/src/lod_tests.rs index d7cd983c9..223468d92 100644 --- a/crates/render/src/lod_tests.rs +++ b/crates/render/src/lod_tests.rs @@ -48,11 +48,11 @@ fn cards() -> (Document, NodeId) { } let mut title = TextData::new(format!("Card number {i}")); title.style.font_size = 16.0; - d.create(card, NodeKind::Text(title), "Title", 84.0, 36.0, 110.0, 20.0).unwrap(); + d.create(card, NodeKind::Text(title.into()), "Title", 84.0, 36.0, 110.0, 20.0).unwrap(); let mut body = TextData::new("Some body text that wraps onto a second line"); body.auto_resize = figcraft_doc::TextAutoResize::Height; body.style.font_size = 11.0; - d.create(card, NodeKind::Text(body), "Body", 84.0, 60.0, 110.0, 30.0).unwrap(); + d.create(card, NodeKind::Text(body.into()), "Body", 84.0, 60.0, 110.0, 30.0).unwrap(); } (d, page) } @@ -117,7 +117,7 @@ fn region_paints_disable_vector_and_ancestor_splatting() { let parent = d.create(page, NodeKind::Frame, "Parent", 0.0, 0.0, 4.0, 4.0).unwrap(); let mut network = VectorNetwork::default(); network.regions.push(Region { loops: Vec::new(), winding: Default::default(), fills: Some(Vec::new()), ..Default::default() }); - let vector = d.create(parent, NodeKind::Vector { network }, "Styled", 0.0, 0.0, 2.0, 2.0).unwrap(); + let vector = d.create(parent, NodeKind::Vector { network: network.into() }, "Styled", 0.0, 0.0, 2.0, 2.0).unwrap(); let node = d.node(vector).unwrap(); assert!(!lod::splattable(&d, node, 0)); assert!(!lod::splattable(&d, d.node(parent).unwrap(), 0)); @@ -251,7 +251,7 @@ fn greeked_text_stays_inside_its_bounds() { let p = d.first_page().unwrap(); let mut t = TextData::new("Greeked text on a line\nand a second line"); t.style.font_size = 20.0; - let id = d.create(p, NodeKind::Text(t), "T", 100.0, 100.0, 300.0, 60.0).unwrap(); + let id = d.create(p, NodeKind::Text(t.into()), "T", 100.0, 100.0, 300.0, 60.0).unwrap(); let n = d.node(id).unwrap(); assert!(lod::greeked(n, 0.1) && !lod::greeked(n, 0.5)); let v = View { origin: (0.0, 0.0), scale: 0.1, width: 60, height: 30 }; diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index 56de03464..c62d553c2 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -145,13 +145,17 @@ pub fn prepare_at(paint: &Paint, w: f64, h: f64, scale: f64, doc: &Document, tim Some(f) => f.clone(), None => still(img, data, w, h, scale, doc, preview)?, }; - let transform = image_transform(img, f64::from(pm.width()), f64::from(pm.height()), w, h); + let (pw, ph) = (f64::from(pm.width()), f64::from(pm.height())); if img.scale_mode == ImageScaleMode::Tile { + let transform = image_transform(img, pw, ph, w, h); return Some(Prepared::Pattern { pixmap: pm, mode: SpreadMode::Repeat, quality: FilterQuality::Bicubic, opacity: op, transform }); } + // A smaller copy goes where the image itself would. + let (iw, ih) = crate::images::source_size(data, &pm); + let transform = Transform::from_scale((iw / pw) as f32, (ih / ph) as f32).post_concat(image_transform(img, iw, ih, w, h)); // An image covering the whole box fills it to its edges (a transparent border would // fade them where the image is scaled up). - if covers_box(img, f64::from(pm.width()), f64::from(pm.height()), w, h) { + if covers_box(img, iw, ih, w, h) { return Some(Prepared::Pattern { pixmap: pm, mode: SpreadMode::Pad, quality: FilterQuality::Bicubic, opacity: op, transform }); } // Fit/Crop: a transparent 1-px border so Pad spreads transparency, not edge pixels. @@ -169,17 +173,30 @@ pub fn prepare_at(paint: &Paint, w: f64, h: f64, scale: f64, doc: &Document, tim /// The pixmap image paint `img` draws in a `w` × `h` box at `scale` device pixels per unit: on the /// canvas (`preview`) a copy no larger than the image shows ([`crate::images::shown`]), else the -/// image itself. Tiles keep the image: their size is in its pixels. +/// image itself, scaled down where it shows at half its size or less ([`crate::images::filtered`]). +/// Tiles keep the image: their size is in its pixels. +/// shortcut: tiles shown much smaller can still alias; scale their transform with the copy if that turns up. fn still(img: &ImagePaint, data: Option<&ImageData>, w: f64, h: f64, scale: f64, doc: &Document, preview: bool) -> Option> { let (iw, ih) = data.map_or((0, 0), |d| (d.width, d.height)); - if preview && img.scale_mode != ImageScaleMode::Tile && iw > 0 && ih > 0 { + if img.scale_mode != ImageScaleMode::Tile && iw > 0 && ih > 0 { let t = image_transform(img, f64::from(iw), f64::from(ih), w, h); - let side = scale * f64::from(t.sx * t.sy - t.kx * t.ky).abs().sqrt() * f64::from(iw.max(ih)); - return crate::images::shown(&img.image, data, &img.filters, doc.color_profile, side); + // `scale` is the layer's largest stretch, so the product bounds what any direction shows. + let stretch = max_stretch(t.sx.into(), t.ky.into(), t.kx.into(), t.sy.into()); + let side = scale * stretch * f64::from(iw.max(ih)); + let pick = if preview { crate::images::shown } else { crate::images::filtered }; + return pick(&img.image, data, &img.filters, doc.color_profile, side); } crate::images::get(&img.image, data, &img.filters, doc.color_profile) } +/// The most the linear map `[a c; b d]` stretches any direction (its largest singular value): the +/// scale for uniform scaling and rotation, the longer axis for a squeeze. +pub(crate) fn max_stretch(a: f64, b: f64, c: f64, d: f64) -> f64 { + let sum = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt() +} + /// Whether image paint `img` paints its whole `w` × `h` box opaque: an image without transparent /// pixels that covers the box (or tiles it). /// shortcut: always looks at the image itself (exact, also on the canvas), so a large image with diff --git a/crates/render/src/paint_behaviour_tests.rs b/crates/render/src/paint_behaviour_tests.rs index 30c583d03..1de73777a 100644 --- a/crates/render/src/paint_behaviour_tests.rs +++ b/crates/render/src/paint_behaviour_tests.rs @@ -642,7 +642,7 @@ fn text_strokes_follow_their_alignment() { let (mut d, p) = page(); let mut td = figcraft_doc::TextData::new("I"); td.style.font_size = 120.0; - let t = d.create(p, NodeKind::Text(td), "T", 60.0, 30.0, 1.0, 1.0).unwrap(); + let t = d.create(p, NodeKind::Text(td.into()), "T", 60.0, 30.0, 1.0, 1.0).unwrap(); let n = d.get_mut(t).unwrap(); n.fills.clear(); n.strokes = vec![Paint::solid(hex("#000000"))]; diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index c74eb1a70..2d8bbdce3 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -195,12 +195,28 @@ impl Steps { #[derive(Default)] pub struct Retained { last: Option, + /// See [`Self::patched`]. + patched: Option>, } impl Retained { /// Forget the kept image (the next render is full). pub fn clear(&mut self) { self.last = None; + self.patched = None; + } + + /// The image kept from the last render. + pub fn image(&self) -> Option<&Pixmap> { + self.last.as_ref().map(|f| &f.pix) + } + + /// Where the last render's image differs from the one before it, when it is that image with + /// some areas drawn again in place (`[x, y, width, height]` in its pixels; none for a render + /// reused as it was): whoever holds the image before needs only these to have this one. + /// `None` after a full render and after a pan, which moves every pixel. + pub fn patched(&self) -> Option<&[[u32; 4]]> { + self.patched.as_deref() } /// Render `view` of `page`, reusing the previous render where nothing changed. Returns the @@ -267,6 +283,7 @@ impl Retained { /// The previous render patched where it could be (kept, see [`Self::keep`]), or what a full /// render of `view` needs. fn prepare(&mut self, doc: &Arc, page: NodeId, view: &View, opts: &Options) -> Option { + self.patched = None; // A view that can't be put on a pixel grid (non-finite or absurd) draws nothing. let Some((snapped, px)) = snap(view) else { self.last = None; @@ -296,9 +313,10 @@ impl Retained { { let same_doc = Arc::ptr_eq(&last.doc, doc); let s = if same_doc { last.sensitive.clone() } else { Arc::new(sensitive(doc)) }; - if let Some((pix, pixels)) = patch(last, doc, page, &snapped, px, opts, &s) { + if let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) { let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } }; self.keep(doc, page, (&snapped, px, fonts), opts, pix, s); + self.patched = areas; return Some(Prepared::Patched(snapped, work)); } sens = Some(s); @@ -524,8 +542,18 @@ fn moved_points_area(before: &Document, after: &Document, page: NodeId, id: Node } /// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None` -/// when a full render is the better (or only correct) choice. Also returns the pixels rendered. -fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, i64), opts: &Options, s: &Sensitive) -> Option<(Pixmap, u64)> { +/// when a full render is the better (or only correct) choice. Also returns the pixels rendered, +/// and the areas they are in when nothing else of the image changed (it didn't move). +#[allow(clippy::type_complexity)] +fn patch( + last: Frame, + doc: &Arc, + page: NodeId, + view: &View, + px: (i64, i64), + opts: &Options, + s: &Sensitive, +) -> Option<(Pixmap, u64, Option>)> { let (w, h) = (i64::from(view.width), i64::from(view.height)); let (dx, dy) = (px.0.checked_sub(last.px.0)?, px.1.checked_sub(last.px.1)?); if dx.abs() >= w || dy.abs() >= h { @@ -581,7 +609,7 @@ fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, } let mut damage: Vec = damage.iter().filter_map(|d| d.clamp(w, h)).collect(); if damage.is_empty() && dx == 0 && dy == 0 { - return Some((last.pix, 0)); + return Some((last.pix, 0, Some(Vec::new()))); } // Layers whose look depends on where they are cut are redrawn whole. let sensitive: Vec = s.areas.iter().chain(last.sensitive.areas.iter()).filter_map(|r| to_px(*r, view.scale, px)).collect(); @@ -616,7 +644,10 @@ fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, for d in &damage { render_into(FrameRender { doc, page, view, px, opts }, d, margin, &mut pix)?; } - Some((pix, pixels)) + let area = + |d: &Px| Some([u32::try_from(d.x0).ok()?, u32::try_from(d.y0).ok()?, u32::try_from(d.x1 - d.x0).ok()?, u32::try_from(d.y1 - d.y0).ok()?]); + let areas = if dx == 0 && dy == 0 { damage.iter().map(area).collect() } else { None }; + Some((pix, pixels, areas)) } /// Move the image's content by `(-dx, -dy)` pixels in place (what was at `(x, y)` goes to diff --git a/crates/render/src/retained_edit_tests.rs b/crates/render/src/retained_edit_tests.rs index 20086b67d..b711e70d7 100644 --- a/crates/render/src/retained_edit_tests.rs +++ b/crates/render/src/retained_edit_tests.rs @@ -65,6 +65,47 @@ fn a_clip_edge_on_a_pixel_boundary_clips_the_same_in_every_render() { assert_same(&pix, &render_view(&smaller, page, &shown, &opts).unwrap(), &format!("lod {lod}")); } } +/// What a patched render reports as changed ([`Retained::patched`]) takes in every pixel that +/// differs from the image before: whoever holds that image needs no more to have the new one. +#[test] +fn a_patched_render_says_where_it_differs_from_the_one_before() { + let mut d = Document::new("patched"); + let page = d.first_page().unwrap(); + let back = d.create(page, NodeKind::Rectangle, "Back", 0.0, 0.0, 200.0, 140.0).unwrap(); + d.get_mut(back).unwrap().fills = vec![Paint::solid(Color::from_hex("F4F6F5").unwrap())]; + let shape = d.create(page, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Shape", 30.0, 30.0, 72.0, 49.0).unwrap(); + d.get_mut(shape).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())]; + let v = View { origin: (0.0, 0.0), scale: 3.0, width: 600, height: 400 }; + let doc = Arc::new(d); + let mut r = Retained::default(); + r.render(&doc, page, &v, &Options::default()).unwrap(); + assert!(r.patched().is_none(), "a full render"); + let before = r.image().unwrap().clone(); + let mut d2 = (*doc).clone(); + d2.get_mut(shape).unwrap().height = 30.0; + let d2 = Arc::new(d2); + let (_, after, work) = r.render(&d2, page, &v, &Options::default()).unwrap(); + let after = after.clone(); + let areas = r.patched().expect("patched in place").to_vec(); + let Work::Partial { pixels } = work else { panic!("{work:?}") }; + assert_eq!(areas.iter().map(|a| u64::from(a[2]) * u64::from(a[3])).sum::(), pixels); + let w = after.width() as usize; + let (mut differ, mut outside) = (0, 0); + for (i, (a, b)) in before.data().chunks_exact(4).zip(after.data().chunks_exact(4)).enumerate() { + if a != b { + differ += 1; + let (x, y) = ((i % w) as u32, (i / w) as u32); + outside += usize::from(!areas.iter().any(|&[ax, ay, aw, ah]| x >= ax && y >= ay && x < ax + aw && y < ay + ah)); + } + } + assert!(differ > 1000 && outside == 0, "{differ} pixels differ, {outside} of them outside {areas:?}"); + // The same again: nothing to hand over. A pan: every pixel moved. + r.render(&d2, page, &v, &Options::default()).unwrap(); + assert_eq!(r.patched(), Some(&[][..])); + r.render(&d2, page, &View { origin: (2.0, 0.0), ..v }, &Options::default()).unwrap(); + assert!(r.patched().is_none(), "a pan"); +} + /// A closed zigzag of `2 * teeth + 2` points, 240 × 120 units at (20, 20): a ridge. fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId { let mut pts = vec![figcraft_geom::Point::new(0.0, 120.0)]; @@ -73,7 +114,7 @@ fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId { } pts.push(figcraft_geom::Point::new(240.0, 120.0)); let network = figcraft_doc::VectorNetwork::from_points(&pts, true); - let id = d.create(page, NodeKind::Vector { network }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap(); + let id = d.create(page, NodeKind::Vector { network: network.into() }, "Ridge", 20.0, 20.0, 240.0, 120.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())]; id } diff --git a/crates/render/src/retained_tests.rs b/crates/render/src/retained_tests.rs index 103178542..7a0312d94 100644 --- a/crates/render/src/retained_tests.rs +++ b/crates/render/src/retained_tests.rs @@ -53,7 +53,7 @@ fn scene(cut_sensitive: bool) -> Scene { let mut td = TextData::new("A line of text that overflows its box"); td.auto_resize = TextAutoResize::None; td.style.font_size = 14.0; - let text = d.create(page, NodeKind::Text(td), "T", 20.0, 270.0, 60.0, 20.0).unwrap(); + let text = d.create(page, NodeKind::Text(td.into()), "T", 20.0, 270.0, 60.0, 20.0).unwrap(); if cut_sensitive { let inner = d.create(page, NodeKind::Rectangle, "Inner", 180.0, 150.0, 70.0, 50.0).unwrap(); solid(d.get_mut(inner).unwrap(), "FFFFFF"); @@ -277,7 +277,7 @@ fn overflowing_text_is_drawn_while_its_box_is_out_of_view() { let mut td = TextData::new("Overflowing far to the right of a one pixel box"); td.auto_resize = TextAutoResize::WidthAndHeight; td.style.font_size = 16.0; - let t = d.create(page, NodeKind::Text(td), "T", 100.0, 10.0, 1.0, 20.0).unwrap(); + let t = d.create(page, NodeKind::Text(td.into()), "T", 100.0, 10.0, 1.0, 20.0).unwrap(); let Some((layout, _)) = figcraft_text::layout_node(d.node(t).unwrap()) else { return }; if layout.glyphs.is_empty() || layout.width < 120.0 { return; // no fonts on this machine diff --git a/crates/render/src/rtl_list_tests.rs b/crates/render/src/rtl_list_tests.rs index 3dde82f32..c04dcc973 100644 --- a/crates/render/src/rtl_list_tests.rs +++ b/crates/render/src/rtl_list_tests.rs @@ -17,7 +17,7 @@ fn doc() -> (Document, NodeId, TextData) { td.auto_resize = TextAutoResize::Height; let mut d = Document::new("rtl"); let p = d.first_page().unwrap(); - let id = d.create(p, NodeKind::Text(td.clone()), "T", 0.0, 0.0, W, 40.0).unwrap(); + let id = d.create(p, NodeKind::Text(td.clone().into()), "T", 0.0, 0.0, W, 40.0).unwrap(); (d, id, td) } diff --git a/crates/render/src/shadow_silhouette_tests.rs b/crates/render/src/shadow_silhouette_tests.rs index 80dcf536a..d16ed9855 100644 --- a/crates/render/src/shadow_silhouette_tests.rs +++ b/crates/render/src/shadow_silhouette_tests.rs @@ -37,9 +37,9 @@ fn a_sharp_shadow_under_a_stroked_layer_has_no_light_line_along_the_layers_edge( // its outline) and, where a font loads, a letter. let notch = [(0.0, 0.0), (60.0, 0.0), (60.0, 60.0), (40.0, 60.0), (30.0, 20.0), (20.0, 60.0), (0.0, 60.0)].map(|(x, y)| Point::new(x, y)); let kinds = [ - ("notch", NodeKind::Vector { network: VectorNetwork::from_points(¬ch, true) }), + ("notch", NodeKind::Vector { network: VectorNetwork::from_points(¬ch, true).into() }), ("ellipse", NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }), - ("letter", NodeKind::Text(letter)), + ("letter", NodeKind::Text(letter.into())), ]; let shadow = hex("#000000").to_rgba8(); for (name, kind) in &kinds { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 7de727dca..d539a675c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -54,7 +54,7 @@ fn vector_regions_use_their_own_paints_and_empty_regions_do_not_erase() { Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(vec![]), ..Default::default() }, ], }; - let id = d.create(page, NodeKind::Vector { network }, "V", 10.0, 10.0, 20.0, 10.0).unwrap(); + let id = d.create(page, NodeKind::Vector { network: network.into() }, "V", 10.0, 10.0, 20.0, 10.0).unwrap(); d.get_mut(id).unwrap().fills.clear(); let pix = render_view(&d, page, &view(40, 30), &Options { background: Some(Color::WHITE), ..Default::default() }).unwrap(); assert_eq!(px(&pix, 15, 15), [255, 0, 0, 255]); @@ -106,7 +106,7 @@ fn region_paint_space_preserves_gradient_image_and_pattern_placement() { region.paint_space = Some(RegionPaintSpace { width: 60.0, height: 30.0, transform: frame }); } let n = d.get_mut(id).unwrap(); - n.kind = NodeKind::Vector { network }; + n.kind = NodeKind::Vector { network: network.into() }; n.transform = Affine::IDENTITY; n.width = 120.0; n.height = 100.0; @@ -145,7 +145,7 @@ fn styled_vector_mask_unions_region_windings_and_excludes_unpainted_regions() { }); } network.regions = regions; - let mask = d.create(group, NodeKind::Vector { network }, "Mask", 0.0, 0.0, 60.0, 20.0).unwrap(); + let mask = d.create(group, NodeKind::Vector { network: network.into() }, "Mask", 0.0, 0.0, 60.0, 20.0).unwrap(); { let n = d.get_mut(mask).unwrap(); n.fills.clear(); @@ -182,7 +182,7 @@ fn inherited_paint_frames_keep_overlapping_regions_in_vector_masks() { paint_space: Some(figcraft_doc::RegionPaintSpace { width: 20.0, height: 20.0, transform: Affine::translate((x, 0.0)) }), }); } - let mask = d.create(group, NodeKind::Vector { network }, "Mask", 0.0, 0.0, 30.0, 20.0).unwrap(); + let mask = d.create(group, NodeKind::Vector { network: network.into() }, "Mask", 0.0, 0.0, 30.0, 20.0).unwrap(); let n = d.get_mut(mask).unwrap(); n.fills = vec![Paint::solid(Color::BLACK)]; n.is_mask = true; @@ -432,7 +432,7 @@ fn text_renders_something() { let p = d.first_page().unwrap(); let mut td = TextData::new("Hello"); td.style.font_size = 32.0; - d.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 200.0, 50.0).unwrap(); + d.create(p, NodeKind::Text(td.into()), "T", 0.0, 0.0, 200.0, 50.0).unwrap(); let pix = render_view(&d, p, &view(200, 60), &Options { background: Some(Color::WHITE), ..Default::default() }).unwrap(); let dark = pix.data().as_chunks::<4>().0.iter().filter(|c| c[0] < 100).count(); if figcraft_text::find_face("Inter", "Regular").is_some() { @@ -455,7 +455,7 @@ fn colour_emoji_draw_their_pixels() { let mut td = TextData::new("\u{1F600}"); (td.style.font_family, td.style.font_style) = (family.clone(), style.clone()); td.style.font_size = 48.0; - d.create(p, NodeKind::Text(td), "T", 0.0, 0.0, 200.0, 64.0).unwrap(); + d.create(p, NodeKind::Text(td.into()), "T", 0.0, 0.0, 200.0, 64.0).unwrap(); let pix = render_view(&d, p, &view(100, 80), &Options { background: Some(Color::WHITE), ..Default::default() }).unwrap(); // The emoji is the only thing in this document that paints saturated colour. let coloured = pix diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index c12bb21ea..6bf349d24 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -420,7 +420,7 @@ fn path(cx: &mut Ctx, p: &usvg::Path, parent: NodeId, base: Affine) { if !filled { network.regions.clear(); } - NodeKind::Vector { network } + NodeKind::Vector { network: network.into() } }; let at = Affine::translate((bb.x0, bb.y0)); // Fill closes every subpath; a stroke only those that close themselves. A filled diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 6f557fb13..5eeac0259 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -360,7 +360,7 @@ fn add_layer(cx: &mut Ctx, layer: TextLayer<'_, '_, '_>) { } td.normalize(); let name = if t.id().is_empty() { first.text.chars().take(64).collect() } else { layer_name(t.id(), "Text") }; - let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Text(td), name, w, h); + let mut n = Node::new(cx.doc.alloc_id(), NodeKind::Text(td.into()), name, w, h); n.transform = transform; n.fills = base_fill; if let Some(st) = spans.first().and_then(|sp| sp.stroke()) { diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 450373805..258a6749f 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -49,7 +49,7 @@ fn export_vector_region_paints_independently() { 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, 20.0, 10.0).unwrap(); + let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 20.0, 10.0).unwrap(); let svg = export_svg(&d, &[id], &SvgOptions::default()).unwrap(); assert!(svg.contains("#FF0000") && svg.contains("#0000FF"), "{svg}"); assert_eq!(svg.matches(" (Document, figcraft_doc::NodeId) { style.fills = Some(vec![Paint::solid(Color::from_hex("00FF00").unwrap())]); text.runs.push(StyleRun { start: 1, end: 2, style }); text.normalize(); - let id = d.create(page, NodeKind::Text(text), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; (d, id) } @@ -176,7 +176,7 @@ fn title_case_does_not_restart_words_across_fill_runs_in_live_text() { style.fills = Some(vec![Paint::solid(Color::from_hex("00FF00").unwrap())]); text.runs.push(StyleRun { start: 2, end: 3, style }); text.normalize(); - let id = d.create(page, NodeKind::Text(text), "Text", 0.0, 0.0, 200.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 200.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let svg = export_svg(&d, &[id], &SvgOptions { outline_text: false, ..SvgOptions::default() }).unwrap(); assert!(svg.contains(">He") && svg.contains(">l") && svg.contains(">lo"), "{svg}"); @@ -199,7 +199,7 @@ fn live_text_export_drops_xml_forbidden_control_characters() { text.runs.push(StyleRun { start: 5, end: 12, style }); text.normalize(); } - let id = d.create(page, NodeKind::Text(text), "Text", 0.0, 0.0, 600.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 600.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let svg = export_svg(&d, &[id], &SvgOptions { outline_text: false, ..SvgOptions::default() }).unwrap(); assert!(!svg.contains('\u{b}') && !svg.contains('\u{1}'), "{svg:?}"); @@ -223,7 +223,7 @@ fn ids_and_font_families_drop_xml_forbidden_control_characters() { let mut text = TextData::new(format!("a{junk}b")); text.style.font_size = 24.0; text.style.font_family = format!("Font{junk}<&\""); - let id = d.create(page, NodeKind::Text(text), &format!("Layer{junk}"), 0.0, 0.0, 600.0, 40.0).unwrap(); + let id = d.create(page, NodeKind::Text(text.into()), &format!("Layer{junk}"), 0.0, 0.0, 600.0, 40.0).unwrap(); d.get_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let svg = export_svg(&d, &[id], &SvgOptions { outline_text: false, include_ids: true, ..SvgOptions::default() }).unwrap(); assert!(!svg.contains(forbidden), "{svg:?}"); @@ -267,7 +267,7 @@ fn point_joins_equal_to_the_layer_join_keep_a_plain_stroke() { } let mut d = Document::new("t"); let p = d.first_page().unwrap(); - let v = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 50.0).unwrap(); + let v = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 50.0).unwrap(); let n = d.get_mut(v).unwrap(); n.strokes = vec![Paint::solid(Color::from_hex("000000").unwrap())]; n.stroke.weight = 2.0; @@ -397,7 +397,7 @@ fn a_dash_cap_writes_the_line_cap_of_a_dashed_stroke() { fn a_dashed_line_exports_as_the_canvas_draws_it() { let line = Segment::line(0, 1); let open = VectorNetwork { vertices: vec![Vertex::new(0.0, 0.0), Vertex::new(107.0, 0.0)], segments: vec![line], ..Default::default() }; - let svg = dashed(NodeKind::Vector { network: open }, vec![10.0, 10.0]); + let svg = dashed(NodeKind::Vector { network: open.into() }, vec![10.0, 10.0]); assert_eq!(dash_attrs(&svg), [("10.7 10.7".to_string(), Some("5.35".to_string()))], "{svg}"); } @@ -415,7 +415,7 @@ fn each_subpath_of_a_dashed_vector_exports_its_own_fit() { segments: vec![Segment::line(0, 1), Segment::line(2, 3)], ..Default::default() }; - let svg = dashed(NodeKind::Vector { network: two }, vec![10.0, 10.0]); + let svg = dashed(NodeKind::Vector { network: two.into() }, vec![10.0, 10.0]); assert_eq!(dash_attrs(&svg).len(), 2, "{svg}"); } diff --git a/crates/text/src/onpath_tests.rs b/crates/text/src/onpath_tests.rs index f3bb999fb..e639e2c7b 100644 --- a/crates/text/src/onpath_tests.rs +++ b/crates/text/src/onpath_tests.rs @@ -68,7 +68,7 @@ fn laid_out_glyphs_sit_on_the_path() { let mid = g.warp * Point::new(g.x + g.advance * 0.25, g.y - 5.0); assert_eq!(l.hit(mid.x, mid.y), g.char_start); // A text node on a path keeps its box. - let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t), "t", 10.0, 1000.0); + let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t.into()), "t", 10.0, 1000.0); if let figcraft_doc::NodeKind::Text(t) = &mut n.kind { t.auto_resize = TextAutoResize::WidthAndHeight; } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index d14b3a3c5..d03589243 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -315,16 +315,16 @@ fn vertical_alignment_in_fixed_box() { let mut t = TextData::new("Hi"); t.auto_resize = figcraft_doc::TextAutoResize::None; t.align_v = figcraft_doc::TextAlignV::Bottom; - let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t.clone()), "t", 100.0, 100.0); + let mut n = figcraft_doc::Node::new(figcraft_doc::NodeId(1), figcraft_doc::NodeKind::Text(t.clone().into()), "t", 100.0, 100.0); let (l, dy) = layout_node(&n).unwrap(); assert!((dy + l.height - 100.0).abs() < 1e-6); t.align_v = figcraft_doc::TextAlignV::Middle; - n.kind = figcraft_doc::NodeKind::Text(t.clone()); + n.kind = figcraft_doc::NodeKind::Text(t.clone().into()); let (l, dy) = layout_node(&n).unwrap(); assert!((dy - (100.0 - l.height) / 2.0).abs() < 1e-6); // Auto height ignores vertical alignment. t.auto_resize = figcraft_doc::TextAutoResize::Height; - n.kind = figcraft_doc::NodeKind::Text(t); + n.kind = figcraft_doc::NodeKind::Text(t.into()); assert_eq!(layout_node(&n).unwrap().1, 0.0); } diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index a7dbf1b42..5e0962c53 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -46,6 +46,7 @@ name = "Svenska" "Add a layer or component to tile first" = "Lägg först till ett lager eller en komponent att lägga sida vid sida" "Add a minute" = "Lägg till en minut" "Add a note for developers" = "Lägg till en anteckning för utvecklare" +"Add a rule" = "Lägg till en regel" "Add action" = "Lägg till åtgärd" "Add actions for when no condition holds" = "Lägg till åtgärder för när inget villkor uppfylls" "Add an annotation for developers" = "Lägg till en annotering för utvecklare" @@ -73,6 +74,7 @@ name = "Svenska" "Add properties to make instances configurable" = "Lägg till egenskaper för att göra instanser konfigurerbara" "Add reaction" = "Lägg till reaktion" "Add row" = "Lägg till rad" +"Add rule" = "Lägg till regel" "Add starting point" = "Lägg till startpunkt" "Add stroke" = "Lägg till kontur" "Add variant" = "Lägg till variant" @@ -103,6 +105,7 @@ name = "Svenska" "All comments" = "Alla kommentarer" "All components" = "Alla komponenter" "All fonts" = "Alla typsnitt" +"All libraries" = "Alla bibliotek" "All objects" = "Alla objekt" "All supported properties" = "Alla egenskaper som stöds" "All the fonts this file uses are installed" = "Alla typsnitt som filen använder är installerade" @@ -159,6 +162,7 @@ name = "Svenska" "Auto (space between)" = "Auto (utrymme mellan)" "Auto (space evenly)" = "Auto (jämnt utrymme)" "Auto ({mode})" = "Auto ({mode})" +"Auto: black, or white on a dark background" = "Auto: svart, eller vit på mörk bakgrund" "Auto columns" = "Automatiska kolumner" "Auto gap" = "Automatiskt mellanrum" "Auto height" = "Automatisk höjd" @@ -178,6 +182,7 @@ name = "Svenska" "Back to the values the font style implies" = "Tillbaka till värdena som teckenstilen anger" "Background" = "Bakgrund" "Background blur" = "Bakgrundsoskärpa" +"Bash" = "Bash" "Basics" = "Grunder" "Before" = "Före" "Bend" = "Böj" @@ -186,6 +191,7 @@ name = "Svenska" "Bevel" = "Fasning" "Binary assets added" = "Binära resurser tillagda" "Binary assets removed" = "Binära resurser borttagna" +"Black" = "Svart" "Black & white" = "Svartvitt" "Bleed" = "Utfall" "Bleed marks" = "Utfallsmärken" @@ -226,6 +232,7 @@ name = "Svenska" "Bulleted list" = "Punktlista" "C or Shift+C" = "C eller Shift+C" "C or ⇧C" = "C eller ⇧C" +"C++" = "C++" "Changed {date}" = "Ändrad {date}" "CMYK colour" = "CMYK-färg" "Can view" = "Kan visa" @@ -295,6 +302,7 @@ name = "Svenska" "Close version history" = "Stäng versionshistorik" "Close when clicking outside" = "Stäng vid klick utanför" "Code" = "Kod" +"Code block" = "Kodblock" "Code syntax" = "Kodsyntax" "Collapse" = "Komprimera" "Collection" = "Samling" @@ -361,6 +369,7 @@ name = "Svenska" "Copy fill" = "Kopiera fyllning" "Copy for AI" = "Kopiera för AI" "Copy link" = "Kopiera länk" +"Copy link to page" = "Kopiera länk till sida" "Copy stroke" = "Kopiera kontur" "Copy the {label}" = "Kopiera {label}" "Copy {value}" = "Kopiera {value}" @@ -389,9 +398,13 @@ name = "Svenska" "Crop" = "Beskär" "Crop image" = "Beskär bild" "Crop marks" = "Skärmärken" +"CSS" = "CSS" "Ctrl+arrows" = "Ctrl+piltangenter" "Ctrl+click" = "Ctrl+klick" "Ctrl+click a padding field" = "Ctrl+klicka på ett padding-fält" +"In code" = "I kod" +"Source file" = "Källfil" +"Variant value" = "Variantvärde" "⌘ click a padding field" = "⌘ klicka på ett padding-fält" "Ctrl+scroll" = "Ctrl+rullning" "Current name" = "Aktuellt namn" @@ -449,6 +462,7 @@ name = "Svenska" "Default" = "Standard" "Default content" = "Standardinnehåll" "Default value (the top-left variant)" = "Standardvärde (varianten längst upp till vänster)" +"This variant's value" = "Den här variantens värde" "Delay" = "Fördröjning" "Delete" = "Radera" "Delete category (its annotations stay)" = "Radera kategori (dess anteckningar finns kvar)" @@ -470,6 +484,7 @@ name = "Svenska" "Description" = "Beskrivning" "Description (optional)" = "Beskrivning (valfritt)" "Design" = "Design" +"Design it's a version of" = "Design som detta är en version av" "Design panel" = "Designpanel" "Design system starter" = "Startmall för designsystem" "Desktop" = "Skrivbord" @@ -674,10 +689,12 @@ name = "Svenska" "Getting started" = "Kom igång" "Give the address of a server open to the public, or a server's address with its key (`figcraft-server key` prints it)." = "Ange adressen till en server som är öppen för alla, eller en servers adress med dess nyckel (`figcraft-server key` skriver ut den)." "Glass" = "Glas" +"Go" = "Go" "Go to main component" = "Gå till huvudkomponent" "Go to {name}" = "Gå till {name}" "Grab bag" = "Blandat" "Gradient" = "Gradient" +"GraphQL" = "GraphQL" "Graph paper" = "Rutat papper" "Gray" = "Grå" "Green" = "Grön" @@ -729,6 +746,7 @@ name = "Svenska" "Hue" = "Nyans" "Hug" = "Omslut" "Hug contents" = "Omslut innehåll" +"HTML" = "HTML" "Icon components on a 24 px grid with keylines and a size preview" = "Ikonkomponenter på ett 24 px-rutnät med hjälplinjer och en förhandsgranskning av storlekar" "Icon set starter" = "Startpaket för ikonuppsättning" "If it keeps happening, please report it at {link} with this message." = "Om det fortsätter att hända kan du rapportera det på {link} och bifoga det här meddelandet." @@ -787,6 +805,8 @@ name = "Svenska" "It asks permission to:" = "Den ber om behörighet att:" "Jan" = "jan" "Join" = "Gå med" +"JavaScript" = "JavaScript" +"JSON" = "JSON" "Join code copied" = "Anslutningskoden har kopierats" "Join code or invite link" = "Anslutningskod eller inbjudningslänk" "Join live session" = "Gå med i livesession" @@ -807,6 +827,7 @@ name = "Svenska" "Keep appearance converts every color value to {profile} so colors look the same. Keep values leaves the numbers as they are, so colors shift." = "Behåll utseende konverterar varje färgvärde till {profile} så att färgerna ser likadana ut. Behåll värden lämnar siffrorna som de är, så färgerna förskjuts." "Keep tool selected after use" = "Behåll verktyget markerat efter användning" "Keep values" = "Behåll värden" +"Kotlin" = "Kotlin" "Key/Gamepad" = "Tangent/spelkontroll" "Key/Gamepad {key}" = "Tangent/spelkontroll {key}" "Keyboard shortcuts" = "Kortkommandon" @@ -916,6 +937,7 @@ name = "Svenska" "Merged PRs" = "Sammanslagna PR:er" "Min H" = "Min H" "Min W" = "Min B" +"Mind map" = "Tankekarta" "Minimize" = "Minimera" "Minutes" = "Minuter" "Mirror angle" = "Spegla vinkel" @@ -931,6 +953,7 @@ name = "Svenska" "Mixed" = "Blandat" "Mixed fonts" = "Blandade typsnitt" "Mixed interactions: click + to replace them" = "Blandade interaktioner: klicka på + för att ersätta dem" +"Mobile" = "Mobil" "Mobile app" = "Mobilapp" "Mode" = "Läge" "Model" = "Modell" @@ -962,8 +985,10 @@ name = "Svenska" "Nested instance" = "Kapslad instans" "New board" = "Ny whiteboard" "New design file" = "Ny designfil" +"New from selection" = "Ny från markering" "Newest first" = "Nyaste först" "Next frame" = "Nästa frame" +"Next or previous control" = "Nästa eller föregående kontroll" "Next ready for dev" = "Nästa redo för utveckling" "Next size option" = "Nästa storleksalternativ" "No assets: no export settings, icons or images. Add export settings in the Design tab." = "Inga resurser: inga exportinställningar, ikoner eller bilder. Lägg till exportinställningar på fliken Design." @@ -1115,6 +1140,7 @@ name = "Svenska" "Pause" = "Pausa" "Pink" = "Rosa" "Placed on the current page" = "Placerat på den aktuella sidan" +"Plain text" = "Oformaterad text" "Pages: {pages}" = "Sidor: {pages}" "Paint bucket" = "Färghink" "Pan the canvas" = "Panorera arbetsytan" @@ -1208,6 +1234,7 @@ name = "Svenska" "Published · {people}" = "Publicerad · {people}" "Publishing with the server's key." = "Publicerar med serverns nyckel." "Publishing…" = "Publicerar…" +"Python" = "Python" "Push" = "Skjut" "Push changes to main component" = "Skicka ändringar till huvudkomponenten" "Put text on path" = "Placera text på bana" @@ -1334,9 +1361,12 @@ name = "Svenska" "Row span" = "Radspann" "Rows" = "Rader" "Rows {count}" = "Rader {count}" +"Ruby" = "Ruby" "Rulers" = "Linjaler" +"Rules appear under Annotations, in the Responsive category." = "Regler visas under Annoteringar, i kategorin Responsiv." "Run" = "Kör" "Run {label}" = "Kör {label}" +"Rust" = "Rust" "Save file" = "Spara fil" "Save files automatically" = "Spara filer automatiskt" "Search templates" = "Sök mallar" @@ -1357,6 +1387,7 @@ name = "Svenska" "Scatter" = "Spridning" "Scoping: where pickers offer it" = "Omfång: var väljarna erbjuder den" "Screen" = "Skärm" +"Screen sizes" = "Skärmstorlekar" "Scroll behavior" = "Rullningsbeteende" "Scroll to" = "Rulla till" "Scroll to layer" = "Rulla till lager" @@ -1450,6 +1481,7 @@ name = "Svenska" "Show/Hide UI" = "Visa/dölj gränssnitt" "Side by side" = "Sida vid sida" "Sidebar" = "Sidofält" +"Sidebar becomes a drawer below 768 px" = "Sidofältet blir en utfällbar panel under 768 px" "Simplify stroke" = "Förenkla kontur" "Size" = "Storlek" "Size jitter" = "Storleksvariation" @@ -1465,6 +1497,8 @@ name = "Svenska" "Small caps" = "Kapitäler" "Smart animate" = "Smart animering" "Snap to pixel grid" = "Fäst mot pixelrutnät" +"Snap to pixel grid off" = "Fäst mot pixelrutnät av" +"Snap to pixel grid on" = "Fäst mot pixelrutnät på" "Social and slides" = "Sociala medier och presentationer" "Social media" = "Sociala medier" "Social post sizes" = "Storlekar för inlägg i sociala medier" @@ -1472,6 +1506,8 @@ name = "Svenska" "Solid" = "Enfärgad" "Some variants have the same property values: give each one a unique combination" = "Vissa varianter har samma egenskapsvärden: ge var och en en unik kombination" "Sort" = "Sortera" +"Sort A to Z" = "Sortera A till Ö" +"Sort Z to A" = "Sortera Ö till A" "Sort by" = "Sortera efter" "Sort by date" = "Sortera efter datum" "Sort by page" = "Sortera efter sida" @@ -1503,6 +1539,7 @@ name = "Svenska" "Spotlight me" = "Rikta strålkastaren mot mig" "Spread" = "Spridning" "Square" = "Kvadrat" +"SQL" = "SQL" "Stamp" = "Stämpel" "Stamps" = "Stämplar" "Standard" = "Standard" @@ -1549,9 +1586,11 @@ name = "Svenska" "Stylistic set 3" = "Stiluppsättning 3" "Stylistic set 4" = "Stiluppsättning 4" "Stylistic set 5" = "Stiluppsättning 5" +"Subscript" = "Nedsänkt" "Subtract" = "Subtrahera" "Subtracts" = "Subtraktioner" "Suffix" = "Suffix" +"Superscript" = "Upphöjd" "Suspend snapping while dragging" = "Stäng av fästfunktionen medan du drar" "Swap instance" = "Byt instans" "Swap library: use another library's assets of the same names" = "Byt bibliotek: använd resurser med samma namn från ett annat bibliotek" @@ -1563,6 +1602,7 @@ name = "Svenska" "Swapped {n} assets" = { one = "Bytte {n} resurs", other = "Bytte {n} resurser" } "Swapped {n} assets; {missed} had no match and still use the old library" = { one = "Bytte {n} resurs; {missed} saknade motsvarighet och använder fortfarande det gamla biblioteket", other = "Bytte {n} resurser; {missed} saknade motsvarighet och använder fortfarande det gamla biblioteket" } "Sweep" = "Svep" +"Swift" = "Swift" "System" = "Enligt systemet" "Tab / Shift+Tab" = "Tab / Shift+Tab" "Table" = "Tabell" @@ -1588,6 +1628,7 @@ name = "Svenska" "Huge" = "Enorm" "Text style" = "Textstil" "Text styles" = "Textstilar" +"Text tools" = "Textverktyg" "Texts" = "Texter" "Texture" = "Textur" "The canvas previews colors in sRGB; PNG, JPG and WebP exports that use the file's profile are tagged Display P3." = "Arbetsytan förhandsgranskar färger i sRGB; PNG-, JPG- och WebP-filer som exporteras med filens profil märks med Display P3." @@ -1664,6 +1705,7 @@ name = "Svenska" "Two digits" = "Två siffror" "Type" = "Typ" "Type settings" = "Textinställningar" +"TypeScript" = "TypeScript" "Type the join code you were given, or paste an invite link." = "Skriv anslutningskoden du fick, eller klistra in en inbjudningslänk." "Typography" = "Typografi" "Underline" = "Understrykning" @@ -1753,6 +1795,7 @@ name = "Svenska" "What it's for" = "Vad den är till för" "What this changed from isn't known: it changed before FigCraft kept a copy of ready-for-dev frames. Resolve the change (or mark it ready again) to compare from now on." = "Vad detta ändrades från är okänt: ändringen gjordes innan FigCraft började spara en kopia av frames som är klara för utveckling. Lös ändringen (eller markera den som klar igen) för att kunna jämföra från och med nu." "When marked ready" = "När den märktes som klar" +"While editing text: next or previous text layer" = "Vid textredigering: nästa eller föregående textlager" "While hovering" = "Vid hovring" "While pressing" = "Vid nedtryckning" "White" = "Vit" @@ -1872,6 +1915,7 @@ name = "Svenska" "offer files to save if it asks to (you choose where each one goes)" = "erbjuda filer att spara om den ber om det (du väljer var varje fil hamnar)" "only in a text style or variable" = "endast i en textstil eller variabel" "or" = "eller" +"pattern paints without a source layer were skipped" = "mönsterfyllningar utan källager hoppades över" "point stroke joins were preserved; dashed or variable-width strokes render with the layer join" = "punkternas hörntyper behölls; streckade konturer och konturer med variabel bredd ritas med lagrets hörntyp" "preferred slot component keys cannot be resolved to file nodes and were skipped" = "nycklar för föredragna komponenter i fack kan inte kopplas till lager i filen och hoppades över" "prototype actions of unknown types were skipped" = "prototypåtgärder av okända typer hoppades över" @@ -2066,14 +2110,18 @@ name = "Svenska" "arrange.spacing" = "Avstånd" "arrange.tidy" = "Snygga till" "board.addConnected" = "Lägg till ansluten form" +"board.codeBlock" = "Kodblock" "board.connector" = "Koppling" "board.grid" = "Tavlans rutnät" "board.ink" = "Märkpennsdrag" "board.label" = "Kopplingsetikett" +"board.mindMap" = "Tankekarta" +"board.mindMapAdd" = "Lägg till nod i tankekarta" "board.nextSticky" = "Nästa lapp" "board.reattach" = "Koppla om koppling" "board.reshape" = "Omforma koppling" "board.setColor" = "Whiteboardfärg" +"board.setLanguage" = "Kodspråk" "board.setStyle" = "Whiteboardstil" "board.shape" = "Form med text" "board.stamp" = "Stämpel" @@ -2269,6 +2317,7 @@ name = "Svenska" "inspect.assets" = "Resurser" "inspect.code" = "Kod" "inspect.componentCode" = "Komponentkod" +"inspect.designContext" = "Designkontext" "inspect.properties" = "Egenskaper" "inspect.readyForDev" = "Redo för utveckling" "instance.create" = "Skapa instans" @@ -2350,6 +2399,7 @@ name = "Svenska" "page.rename" = "Byt namn på sida" "page.select" = "Gå till sida" "page.setBackground" = "Sidbakgrund" +"page.setOpening" = "Ange som startsida" "paint.documentColors" = "Dokumentfärger" "plugin.close" = "Stäng plugin-panelen" "plugin.directory.install" = "Installera plugin från katalogen" @@ -2536,6 +2586,7 @@ name = "Svenska" "tool.highlighter" = "Överstrykningspenna" "tool.line" = "Linje" "tool.marker" = "Märkpenna" +"tool.mindMap" = "Verktyget Tankekarta" "tool.move" = "Flytta" "tool.pen" = "Penna" "tool.pencil" = "Blyertspenna" diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index ea54baaf1..2d94107b2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,5 +1,5 @@ use super::clock::{AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, CJK_CHANGES, FrameClock, TOAST_SECS, ToastClock, repaint_in}; -use super::open::OPEN_EXTENSIONS; +use super::open::open_extensions; use super::services::{DialogFuture, PickFuture, Picked, RepaintWaker, Services}; use super::state::{LEFT_PANEL, LeftTab, MOBILE_STRIP, MobilePanel, NARROW_WIDTH, PANEL_DEFAULT, RIGHT_PANEL, RightTab, TitleBar, fit_panels}; use super::{ diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 1ae5e5679..fb7b9539a 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,6 +1,6 @@ use super::{ - AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OPEN_EXTENSIONS, OsStr, Path, PathBuf, PendingDialog, PickFuture, - Picked, Poll, RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows, + AUTO_SAVE_RETRY_SECS, AUTO_SAVE_SECS, AUTOSAVE_SECS, Arc, DialogFuture, FigApp, OsStr, Path, PathBuf, PendingDialog, PickFuture, Picked, Poll, + RepaintWaker, Services, TaskContext, Value, Waker, dialogs, i18n, json, repaint_in, windows, }; impl FigApp { @@ -73,7 +73,7 @@ impl FigApp { pub fn open_dialog(&mut self) { // Opening needs no file in front: it goes ahead even if that file closed meanwhile. - self.pick_file(i18n::tr("Open"), OPEN_EXTENSIONS, false, |app, file| { + self.pick_file(i18n::tr("Open"), &super::open_extensions(), false, |app, file| { if app.run_user("file.open", file).is_some() { app.ui.home = false; } @@ -86,8 +86,10 @@ impl FigApp { } else { &["penpot", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff", "figcraft", "fig", "jam", "sketch"] }; + // Camera raw files place as the image they develop to. + let exts: Vec<&str> = exts.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect(); let title = if place { i18n::tr("Place image") } else { i18n::tr("Import") }; - self.pick_file(title, exts, true, |app, file| { + self.pick_file(title, &exts, true, |app, file| { app.run_user("file.import", file); }); } diff --git a/crates/ui-egui/src/board_line_tests.rs b/crates/ui-egui/src/board_line_tests.rs index 4303e7bd8..9b420b6ba 100644 --- a/crates/ui-egui/src/board_line_tests.rs +++ b/crates/ui-egui/src/board_line_tests.rs @@ -85,6 +85,28 @@ fn the_connector_bar_sets_its_ends_dashes_and_weight() { assert_eq!(stroke(&u).weight, 4.0, "the weight is its own step"); } +/// A connector drawn from right to left (#1744): its end point's menu comes first, so the menu on +/// the left sets the end on the left. +#[test] +fn the_left_menu_sets_the_left_end_of_a_connector_drawn_right_to_left() { + let mut s = Session::new(); + s.execute("file.newBoard", &json!({})).unwrap(); + let a = s.execute("board.sticky", &json!({"x": 400, "y": 300})).unwrap()["id"].clone(); + let b = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone(); + let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "elbow"})).unwrap()); + let mut u = Ui::new(s); + u.frame(vec![]); + u.frame(vec![]); + let stroke = |u: &Ui| u.app.session.doc().unwrap().node(c).unwrap().stroke.clone(); + // The two menus' places on the bar, named for a connector drawn left to right. + let (left, right) = (START, END); + pick(&mut u, left, "Circle"); + assert_eq!(stroke(&u).cap_end, StrokeCap::CircleFilled, "the left menu is the end's"); + assert_ne!(stroke(&u).cap_start, StrokeCap::CircleFilled); + pick(&mut u, right, "Diamond"); + assert_eq!(stroke(&u).cap_start, StrokeCap::DiamondFilled, "the right menu is the start's"); +} + #[test] fn the_colour_wheel_opens_the_picker_for_connectors_only() { let (mut u, c, b) = connector(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 132079cd3..3e00e44e9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -65,6 +65,9 @@ pub struct CanvasState { tex_skipped: bool, /// The request the texture answers ([`crate::render_worker::Done::seq`]). tex_seq: u64, + /// Which of the worker's images the texture holds ([`render_worker::Done::frame`]), when it + /// is one of them: what the next render may hand over patches of. + tex_frame: Option, /// Refined images of the files and pages shown before, newest first: switching back to one /// shows its image at once while it renders again, instead of a blank canvas (and, where /// renders are slow, a coarse preview). @@ -154,6 +157,7 @@ impl Default for CanvasState { tex_coarse: false, tex_skipped: false, tex_seq: 0, + tex_frame: None, kept: Vec::new(), surround: None, submitted: None, @@ -191,6 +195,20 @@ struct Kept { seq: u64, } +/// `part` put on `image` at (x, y) `at`, as [`egui::TextureHandle::set_partial`] puts it on the +/// texture; rows that don't lie in the image are left out. +fn put_patch(image: &mut egui::ColorImage, at: [usize; 2], part: &egui::ColorImage) { + let (w, [x, y]) = (image.size[0], at); + for (r, row) in part.pixels.chunks(part.size[0].max(1)).enumerate() { + let start = (y + r) * w + x; + if x + row.len() <= w + && let Some(into) = image.pixels.get_mut(start..start + row.len()) + { + into.copy_from_slice(row); + } + } +} + impl CanvasState { /// When the file or page shown is no longer the one the texture is of, set the texture aside /// (if refined) and bring back the image kept for `shown`, if any. Images of files that are no @@ -206,6 +224,8 @@ impl CanvasState { self.kept.insert(0, Kept { texture, view, of, seq: self.tex_seq }); } self.tex_coarse = false; + // The worker's image is of the other file or page: this texture is none of its. + self.tex_frame = None; self.tex_skipped = false; if let Some(k) = back { (self.texture, self.tex_view, self.tex_of, self.tex_seq) = (Some(k.texture), Some(k.view), Some(k.of), k.seq); @@ -221,6 +241,31 @@ impl CanvasState { self.kept.retain(|k| open(k.of.0)); } + /// Put a finished render's pixels on the texture, and on the copy kept of it + /// ([`Self::pixel_under`] reads that, so the colour it gives is the one shown). + fn take_pixels(&mut self, ctx: &egui::Context, pixels: render_worker::Pixels, filter: egui::TextureOptions) { + match pixels { + render_worker::Pixels::Whole(image) => { + let image = Arc::new(image); + match &mut self.texture { + Some(t) => t.set(Arc::clone(&image), filter), + None => self.texture = Some(ctx.load_texture("figcraft-canvas", Arc::clone(&image), filter)), + } + self.tex_pixels = Some(image); + } + // Patches of the image the texture holds (the worker was told which). + render_worker::Pixels::Patches(parts) => { + let Some(t) = &mut self.texture else { return }; + for (at, part) in parts { + if let Some(kept) = &mut self.tex_pixels { + put_patch(Arc::make_mut(kept), at, &part); + } + t.set_partial(at, part, filter); + } + } + } + } + pub(crate) fn pixel_under(&self, p: Point, of: Option<(u64, NodeId)>, page: Color32) -> Option { let (image, v) = (self.tex_pixels.as_ref()?, self.tex_view.as_ref()?); if of.is_none() || self.tex_of != of { @@ -396,6 +441,9 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok(); let docs = &app.session.docs; app.canvas.switch_texture(shown, |uid| docs.iter().any(|d| d.uid == uid)); + // The browser's worker hands over only what changed of the image the texture holds. + #[cfg(target_arch = "wasm32")] + worker.texture_holds(app.canvas.tex_frame.filter(|_| app.canvas.texture.is_some() && app.canvas.tex_of == shown && !app.canvas.tex_coarse)); if let Some(done) = worker.poll() && shows(&app.canvas, &done, shown) { @@ -409,12 +457,8 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { } else { egui::TextureOptions::LINEAR }; - let pixels = Arc::new(done.image); - match &mut app.canvas.texture { - Some(t) => t.set(Arc::clone(&pixels), filter), - None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", Arc::clone(&pixels), filter)), - } - app.canvas.tex_pixels = Some(pixels); + app.canvas.take_pixels(&ctx, done.image, filter); + app.canvas.tex_frame = (done.frame != 0 && !done.coarse).then_some(done.frame); let done_at = done.at; let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0); if done.coarse { @@ -429,17 +473,19 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_seq = done.seq; drag_sprite::arrived(&mut app.canvas, done_at, done.coarse); } + // The image around the view always comes whole (nothing tells its worker what is held). if let Some(around) = worker.surround() && shown == Some((around.uid, around.page)) + && let render_worker::Pixels::Whole(image) = around.image { let of = (around.uid, around.page); match &mut app.canvas.surround { Some((t, view, at)) => { - t.set(around.image, egui::TextureOptions::LINEAR); + t.set(image, egui::TextureOptions::LINEAR); (*view, *at) = (around.view, of); } None => { - let t = ctx.load_texture("figcraft-canvas-surround", around.image, egui::TextureOptions::LINEAR); + let t = ctx.load_texture("figcraft-canvas-surround", image, egui::TextureOptions::LINEAR); app.canvas.surround = Some((t, around.view, of)); } } diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index 84ebede97..022f3f84c 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -135,6 +135,9 @@ struct Line { dashed: bool, /// Every selected connector is a mind map's branch: no line types. branch: bool, + /// The first connector's start lies to the right of its end on the canvas, so the bar shows its + /// end point's menu first (#1744). + start_right: bool, ids: Vec, } @@ -171,6 +174,7 @@ fn has(app: &FigApp) -> Option { weight: s.weight, dashed: !s.dashes.is_empty(), branch: true, + start_right: start_right(&ds.doc, c), ids: Vec::new(), }); line.branch &= c.branch; @@ -494,17 +498,26 @@ fn line_part(app: &mut FigApp, ui: &mut Ui, line: &Line, at: Pos2, t: &Tokens) { } x = divider(ui, t, x - 2.0, at.y); } - for (start, cap) in [(true, line.start), (false, line.end)] { - cap_menu(app, ui, t, pos2(x, at.y), start, cap); + // Each end's menu sits on the side where that end lies on the canvas, so the left menu sets + // the left end whichever way the connector was drawn (#1744). + let ends = if line.start_right { [(false, line.end), (true, line.start)] } else { [(true, line.start), (false, line.end)] }; + for (i, (start, cap)) in ends.into_iter().enumerate() { + cap_menu(app, ui, t, pos2(x, at.y), start, cap, i == 0); x += CAP_W + 2.0; } x = divider(ui, t, x - 2.0, at.y); style_menu(app, ui, t, pos2(x, at.y), line); } +/// Whether connector `c`'s start lies to the right of its end on the canvas. +fn start_right(doc: &figcraft_doc::Document, c: &figcraft_doc::Connector) -> bool { + let points = figcraft_engine::board::route(doc, c).unwrap_or_default(); + matches!((points.first(), points.last()), (Some(a), Some(b)) if a.x > b.x) +} + /// The menu of a connector's start (`start`) or end point at `at` (its left edge and middle), -/// showing `cap`. -fn cap_menu(app: &mut FigApp, ui: &mut Ui, t: &Tokens, at: Pos2, start: bool, cap: StrokeCap) { +/// showing `cap`, its pictures pointing left when it is the left one of the two (`left`). +fn cap_menu(app: &mut FigApp, ui: &mut Ui, t: &Tokens, at: Pos2, start: bool, cap: StrokeCap, left: bool) { let r = Rect::from_min_size(pos2(at.x, at.y - CELL / 2.0), vec2(CAP_W, CELL)); let label = if start { tr("Start point") } else { tr("End point") }; let resp = ui.interact(r, ui.scope_id().with(("bb_cap", start)), Sense::click()).on_hover_text(label); @@ -514,12 +527,12 @@ fn cap_menu(app: &mut FigApp, ui: &mut Ui, t: &Tokens, at: Pos2, start: bool, ca } // The picture ends 14 before the rectangle it is given: 4 in from this cell's left edge. let art = Rect::from_min_max(pos2(r.min.x, r.min.y), pos2(r.min.x + 62.0, r.max.y)); - crate::right::cap_art(ui.painter(), art, t.icon, cap, start); + crate::right::cap_art(ui.painter(), art, t.icon, cap, left); icons::paint(ui.painter(), Rect::from_center_size(pos2(r.max.x - 7.0, at.y), vec2(12.0, 12.0)), Icon::Chevron, t.icon_secondary); let key = if start { "startCap" } else { "endCap" }; crate::right::menu_popup(&resp).show(|ui| { for c in StrokeCap::ALL { - let art = |p: &egui::Painter, row: Rect, ink: Color32| crate::right::cap_art(p, row, ink, c, start); + let art = |p: &egui::Painter, row: Rect, ink: Color32| crate::right::cap_art(p, row, ink, c, left); if crate::right::menu_item_with(ui, tr(c.label()), "", crate::right::CAP_ART_W, art) { app.run("board.setStyle", json!({key: c})); ui.close(); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b82270937..e854a1630 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -868,7 +868,7 @@ mod caret_tests { use figcraft_doc::{Node, NodeId, NodeKind, StyleRun, TextData}; fn text(chars: &str, fills: Vec) -> Node { - let mut n = Node::new(NodeId(1), NodeKind::Text(TextData { characters: chars.into(), ..TextData::default() }), "Text", 100.0, 20.0); + let mut n = Node::new(NodeId(1), NodeKind::Text(TextData { characters: chars.into(), ..TextData::default() }.into()), "Text", 100.0, 20.0); n.fills = fills; n } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 22a9cf0f8..dc7294a0c 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -77,9 +77,33 @@ pub struct Job { pub at: Instant, } +/// What a finished render hands the canvas for its texture. +pub enum Pixels { + /// The whole image. + Whole(egui::ColorImage), + /// The parts that differ from the image the canvas said its texture holds + /// ([`Inline::texture_holds`]): each goes at its position (x, y) in that texture. An edit + /// redraws a part of the view; converting and uploading all of it again cost more than + /// drawing the part. + Patches(Vec<([usize; 2], egui::ColorImage)>), +} + +impl Pixels { + /// The whole image, when that is what this is. + pub fn whole(&self) -> Option<&egui::ColorImage> { + match self { + Pixels::Whole(image) => Some(image), + Pixels::Patches(_) => None, + } + } +} + pub struct Done { /// The image, ready for a texture (converted off the UI thread). - pub image: egui::ColorImage, + pub image: Pixels, + /// Which image of the worker's this is, numbered as they are drawn (0: a preview, or a + /// worker that doesn't number them): what the canvas reports back as its texture's. + pub frame: u64, /// The view the image shows (the requested one snapped outwards to whole device pixels). pub view: View, pub ms: f64, @@ -99,15 +123,39 @@ pub struct Done { /// A render of a document in `profile` as a texture image for the screen (sRGB). pub fn screen_image(pix: &Pixmap, profile: ColorProfile) -> egui::ColorImage { - let size = [pix.width() as usize, pix.height() as usize]; + screen_pixels([pix.width() as usize, pix.height() as usize], pix.data(), profile) +} + +/// [`screen_image`] of `size` premultiplied RGBA pixels. +fn screen_pixels(size: [usize; 2], rgba: &[u8], profile: ColorProfile) -> egui::ColorImage { if profile.is_srgb() { - return egui::ColorImage::from_rgba_premultiplied(size, pix.data()); + return egui::ColorImage::from_rgba_premultiplied(size, rgba); } - let mut data = pix.data().to_vec(); + let mut data = rgba.to_vec(); profile.conversion_to(ColorProfile::Srgb).apply_pixels(&mut data); egui::ColorImage::from_rgba_premultiplied(size, &data) } +/// The areas `[x, y, width, height]` of `pix` as texture images at their positions; `None` when +/// one doesn't lie in it. +fn screen_patches(pix: &Pixmap, areas: &[[u32; 4]], profile: ColorProfile) -> Option> { + let row = pix.width() as usize * 4; + areas + .iter() + .map(|&[x, y, w, h]| { + let (x, y, w, h) = (x as usize, y as usize, w as usize, h as usize); + if w == 0 || h == 0 || x + w > pix.width() as usize || y + h > pix.height() as usize { + return None; + } + let mut rgba = Vec::with_capacity(w * h * 4); + for r in y..y + h { + rgba.extend_from_slice(pix.data().get(r * row + x * 4..r * row + (x + w) * 4)?); + } + Some(([x, y], screen_pixels([w, h], &rgba, profile))) + }) + .collect() +} + /// Soft proof: grey diagonal stripes over the pixels whose colours sRGB can't show. fn mark_outside_srgb(image: &mut egui::ColorImage, pix: &Pixmap, profile: ColorProfile) { let w = image.size[0].max(1); @@ -138,16 +186,25 @@ fn options(job: &Job) -> figcraft_render::Options { fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option { let t0 = Instant::now(); let (view, pix, work) = retained.render(&job.doc, job.page, view, &options(job))?; - Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse)) + Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse, None)) } -/// The image `pix` of `view`, rendered for `job` in `ms`. -fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) -> Done { - let mut image = screen_image(pix, job.doc.color_profile); - if job.proof { - mark_outside_srgb(&mut image, pix, job.doc.color_profile); - } - Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, skipped: !job.skip.is_empty(), at: job.at, seq: 0 } +/// The image `pix` of `view`, rendered for `job` in `ms`. With `patched`, only those areas of it +/// (see [`Pixels::Patches`]): the caller knows the canvas holds the rest. A soft proof stripes the +/// whole image, so it is always handed over whole. +fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool, patched: Option<&[[u32; 4]]>) -> Done { + let patches = patched.filter(|_| !job.proof).and_then(|areas| screen_patches(pix, areas, job.doc.color_profile)); + let image = match patches { + Some(parts) => Pixels::Patches(parts), + None => { + let mut image = screen_image(pix, job.doc.color_profile); + if job.proof { + mark_outside_srgb(&mut image, pix, job.doc.color_profile); + } + Pixels::Whole(image) + } + }; + Done { image, frame: 0, view, ms, work, uid: job.uid, page: job.page, coarse, skipped: !job.skip.is_empty(), at: job.at, seq: 0 } } /// The coarse image around the view is this many views wide and tall, centred on it. @@ -213,7 +270,7 @@ impl Surround { let t0 = Instant::now(); let d = guarded(&mut self.retained, |r| { let (snapped, pix, work) = r.render(&job.doc, job.page, &view, &options(job))?; - (!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true)) + (!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true, None)) }); if d.is_some() { self.of = Some((job.uid, job.page, view, job.proof)); @@ -243,6 +300,11 @@ pub struct Renders { /// A full render being drawn band by band (the browser): the job it was started for, the /// font generation then, the bands and the time they took so far. steps: Option, + /// The number of the image `full` keeps: every image drawn there gets the next one + /// ([`Done::frame`]), handed to the canvas or not. + frame: u64, + /// Whether that image was handed over with a soft proof's stripes ([`Job::proof`]). + frame_proofed: bool, #[cfg(test)] refine_gate: Option, } @@ -314,6 +376,8 @@ impl Renders { full_ms: 0.0, preview_after_ms: ms, steps: None, + frame: 0, + frame_proofed: false, #[cfg(test)] refine_gate: None, } @@ -389,6 +453,13 @@ impl Renders { done } + /// `d`, an image drawn in `full` just now for a job with soft proof `proofed`, numbered. + fn numbered(&mut self, d: Done, proofed: bool) -> Done { + self.frame += 1; + self.frame_proofed = proofed; + Done { frame: self.frame, ..d } + } + /// The image of `job`'s view, built on the kept one where it can be. pub fn refine(&mut self, job: &Job) -> Option { let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)); @@ -397,6 +468,7 @@ impl Renders { Some(gate) => gate(job, done), None => done, }; + let done = done.map(|d| self.numbered(d, job.proof)); if let Some(d) = &done { self.keep(job, d); if d.work == Work::Full { @@ -408,7 +480,10 @@ impl Renders { /// [`Self::refine`] for about `budget_ms` at a time (the browser): a full render is drawn band by /// band over several calls, the kept image (re-projected) or the preview showing meanwhile. - pub fn refine_for(&mut self, job: &Job, budget_ms: f64) -> Refined { + /// + /// `holds` is the number of the image the canvas's texture holds ([`Done::frame`]), if it is + /// one of these: a render that only patches that image hands over the patches. + pub fn refine_for(&mut self, job: &Job, budget_ms: f64, holds: Option) -> Refined { let t0 = Instant::now(); if let Some(s) = self.steps.as_ref() && !same_settings(&s.job, job) @@ -419,7 +494,7 @@ impl Renders { self.steps = None; } if self.steps.is_none() - && let Some(r) = self.begin(job, t0, None) + && let Some(r) = self.begin(job, t0, None, holds) { return r; } @@ -444,14 +519,15 @@ impl Renders { self.full_ms = spent; // The image of the job it was started for: its document's colour profile, its // proof setting and its request time. - let drawn = done(&drawn_for, view, pix, Work::Full, spent, false); + let drawn = done(&drawn_for, view, pix, Work::Full, spent, false, None); + let drawn = self.numbered(drawn, drawn_for.proof); // Drawn for this very request: shown, done. Otherwise kept, then started on like // any render: an edit, a pan or images that came meanwhile are patched in, or it // is drawn again in steps (never all at once here), this one shown till then. if same_request(&drawn_for, fonts, job) { return Refined::Done(self.finished(job, Some(drawn))); } - self.begin(job, t0, Some(drawn)).unwrap_or(Refined::More) + self.begin(job, t0, Some(drawn), holds).unwrap_or(Refined::More) } Err(_) => { self.steps = None; @@ -464,18 +540,30 @@ impl Renders { /// Start `job` on the kept image: done when it is reused or patched, `None` when a full render /// is now drawn in steps. `drawn` is the kept image just drawn in steps: what a reuse shows, /// else shown while it is drawn again. - fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option) -> Option { + fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option, holds: Option) -> Option { // The snapped view may be a row taller. let rows = job.view.height.saturating_add(1).div_ceil(MAX_BANDS).max(MIN_BAND_ROWS); - let begun = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match self.full.begin(&job.doc, job.page, &job.view, &options(job), rows) { - Some(Begun::Done(view, pix, work)) => Err(Box::new(match drawn.take() { - Some(d) if work == Work::Reused => Some(d), - _ => Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false)), - })), - Some(Begun::Steps(steps)) => Ok(steps), - None => Err(Box::new(None)), - })); + // The canvas holds the image this render starts from: one that only patches it hands + // over the patches. + // Not when that image was handed over with a soft proof's stripes on it: the renderer's + // image has none, so patches of it (none at all, when only the proof was turned off) + // would leave them on the texture. + let held = holds.is_some_and(|f| f == self.frame) && !self.frame_proofed; + let full = &mut self.full; + let begun = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (view, work) = match full.begin(&job.doc, job.page, &job.view, &options(job), rows) { + Some(Begun::Done(view, _, work)) => (view, work), + Some(Begun::Steps(steps)) => return Ok(steps), + None => return Err(Box::new(None)), + }; + Err(Box::new(match drawn.take() { + Some(d) if work == Work::Reused => Some((d, false)), + _ => full.image().map(|pix| { + let patched = full.patched().filter(|_| held); + (done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false, patched), true) + }), + })) + })); match begun { Ok(Ok(steps)) => { // A pan or an edit at this zoom builds on this render: no preview for it. @@ -486,7 +574,11 @@ impl Renders { Refined::Shown(d) }) } - Ok(Err(d)) => Some(Refined::Done(self.finished(job, *d))), + Ok(Err(d)) => { + // An image drawn now gets its number; one drawn in steps just before has it. + let d = d.map(|(d, new)| if new { self.numbered(d, job.proof) } else { d }); + Some(Refined::Done(self.finished(job, d))) + } Err(_) => { self.full.clear(); Some(Refined::Done(None)) @@ -768,6 +860,8 @@ pub struct Inline { /// The wait for the pending job's preview. wait: std::time::Duration, renders: Renders, + /// See [`Self::texture_holds`]. + holds: Option, } #[cfg(target_arch = "wasm32")] @@ -789,6 +883,7 @@ impl Inline { settle, wait: settle, renders: Renders::default(), + holds: None, } } /// Previewing when renders from scratch take at least `ms` (tests: 0, whatever the machine). @@ -812,6 +907,12 @@ impl Inline { pub fn surround(&mut self) -> Option { None } + /// Tell the worker which of its images the canvas's texture holds ([`Done::frame`]; `None`: + /// none of them, or not for sure). The next image comes as patches of that one when that is + /// all that changed ([`Pixels::Patches`]); without this, every image comes whole. + pub fn texture_holds(&mut self, frame: Option) { + self.holds = frame; + } pub fn poll(&mut self) -> Option { self.poll_at(Instant::now()) } @@ -836,7 +937,7 @@ impl Inline { } } let job = self.pending.as_ref()?; - match self.renders.refine_for(job, STEP_MS) { + match self.renders.refine_for(job, STEP_MS, self.holds) { Refined::Done(d) => { self.pending = None; d.map(|d| answering(d, self.submitted)) diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index 2b7e0be2e..6ab3fc463 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -20,9 +20,15 @@ use super::{CanvasState, shows}; use figcraft_render::Retained; use crate::render_worker::{ - Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now, + Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Pixels, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now, }; +/// The whole image a render handed over (these all are: nothing here tells the worker what the +/// canvas holds). +fn whole(d: &Done) -> &egui::ColorImage { + d.image.whole().expect("a whole image") +} + /// A page of ellipses with a rectangle on top; the session and the rectangle. The system fonts are /// scanned first (once per process, and a concurrent caller waits for it): the scan another test /// starts bumps the global font generation, and a render kept from before it is stale, so a pan @@ -93,17 +99,17 @@ pub(super) fn job(doc: &Arc, page: NodeId, uid: u64, view: View) -> Jo /// Every pixel of `a` and `b` alike. fn same_pixels(a: &Done, b: &Done) -> bool { - a.image.size == b.image.size && a.image.pixels == b.image.pixels + whole(a).size == whole(b).size && whole(a).pixels == whole(b).pixels } /// The same image up to where render bands meet ([`figcraft_render::Steps`] and the desktop's /// parallel bands cut the view in different places): on each row, under a quarter of a level on /// average and at most one pixel in twenty off. fn close_pixels(a: &Done, b: &Done) -> bool { - let [w, h] = a.image.size; - a.image.size == b.image.size + let [w, h] = whole(a).size; + whole(a).size == whole(b).size && (0..h).all(|y| { - let row = |d: &Done| d.image.pixels[y * w..(y + 1) * w].to_vec(); + let row = |d: &Done| whole(d).pixels[y * w..(y + 1) * w].to_vec(); let (ra, rb) = (row(a), row(b)); let diffs: Vec = ra.iter().zip(&rb).map(|(p, q)| p.to_array().iter().zip(q.to_array()).map(|(x, y)| u32::from(x.abs_diff(y))).sum()).collect(); @@ -135,7 +141,7 @@ fn refined_at(w: &mut Inline, now: Instant) -> Option { /// Refine `job` through `r` with no time to spare (a band a call); the image and how many calls. fn stepped(r: &mut Renders, job: &Job) -> (Option, usize) { for n in 1..1000 { - match r.refine_for(job, 0.0) { + match r.refine_for(job, 0.0, None) { Refined::Done(d) => return (d, n), Refined::Shown(_) | Refined::More => {} } @@ -162,7 +168,7 @@ fn a_zoom_out_previews_the_whole_view_then_refines_to_a_fresh_render() { let p = r.preview(&out).expect("a preview first"); assert!(p.coarse && (p.uid, p.page) == (ds.uid, ds.page)); assert!(covers(&p.view, &out.view), "the preview shows the whole view asked for"); - let pixels = |d: &Done| d.image.size[0] * d.image.size[1]; + let pixels = |d: &Done| whole(d).size[0] * whole(d).size[1]; let fresh = render_now(&out).unwrap(); assert!( (pixels(&p) as f64) * PREVIEW_FACTOR * PREVIEW_FACTOR < 1.5 * pixels(&fresh) as f64, @@ -660,7 +666,7 @@ fn the_browser_draws_a_full_render_band_by_band() { assert!(n > 2 && !r.stepping(), "several calls, then done ({n})"); assert!(close_pixels(&d, &render_now(&at(300.0)).unwrap())); // Kept: a pan now patches it at once. - assert!(matches!(r.refine_for(&at(320.0), 0.0), Refined::Done(Some(d)) if d.work != Work::Full)); + assert!(matches!(r.refine_for(&at(320.0), 0.0, None), Refined::Done(Some(d)) if d.work != Work::Full)); } #[test] @@ -670,14 +676,14 @@ fn a_pan_while_drawing_finishes_the_render_then_patches_it_and_a_zoom_drops_it() let ds = s.ds().unwrap(); let at = |x, scale| job(&ds.doc, ds.page, ds.uid, view(x, scale)); let mut r = Renders::default(); - assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0, None), Refined::More)); // Panned meanwhile: the same render goes on, and what comes is the panned view. let (d, _) = stepped(&mut r, &at(330.0, 1.0)); let d = d.expect("drawn"); assert!(close_pixels(&d, &render_now(&at(330.0, 1.0)).unwrap()), "the panned view"); // Zoomed meanwhile: the render under way is dropped for one of the new zoom. let mut r = Renders::default(); - assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0, None), Refined::More)); let (d, _) = stepped(&mut r, &at(300.0, 2.0)); assert_eq!(d.expect("drawn").view.scale, 2.0); } @@ -691,7 +697,7 @@ fn an_edit_while_drawing_shows_in_what_comes() { (ds.doc.clone(), ds.page, ds.uid) }; let mut r = Renders::default(); - assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0, None), Refined::More)); // Edited meanwhile, the view unchanged: the render goes on and what comes shows the edit. s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 400, "height": 400})).unwrap(); let edited = job(&s.ds().unwrap().doc, page, uid, v); @@ -705,11 +711,11 @@ fn a_render_overtaken_by_a_long_pan_is_shown_then_drawn_again() { let s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS); let ds = s.ds().unwrap(); let mut r = Renders::default(); - assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0, None), Refined::More)); // Panned more than a view meanwhile: nothing to patch. What was drawn shows, then the new view. let far = job(&ds.doc, ds.page, ds.uid, view_at((1500.0, 200.0), 1.0, 600, 600)); let mut shown = vec![]; - let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0) { + let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0, None) { Refined::More => None, Refined::Shown(d) => { shown.push(d); @@ -751,7 +757,7 @@ fn a_change_of_options_while_drawing_drops_the_render() { outlined.outline = true; let (_, alone) = stepped(&mut Renders::default(), &outlined); let mut r = Renders::default(); - assert!(matches!(r.refine_for(&plain, 0.0), Refined::More)); + assert!(matches!(r.refine_for(&plain, 0.0, None), Refined::More)); let (d, n) = stepped(&mut r, &outlined); assert!(d.is_some_and(|d| !d.coarse)); assert!(n <= alone + 1, "the old render's bands are dropped: {n} calls against {alone} alone"); @@ -768,10 +774,88 @@ fn a_render_dropped_while_drawing_leaves_its_time_as_the_measure() { let at = |scale| job(&ds.doc, ds.page, ds.uid, view(scale)); // Previews once renders have taken any time at all: a band has, where no measure (0 ms) hasn't. let mut r = Renders::with_threshold(1e-9); - assert!(matches!(r.refine_for(&at(1.0), 0.0), Refined::More)); + assert!(matches!(r.refine_for(&at(1.0), 0.0, None), Refined::More)); assert!(r.preview(&at(2.0)).is_some(), "the zoom gets a preview by the dropped render's measure"); } +/// `parts` put on `image` at their positions, as the canvas puts them on its texture. +fn patched(image: &egui::ColorImage, parts: &[([usize; 2], egui::ColorImage)]) -> egui::ColorImage { + let mut out = image.clone(); + let w = out.size[0]; + for ([x, y], part) in parts { + for (r, row) in part.pixels.chunks(part.size[0]).enumerate() { + out.pixels[(y + r) * w + x..(y + r) * w + x + row.len()].copy_from_slice(row); + } + } + out +} + +/// An edit redraws a part of the view. Told which image the canvas holds, the worker hands over +/// that part only; put on that image, it makes the new one. Converting and uploading the whole +/// image again after every edit cost more than drawing the part. +#[test] +fn an_edit_hands_over_only_what_changed_of_the_image_the_canvas_holds() { + let (mut s, rect) = document(); + let view = view_at((300.0, 250.0), 1.0, 700, 600); + let now = |s: &Session| { + let ds = s.ds().unwrap(); + job(&ds.doc, ds.page, ds.uid, view.clone()) + }; + let widen = |s: &mut Session, w: u32| s.execute("node.set", &json!({"id": rect, "width": w})).unwrap(); + let mut r = Renders::default(); + let first = stepped(&mut r, &now(&s)).0.expect("drawn"); + assert_ne!(first.frame, 0, "a numbered image"); + // Not told what the canvas holds: the whole image. + widen(&mut s, 280); + let Refined::Done(Some(second)) = r.refine_for(&now(&s), 0.0, None) else { panic!("a patch is done at once") }; + assert!(matches!(second.work, Work::Partial { .. }) && second.image.whole().is_some()); + // Told it holds that image: the changed part only, and with it the canvas has the new image. + widen(&mut s, 240); + let Refined::Done(Some(third)) = r.refine_for(&now(&s), 0.0, Some(second.frame)) else { panic!("a patch is done at once") }; + let Pixels::Patches(parts) = &third.image else { panic!("patches of the image the canvas holds") }; + let handed: usize = parts.iter().map(|(_, p)| p.pixels.len()).sum(); + let all = whole(&second).pixels.len(); + assert!(handed > 0 && handed * 4 < all, "{handed} of {all} pixels handed over"); + let fresh = stepped(&mut Renders::default(), &now(&s)).0.expect("drawn"); + let have = Done { image: Pixels::Whole(patched(whole(&second), parts)), ..render_now(&now(&s)).unwrap() }; + assert!(close_pixels(&have, &fresh), "the patched image is the new one"); + assert!(!close_pixels(&second, &fresh), "and the one before it is not"); + // A canvas that holds an older image (it showed none of the last) gets the whole one. + widen(&mut s, 200); + let Refined::Done(Some(fourth)) = r.refine_for(&now(&s), 0.0, Some(second.frame)) else { panic!("a patch is done at once") }; + assert!(fourth.image.whole().is_some(), "whole for a canvas an image behind"); + // Nothing changed: nothing to hand over. + let Refined::Done(Some(same)) = r.refine_for(&now(&s), 0.0, Some(fourth.frame)) else { panic!("reused at once") }; + assert!(matches!(&same.image, Pixels::Patches(parts) if parts.is_empty()) && same.work == Work::Reused); + // A pan moves every pixel: whole. + let ds = s.ds().unwrap(); + let panned = job(&ds.doc, ds.page, ds.uid, view_at((320.0, 250.0), 1.0, 700, 600)); + let Refined::Done(Some(moved)) = r.refine_for(&panned, 0.0, Some(same.frame)) else { panic!("a pan is patched at once") }; + assert!(moved.image.whole().is_some(), "whole after a pan"); +} + +/// A soft proof stripes the image handed over, not the renderer's own. With the proof turned off +/// and nothing else changed, the renderer has nothing to redraw: the canvas still gets the whole +/// image, or the stripes would stay on its texture. +#[test] +fn turning_soft_proof_off_hands_over_the_whole_image() { + let (mut s, rect) = document(); + let view = view_at((300.0, 250.0), 1.0, 700, 600); + let now = |s: &Session, proof: bool| { + let ds = s.ds().unwrap(); + Job { proof, ..job(&ds.doc, ds.page, ds.uid, view.clone()) } + }; + let mut r = Renders::default(); + let proofed = stepped(&mut r, &now(&s, true)).0.expect("drawn"); + assert!(proofed.image.whole().is_some()); + let Refined::Done(Some(plain)) = r.refine_for(&now(&s, false), 0.0, Some(proofed.frame)) else { panic!("reused at once") }; + assert!(plain.image.whole().is_some(), "the whole image without the stripes"); + // From there on, edits are patches again. + s.execute("node.set", &json!({"id": rect, "width": 240})).unwrap(); + let Refined::Done(Some(edited)) = r.refine_for(&now(&s, false), 0.0, Some(plain.frame)) else { panic!("a patch is done at once") }; + assert!(matches!(&edited.image, Pixels::Patches(parts) if !parts.is_empty())); +} + fn until_late_preview_of(w: &mut Worker, seq: u64) -> Vec<(u64, bool)> { let start = std::time::Instant::now(); let mut got = vec![]; @@ -825,3 +909,19 @@ fn a_zoom_in_after_a_late_preview_left_on_screen_is_measured_from_that_preview() got.extend(until_idle(&mut w)); assert_eq!(got, [(3, true), (3, false)], "the 1x image is gone from the screen: the zoom in gets its late preview"); } + +/// The canvas keeps a copy of its texture's pixels for the eyedropper. Patches put on the texture +/// go on that copy too: a colour picked where an edit redrew is the one shown, not the one before. +#[test] +fn the_colour_read_from_the_canvas_is_the_patched_one() { + let ctx = egui::Context::default(); + let (red, blue) = (egui::Color32::from_rgb(255, 0, 0), egui::Color32::from_rgb(0, 0, 255)); + let of = Some((1, NodeId(1))); + let mut canvas = CanvasState { tex_view: Some(view_at((20.0, 15.0), 1.0, 40, 30)), tex_of: of, ..Default::default() }; + let under = |c: &CanvasState, x: f64, y: f64| c.pixel_under(figcraft_geom::Point::new(x, y), of, egui::Color32::WHITE); + let filter = egui::TextureOptions::NEAREST; + canvas.take_pixels(&ctx, Pixels::Whole(egui::ColorImage::filled([40, 30], red)), filter); + assert_eq!(under(&canvas, 12.5, 8.5), Some(red)); + canvas.take_pixels(&ctx, Pixels::Patches(vec![([10, 5], egui::ColorImage::filled([6, 4], blue))]), filter); + assert_eq!((under(&canvas, 12.5, 8.5), under(&canvas, 9.5, 8.5), under(&canvas, 12.5, 9.5)), (Some(blue), Some(red), Some(red))); +} diff --git a/crates/ui-egui/src/context_menu_tests.rs b/crates/ui-egui/src/context_menu_tests.rs index dce0ad1f4..1c32949f0 100644 --- a/crates/ui-egui/src/context_menu_tests.rs +++ b/crates/ui-egui/src/context_menu_tests.rs @@ -72,17 +72,28 @@ fn the_context_menu_offers_go_to_main_for_an_instance() { assert!(!has_text(&shapes, "Create component"), "not offered for an instance"); } +/// Press Cmd/Ctrl+L on the canvas. +fn cmd_l(u: &mut Ui) { + let held = egui::Modifiers { command: true, mac_cmd: cfg!(target_os = "macos"), ctrl: !cfg!(target_os = "macos"), ..egui::Modifiers::NONE }; + let l = |pressed| egui::Event::Key { key: egui::Key::L, physical_key: Some(egui::Key::L), pressed, repeat: false, modifiers: held }; + u.frame_with(vec![l(true), l(false)], held); +} + +/// With nothing selected, Cmd/Ctrl+L copies the link of the page shown (#2507), not of a layer. #[test] -fn copying_a_link_with_nothing_selected_copies_nothing() { +fn cmd_l_with_nothing_selected_copies_the_pages_link() { let mut s = Session::new(); - s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap(); + let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap()); s.execute("select.none", &json!({})).unwrap(); + let page = s.page().unwrap(); let copied = Arc::new(Mutex::new(Vec::new())); let mut u = Ui::new(s); u.app.services = Box::new(Copied(copied.clone())); - crate::menus::invoke(&mut u.app, "edit.copyLink"); - assert!(copied.lock().unwrap().is_empty(), "no link to node 0"); - assert!(u.app.ui.toast.is_none()); + u.frame(vec![]); + cmd_l(&mut u); + assert_ne!(page, frame); + assert_eq!(*copied.lock().unwrap(), [format!("figcraft://node/{}", page.0)]); + assert_eq!(u.app.ui.toast.as_ref().map(|t| t.0.as_str()), Some("Link copied")); } /// With a section selected, a right-click on either frame inside it links that frame, not the @@ -236,8 +247,6 @@ fn cmd_l_copies_the_link_of_the_selected_frame() { let mut u = Ui::new(s); u.app.services = Box::new(Copied(copied.clone())); u.frame(vec![]); - let held = egui::Modifiers { command: true, mac_cmd: cfg!(target_os = "macos"), ctrl: !cfg!(target_os = "macos"), ..egui::Modifiers::NONE }; - let l = |pressed| egui::Event::Key { key: egui::Key::L, physical_key: Some(egui::Key::L), pressed, repeat: false, modifiers: held }; - u.frame_with(vec![l(true), l(false)], held); + cmd_l(&mut u); assert_eq!(copied.lock().unwrap().last().cloned(), Some(format!("figcraft://node/{}", frame.0))); } diff --git a/crates/ui-egui/src/dev_mode_tests.rs b/crates/ui-egui/src/dev_mode_tests.rs index 0e8fa2726..b8bdad819 100644 --- a/crates/ui-egui/src/dev_mode_tests.rs +++ b/crates/ui-egui/src/dev_mode_tests.rs @@ -257,3 +257,124 @@ fn a_rule_draft_belongs_to_its_document_and_outlives_a_refusal() { u.run("file.new", json!({})); assert_ne!(crate::dev_mode::rule_draft(&u.app, f), field); } + +#[test] +fn a_typed_rule_stays_when_the_field_loses_focus() { + let mut s = Session::new(); + let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": "Home"})).unwrap()); + s.execute("select.set", &json!({"ids": [f]})).unwrap(); + let mut u = crate::layers_drag_tests::Ui::new(s); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + u.frame(vec![]); + let te = crate::dev_mode::rule_editor(&u.app, f).with("te"); + u.ctx.memory_mut(|m| m.request_focus(te)); + u.frame(vec![]); + u.frame(vec![Event::Text("Cards stack".into())]); + // Click something else in the panel: the field loses focus as it does in use. + let mobile = tree(&mut u).into_iter().find(|n| n.role() == Role::Button && n.label() == Some("Mobile")).expect("the Mobile button"); + click(&mut u, centre(&mobile)); + u.frame(vec![]); + let draft = u.ctx.data(|d| d.get_temp::(crate::dev_mode::rule_draft(&u.app, f))); + assert_eq!(draft.as_deref(), Some("Cards stack")); +} + +/// The text the field whose editor is `te` shows, as assistive technology reads it. +fn shown(u: &mut crate::layers_drag_tests::Ui, te: egui::Id) -> String { + let nodes = u.frame_output(vec![]).platform_output.accesskit_update.unwrap().nodes; + let field = nodes.into_iter().find(|(at, _)| *at == te.accesskit_id()).expect("the field").1; + field.value().unwrap_or_default().to_string() +} + +/// `n` frames with no input. +fn idle(u: &mut crate::layers_drag_tests::Ui, n: usize) { + for _ in 0..n { + u.frame(vec![]); + } +} + +/// A frame named `name`, marked desktop and selected, with the Inspect tab drawn. +fn marked_frame(u: &mut crate::layers_drag_tests::Ui, name: &str) -> NodeId { + let f = id(&u.app.run("frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": name})).unwrap()); + u.app.run("responsive.set", json!({"ids": [f], "viewport": "desktop"})); + u.app.run("select.set", json!({"ids": [f]})); + idle(u, 3); + f +} + +#[test] +fn an_unfinished_group_edit_stays_with_its_document() { + let mut u = crate::layers_drag_tests::Ui::new(Session::new()); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + let a = marked_frame(&mut u, "Home"); + let field = tree(&mut u).into_iter().find(|n| n.label() == Some("Design it's a version of")).expect("the group field"); + click(&mut u, centre(&field)); + u.frame(vec![Event::Text("Alpha".into())]); + // Left unfinished: another document opens, with a layer of the same id. + u.app.run("file.new", json!({})); + let b = marked_frame(&mut u, "Pricing"); + assert_eq!(a, b, "the same layer id in both documents"); + let enter = |pressed| Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + u.frame(vec![enter(true), enter(false)]); + idle(&mut u, 2); + let group = u.app.session.doc().unwrap().node(b).unwrap().plugin_data.get("figcraft.viewportGroup").cloned(); + assert_ne!(group.as_deref(), Some("Alpha"), "the other document's edit didn't land here"); +} + +#[test] +fn a_rule_left_typed_when_the_section_hid_isnt_added_unseen() { + let mut u = crate::layers_drag_tests::Ui::new(Session::new()); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + let f = marked_frame(&mut u, "Home"); + let te = crate::dev_mode::rule_editor(&u.app, f).with("te"); + u.ctx.memory_mut(|m| m.request_focus(te)); + u.frame(vec![]); + u.frame(vec![Event::Text("Stale".into())]); + // The section goes while the field has focus, then comes back. + u.app.run("select.set", json!({"ids": []})); + idle(&mut u, 3); + u.app.run("select.set", json!({"ids": [f]})); + idle(&mut u, 3); + let add = tree(&mut u).into_iter().find(|n| n.role() == Role::Button && n.label() == Some("Add rule")).expect("Add rule"); + click(&mut u, centre(&add)); + idle(&mut u, 2); + let rules = u.app.session.doc().unwrap().node(f).unwrap().annotations.len(); + assert_eq!(rules, 0, "nothing the field doesn't show is added"); + // Nor does it come back when the field is edited again. + u.ctx.memory_mut(|m| m.request_focus(te)); + idle(&mut u, 2); + assert_eq!(shown(&mut u, te), "", "the field starts from what it showed"); +} + +#[test] +fn a_rule_added_while_its_field_keeps_focus_is_added_once() { + let mut u = crate::layers_drag_tests::Ui::new(Session::new()); + u.app.ui.right_tab = crate::RightTab::Inspect; + u.ctx.enable_accesskit(); + let f = marked_frame(&mut u, "Home"); + let te = crate::dev_mode::rule_editor(&u.app, f).with("te"); + u.ctx.memory_mut(|m| m.request_focus(te)); + u.frame(vec![]); + u.frame(vec![Event::Text("Cards stack".into())]); + // An assistive Click activates the button without taking focus from the field. + let nodes = u.frame_output(vec![]).platform_output.accesskit_update.unwrap().nodes; + let add = nodes.iter().find(|(_, n)| n.role() == Role::Button && n.label() == Some("Add rule")).expect("Add rule").0; + let activate = || { + Event::AccessKitActionRequest(egui::accesskit::ActionRequest { + action: egui::accesskit::Action::Click, + target_tree: egui::accesskit::TreeId::ROOT, + target_node: add, + data: None, + }) + }; + u.frame(vec![activate()]); + idle(&mut u, 2); + assert!(u.ctx.memory(|m| m.has_focus(te)), "the field kept focus"); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().annotations.len(), 1); + assert_eq!(shown(&mut u, te), "", "the field clears once the rule is added"); + u.frame(vec![activate()]); + idle(&mut u, 2); + assert_eq!(u.app.session.doc().unwrap().node(f).unwrap().annotations.len(), 1, "a second activation adds nothing"); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index f8a793154..42450a010 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -69,6 +69,14 @@ pub fn record_recent(app: &mut FigApp, key: &str) { r.truncate(figcraft_engine::MAX_RECENT_ACTIONS); } +/// Put `id`'s link (`figcraft://node/`) on the clipboard and say so. It goes through the +/// control-channel fence (`clipboard_set_text`): a synthetic gesture never replaces the user's +/// clipboard. +pub(crate) fn copy_link(app: &mut FigApp, id: figcraft_doc::NodeId) { + app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); + app.toast(tr("Link copied")); +} + /// Run a menu, shortcut or palette action by id: actions that need the UI (dialogs, panels, the /// clipboard) are handled here, the rest go to the engine. pub fn invoke(app: &mut FigApp, id: &str) { @@ -150,11 +158,9 @@ pub fn invoke(app: &mut FigApp, id: &str) { app.toast(tr("Copied as text")); } "edit.copyLink" => { - // Only a selected layer has a link, and the copy goes through the control-channel fence - // (`clipboard_set_text`): a synthetic gesture never replaces the user's clipboard. - if let Some(id) = app.session.selection().first() { - app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); - app.toast(tr("Link copied")); + // The selected layer's link, else the page's (#2507). + if let Some(id) = app.session.selection().first().copied().or_else(|| app.session.page().ok()) { + copy_link(app, id); } } "edit.findReplace" => app.ui.find = Some((String::new(), String::new())), diff --git a/crates/ui-egui/src/open.rs b/crates/ui-egui/src/open.rs index b9ffb7c2c..ca63910f9 100644 --- a/crates/ui-egui/src/open.rs +++ b/crates/ui-egui/src/open.rs @@ -7,9 +7,16 @@ use super::{OsStr, Path, theme}; pub(crate) const OPEN_EXTENSIONS: &[&str] = &["figcraft", "fig", "jam", "penpot", "sketch", "json", "svg", "png", "jpg", "jpeg", "webp", "gif", "tif", "tiff"]; +/// [`OPEN_EXTENSIONS`] and the camera raw files, which open as an image too: what File ▸ Open offers. +pub(crate) fn open_extensions() -> Vec<&'static str> { + OPEN_EXTENSIONS.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect() +} + /// Whether `path` names a file type that opens as a document (the extension, in any case). pub(crate) fn opens(path: &Path) -> bool { - path.extension().and_then(OsStr::to_str).is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e))) + path.extension() + .and_then(OsStr::to_str) + .is_some_and(|e| OPEN_EXTENSIONS.iter().any(|x| x.eq_ignore_ascii_case(e)) || figcraft_format::raw::is_extension(e)) } /// Whether `path` is a whole document (`.figcraft`, `.fig`, `.jam`, `.penpot`, `.sketch`, file JSON) rather than an image or SVG: diff --git a/crates/ui-egui/src/panels/dev_mode.rs b/crates/ui-egui/src/panels/dev_mode.rs index ea9a27bf4..dbb6921ce 100644 --- a/crates/ui-egui/src/panels/dev_mode.rs +++ b/crates/ui-egui/src/panels/dev_mode.rs @@ -572,19 +572,30 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod let group = responsive::group_of(n); row(ui, 32.0, |ui| { let width = ui.available_width() - 2.0 * PAD; - if let Some(v) = widgets::text_field(ui, Id::unique(("responsive_group", id)), group, width, tr("Design it's a version of")) { + if let Some(v) = widgets::text_field(ui, group_field(app, id), group, width, tr("Design it's a version of")) { // Emptied: back to the frame's name. let group = if v.trim().is_empty() { json!(null) } else { json!(v) }; app.run("responsive.set", json!({"id": id, "viewport": current, "group": group})); } }); } - let field = rule_draft(app, id); - let draft = ui.data(|d| d.get_temp::(field)).unwrap_or_default(); + let (field, editor) = (rule_draft(app, id), rule_editor(app, id)); + let mut draft = ui.data(|d| d.get_temp::(field)).unwrap_or_default(); widgets::sublabels(ui, tr("Add a rule"), None); - if let Some(v) = widgets::multiline_field(ui, field, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) { - ui.data_mut(|d| d.insert_temp(field, v)); + if let Some(v) = widgets::multiline_field(ui, editor, &draft, tr("Sidebar becomes a drawer below 768 px"), 3) { + ui.data_mut(|d| d.insert_temp(field, v.clone())); + draft = v; } + // While the field has focus, what it holds is the rule. Without focus, text it kept when the + // section went away mid-edit was never shown: it isn't sent, and it's dropped so the next + // edit starts from the draft the field shows. + let focused = ui.memory(|m| m.has_focus(editor.with("te"))); + let draft = if focused { + ui.data(|d| d.get_temp::(editor)).unwrap_or(draft) + } else { + ui.data_mut(|d| d.remove_temp::(editor)); + draft + }; row(ui, 32.0, |ui| { if widgets::button(ui, tr("Add rule"), false, !draft.trim().is_empty()).clicked() { add_rule(app, ui.ctx(), id, &draft); @@ -593,6 +604,18 @@ pub fn responsive_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: Nod widgets::note(ui, tr("Rules appear under Annotations, in the Responsive category."), t.text_secondary); } +/// The Screen sizes section's field for the design layer `id` is a version of. +pub(crate) fn group_field(app: &FigApp, id: NodeId) -> Id { + // Layer ids repeat across open documents. + Id::unique(("responsive_group", app.session.ds().ok().map(|d| d.uid), id)) +} + +/// The rule field's own editing state for layer `id`. +pub(crate) fn rule_editor(app: &FigApp, id: NodeId) -> Id { + // Apart from the draft: the field drops its editing state when it loses focus. + rule_draft(app, id).with("editor") +} + /// Where the Screen sizes section keeps the rule being typed for layer `id`. pub(crate) fn rule_draft(app: &FigApp, id: NodeId) -> Id { // Layer ids repeat across open documents. @@ -601,9 +624,13 @@ pub(crate) fn rule_draft(app: &FigApp, id: NodeId) -> Id { /// Add `text` as a rule on `id`. The draft stays when the rule is refused, so nothing typed is lost. pub(crate) fn add_rule(app: &mut FigApp, ctx: &egui::Context, id: NodeId, text: &str) { - let field = rule_draft(app, id); + let (field, editor) = (rule_draft(app, id), rule_editor(app, id)); if app.run("responsive.rule", json!({"id": id, "text": text})).is_some() { - ctx.data_mut(|d| d.remove_temp::(field)); + // Both: a field that kept focus (an assistive Click doesn't move it) would bring the rule back. + ctx.data_mut(|d| { + d.remove_temp::(field); + d.remove_temp::(editor); + }); } } diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 5c39c4375..741babeac 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -346,8 +346,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { } // Copy link to page (#2379); a divider can't be linked. if !divider && ui.button(tr("Copy link to page")).clicked() { - app.clipboard_set_text(&format!("figcraft://node/{}", id.0)); - app.toast(tr("Link copied")); + crate::menus::copy_link(app, id); ui.close(); } // The page the file opens on, for everyone (#1817); a divider can't be one. diff --git a/crates/ui-egui/src/panels/typography/glyphs.rs b/crates/ui-egui/src/panels/typography/glyphs.rs index 5b379f4fa..f09cf1ead 100644 --- a/crates/ui-egui/src/panels/typography/glyphs.rs +++ b/crates/ui-egui/src/panels/typography/glyphs.rs @@ -272,7 +272,7 @@ mod tests { let id = doc.alloc_id(); let mut td = TextData::new("Hello world"); td.restyle(6, 11, |s| s.font_size = 40.0); - doc.insert(Node::new(id, NodeKind::Text(td), "t", 10.0, 10.0), page, None).unwrap(); + doc.insert(Node::new(id, NodeKind::Text(td.into()), "t", 10.0, 10.0), page, None).unwrap(); assert_eq!(target_styles(&doc, &[id], Some((id, 0, 5))).len(), 1); assert_eq!(target_styles(&doc, &[id], Some((id, 4, 8))).len(), 2); assert_eq!(target_styles(&doc, &[id], Some((id, 3, 3))).len(), 2); diff --git a/crates/ui-egui/src/region_fill_rows_tests.rs b/crates/ui-egui/src/region_fill_rows_tests.rs index 5d071bca3..247f3b0c1 100644 --- a/crates/ui-egui/src/region_fill_rows_tests.rs +++ b/crates/ui-egui/src/region_fill_rows_tests.rs @@ -34,7 +34,7 @@ pub(crate) fn two_region_vector(s: &mut Session) -> NodeId { square(&mut n, 60.0, 60.0, 80.0); n.regions = vec![Region { loops: vec![vec![0, 1, 2, 3]], ..Default::default() }, Region { loops: vec![vec![4, 5, 6, 7]], ..Default::default() }]; - node.kind = NodeKind::Vector { network: n }; + node.kind = NodeKind::Vector { network: n.into() }; node.transform = figcraft_geom::Affine::IDENTITY; node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)]; figcraft_engine::vectoredit::refit(doc, id).unwrap(); diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index ff8456973..ba481f118 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -640,7 +640,9 @@ fn picked_bytes(file: &serde_json::Value) -> Option> { /// Ask for an image file for `target`: layers' paints keep their fill mode, crop and position. fn upload_image(app: &mut FigApp, target: &PickerTarget) { let target = target.clone(); - app.pick_file(tr("Choose image"), &IMAGE_FILES, true, move |app, file| { + // Camera raw files fill as the image they develop to. + let files: Vec<&str> = IMAGE_FILES.iter().chain(figcraft_format::raw::EXTENSIONS.iter()).copied().collect(); + app.pick_file(tr("Choose image"), &files, true, move |app, file| { if let PickerTarget::Paint { fills, index, ids } = &target && !region_backed(app, &target) { diff --git a/crates/ui-egui/src/widgets/font_preview.rs b/crates/ui-egui/src/widgets/font_preview.rs index f465041e7..4b8c32050 100644 --- a/crates/ui-egui/src/widgets/font_preview.rs +++ b/crates/ui-egui/src/widgets/font_preview.rs @@ -73,7 +73,7 @@ fn render(ctx: &egui::Context, style: &TextStyle, text: &str, ppp: f64) -> Optio let id = doc.alloc_id(); let mut td = TextData::new(text); td.style = TextStyle { fills: None, link: None, style_id: None, ..style.clone() }; - let mut n = Node::new(id, NodeKind::Text(td), "preview", 1.0, 1.0); + let mut n = Node::new(id, NodeKind::Text(td.into()), "preview", 1.0, 1.0); n.fills = vec![Paint::solid(Color::WHITE)]; let (w, h) = figcraft_text::auto_size(&n)?; n.width = w.min(400.0); diff --git a/crates/vectordrawable/src/tests/shapes.rs b/crates/vectordrawable/src/tests/shapes.rs index e0f789ccf..2d29489cd 100644 --- a/crates/vectordrawable/src/tests/shapes.rs +++ b/crates/vectordrawable/src/tests/shapes.rs @@ -163,7 +163,7 @@ fn text_is_glyph_outlines_one_path_per_styled_run() { style.fills = Some(vec![Paint::solid(hex("00FF00"))]); text.runs.push(StyleRun { start: 1, end: 2, style }); text.normalize(); - let t = d.create(p, NodeKind::Text(text), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); + let t = d.create(p, NodeKind::Text(text.into()), "Text", 0.0, 0.0, 100.0, 40.0).unwrap(); d.get_mut(t).unwrap().fills = vec![Paint::solid(Color::BLACK)]; let out = export(&d, &[t], Compat::BestEffort); let fills: Vec<_> = paths_of(&out.xml).iter().map(|e| e.get("fillColor").unwrap().to_string()).collect(); diff --git a/docs/auto-layout-parity.md b/docs/auto-layout-parity.md index 2e512cf6e..3a8011bb9 100644 --- a/docs/auto-layout-parity.md +++ b/docs/auto-layout-parity.md @@ -1,6 +1,6 @@ # Auto layout and constraints parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-27 · **Change:** patch (Shift-dragging a padding grip or gap band snaps to multiples of the big nudge; Alt links the opposite side; a child with its aspect ratio locked that fills one axis and is fixed on the other keeps its proportions: the fixed side follows the filled one; Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size, as measured in Figma (#2091, #2034); padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-27 · **Change:** patch (Shift-dragging a padding grip or gap band snaps to multiples of the big nudge; Alt links the opposite side; a child with its aspect ratio locked that fills one axis and is fixed on the other keeps its proportions: the fixed side follows the filled one; Fill on a child turns its hugging parent Fixed along the flow only; across the flow the parent keeps hugging and the child takes the line's cross size, as measured in Figma (#2091, #2034); padding grip fills and outlines follow theme tokens; padding grips preserve canvas hover and right-click menus; padding grips stay reachable on tiny frames and at reduced zoom; Add auto layout picks the sizing, gap and padding Figma does, measured with synthetic rectangles: height hugs, width fixed in a vertical flow or with an Auto gap, Space between for two far-apart layers, padding from the converted frame's left and top offsets, 10 around a single wrapped layer; grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) -- this replaces the 2026-10-11 rule from the documentation; a child dragged within its own auto layout row or column passes a sibling when its leading edge reaches the sibling's middle, as measured in Figma's web app, wherever it is grabbed; a Cmd/Ctrl-click on a padding field sets all four sides with the value typed, as the Guide to auto layout's shortcut guide says; Suggest auto layout is its own command, as the help center says: it adds as many auto layout frames as needed, splitting a frame's layers into rows or columns by the gaps between them, and keeps the placement of the design where the gaps are even (#1823); baseline alignment puts a layer without text with its bottom on the line, as the help center's figure shows an icon next to text (#1825); fill children share the free space by their content area, border-box fashion, as the Flexbox article says (#1824); double-click an edge of an auto layout frame's box for Hug contents, Alt+double-click an edge of a child's box for Fill container, as the Guide to auto layout says (#1838); a child resized to the full available space of its auto layout frame becomes Fill container on that axis, as the Guide to auto layout says; a text keeps a max height or a number of max lines, not both, as the Guide to auto layout says: a max height sets max lines to Auto and max lines remove the max height; Remove all auto layout, as the help center's More layout options has it: `layout.removeAll` takes the auto layout off a frame and every frame nested in it in one undo step; grid auto-placement looks for free cells a 64-bit word at a time and skips what blocks it, with the same placements (#1083); Layout sidebar: Add auto layout (+) is available for groups and converts a single group to a frame in place, with mask order, flow-only inference and Fill sizing preserved; adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys only to frames, with warnings (#603); core editor leftovers: auto gap handles, wrapped-line alignment; behaviour suite written from the public documentation, every rule's status; fixes and the missing settings it found) · **Target:** Figma Design (desktop app 126.10.7) Auto layout is the most used layout feature in Figma and the one where small differences (a hugging frame one pixel off, text wrapping at another width) break real files. **Breadth ~98%, @@ -15,7 +15,7 @@ With one group selected, Add auto layout converts that group into a frame in pla id, name, parent and direct children. The Layout sidebar’s +, context menu, Shift+A and API calls all dispatch `layout.add`, so they share the conversion and a single undo step restores the group. The layout settings are inferred from visible, non-absolute children, matching the layout engine’s -flow. Hidden and absolute children therefore do not distort direction, gap or padding. A converted +flow, so hidden and absolute children do not distort direction, gap or padding. The sizing, gap and padding defaults are the ones measured in Figma (see the Add auto layout row below): a converted group follows the rule for a wrap of several layers and ends with no fill and clip off. A converted group keeps Fill sizing on either axis in its auto layout parent. Sorting by position preserves mask boundaries and the paint order within masked runs. The sidebar offers Add only when every selected container has no auto layout, including mixed selections. @@ -109,7 +109,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | Constraints: left, right, left and right, centre, scale; top/bottom likewise | done | | | Layout grids: columns, rows, grid; stretch/left/centre/right; variables bound | done | | | Suggest auto layout | done | The target works out which layers belong together and adds as many auto layout frames as the design needs, in one step, keeping the placement. `layout.suggest` used to run `layout.add` and made one row of everything (#1823). Now it splits a frame's layers, by their boxes in the frame, along the vertical axis first: sorted by top edge, a layer joins the current row while it starts above the row's bottom (or together with it), and a gap, even a zero one, between the row and the next layer starts a new row. With two or more rows the frame becomes a Vertical auto layout whose items are the rows; otherwise the same split by columns gives a Horizontal one; if the layers overlap along both axes the frame gets no auto layout and the result carries a warning. A row or column of several layers goes into a new frame without fill or clipping, sized to it and inserted in its place (it hugs its content once the split gives it auto layout; a band whose own layers overlap along both axes gets none, with a warning, and stays a Fixed frame that cannot reflow those layers), and the split repeats inside it, to a depth of 16 and for up to 1,000 layers per frame (past that, or when a mask is among the layers, the layers are laid out in one list as Add auto layout does, with a warning). The frame keeps its size, Fixed: the gap is the distance between the bands, the padding along the flow is the first band's offset and the room left after the last, across the flow the smallest offset (alignment start), so with equal gaps and bands that start at the same offset every layer keeps its box exactly. When the gaps differ by more than 0.5 px the smallest is used and `warnings` says the later bands move; when the bands start at different offsets across the flow (a centred title above a card) they line up at the smallest, which moves the others, and `warnings` says so. Instances and layers inside them are refused with the error Convert to group gives, before anything changes; a main component works. `direction` sets the top level only. A single group becomes a frame in place and several layers are wrapped in a frame (both hug), as Add auto layout does; a frame with fewer than two layers is laid out as Add auto layout does. One undo step. Tests in `crates/engine/src/layout_suggest_tests.rs`: `two_rows_of_two_squares_become_a_vertical_frame_of_two_horizontal_rows`, `suggesting_auto_layout_is_one_undo_step`, `three_squares_in_a_row_get_one_horizontal_layout_without_nesting`, `three_squares_in_a_column_get_one_vertical_layout_without_nesting`, `a_header_above_two_columns_of_squares_gives_a_row_per_line`, `a_header_above_a_tall_layer_beside_a_column_nests_three_levels`, `unequal_gaps_use_the_smallest_and_say_so`, `overlapping_layers_leave_the_frame_without_auto_layout_and_say_so`, `a_group_becomes_a_frame_in_place_and_follows_the_rules`, `several_layers_are_wrapped_in_a_frame_that_is_then_split`, `a_direction_forces_the_top_level_and_nested_frames_follow_the_gaps`, `a_frame_with_one_layer_is_laid_out_like_add_auto_layout`, `add_auto_layout_still_makes_a_single_row`, `a_centred_title_above_a_card_is_lined_up_at_the_card_edge_with_a_warning`, `instances_and_layers_inside_them_are_refused_and_a_main_component_works`. Not attempted: overlapping layers, keeping uneven offsets across the flow (they line up at the smallest, with a warning), grids | -| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20); a frame with content still hugs it, as does a new frame wrapped around a selection (#369). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) | +| "Add auto layout" on a selection | done | the Layout sidebar exposes Add auto layout (+) for groups and frames using the same `layout.add` command as the context menu; a single group becomes a frame in place, keeping its id, name and direct children; adding auto layout to an empty frame keeps its size, Fixed (it collapsed to 20×20, #369). A frame with content, and a new frame wrapped around a selection, take the defaults measured in Figma's web app with synthetic rectangles, 2026-11-09 (`al_behaviour_tests::shift_a_*`): the height hugs; the width is fixed in a vertical flow (a converted frame shrinks to its content plus the left and right padding) and with an Auto gap, and hugs otherwise; the gap is Auto (main align Space between, the measured gap stored) only in a horizontal flow of exactly two layers whose gap is at least the narrower layer's width (for a converted frame also with equal left and right offsets within 0.5 px), otherwise the rounded mean of the gaps; a converted frame takes the content's left offset for left and right padding and its top offset for top and bottom, a wrap of several layers has no padding, and a wrap of one layer pads 10 on every side with a gap of 10, hugs both ways and keeps the layer in place on the canvas (converting a frame with one child is unmeasured and unchanged). `node.set` with auto layout keys on a mix of layers applies them to the frames and warns about the rest instead of failing the whole call (#603) | | Real Figma files laid out identically | **not checked** | needs `.fig` or REST import of real files ([gaps](gaps.md) #1, #3) | | Performance: re-flow only where sizes or places changed | done | measured in `cargo xtask bench` (components at scale) | @@ -122,6 +122,7 @@ Status: **pass** (a case in the suite holds), **fixed** (the suite found a diver | 2026-11-13 | patch | M2, #2152: Padding grip fills and outlines come from dedicated theme tokens, preserving linked-state emphasis and border widths. A rendering regression checks custom light and dark palettes. | | 2026-11-13 | patch | M2, #2152: Padding grips preserve canvas hover and secondary-click context menus while retaining their resize cursor. Only primary presses and active handle drags capture input. Regressions reproduce both stale layer hover and blocked right-click menus. | | 2026-11-08 | patch | M2, #2091, #2034: Fill on a child of a hugging auto layout frame turns the frame Fixed only along the flow, as measured in Figma; across the flow the frame keeps hugging and the child takes the line's cross size (the largest child that doesn't fill, a Fill child's min counted, padding outside, the frame's own min/max applied), re-laid out at that size, and a text filling the width of a hugging stack reflows before the stack hugs it. The frame turns Fixed (notice "Height set to Fixed for ", also "Width ..." along the flow) only when no non-Fill child is left; in a wrapping row that hugs the axis Fill is refused (`node.set`), not offered (Layout panel) and read as Fixed by `coherent_sizing`. A `.fig` STRETCH bar beside a two-line text now takes the text's height. | +| 2026-11-09 | patch | M2: Add auto layout (`layout.add`, Shift+A) picks Figma's defaults, measured in Figma's web app with synthetic rectangles: height Hug; width Fixed in a vertical flow (a converted frame shrinks to its content plus padding) and with an Auto gap, Hug otherwise; Auto gap (Space between) for two layers in a horizontal flow whose gap is at least the narrower one (a converted frame also needs equal left and right offsets); a converted frame's padding is its left and top offsets mirrored; one wrapped layer gets padding 10, gap 10 and keeps its place. Tests: `al_behaviour_tests::shift_a_*`. Numbers unchanged | | 2026-11-11 | patch | M2.1: grid Fill (`fr`) tracks share the space of a fixed-size axis by their fractions and let a fixed-size child overflow, as measured in Figma (300 x 200, two rows, 100 x 150 and 100 x 20 children: rows 100 / 100, second child at y 100; with a row gap of 10, rows 95 / 95 and y 105; on Hug the rows fit their content, 150 / 20) (this replaces the 2026-10-11 rule from the documentation). Layout behaviour suite: three cases flipped, three added | | 2026-11-10 | patch | M2: Opposite padding grips separate to at least 20 screen pixels on tiny frames or at reduced zoom. Overlapping targets select the nearest visible grip, shared by hover, highlighting and drag. Regression tests click every painted grip, drag and undo on thin, narrow and tiny frames, including an inside stroke and 25% zoom. | | 2026-11-09 | patch | M2: Canvas padding bands have a central grip on each side; only pressing and dragging that grip edits padding. Hover still highlights the band and shows its value beside the grip. Each grip keeps its vertical or horizontal resize cursor on hover. Alt links the opposite side, Alt+Shift links all four, and affected bands and grips highlight as modifiers change, before and during dragging. Headless tests cover cursors, all sides, modifier previews, dragging and one-step undo. | diff --git a/docs/cli.md b/docs/cli.md index 2faf1d1f0..28facebab 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -192,7 +192,9 @@ figcraft-cli export app.figcraft -o handoff.fig By extension. Inputs: `.figcraft`, `.json` (FigCraft or REST API file JSON), `.fig` (best effort), `.sketch` (Sketch 48 or newer, best effort), `.penpot` (Penpot 2.x archive, best effort), `.svg` (an editable frame: groups, shapes, text, gradients, masks and effects; `info` lists what it left out as `note:` lines), `.png/.jpg/.webp/.gif/.tif/.bmp` -(an image layer). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`, +(an image layer), camera raw files (`.rw2`, `.cr2`, `.cr3`, `.nef`, `.arw`, `.raf`, `.orf`, `.dng` and the other +containers craft-raw reads: an image layer of the picture developed with the camera's as-shot white balance and a +neutral tone curve; the document keeps that picture, not the raw file). Outputs: `.figcraft`, `.json` (FigCraft JSON, pretty-printed), `.svg`, `.png/.jpg/.webp` (the current page rendered at 1x with its background), `.pdf` (the current page's frames, one page each), `.fig` (the whole file, experimental, as `export --format fig`), `.penpot` (the whole file as a Penpot 2.x archive, as `export --format penpot`). @@ -297,19 +299,22 @@ the flags leave the output identical when nothing strays outside the roots. Every command with its label, shortcut, undoable flag (`*`) and parameter docs; `--json` for machines. -### `mcp [--attach PORT] [--automation-read-root DIR]… [--automation-write-root DIR]…` +### `mcp [--attach PORT] [--automation-read-root DIR]… [--automation-write-root DIR]… [--automation-allow-server URL]…` Serve MCP on stdio: headless by default, or attached to a running app started with `figcraft --control PORT`. See [mcp.md](mcp.md). The automation roots (each repeatable; existing folders) confine the files the agent's calls read (inside a read or write root) and write (inside a write root); everything else is refused ([mcp.md › Confining file access](mcp.md#confining-file-access)). +Headless MCP requires both `--automation-read-root` and `--automation-write-root`; `--attach` uses +the attached app's roots instead. They apply to the headless session only, and that is why `--attach` refuses them: an attached server is confined by the app it attaches to, from the flags that app was started with. With `--attach`, `--timeout SECONDS` (1–600, default 60) is how long the app may take over each request. The headless -session can host, join and publish -live sessions (`collab.*`: without a key on a server open to the public, with `collab.serverInfo`, -`collab.manageFile` for the owner token and `collab.report`) and use plugin directories -(`plugin.directory.*`); the one-shot `run` can't (no network link). +session can join a shared file on an explicitly allowed server with `--automation-allow-server +wss://host/`; the file must already have been published and the agent needs its edit link. That +flag only permits `collab.join` to the named server. Other network commands remain disabled; without +the flag, all network commands remain disabled as well. See [Confining file access](mcp.md#confining-file-access). +The one-shot `run` has no network link. ### `plugin publish --server ws://host:port/[?key=KEY] [--key KEY]` diff --git a/docs/collaboration-parity.md b/docs/collaboration-parity.md index 18ef2efe9..0998cde7f 100644 --- a/docs/collaboration-parity.md +++ b/docs/collaboration-parity.md @@ -27,6 +27,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M9, #2495: Stop sharing failed on a private server for a file shared with the server key typed under Advanced ("that owner token doesn't manage a file of that id here"). Such a file has no owner token, and the key went only with the publish. `collab.share {key}` now keeps the key with the share in this session, in the address as `collab.share {server: "…?key=…"}` would give it, so Stop sharing and sharing again ask as the server's operator. The key is never in a command result. Test: `live_share_tests::stopping_a_file_shared_with_a_separate_key_asks_with_that_key`. Numbers unchanged | | 2026-11-26 | minor | M10, gap 17: shared branches sync across live sessions. Capability-gated on `branches` in `Hello::client_version` (`ServerMsg::Branches` / `Branch`, `ClientMsg::Branch` with `Create`, `Edit`, `UpdateFromMain`, `SetState`), persisted in `SessionState::branches` and the server journal (with fallback decoding for pre-branch `figcraft-server` snapshots). Any editor can open, co-edit, update from main, review, archive and merge another peer's branch (remote merges/archives close open branch tabs on peers and switch back to main); view and comment links are refused; node/entry id spaces, geometry and image entries are validated on every branch mutation; older clients and servers stay compatible (local-only branches). Tests: `collab::branch_tests`, `engine::branch_live_tests`, `figcraft-server::server_tests::shared_branches_sync_and_survive_a_server_restart`, `figcraft-server::disk::tests::decode_snapshot_reads_pre_branch_v1_snapshots`. Numbers unchanged. | | 2026-11-16 | patch | M9, #2365: a server predating reconnect secrets sends a complete `Welcome` ending at `access`; postcard does not honor a missing trailing field through `serde(default)`. The client reads that exact legacy layout, preserves access, and keeps strict size, version and message-boundary checks. Native and browser transports use this reader; reconnects without a secret send a fresh authenticated hello. Covered by codec and connection-driver regressions. A patched 0.15.1 desktop build was also checked against the public service with separate view-only access and annotation reads; writes remained denied. The public server still needs upgrading. Numbers unchanged. | | 2026-11-06 | minor | M9, #1972 review: the opening-page row said **done** but the default differs from the reference. With no opening page set, a file opens on the page that was current when it was saved or published (`Document::current_page`, written by save), which can be any page, where the reference opens on the first page, and a link cannot name a page. Regraded **partial**; setting the opening page is unchanged. Numbers unchanged. | diff --git a/docs/components-parity.md b/docs/components-parity.md index 97f6de91a..0dd64a248 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; 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; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (a page's background can follow a colour variable in the page's own mode, set from the Page section's variable button or `page.setBackground {color: {$var}}` (#2343); Swap library re-points the styles and variables of the library copies that stay, so instances placed after a swap follow it too (#2568); the Local variables window reorders variables: Move up and Move down (Alt+↑ / Alt+↓) on a row, Sort A to Z and Z to A on a collection or group, numbers by value (#2633); `library.swap` lists the unused copies of the old library it removes in `dropped` (#2569); with several instances selected, the Design panel shows the properties they share, Mixed where their values differ, and sets a value on all of them; an enabled library's styles are offered in the style pickers without opening the Assets tab first, and the picker filters its list by source (All libraries, This file, one library); with a variable group shown in the Local variables window, Create variable makes the variable in that group, and renaming a variable in its row changes the part shown and keeps its group; a layer inside an instance bound to a variable its main layer doesn't bind keeps that binding as an override when instances are relinked after an import, a detach or a restore, and when its value is set back to the main's, so a library copy or an edit of the main no longer drops it; switching variants keeps the text typed into an instance when the other variant nests that text layer in other frames, matched by its name; a main component copied from a library file and pasted into another file is an instance of it from that library, instead of a new main; copied variants pasted with their own set, or a layer in it, selected join the set as new variants; the Scale tool keeps variable-bound lengths scaled: a scaled instance keeps its bindings and draws them at the variable's value times its scale factor, other scaled layers keep the scaled value and drop the binding (#2090); a style of one library that reaches a file through another library's component is, in a file linking both, the first library's own bound copy, so its modes colour it (#2414); with a variant selected, its property dropdowns show its own values and choosing one renames only that variant, instead of setting the set's default and moving the variants (#2349); library analytics count insertions and detachments of styles and variables; combining components gives every variant the properties any of them had; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); 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); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; 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; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7) Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300 @@ -71,6 +71,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step); variables keep the order they are put in: Move up / Move down (Alt+↑ / Alt+↓) on a row and Sort A to Z / Z to A on a collection or group, numbers by value (`variable.move`, `variable.sort`, #2633); the window resizes from its edges and corners (minimum 600 x 240) and keeps its size and place while the app runs, #2354 | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | +| Text styles in the Variables JSON export and import (`textStyles`, a FigCraft extension: the REST `styles` metadata has no values) | done | `variable.export {format: "json"}` adds a top-level `textStyles` array (values and `bound`, ids matching `meta.variables`); `variable.import` merges it by style name and re-points bindings; CSS, Tailwind and Dart are variables only | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | | Bindings: fills, strokes, effects, opacity, padding, gaps, sizes, radius, font family/style, font size/weight, line height, letter spacing, paragraph spacing/indent, text, visibility, layout grids, instance properties | done | type-checked per field, an effect's only where its effect has the field (as in effect styles); glass fields too (light angle, intensity, refraction, depth, dispersion, frost and splay, percentages as the Design panel shows them, a light angle past ±180 turned round); number variables fill text content; the Design panel's font family and font style menus start with Apply variable (string variables), and a bound one shows its variable in place of the menu; a colour variable bound to a solid paint brings its whole colour, alpha included, once (the paint's opacity restarts at 100% on binding, an opacity set while bound multiplies on top; unbinding moves the alpha back into the opacity); on a scaled instance a bound length draws at the variable's value times the instance's scale factor (#2090); a scale that would take an instance past 0.001 to 1000 times is refused | | Explicit modes per frame and per page (Page section), library collections' modes | done | stored variable and collection references resolve by exact id in export, library copies and swaps, imported aliases, alias deletion and cycle checks, Dev Inspect, the library mode picker and prototype playback; a collection or variable named like another's id no longer stands in for it there | @@ -102,6 +103,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | 2026-11-14 | patch | M3, #2354: the Local variables window resizes from its edges and corners, width and height (minimum 600 x 240), and keeps its size and place while the app runs. | | 2026-11-09 | patch | M3, #2090: the Scale tool no longer snaps variable-bound lengths back to the variable's value. An instance multiplies its new `scale_factor` and keeps its bindings, drawn at the variable's value times the factor (modes and variable edits stay live); every other scaled layer outside an instance keeps the scaled value and drops the binding of the length fields it scaled, and so does a scaled instance's own layer when the instance is detached (the instances inside it take its factor on). Measured in the incumbent for the gap only (an instance keeps the binding at value x factor, a plain frame bakes it, and detaching a scaled instance bakes it); the other lengths are assumed to follow, and a main component is unmeasured; a scale that would take an instance past 0.001 to 1000 times is refused. Tests: `scale_bound_values_tests`. | | 2026-11-07 | patch | M3, #2090: an instance's own resizing follows its main's unless its size is overridden. Measured in Figma: a plain instance turns Fixed when its main's width does (a child set to Fill along it) and back to Hug with it; an instance whose width was typed keeps it; Fill in its own auto layout parent is kept. Tests: `components_behaviour_tests::a_plain_instances_resizing_follows_the_mains_root_both_ways` and the instance resizing tests beside it. | +| 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` holding the ids `meta.variables` is keyed by), and `variable.import` reads it back (styles merged by name, bindings re-pointed, a binding to a variable the JSON lacks dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Create component, instances, detach, reset, go to main, restore main, push changes. | | 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. | | 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged | diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 8708d5b24..9b6b62f6f 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,6 @@ # Dev Mode parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-14 · **Change:** minor (Uno C# Markup code generation for layers, with auto layout and vectors as paths; earlier: SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) > > **2026-11-27 patch:** SwiftUI, Compose and Flutter code keep a layer's image fills in paint order, so a photo under a colour overlay stays under it; the image is its asset from `file.exportAssets` by the same content name, fitted by its scale mode; a pattern fill is left out with a comment saying so (#2271). > @@ -22,7 +22,7 @@ repository, third-party integrations. Remaining: 1–2 h. | 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why | | Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) | -| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); image fills too, as their handed-over asset with the closest fit for their scale mode, while a pattern fill is left out with a comment; ArkUI and text still take one colour (#2271) | +| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue, Leptos and Uno C# Markup (ours; Uno writes layers only for now, as locals whose children are added with `Children.Add`: frames with auto layout (`AutoLayout`, `Grid`), text and vectors (`Path`), each layer's name as the last comment line above the statement that creates its element (a plugin pairs code with layers by it), the half-leading of explicit line heights depends on the fonts installed where the code is written; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); image fills too, as their handed-over asset with the closest fit for their scale mode, while a pattern fill is left out with a comment; ArkUI and text still take one colour (#2271) | | Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours | | Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | Screen sizes (which version of a design a frame is, rules for other sizes) | done | ours: the incumbent has no such field. A frame or section is marked mobile, tablet or desktop and named after the design it is a version of (layer data, so no file format change); rules are notes in the Responsive annotation category. Agents read only what was stated (`responsive.list`, `design_context`'s `responsive`); nothing is inferred from names or sizes | @@ -43,6 +43,8 @@ repository, third-party integrations. Remaining: 1–2 h. | 2026-11-24 | patch | Vector code export embeds a self-contained SVG asset, not a rectangle made from the path's stroke (#2270). Percentages and hours unchanged. | | 2026-11-19 | minor | Screen sizes: the Inspect tab's Screen sizes section, `responsive.set` (frames and sections; `group: null` goes back to the frame's name), `responsive.rule` (a note in the Responsive annotation category, with `annotation.add`'s limits; pages refused) and `responsive.list`. Developer Mode makes these edits, like its annotations. Stored values that aren't a version are ignored. `inspect.designContext` returns the target's under `responsive` and names the missing breakpoints only when nothing was stated. Percentages and hours unchanged | | 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Code: CSS, iOS (SwiftUI), Android (Compose), Flutter. | +| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | +| 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Numbers unchanged (the incumbent has no such target). | | 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | 2026-10-30 | minor | Gap 16: `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file (as the incumbent's Code Connect CLI publishes a repository's mappings): it links each entry's component or set by name, warns about and skips links that don't fit, saves the file in place through the engine's save (or not, with `--dry-run`) and fails when nothing links. Dev Mode breadth (~98%) and ready (~78%) unchanged at this rounding; hours unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c5fef2d36..32bc84481 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (`.fig` export writes SLOT component properties, their layer references and each instance's own slot content, and no longer clears a main's property bindings with an "unset" override row; REST import reads pattern fills; saving to another file names the document and its tab after that file; a layer exports at the size of what it draws, its strokes as drawn: an icon whose strokes stay inside its frame exports at the frame's size; JPG exports keep full chroma resolution (4:4:4) again (#2521); SVG import's limits are craft-svg's since #2468: elements nest at most 256 levels deep, references followed, and its own byte scanners and budget module are gone; REST import no longer reports node-level `fills`, `strokes`, `effects` or `textRangeFills` bindings as skipped when each paint, stop or effect binds those variables itself (#2441); `.fig` export writes ruler guides (#2336); the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); `.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -22,7 +22,7 @@ and prototype interactions are still unchecked there. | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808), shapes with text as native board shapes for the 23 kinds FigCraft draws (their paints and weight kept, the outline FigCraft's own; the 7 others keep their generated backgrounds and text, #1341, as ordinary layers) (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | | `.deck` (Slides) | native to other Figma products | no | no | out of scope | — | -| REST API file JSON (`GET /v1/files/:key`) + local variables JSON + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | +| REST API file JSON (`GET /v1/files/:key`) + local variables JSON (+ a FigCraft `textStyles` array, written by `variable.export` and read only by `variable.import`: `file.open` and `file.import` read the variables but not `textStyles`) + `images/` folder | the API's output | **yes** (`file.open`, `file.import`, CLI) | no | pages, layer tree, geometry, paints (pattern fills tile the layer their `sourceNodeId` names, wherever it comes in the file; one whose layer isn't in the file is left out with a warning), strokes, effects, text runs, vectors, auto layout (sizing modes left out read as hug, as documented; grid track sizes from `gridColumnsSizing` / `gridRowsSizing`: px, fr, auto, `minmax(0, 1fr)`, `repeat()`), constraints, grids, components, sets, instances with overrides (sizes and resizing included), component properties, slots (`SLOT` layers bound to their slot property; an instance's slot keeps its content as the instance's own unless its property value is the main's default content; slot limits and preferred components are warnings), styles, prototyping (incl. conditionals and variable modes), variables with modes, aliases, scopes and bindings, image adjustments (the same tint sign as `.fig`); the import report after opening; warnings for what's skipped (video triggers and actions, modifier keys). Unit tests in `crates/format/src/rest/*_tests.rs` | — | | `.figcraft` (ours: zip of `document.json` + images, versions inside) | — | yes | yes | streamed JSON, 50k layers save ~0.09 s / load ~0.16 s (`cargo xtask bench`); old files keep opening (`large_tests.rs`); image members are `images/`, and a key that can't be one — path text, a space, over 128 chars — is left out with a complaint instead of loaded (`image_tests`); saves write a unique staging file and rename it into place (#284); optional auto-save of files with a path (`pref.autoSave`, #305); Save and auto-save refuse to write over a file another app (figcraft-cli, say) changed since it was opened or saved here, judged by its size and modification time: Revert to saved loads those changes, Save as keeps both, `file.save {overwrite: true}` replaces them (#1330); `kind: "board"` marks a board (left out for design files, so files from before boards are design files; the home screen reads it for the file's mark); board objects keep their `board` metadata on the layer; Developer Mode measurements are kept on the layer they start from (`measurements: [{to} | {side}]`, left out when there are none, so older files open with none) | — | | Local library files | team libraries in the cloud | yes (enable a `.figcraft` as a library) | yes (publish) | per-asset versions, updates with overrides kept | see [collaboration-parity](collaboration-parity.md) | @@ -37,6 +37,7 @@ and prototype interactions are still unchecked there. | HEIC | yes | **no** | shortcut: no Rust decoder; the usable ones (libheif, libde265) are C libraries, and HEVC carries patents. Revisit when a Rust decoder exists | 2–3 | | TIFF | Safari only | **yes** | open, import, place, drop (the `image` crate's TIFF decoder; its embedded ICC profile is honoured); SVG exports embed it (and BMP) as PNG, which SVG viewers show | — | | BMP | — | yes | | — | +| Camera raw (RW2, CR2, CR3, NEF, ARW, RAF, ORF, DNG and the other containers craft-raw reads) | no | **yes**, developed | open, import, place, drop, image fills: the raw is developed once as it comes in (craft-raw decode; craft-develop demosaic, as-shot white balance, colour matrices, highlight rebuild and neutral tone curve) and the document keeps the picture as a JPEG at quality 95 with full chroma, not the raw file; a raw variant craft-raw doesn't decode is refused with its reason. Not applied: DNG camera-profile looks, lens corrections kept only as metadata, noise reduction, sharpening | — | | MP4, MOV, WebM (video fills, paid plans) | yes | **no** | shortcut: decoding H.264/HEVC/VP9 needs non-Rust libraries (FFmpeg or each platform's media framework); presenter playback would reuse the animated GIF clock | 4–8 | | Images over 4096 px | downscaled to 4096 | kept | | — | | Pasted content from other apps | images, SVG, text, Figma clipboard | images, SVG, text (newest clipboard content wins), **layers copied from another design app, best effort** | Cmd/Ctrl+V reads an image copied in another app (under Wayland through the data-control protocol, not run on Linux here; Linux and BSD clipboard reads give up after 2 s). On macOS, pasting a single supported raster file copied in Finder places the file’s image on the canvas. Copied design layers: the `.fig` canvas in the clipboard's HTML is read like a `.fig` file (with its warnings) and pasted as Paste pastes, in place or into the selected frame (`edit.pasteDesignLayers {html \| data}`, refused over 256 MB before decoding); text copied later pastes as text again. Shared paint, text and effect styles that a pasted layer links by the guid of the library it came from are found by their library asset, so the layers keep the style's colours and their link to it; a link to a style the clipboard doesn't hold keeps the layer's stored colours, with a note (#1638). An image the clipboard doesn't carry keeps its name on the fill and shows the missing-image placeholder (light grey with darker stripes), and the paste names those layers and lists its notes in the import report (#1646). Tested with clipboard HTML made from our own `.fig` export (`design_paste_tests`) and with design data built in code (`paste_style_tests`), never with a real clipboard from other software | with `.fig` | @@ -108,15 +109,17 @@ scales and empty-style clears; they have not been checked in other software. "Semi Bold" in Inter; size; line height, a share of the font size as a raw multiplier; letter spacing, case, decoration, links), alignment, auto resize, truncation, paragraph spacing and indent, list spacing, hanging punctuation and hanging lists, vertical trim, list types and styled runs with their fills (indexed - by UTF-16 unit); components (description, boolean, text and instance swap properties and the - layers bound to them, with their values also as variable data), component sets (the set holds + by UTF-16 unit); components (description, boolean, text, instance swap and slot properties and + the layers bound to them, with their values also as variable data), component sets (the set holds the definitions, variant properties included with their values in order; each variant has its own copy of each definition and its variant values, and its layers and instances name that copy), instances (their main, property values, what the instance itself changes from its main, such as its size, name and paints, as an override addressed by the main's id, the fields its layers change, by id path, through nested instances and swaps, and what follows from those as derived data: each layer's size, place and outline and the colours its - variables give in the instance's mode; an instance scaled as a whole says its scale factor); + variables give in the instance's mode; an instance scaled as a whole says its scale factor; + a slot whose content is the instance's own names a private `isSlotContent` frame on the hidden + page, whose layers are written below it); variable collections with their modes and variables (colour, number, string and boolean values per mode, aliases, colour calculations as the colour they show in each mode, descriptions, scopes) as nodes on a hidden page, the variables bound to @@ -137,7 +140,7 @@ scales and empty-style clears; they have not been checked in other software. properties, arc fields, font weight: written as the values they give), text styles on part of a text (written as values), the paint frames of vector regions, variables' publishing, code syntax and inheritance settings, extended collections (written as collections of their own), comments, Developer Mode annotations, statuses, - resources, measurements and code links, plugin data, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush + resources, measurements and code links, plugin data, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), brush strokes (written plain), strokes wider on one side of their path (written as filled outlines, or with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), glass settings other than frost, springs other than Gentle (written as ease @@ -145,9 +148,11 @@ scales and empty-style clears; they have not been checked in other software. that read the current mode of a collection) or nesting beyond the Kiwi limit, which instance overrides reach two levels sooner, scroll-to offsets, text decoration looks, variable font axes, text on a path with more than one line or on a path the format can't hold (written as plain text), the parts of a text's path after the first, text on a path in an instance but not in its main or the other way round (written as the main has it), an instance's text of more than one line on a main on a path (it stays on that path, as an override can't take it off), nested list levels, OpenType features, per-layer operations inside boolean groups, different stroke ends - on lines, the Dash cap (no public name for it). Not written at all: stroke outlines of dashed and per-side strokes and of inside or - outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays text out - with its own fonts), version history and branches. + on lines, the Dash cap (no public name for it), preferred slot components (the editor keeps no + field for the components a slot suggests). Not written at all: slot insertion and child-count + settings (the editor keeps no fields for them), stroke outlines of dashed and per-side strokes and + of inside or outside strokes on polygons, stars and vectors, glyph outlines of text (a reader lays + text out with its own fonts), version history and branches. - **Checked by opening written files in other software:** the example documents and a small test file open there, and layers, fills, gradients, strokes, shadows, vectors, components and text draw as in FigCraft. A file saved again there and read back keeps the layer tree and properties; two @@ -215,6 +220,7 @@ scales and empty-style clears; they have not been checked in other software. | 2026-11-12 | minor | M6, #2305: the `.fig` export writes a text's list spacing (`listSpacing`), hanging punctuation (`hangingPunctuation`), hanging lists (`hangingList`) and vertical trim (`leadingTrim`: none or cap height), which the importer already read. A field is written only when it differs from its default (in a design file saved by Figma, a text at the defaults carries none of the four), and an instance override that goes back to the default clears it. The warning narrows to OpenType features, which the importer does not read from a `.fig`. Checked through the importer only, not in other software. | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius and smoothing are read and written by the `.fig` importer and exporter, and by the REST importer | | 2026-11-07 | patch | Fonts, #2092: a font loaded with `text.loadFont` is the counterpart of a font uploaded to the organization, which Figma's help center ("Manage conflicting fonts") ranks first, ahead of installed fonts and the web fonts. FigCraft chose the first face added for a family and style, so the built-in Inter 4.x kept Regular, SemiBold and Bold after Inter 3.19 was loaded and only Medium refitted. A loaded face now wins over the other faces of its family and style, the latest load over earlier ones; style matching and fallbacks are unchanged, and `refitted` lists the text whose size changes. Installed versus built-in order is not changed here. Test: `fontdb::tests::a_loaded_face_wins_over_the_built_in_one_of_its_family_and_style`. Numbers unchanged. | +| 2026-11-11 | minor | `.fig` export keeps component properties through a round trip: SLOT definitions, the `SLOT_CONTENT_ID` reference on a main's slot frame and an instance's slot assignment use the format's real field ids (7 / 40 / 4 / 18 / 12 / 18 / 495), and an instance's own slot content is written as a private `isSlotContent` frame on the hidden page. Property bindings belong to the main: instance override rows no longer write an "unset" `parameterConsumptionMap` for layers that simply do not repeat them, which used to clear every binding — slots included — on import. Synthetic round trips cover defaults, variants, synced instances and the written message (`fig::export_slot_tests`). Not checked in other software. Numbers unchanged | | 2026-11-08 | minor | M6, #2097 follow-up: per-point vector corner radii take the scale of the row supplying `vectorData`, including nested instance rows; override and derived rows are not scaled twice. Network caching distinguishes the instance scale even when resizing gives two vectors the same final box. Synthetic tests cover missing/unit factors, half/double scale, derived size alone, overridden and derived vector data, nested scale and equal-size cache separation. Layer-radius fallback remains the separate #2115 change. Numbers unchanged. | | 2026-11-08 | patch | #2097 / #2100: scaled-instance lengths reset to the unscaled main value survive export/import as explicit overrides. Dimensionless values and zero do not gain scale overrides. Exported factors stay within the importer's 0.001–1000 range; larger or smaller ratios use explicit values instead. Effect/grid payload rows above an inherited style link take precedence at their own scale, including nested instances and empty-list clears, without detaching styles. Synthetic regressions cover corners, dashes/shadows, layout/grids and bounds, typography and styled runs, linked text and nested styles. Numbers unchanged. | | 2026-11-07 | minor | `.fig` import, #2091 item 1: an instance scaled with the Scale tool stores `symbolData.uniformScaleFactor`, which the import never read, so the layers of a 128 px instance of a 256 px component came in at 256 px with the main's radii, strokes and spacing. The layers of an instance now take the main's lengths times the factor (composed through nested instances, so 0.5 inside 0.5 is 0.25 for the inner layers), the lengths the Scale tool scales: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent. A value an override or derived row gives is taken as written, already at the instance's scale; the instance's own size is the file's; a missing, non-finite, non-positive or out-of-range factor (outside 0.001 to 1000) changes nothing. Not scaled: vector outline paths (a network's points follow the layer's size), per-point corner radii, fixed grid tracks, image tile scales and glass effects. Tests: `fig::tests::a_scaled_instance_draws_its_layers_at_the_factor` and `fig::scale_factor_tests`. Numbers unchanged | diff --git a/docs/gaps.md b/docs/gaps.md index d84705d27..c7d995a60 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (gap 24: code blocks from the toolbar and the `` ` `` key, a language menu and width-only edge handles (#2237); gap 7: drop shadows of opaque shapes are cast from their outline, where they show, at the resolution their blur needs; gap 7: a clipping frame that takes in the whole pixmap costs no layer, mask or copy; gap 7: a patch goes into the kept canvas image row by row; gap 7: the browser build compiles the rasteriser for speed; gap 7: a moved point redraws its vector around it only; gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: 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; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; 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; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-28 · **Change:** minor (gap 7: the browser uploads only what an edit changed of the canvas image; gap 24: code blocks from the toolbar and the `` ` `` key, a language menu and width-only edge handles (#2237); gap 7: drop shadows of opaque shapes are cast from their outline, where they show, at the resolution their blur needs; gap 7: a clipping frame that takes in the whole pixmap costs no layer, mask or copy; gap 7: a patch goes into the kept canvas image row by row; gap 7: the browser build compiles the rasteriser for speed; gap 7: a moved point redraws its vector around it only; gap 24: mind maps from the toolbar and the keyboard (#2226); gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; the local variables JSON carries the file's text styles (`textStyles` in `variable.export`, read back by `variable.import` with their variable bindings re-pointed; a file's own export leaves its text styles alone) (#2173); gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: 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; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; 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; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -287,6 +287,14 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe sixteenth of the pixels first, then refined. With no measure to go by (the first render, another page, a zoom after quick renders), a watchdog thread previews any such render still running after 12 ms (desktop only; the browser renders inline). +- **Landed (2026-11-24):** the browser's canvas uploads only what an edit changed of its image. + Every finished render was converted to a texture image and uploaded whole: after an edit that + redrew a part of the view, all of the view and its margin again, every frame of a drag (37 MB + for a 4112 × 2292 view). The retained renderer says where a patched image differs from the one + before (`Retained::patched`; nothing after a full render or a pan, which moves every pixel), + the browser's worker numbers its images and is told which one the canvas's texture holds, and + a render that only patches that image hands over the patches, put on the texture in place. The + desktop's render thread hands over whole images, as before. - **Landed (2026-11-24):** a moved point redraws its vector around it only. A point dragged in the vector editor changed the vector, so its whole box was drawn again; zoomed to the vector, as the editor does, that is most of the view, past the share a patch may cover (60%), and every frame of @@ -463,7 +471,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed:** extended collections (`library.extendCollection`: a library collection's modes and variables in a collection of this file, values overridden per mode with reset, following library updates, variables of its own), variables import/export (`variable.export` / `variable.import`: - the REST local variables JSON, merged by name; CSS custom properties), gradient stops and variant + the REST local variables JSON, merged by name, with the file's text styles under `textStyles`; CSS custom properties), gradient stops and variant properties bound to variables. - **Landed (2026-10-12):** variables a library adds to a collection this file extends are a library update of their own (`library.updates` lists them by name, without an `id` until they have a @@ -530,6 +538,12 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe - **Landed (2026-10-24):** files dropped on the canvas, the Pages list and the Assets panel no longer edit the design in Dev Mode (a dropped document still opens as a file of its own, and the Pages list only opens pages). +- **Landed (2026-11-14):** Uno Platform C# Markup for layers: `inspect.code {language: uno}` writes frames with horizontal, vertical or + grid auto layout (`AutoLayout`, `Grid`; sizing per axis, absolute children, first-on-top order), frames without auto layout + (`Border` with a `Canvas`, one warning per view), groups, rectangles, ellipses, text (also mixed styles, with the half-leading of + explicit line heights), vectors and booleans as `Path` data, and PNG assets for what a path cannot draw. Children are added with + `Children.Add` / `Child =`. Still to do: wrapping layouts (`FlexPanel`, needs Uno Toolkit 10), variables as theme resources, + components, variants and code connect for Uno, a folder export that writes the asset files. - **Landed (2026-10-30):** `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file, so code owners keep them with the code and publish them from CI ([cli.md](cli.md)). @@ -654,6 +668,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| | 2026-11-28 | minor | Gap 24: code blocks from the toolbar's Text tools flyout and the `` ` `` key (`tool.codeBlock`), a language menu in the bar over a selected block, and handles on a block's left and right edges only (#2237, step 2); highlighting landed earlier the same day, so the line numbers and `.jam` import are what is missing. | +| 2026-11-24 | minor | Gap 7: after an edit the browser converts and uploads only the redrawn areas of the canvas image to its texture, not all of it. Numbers unchanged | | 2026-11-24 | minor | Gap 7: a point moved in the vector editor redraws the segments that moved and their neighbours, not the vector's whole box (a full render of the view when the vector fills it). Numbers unchanged | | 2026-11-24 | minor | Gap 7: the browser build compiles tiny-skia, tiny-skia-path and figcraft-render at opt-level 3 (the rest stays at "z" for the size gate): a full render of a close-up view took 117 ms where it took 296 ms in a 0.18.1 build; the bundle grows by about 0.2 MB. Numbers unchanged | | 2026-11-24 | minor | Gap 7: a re-rendered area is copied into the kept canvas image row by row, not cut out and drawn (16.9 → 2.8 ms a frame for a 4.7 megapixel patch of flat fills, one thread). Numbers unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index 35358f49d..10350d628 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -70,8 +70,9 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: and correct, for example `automation path rejected: /etc/x.png is outside the folders that may be written: /work/project/out`. Nothing is written and the server keeps serving. - Read and write authority are separate. With only `--automation-read-root` nothing can be written - to disk (`export` and the export commands without a `path` still return the bytes). Without either - flag nothing changes. + to disk (`export` and the export commands without a `path` still return the bytes). Headless MCP + refuses to start unless both `--automation-read-root` and `--automation-write-root` are supplied. + Attached MCP takes neither flag; the attached app's roots govern its file access. - The roots must be existing folders: a missing one, or a file, stops the server at startup. `initialize`'s `instructions` name the folders, so the agent knows where it may work. - **What is covered:** everything a call does, because the engine reaches the file system through @@ -102,16 +103,42 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: refused too. A local volume's `\\?\Volume{…}\` path is let through. A link whose text is a native NT name (`\Device\…`, `\??\…`, `\GLOBAL??\…`) is refused as a device path, and so is a name that ends in a period or a space, in a path or as a link's target, since Windows trims it where it looks a name up. -- **The network:** a confined call reaches no FigCraft or plugin server, so it can't send a - document anywhere through one. Hosting, joining, publishing and sharing a file (`collab.host`, - `collab.join`, `collab.publish`, `collab.share` …), team libraries on a server (`library.check` - refuses, and `library.updates` / `library.list` report the refusal for each instead of the last - version fetched) and plugin directories are refused with `automation roots are set: commands - don't reach the network …`. The app started with the flags confines its own window too, so its - sharing is off as well. One exception: a root on a network share (a UNC path such as - `\\server\share\…`, or a mounted network drive) is still a root, so reading and writing inside - it reaches that file server, and saving there sends the document to it. Give only roots you would - let the agent's files go to. +- **The network:** confined calls cannot reach a FigCraft or plugin server, except for headless + MCP's `collab.join` to a server explicitly allowed with `--automation-allow-server` (below). + Hosting, publishing and sharing a file (`collab.host`, `collab.publish`, `collab.share` …), team + libraries on a server (`library.check` refuses, and `library.updates` / `library.list` report the + refusal for each instead of the last version fetched) and plugin directories remain refused with + `automation roots are set: commands don't reach the network …`. The app started with the flags + confines its own window too, so its sharing is off as well. One exception: a root on a network + share (a UNC path such as `\\server\share\…`, or a mounted network drive) is still a root, so + reading and writing inside it reaches that file server, and saving there sends the document to + it. Give only roots you would let the agent's files go to. +- **Joining one approved server (headless only):** add one or more + `--automation-allow-server wss://figcraft.example.com/` flags. Each URL must be a `ws://` or + `wss://` server address with no query or key. A join link is accepted only when its parsed + scheme, host and port match an allowed server and its path is within that server's path prefix. + The only newly permitted network operation is `collab.join` to such a server. Hosting, publishing + a new file, team libraries and plugin directories remain blocked; the server's administrative + key is not needed or accepted in the allowlist. Without this flag the network remains blocked, + as before. + + This lets an agent join a file that was published once from the desktop app. Give headless MCP + the file's **edit link**, then call `collab.join` with it. The server-hosted document is the shared + source of truth: the agent's edits sync to the server and other clients in the live session, and + the server keeps confirmed edits after everyone disconnects. A later headless MCP process can + join again with the same link. The desktop app does not need to stay open on the publishing + machine. A local `.figcraft` file is not automatically kept in sync; use `file.saveAs` to save a + separate local snapshot inside a write root when needed. + + For example: + + ```sh + figcraft-cli mcp --automation-read-root /work/designs --automation-write-root /work/designs \ + --automation-allow-server wss://figcraft.example.com/ + ``` + + The edit link is a file-specific secret; give it only to the agent and clients you trust. Use an + edit link, not a view link, when the agent must change the file. - Not confined: the app's own folders, which no tool names (preferences, Data Recovery copies, plugins installed from a plugin directory, the system fonts). - `--attach` with either flag is a usage error: the app runs the commands, so only the app can @@ -1422,13 +1449,13 @@ Dart constants for Flutter (`format: "dart"`: an `abstract final class` per coll default mode's named after the collection and the others after the collection and the mode, with a `static const` `Color`, `double`, `String` or `bool` per variable; names become camelCase Dart identifiers kept apart, aliases are resolved to their value in that mode), and -returns `{text}` (or writes `path` and returns `{path}`). `variable.import {variables}` (an object, +returns `{text}` (or writes `path` and returns `{path}`). The JSON format also carries a top-level `textStyles` array beside `meta`, a FigCraft extension (the REST `styles` metadata has no values): each entry is what `style.list {type: "text"}` returns (`name`, `style`, `paragraph`, and `bound` holding the ids `meta.variables` is keyed by, which it holds only for the variables of the exported local collections, so a file's own export with `collections` left out of it names variables its `meta` lacks, and an import keeps such a binding on the style it replaces; an entry's `style` keys are snake_case and its `bound` keys camelCase, `bound.fontSize` binding `style.font_size`); CSS, Tailwind and Dart are variables only. `variable.import {variables}` (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) reads one back: a collection joins this file's collection of the same name (values matched by mode name, new modes and variables added, a same-named variable of another type skipped with a warning; library copies and extended collections are never targets), others are -added; aliases are checked for loops; it returns `{collections, variables, updated, warnings}`, +added; aliases are checked for loops; a `textStyles` array is read too (a style joins this file's text style of the same name, others are added; bindings follow the imported variables; one to a variable the JSON lacks (unless the style it replaces already holds that id), to a field the style lacks or to a variable of another type is dropped with a warning; at most 10,000 styles and 32 bindings each are read); it returns `{collections, variables, updated, styles: {added, updated}, warnings}`, with a warning when the JSON holds no variables (`no variables found: expected meta.variables …`) or fewer than its collections list in `variableIds`. The Variables editor's Import… and Export… buttons do the same through file dialogs. @@ -1928,6 +1955,34 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path are snake_case, Dart enum members lowerCamel; names that would shadow framework types get one too, `Text` → `TextComponent`). `inspect.componentCode {id?, language?}` returns the parts: `{component, name, set, properties: [{name, param, type, default, value? (instances)}], definition, usage? (instances)}`. +- **Uno C# Markup:** `inspect.code {id, language: uno}` (aliases `csharp-markup`, `cs-markup`) writes the layer and its subtree as a + `UserControl` class (file-scoped `namespace MyApp;`, the class named after the layer plus `View`, internal) whose constructor builds the + tree with Uno C# Markup (`Uno.Extensions.Markup`) and ends with `Content = root;`. Each element is a local with fluent property setters; + its children are added with `parent.Children.Add(child)` or `parent.Child = child`, never the fluent `.Children(…)` / `.Child(…)`, + whose load time doubles with every level of nesting. A frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes + the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`, `Opacity`) with `Orientation`, `Spacing`, `Padding` (less + the stroke weight unless the layout includes strokes; where a side would go negative the border sits behind the layout in a `Grid`), + `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; space around and evenly are written as space between, baseline alignment + and a wrapping layout are `// not mapped: …` notes (a wrapping layout is one line). Children are sized per axis: fixed writes `Width` / + `Height`, hug writes none, fill stretches with `.AutoLayout(primaryAlignment:, counterAlignment:)`, `MinWidth` / `MaxWidth` / `MinHeight` + / `MaxHeight` go on the child; a child that ignores the layout is `.AutoLayout(isIndependentLayout: true)` at its offset as a `Margin` + (a hugging parent with one is written at its current size), and "first on top" is a descending `.Canvas(zIndex: n)`. A grid is a `Grid` + with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars: fractional shares are scaled up to a factor of 100 or + rounded with a note; at most 64 tracks per axis), `ColumnSpacing` (the layout's gap) and `RowSpacing` (its cross gap), and each child in + its cell with `.Grid(row:, column:, rowSpan:, columnSpan:)` and its alignment in the cell. A frame without auto layout, a group or a + rectangle is a `Border` holding a `Canvas` whose children carry `.Canvas(left:, top:)`, with a stroke and children a `Grid` with the + border behind; one `// warning:` comment above the root counts such frames. Text is a `TextBlock` (`FontFamily`, `FontSize`, + `FontWeight`, `FontStyle`, `Foreground`, `LineHeight`, `CharacterSpacing` in thousandths of an em, `TextAlignment`, `TextWrapping`, + `TextTrimming`, `MaxLines`, `TextDecorations`; case is applied at run time; style runs are `Inlines` of `Run`s); an explicit line height + moves it down by the half-leading `(L - (ascent + descent) / upem * size) / 2` of the face FigCraft draws with (a top padding and a + negative bottom margin in a panel, the offset in a `Canvas`), so the code depends on the fonts installed where `inspect.code` runs; + with the family missing it is a note; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`, with no shift. Vectors, booleans and shapes are a + `Microsoft.UI.Xaml.Shapes.Path` with `Data("F1 M …")` (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid `Fill` and one + solid `Stroke`; gradients, several fills or strokes, effects and bigger outlines are an `Image` on `ms-appx:///Assets/.png` with a + comment to export it. Image fills are an `ImageBrush` on `.png` (names lowercase ASCII, unique in the snippet; the files are not + written). Shadows, blurs, blend modes, masks, gradients beyond the first stop, pattern fills, stroke alignment other than inside, + corner smoothing and arcs are `// not mapped: …` comments. Components and instances are written as the frames they are; + `inspect.componentCode` and code connect do not take `uno` yet. - **Code connect:** link a component (a variant links its set) to the code component it is built as, per language (`react`, `leptos`, `vue`, `swiftui`, `compose`, `arkui`, `flutter`): `codeConnect.set {id?, language?, importPath?, name?, template?}` (undoable; fields left out keep their value; the defaults are the generated diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 265b026e2..6e052d6e9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-27 · **Change:** minor (M8, #2631: a sharp drop shadow under a stroked layer, text included, is one solid silhouette with no light outline along the layer's edge; M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-28 · **Change:** minor (M8, #2664: an image shown at half its pixels or fewer, on the canvas and in exports, blends its fine detail instead of showing moiré; M8, #2631: a sharp drop shadow under a stroked layer, text included, is one solid silhouette with no light outline along the layer's edge; M8, #2635: an opaque inside or outside stroke meets the background and the fill with no light fringe or gap at its edges; mind maps from the toolbar and the keyboard: Shapes ▸ Mind map places one with a click, Cmd/Ctrl+Enter adds a child and Shift+Cmd/Ctrl+Enter a sibling, Tab goes to the next sibling (#2226); M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing; points align and distribute in vector edit mode as in Figma: the six Align commands, the keys Alt+A/H/D/W/V/S, and Distribute horizontal and vertical spacing act on the selected points, each moving along one axis to their box's edge or centre line, spaced evenly between the outermost for distribute, with the alignment row first in the Design panel (#2109); gap 6: the browser build uses team libraries and plugin directories on a server; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename; Align is unavailable in an auto layout frame's flow; the Scale tool pivots on the opposite handle; Paste over selection puts copies above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271); 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps centre in a section or frame without a place, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); a variable group renamed to a path with `/` nests (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); releases FigCraft v0.18.0 and v0.18.1; the 2026-10-17 menu measurement (212 / 212) and every percentage and hour stand, not re-measured) · **Target:** Figma Design (desktop app 126.10.7, macOS) The authoritative assessment of how close FigCraft is to Figma Design. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu checklist is @@ -630,7 +630,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th toolbar with flyouts and mode switcher, Design / Prototype / Inspect panels (Dev Mode: properties with their styles and variables, annotations with pinned properties and categories drawn as coloured callouts on the canvas (filtered by category), a ready-for-dev list, a focus view on one frame with previous / next, Compare changes since a frame - was marked ready (before / after side by side or overlaid, property-level diffs), CSS/HTML/React/Vue/Leptos/SwiftUI/Compose/ArkUI/Flutter + was marked ready (before / after side by side or overlaid, property-level diffs), CSS/HTML/React/Vue/Leptos/SwiftUI/Compose/ArkUI/Flutter/Uno C# Markup code where components take their properties as parameters and instances are calls, components connected to their code components showing the real snippet, read-only plugins), colour picker (HSB square, hue/alpha, hex, gradient stops, image fills), main menu generated from the catalog, @@ -653,6 +653,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M8, #2664: an image fill shown at half its pixels or fewer (a 0.5x export, the canvas zoomed out) turned fine detail, a knitted sweater, into strong moiré bands: the image was sampled straight at the small size, a few source pixels per output pixel, with nothing averaging the rest. Wherever an image shows at half its size or less, it is now drawn from a copy averaged down to under twice the size it shows at (the image halved, or the canvas's smaller copy halved, cached with the decoded images), so each output pixel blends every pixel it covers. Every smaller copy now averages the finished pixels, premultiplied and after the image's adjustments: averaging first darkened the edges of transparent areas and changed the colours of adjusted images (exposure and the rest clamp), which the canvas's smaller copies did before. A copy is placed where the image itself would be, so a thin image keeps its box (each side of a copy rounds apart), and an image squeezed on one axis (by its crop or its layer) keeps the pixels its other axis shows. Images shown larger draw as before (magnified pixels too). Canvas, PNG, JPG and WebP exports and the paints PDF export rasterises (images PDF and SVG embed are scaled by the viewer); tiled images still draw from the image itself. Tests: `downscaled_image_tests::an_image_shown_at_half_its_size_or_less_blends_its_fine_detail_evenly` (fails on main), `an_adjusted_image_shown_smaller_averages_its_adjusted_pixels`, `a_transparent_image_shown_smaller_keeps_its_colour`, `a_thin_image_shown_smaller_still_fills_its_box`, `a_crop_stretching_one_axis_keeps_the_pixels_that_axis_shows` and `a_layer_squeezed_on_one_axis_keeps_the_pixels_its_other_axis_shows`. | | 2026-11-27 | patch | M8, #2631: a drop shadow under a layer with an outside stroke (text especially, a black stroke over a black shadow) showed a light outline along the layer's edge wherever that edge lay over the shadow, in a letter's counters too. Hiding the shadow behind the layer cut the layer's share of each anti-aliased edge pixel out of the shadow, then the layer's own edge pixel drew that share again over what was left, counting the edge twice. The shadow now keeps, at each pixel, its part outside the layer, scaled by what the layer lets through there, so an opaque edge sits on a full shadow and a translucent fill still hides it. What the shadow is cast from and hidden behind follows what the layer fills (the fill out to the middle of an opaque inside or outside stroke, #2635), and stroked text casts and hides its shadows by its glyph outlines and stroke too (it fell back to its pixels). Canvas, PNG and PDF; SVG text with a stroke now cuts its shadow out behind it as other layers do. Test: `shadow_silhouette_tests::a_sharp_shadow_under_a_stroked_layer_has_no_light_line_along_the_layers_edge` (fails on main). | | 2026-11-27 | patch | M8, #2635: a stroked layer showed a thin light line along the outer edge of an inside stroke (the fill under the stroke's anti-aliased edge showed through it), and what lies behind showed between an outside stroke and the fill. Where the stroke hides what is under it (its top paint an opaque solid colour, normal blend, one weight all round, no dashes, width profile or brush), the fill now reaches the middle of the stroke, so neither edge has the fill or the background showing through: rectangles, frames and ellipses by their inset or grown outline, other shapes and text by their outline less or plus the centred stroke. Translucent, gradient and image strokes and even-odd outlines fill as before. Test: `stroke_fringe_tests::an_opaque_stroke_shows_nothing_lighter_than_its_dark_neighbour_at_either_edge` (fails on main). | | 2026-11-19 | patch | M4, #2405: Outline stroke (Cmd/Ctrl+Alt+O) on a text without a stroke turns its glyphs into a vector filled as the text was, with its colour style, in place, instead of doing nothing. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 54a4e08a9..b114ceecf 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -212,6 +212,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-28 | patch | M3, #2507: Cmd/Ctrl+L with nothing selected copied nothing. It now copies the link of the page shown (`figcraft://node/`, what the pages list's Copy link to page copies), with the same "Link copied" toast; with a selection it still copies the selected layer's link. Test: `context_menu_tests::cmd_l_with_nothing_selected_copies_the_pages_link` | | 2026-11-28 | patch | M12, #2641: the Pencil (and the board's Marker, Highlighter and Eraser) showed a crosshair. Its cursor is now the ink's tip: a dot in the colour its stroke takes there, as wide on screen as the stroke, ringed white and dark; the Eraser's is a ring of its reach. Tests: `cursor_tests::each_tool_has_its_cursor_by_modifier_and_what_is_under_the_pointer`, `cursors_tests::the_ink_tools_show_a_dot_in_the_inks_colour_and_width`. | | 2026-11-28 | patch | M12, #2237: the code block tool takes the `` ` `` key on boards (`tool.codeBlock`), pinned like the other board tool keys (60 undocumented bindings). Test: `shortcut_parity_tests::counts_match_the_docs`. | | 2026-11-28 | patch | M4, #2338: superscript and subscript were the layer's, so a footnote marker such as the "(1)" in "$29/month(1)" couldn't be raised alone. Each character now has a position (none, superscript, subscript): `textPosition` on `text.style` (with `start`/`end`) and `node.set`, and Type settings ▸ Details ▸ Position sets the selected characters while editing, else whole layers, and shows theirs. A character's position wins over the layer's `sups` / `subs`, which move onto the characters the first time a position is set, so a range set to none sits on the line. Text styles keep it (`position` in a style's definition; a style that sets none leaves the characters' own, so older styles don't drop a raised marker), inspect reports `textPosition` and its CSS `vertical-align: super` or `sub`, and `.fig` export warns that it was left out. Tests: `text_behaviour_tests::a_range_of_characters_is_raised_or_lowered_on_its_own`, `typography::variable_tests::details_position_sets_superscript_subscript_or_neither`. |