diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..6917bde73 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,29 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ci.yml': [] + '.github/workflows/freebsd.yml': [] + '.github/workflows/house-rules.yml': [] + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nix.yml': [] + '.github/workflows/packaging-lint.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/release.yml': [] + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/windows-arm64.yml': [] +dependencies: + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 000000000..e630c9a8f --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 0a91cc050..f442059bb 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -30,10 +30,10 @@ jobs: runs-on: windows-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Install the pinned packaging toolchain diff --git a/AGENTS.md b/AGENTS.md index e63e92c7c..cc4ea91e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ inspection. It runs natively on macOS, Windows, Linux and FreeBSD, and in the br Siblings: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop-class), `../designcraft` (InDesign-class) and the other Crafting Apps; same conventions. -Repos don't share code. +Share reusable code through craft-libs; do not depend on sibling application crates. ## Start every session here 1. Read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, estimates) and @@ -182,3 +182,7 @@ commit. Grade by behaviour against the incumbent, not by whether a menu item exi - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. diff --git a/Cargo.lock b/Cargo.lock index 37e09b205..879856783 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -253,7 +253,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -1011,6 +1011,53 @@ name = "craft-docpath" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" +[[package]] +name = "craft-fig" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +dependencies = [ + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", + "craft-kiwi", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", + "flate2", + "kurbo", + "ruzstd", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-figcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee#976eb51c59edb0a37f24105850f52d921c8518ee" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee)", + "serde", + "serde_json", + "thiserror 2.0.21", + "zip 9.1.1", +] + +[[package]] +name = "craft-figma-rest" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-figma-rest" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" @@ -1076,6 +1123,11 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-kiwi" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" + [[package]] name = "craft-menu" version = "0.1.0" @@ -1089,6 +1141,17 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-penpot" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a)", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-quit" version = "0.1.0" @@ -1111,6 +1174,18 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "craft-sketch" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd)", + "kurbo", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1158,6 +1233,14 @@ dependencies = [ "zip 9.1.1", ] +[[package]] +name = "craft-vectordrawable" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +dependencies = [ + "kurbo", +] + [[package]] name = "craft-web-api" version = "0.1.0" @@ -1186,6 +1269,55 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=064afccce82b01cbf85da5e265bcf897553bea2a#064afccce82b01cbf85da5e265bcf897553bea2a" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee#976eb51c59edb0a37f24105850f52d921c8518ee" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ff142b3ad58aa7306676749428f4f2f9b277b5dd#ff142b3ad58aa7306676749428f4f2f9b277b5dd" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.1", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -1376,7 +1508,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1718,7 +1850,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1935,6 +2067,11 @@ dependencies = [ name = "figcraft-format" version = "0.18.1" dependencies = [ + "craft-fig", + "craft-figcraft-format", + "craft-figma-rest 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)", + "craft-penpot", + "craft-sketch", "figcraft-doc", "figcraft-layout", "figcraft-pathops", @@ -2068,6 +2205,7 @@ name = "figcraft-svg" version = "0.18.1" dependencies = [ "base64 0.22.1", + "craft-xml", "figcraft-color", "figcraft-doc", "figcraft-geom", @@ -2129,6 +2267,7 @@ dependencies = [ name = "figcraft-vectordrawable" version = "0.18.1" dependencies = [ + "craft-vectordrawable", "figcraft-color", "figcraft-doc", "figcraft-geom", @@ -3885,7 +4024,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4581,7 +4720,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4638,7 +4777,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5207,10 +5346,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -6334,7 +6473,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 0d6e387ad..82831e556 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ rust-version = "1.95" repository = "https://github.com/storytold/figcraft" [workspace.dependencies] +craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } +craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } # internal figcraft-geom = { path = "crates/geom" } figcraft-color = { path = "crates/color" } @@ -56,6 +58,17 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9ae # Where the settings live: the suite's folder rules, portable mode included (craft-libs). craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } +# Penpot export container only; JSON values cross this boundary, not shared model types. +craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "064afccce82b01cbf85da5e265bcf897553bea2a" } + +# The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of +# a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share +# types, so they stay on one rev; they share none with the crates above. +craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "ff142b3ad58aa7306676749428f4f2f9b277b5dd" } +craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } +craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "976eb51c59edb0a37f24105850f52d921c8518ee" } +craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" } + # foundation kurbo = { version = "0.13", features = ["serde"] } thiserror = "2" diff --git a/ROADMAP.md b/ROADMAP.md index 54921fb11..fc03c5385 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-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (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) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (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 @@ -365,6 +365,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| +| 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 | 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-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged | diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index 4696b8664..b8372ece4 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result { /// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1. fn attach(s: &str) -> Result { - if s.contains(':') { + if let Some((host, port)) = s.rsplit_once(':') { + if host.is_empty() || port.parse::().is_err() { + return Err(ValueError::Attach); + } return Ok(s.to_owned()); } let port: u16 = s.parse().map_err(|_| ValueError::Attach)?; @@ -461,6 +464,12 @@ mod tests { assert_eq!(a.attach.as_deref(), Some("127.0.0.1:7979")); let Command::Mcp(a) = ok(&["mcp", "--attach=localhost:7979"]) else { panic!("mcp") }; assert_eq!(a.attach.as_deref(), Some("localhost:7979")); + for address in ["127.0.0.1:7979", "[::1]:7979", "[fe80::1%3]:7979", "localhost:0"] { + let Command::Mcp(a) = ok(&["mcp", "--attach", address]) else { panic!("mcp") }; + assert_eq!(a.attach.as_deref(), Some(address)); + } + let Command::Mcp(a) = ok(&["mcp", "--attach", "0"]) else { panic!("mcp") }; + assert_eq!(a.attach.as_deref(), Some("127.0.0.1:0")); let Command::Mcp(a) = ok(&["mcp", "--attach", "7979", "--timeout", "300"]) else { panic!("mcp") }; assert_eq!(a.timeout, Some(300)); let Command::Mcp(a) = ok(&["mcp", "--automation-read-root", "in", "--automation-write-root", "out"]) else { panic!("mcp") }; @@ -514,6 +523,11 @@ mod tests { (&["perf", "--layers", "10,x"], ValueValidation), (&["perf", "--layers", "10", "--layers", "20"], ArgumentConflict), (&["mcp", "--attach", "notaport"], ValueValidation), + (&["mcp", "--attach", ":7979"], ValueValidation), + (&["mcp", "--attach", "localhost:"], ValueValidation), + (&["mcp", "--attach", "localhost:notaport"], ValueValidation), + (&["mcp", "--attach", "localhost:65536"], ValueValidation), + (&["mcp", "--attach", "[::1]"], ValueValidation), (&["mcp", "--attach", "7979", "--timeout", "0"], ValueValidation), (&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation), (&["mcp", "--timeout", "300"], MissingRequiredArgument), @@ -543,6 +557,7 @@ mod tests { &["export", "x.figcraft", "-o", "out", "--help"], &["export", "-o", "--help"], &["mcp", "--attach", "notaport", "--help"], + &["mcp", "--attach", "localhost:notaport", "--help"], &["mcp", "--bogus", "-h"], &["--no-system-fonts", "plugin", "publish", "--bogus", "--help"], ] { diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs index 165057086..5f4a006f4 100644 --- a/apps/figcraft-cli/src/files.rs +++ b/apps/figcraft-cli/src/files.rs @@ -12,7 +12,7 @@ use crate::{CliError, CliResult}; /// A document's or plugin's text as a terminal should show it: control characters escaped, and /// everything else (quotes, backslashes in paths) left as it is. -fn plain(text: &str) -> String { +pub(crate) fn plain(text: &str) -> String { text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect() } @@ -242,7 +242,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult { fn sanitize(name: &str) -> String { let s = figcraft_engine::cmd::file::safe_file_name(name); let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace()); - if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() } + let cap = |s: &str| s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect::(); + // Truncation can expose a device name; its escape must still fit the limits. + let s = figcraft_engine::file_access::escape_device_names(&cap(s)); + if s.is_empty() { "layer".into() } else { cap(&s) } } /// What `export` exports and how. @@ -543,6 +546,10 @@ mod tests { assert_eq!(sanitize("Home / Hero"), "Home _ Hero"); assert_eq!(sanitize("../.."), "_"); assert_eq!(sanitize(""), "layer"); + assert_eq!(sanitize("CON"), "_CON"); + assert_eq!(sanitize(" .nul.txt. "), "_nul.txt"); + assert_eq!(sanitize("COM1"), "_COM1"); + assert_eq!(sanitize("HomeCON"), "HomeCON"); // The same characters the app's export keeps (#1154): only what file systems refuse goes. assert_eq!(sanitize("Homepage - desktop (live + verbeteringen)"), "Homepage - desktop (live + verbeteringen)"); assert_eq!(sanitize("Q&A, 50% #1 [v2] {x} ~é"), "Q&A, 50% #1 [v2] {x} ~é"); @@ -553,6 +560,16 @@ mod tests { assert_eq!(sanitize(&"\u{1F600}".repeat(100)), "\u{1F600}".repeat(50), "at most 200 bytes, whole characters"); } + #[test] + fn sanitizes_names_that_become_devices_at_the_character_limit() { + assert_eq!(sanitize(&format!("CON{}X", " ".repeat(97))), format!("_CON{}", " ".repeat(96))); + } + + #[test] + fn sanitizes_names_that_become_devices_at_the_byte_limit() { + assert_eq!(sanitize(&format!("NUL{} X", "\u{2003}".repeat(65))), format!("_NUL{} ", "\u{2003}".repeat(65))); + } + #[test] fn default_page_skips_leading_divider() { let mut doc = Document::new("divider"); diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index 2d3596bca..44bdd4520 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -38,14 +38,15 @@ fn main() -> ExitCode { return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2)); } }; + // Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable. match run(cli) { Ok(code) => code, Err(CliError::Usage(msg)) => { - eprintln!("error: {msg}\n\nFor more information, try '--help'."); + eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg)); ExitCode::from(2) } Err(CliError::Failed(msg)) => { - eprintln!("error: {msg}"); + eprintln!("error: {}", files::plain(&msg)); ExitCode::from(1) } } diff --git a/apps/figcraft-cli/tests/it/cli.rs b/apps/figcraft-cli/tests/it/cli.rs index 77d816b60..efc1f0e29 100644 --- a/apps/figcraft-cli/tests/it/cli.rs +++ b/apps/figcraft-cli/tests/it/cli.rs @@ -106,6 +106,22 @@ fn bad_arguments_exit_2_without_panicking() { assert_eq!(out.status.code(), Some(1)); } +#[test] +fn post_parse_errors_escape_terminal_controls() { + let missing = format!("__figcraft_missing_diagnostic_{}_\u{1b}[31m\n.figcraft", std::process::id()); + let failed = ["info", missing.as_str()]; + let usage = ["connect", "publish", "invalid-\u{1b}[31m\n.txt"]; + for (args, expected) in [(&failed[..], 1), (&usage[..], 2)] { + let out = bin().arg("--no-system-fonts").args(args).output().unwrap(); + let error = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(expected), "{args:?}: {error:?}"); + assert!(error.starts_with("error: "), "{args:?}: {error:?}"); + assert!(!error.contains('\u{1b}'), "{args:?}: {error:?}"); + assert!(error.contains(r"\u{1b}[31m\n"), "{args:?}: {error:?}"); + assert!(out.stdout.is_empty(), "{args:?}"); + } +} + /// `--help` / `-h` after a subcommand prints that subcommand's help on stdout and exits 0, as it /// does first (#1155), whatever else is on the line; nothing runs. #[test] diff --git a/contributors/people.toml b/contributors/people.toml index 34f849ed7..03122b978 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -118,3 +118,6 @@ real_name = "Ashok Ram" [people.GiovanniBot] sync_github_name = true + +[people.gmrmad1] +real_name = "Madhav Agarwal" diff --git a/crates/doc/src/client_id_tests.rs b/crates/doc/src/client_id_tests.rs index 94b676c22..da8c6e912 100644 --- a/crates/doc/src/client_id_tests.rs +++ b/crates/doc/src/client_id_tests.rs @@ -112,7 +112,7 @@ fn pages_can_be_inserted_onto_a_page_less_base() { assert!(d.pages.is_empty() && d.node_count() == 0); let p = Node::new( NodeId(C3 | 1), - NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: vec![], prototype: Default::default() }, + NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: vec![], prototype: Default::default(), opening: false }, "P", 0.0, 0.0, diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6a0c2aedf..e0dd356e1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -439,8 +439,13 @@ impl Document { /// Add a page at the end. pub fn add_page(&mut self, name: &str) -> NodeId { let id = self.alloc_id(); - let node = - Node::new(id, NodeKind::Page { background: Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default() }, name, 0.0, 0.0); + let node = Node::new( + id, + NodeKind::Page { background: Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default(), opening: false }, + name, + 0.0, + 0.0, + ); self.nodes.insert(id, Arc::new(node)); self.dirty.touch(id); self.pages.push(id); @@ -1350,6 +1355,8 @@ mod proto_overlay_anchor_tests; #[cfg(test)] mod tests; #[cfg(test)] +mod vector_radius_tests; +#[cfg(test)] mod vector_regions_tests; #[cfg(test)] mod width_sides_tests; diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 719549c96..35279aae4 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -312,7 +312,7 @@ impl Document { let id = self.alloc_id(); let node = Node::new( id, - NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default() }, + NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default(), opening: false }, STORE_NAME, 0.0, 0.0, diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index f9601f362..bea172277 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -91,6 +91,10 @@ pub enum NodeKind { flows: Vec, #[serde(default)] prototype: crate::proto::PrototypeSettings, + /// The page chosen to open the file on for everyone (`page.setOpening`; at most one page): + /// saving writes it as the document's `current_page` instead of the page the saver was viewing. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + opening: bool, }, Frame, Group, diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index fd6d48072..768c2f6ee 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -145,6 +145,25 @@ struct Corner { cut2: f64, } +/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the +/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from +/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths. +struct Turn { + v: usize, + r: f64, + s1: usize, + a1: bool, + s2: usize, + a2: bool, + c1: CubicBez, + c2: CubicBez, + u1: Vec2, + u2: Vec2, + angle: f64, + l1: f64, + l2: f64, +} + /// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to /// those ends, and the point it ends at. struct CornerCurve { @@ -391,10 +410,11 @@ impl VectorNetwork { } /// The network with its rounded points drawn in: each sharp point with a corner radius becomes - /// an arc between its two segments (the radius shrinks so the arc fits in half of each - /// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps - /// the rest of its curve, the arc leaving along its direction there. `None` when no point is - /// rounded. + /// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other + /// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose + /// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where + /// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there. + /// `None` when no point is rounded. pub fn rounded(&self) -> Option { self.rounded_smoothed(0.0) } @@ -424,7 +444,9 @@ impl VectorNetwork { *x = true; } } - let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect(); + let turns: Vec> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect(); + let rounds: Vec = turns.iter().map(Option::is_some).collect(); + let corners: Vec = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect(); let mut out = self.clone(); for v in &mut out.vertices { v.radius = 0.0; @@ -558,10 +580,9 @@ impl VectorNetwork { joining.next().is_none().then_some(first) } - /// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments - /// run on smoothly or fold back. With `smoothing`, a point between two straight segments that - /// are both `on_loop` gets a smoothed corner. - fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option { + /// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two + /// segments that neither run on smoothly nor fold back there. + fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option { let r = self.vertices.get(v)?.radius; let [(s1, a1), (s2, a2)] = *incident else { return None }; if !(r > 0.0 && r.is_finite()) || s1 == s2 { @@ -577,6 +598,23 @@ impl VectorNetwork { if !(l1 > 1e-9 && l2 > 1e-9) { return None; } + Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 }) + } + + /// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner + /// there may reach: all of it when the other end stays sharp, half when that end is rounded + /// too (`rounds`, by point) and takes the other half. + fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 { + let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a }); + if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l } + } + + /// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as + /// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point + /// between two straight segments that are both `on_loop` gets a smoothed corner. + fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option { + let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p; + let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds)); let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false); if smoothing > 0.0 @@ -584,7 +622,7 @@ impl VectorNetwork { && is_line(&c2) && closed(s1) && closed(s2) - && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing) + && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing) && let (Some(first), Some(last)) = (curves.first(), curves.last()) { let (a, b) = (first.p0, last.p3); @@ -595,7 +633,7 @@ impl VectorNetwork { let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2); return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) }); } - let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0); + let t = (r / (angle / 2.0).tan()).min(reach); let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2)); // A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between // them and ρ the radius of the circle through both ends (the corner radius between lines). diff --git a/crates/doc/src/vector_radius_tests.rs b/crates/doc/src/vector_radius_tests.rs new file mode 100644 index 000000000..b48414a76 --- /dev/null +++ b/crates/doc/src/vector_radius_tests.rs @@ -0,0 +1,118 @@ +//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the +//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single +//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other. + +use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg}; +use figcraft_geom::{BezPath, Point}; + +use crate::vector::VectorNetwork; + +/// A 100 × 100 square's points: top left, top right, bottom right, bottom left. +const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + +/// A network through `pts` (closed or open) whose points have radii `radii`. +fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork { + let mut n = VectorNetwork::from_points(pts, closed); + for (v, r) in n.vertices.iter_mut().zip(radii) { + v.radius = *r; + } + n +} + +/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight). +fn curves(path: &BezPath) -> Vec { + path.segments() + .filter_map(|s| match s { + PathSeg::Cubic(c) => Some(c), + _ => None, + }) + .collect() +} + +/// Whether `a` and `b` are the same point to within rounding. +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-9 +} + +/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc +/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the +/// circle's radius is `t`), and no other curve. +fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) { + let got = curves(path); + assert_eq!(got.len(), want.len(), "{why}: {got:?}"); + for &(corner, prev, next, t) in want { + let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t; + let (a, b) = (toward(prev), toward(next)); + let center = a + (b - corner); + let mid = center + (corner - center) / (corner - center).hypot() * t; + // Two arcs can share both ends (opposite corners of a square), so the middle picks one. + let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a)); + let passing: Vec = got.iter().filter(ends).map(|c| c.eval(0.5)).collect(); + assert!( + passing.iter().any(|&m| near(m, mid)), + "{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}" + ); + } +} + +#[test] +fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() { + let [tl, tr, br, bl] = SQUARE; + // (radii of [top left, top right, bottom right, bottom left], each arc as (point, its + // neighbours, how far it reaches along both), derivation) + #[allow(clippy::type_complexity)] + let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![ + ([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"), + ([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"), + ([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"), + ([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"), + ( + [0.0, 10.0, 100.0, 0.0], + vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)], + "the segment to the rounded top right is shared, half each, and the shorter room wins", + ), + ( + [100.0, 0.0, 100.0, 0.0], + vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)], + "opposite points share no segment: each reaches its sharp neighbours (a lens)", + ), + ( + [100.0; 4], + vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)], + "every point rounded: a circle, as before", + ), + ]; + for (radii, want, why) in rows { + let net = network(&SQUARE, true, &radii); + assert_arcs(&net.fill_path(), &want, why); + assert_arcs(&net.stroke_path(), &want, why); + // The stored radii stay as they were set. + assert_eq!(net.vertices.iter().map(|p| p.radius).collect::>(), radii.to_vec(), "{why}"); + } +} + +#[test] +fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() { + let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)]; + // (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no + // room from the middle point. + let rows: Vec<([f64; 3], &str)> = + vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")]; + for (radii, why) in rows { + let net = network(&pts, false, &radii); + assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why); + } +} + +#[test] +fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() { + // Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100 + // side (50) would cut smoothing down; the whole side next to sharp points leaves all of it. + let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]); + let path = net.rounded_smoothed(0.6).unwrap().fill_path(); + let ends: Vec = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect(); + for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] { + assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}"); + } + assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}"); +} diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 2fb64a26d..785e6c748 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -1158,10 +1158,12 @@ pub fn prune(doc: &mut Document, library: &str) -> Result<()> { doc.styles.retain(|s| !unused.contains(&s.id)); doc.libraries_mut().styles.retain(|r| !unused.contains(&r.local)); } - // Variables layers bind or set, local variables alias or extend (with what those alias). + // Variables layers bind or set, styles bind, local variables alias or extend (with what those + // alias). let seeds = doc .nodes() .flat_map(|n| n.bound.values().map(String::as_str).chain(action_variables(n))) + .chain(doc.styles.iter().flat_map(|s| s.bound.values().map(String::as_str))) .chain(doc.variables.variables.iter().filter_map(|v| v.extends.as_deref())) .map(str::to_string) .chain( diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 249d3483c..5eba5a506 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40; /// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute /// is refused as well, rather than left to what comes next. fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option { + // Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given. + if has_trimmed_name(path) { + return Some(Unresolved::Linked); + } // Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a // bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes // `..` by name, so `link\..\x` is `x` and never goes through the link. @@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool { /// the way is opened in turn while the path is resolved, and the device behind a name such as /// `LPT1` can be a printer on another computer. fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option { + // A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names. + if is_native_name(Path::new(p)) { + return Some(Refused::Device); + } match craft_docpath::resolve(p, None) { // With a root passed as the document path (what a link would be relative to), a path on // that root's share is allowed. @@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool { let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else { return false; }; - volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}') + let bytes = volume.as_bytes(); + bytes.len() == 44 + && volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) + && volume.ends_with('}') + && bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() }) } /// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`] @@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - Entry::Link(target) => target, }; let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true }; + // Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive, + // and Win32 trims a trailing period or space that the kernel follows as it is. + if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) { + return true; + } // A relative target is relative to the link's folder; an absolute one replaces it. let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path())); return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look); @@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - false } +/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link +/// may hold: no prefix for `std`, yet the system follows it to wherever it names. +fn is_native_name(path: &Path) -> bool { + let bytes = path.as_os_str().as_encoded_bytes(); + [&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| { + bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\')) + }) +} + +/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no +/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names. +fn is_rooted_without_drive(path: &Path) -> bool { + matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\')) +} + +/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up. +fn has_trimmed_name(path: &Path) -> bool { + path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' ')))) +} + /// `p` with its `.` and `..` taken by name, as Windows takes them. fn lexical(p: &Path) -> PathBuf { let mut out = PathBuf::new(); @@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool { matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f)) } +/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a +/// path that resolving would not be allowed to open (on another computer, or a device: see +/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the +/// callers guard against overwriting a file through another name for it, so it counts as the same: +/// the guard keeps asking (a path like that can't be written anyway). A local path outside the +/// roots is compared. pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { let (a, b) = (a.as_ref(), b.as_ref()); - a == b || same_file::is_same_file(a, b).unwrap_or(false) + if a == b { + return true; + } + if let Some(scope) = current() { + let roots = [scope.read.as_slice(), scope.write.as_slice()].concat(); + if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) { + return true; + } + } + same_file::is_same_file(a, b).unwrap_or(false) } /// `p` without Windows' `\\?\` prefix, for messages. @@ -345,6 +397,12 @@ fn device_name(n: &str) -> bool { && stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³'))) } +/// Prefix Windows device-name components of a generated export path with `_`. +/// Apply after character filtering and suffix construction, so a safe suffix stays unchanged. +pub fn escape_device_names(path: &str) -> String { + path.split('/').map(|name| if device_name(name) { format!("_{name}") } else { name.to_string() }).collect::>().join("/") +} + thread_local! { static ROOTS: RefCell>> = const { RefCell::new(None) }; } diff --git a/crates/engine/src/automation/file_access/tests.rs b/crates/engine/src/automation/file_access/tests.rs index d642befb1..ed8449fb7 100644 --- a/crates/engine/src/automation/file_access/tests.rs +++ b/crates/engine/src/automation/file_access/tests.rs @@ -9,6 +9,27 @@ use serde_json::json; use super::{Access, Roots, allow, confined, current}; use crate::Session; +#[test] +fn generated_export_paths_escape_device_components_and_preserve_other_names() { + for (path, expected) in [ + ("CON", "_CON"), + ("CoN.txt", "_CoN.txt"), + ("nul.txt", "_nul.txt"), + ("PRN/icon", "_PRN/icon"), + ("folder/COM1", "folder/_COM1"), + ("LPT9.png", "_LPT9.png"), + ("COM¹", "_COM¹"), + ("LPT²/icon", "_LPT²/icon"), + ("CONIN$", "_CONIN$"), + ("HomeCON", "HomeCON"), + ("COM10", "COM10"), + ("CON@2x", "CON@2x"), + ("folder/.NUL", "folder/.NUL"), + ] { + assert_eq!(super::escape_device_names(path), expected, "{path}"); + } +} + /// A fresh folder for one test: `/figcraft-roots--`, holding `root/`, `root2/` /// (a sibling whose name starts like the root's) and `outside/`. struct Fixture(PathBuf); @@ -229,6 +250,8 @@ fn spellings_of_other_computers_and_devices_are_refused() { r"C:\work\LPT³\x.png", r"C:\work\conout$", r"C:\work\aux:stream", + // A volume name that is not a GUID could be an alias of anything. + r"\\?\Volume{remote}\x.png", // After a name `craft_docpath` refuses for another reason. r"C:\work\a:b\prn.png", ]; @@ -402,6 +425,34 @@ fn a_parent_after_a_link_is_taken_by_name() { assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root"); } +/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the +/// same file as one inside, even when it is another name for it (a hard link outside the roots). +#[test] +fn same_file_does_not_open_a_path_outside_the_roots() { + let f = Fixture::new("same-file"); + let inside = f.p("root/in.txt"); + let outside = f.p("outside/linked.txt"); + if std::fs::hard_link(&inside, &outside).is_err() { + eprintln!("skipped: hard links can't be made here"); + return; + } + assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file"); + let roots = Arc::new(f.rw()); + confined(Some(&roots), || { + assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file"); + if cfg!(windows) { + assert!( + super::same_file(&inside, r"\\192.0.2.1\share\x"), + "a path on another computer is never opened, and counts as the same so that the guard keeps asking" + ); + } + assert!(super::same_file(&inside, &inside), "a path is the same file as itself"); + let other = f.p("root/sub/other.txt"); + std::fs::write(&other, b"other").unwrap(); + assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ"); + }); +} + /// A path on another computer and a device path are refused before anything is opened: resolving /// them made Windows contact the server, which may send it the signed-in user's credentials /// (#1094). Each is refused with a message that only the check before resolving gives: had the @@ -468,6 +519,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() { assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok()); } +/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the +/// rest of the path after it, reaches `\Device\Mup\...`. +#[test] +fn native_names_are_told_with_or_without_the_closing_separator() { + for p in + [r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"] + { + assert!(super::is_native_name(Path::new(p)), "{p}"); + } + for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] { + assert!(!super::is_native_name(Path::new(p)), "{p}"); + } +} + +/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the +/// link's drive, whichever directory it names. +#[test] +fn rooted_link_targets_without_a_drive_are_refused() { + for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] { + assert!(super::is_rooted_without_drive(Path::new(p)), "{p}"); + } + for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] { + assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}"); + } +} + +/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a +/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the +/// others where it looks a name up but not where the kernel follows a link. +#[test] +#[cfg(windows)] +fn native_names_and_names_windows_trims_are_refused_as_written() { + let f = Fixture::new("native-trimmed"); + let r = f.rw(); + if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native")) + || !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed")) + { + eprintln!("skipped: this system doesn't let tests make symbolic links"); + return; + } + let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be"); + // However the system stores the native name, the link is refused. + let native = f.p("root/native/x.png"); + assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}"); + let p = f.p("root/trimmed/x.png"); + let e = r.check(Path::new(&p), Access::Read).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + let p = f.p("root/remote /x.png"); + let e = r.check(Path::new(&p), Access::Write).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device)); +} + #[test] fn a_scope_confines_the_thread_and_ends_with_it() { let f = Fixture::new("scope"); diff --git a/crates/engine/src/batch_step_ref_tests.rs b/crates/engine/src/batch_step_ref_tests.rs index 17d9fc725..e50824edb 100644 --- a/crates/engine/src/batch_step_ref_tests.rs +++ b/crates/engine/src/batch_step_ref_tests.rs @@ -652,3 +652,60 @@ fn a_continue_batch_reports_runtime_errors_and_runs_later_steps() { assert_eq!(results[6]["ok"], true); assert_eq!(s.doc().unwrap().node(s.page().unwrap()).unwrap().name, "Done"); } + +#[test] +fn a_refused_step_names_its_step_and_keeps_its_kind() { + let mut s = Session::new(); + let comp = id(&s.execute("node.create", &json!({"type": "component", "name": "Button", "width": 100, "height": 40})).unwrap()); + let inst = id(&s.execute("instance.create", &json!({"component": comp})).unwrap()); + let before = s.doc().unwrap().clone(); + let undo = s.undo_depth(); + let result = s.execute( + "command.batch", + &json!({"commands": [ + {"command": "node.create", "params": {"type": "rectangle", "parent": inst, "width": 10, "height": 10}} + ]}), + ); + match result { + Err(EngineError::Disabled(cmd, msg)) => { + assert_eq!(cmd, "node.create"); + assert!(msg.starts_with("step 0: "), "{msg}"); + assert!(msg.contains("can't be added"), "{msg}"); + } + other => panic!("expected Disabled, got {other:?}"), + } + assert_eq!(s.doc().unwrap(), &before, "the batch rolled back"); + assert_eq!(s.undo_depth(), undo, "no undo step for the refused batch"); + // Outside a batch the same refusal keeps its kind and says no step. + match s.execute("node.create", &json!({"type": "rectangle", "parent": inst, "width": 10, "height": 10})) { + Err(EngineError::Disabled(_, msg)) => assert!(!msg.contains("step "), "{msg}"), + other => panic!("expected Disabled, got {other:?}"), + } +} + +#[test] +fn an_internal_step_says_which_step_without_changing_kind() { + use crate::derived; + let mut s = Session::new(); + let r = id(&s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap()); + let before = s.doc().unwrap().clone(); + derived::PANIC.with(|p| p.set(true)); + let result = s.execute( + "command.batch", + &json!({"commands": [ + {"command": "node.set", "params": {"ids": [r], "props": {"name": "Renamed"}}} + ]}), + ); + derived::PANIC.with(|p| p.set(false)); + match result { + Err(EngineError::Internal { cmd, msg }) => { + assert_eq!(cmd, "node.set"); + assert!(msg.starts_with("step 0: "), "{msg}"); + } + other => panic!("expected Internal, got {other:?}"), + } + assert_eq!(s.doc().unwrap(), &before, "the panicking step is rolled back"); + // Kinds without a message are left as they are. + assert!(matches!(EngineError::NoNode(figcraft_doc::NodeId(7)).at_step(2), EngineError::NoNode(_))); + assert!(matches!(EngineError::Waiting.at_step(2), EngineError::Waiting)); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 29b0f63a8..00a237c21 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use figcraft_doc::{Document, Effect, ExportSetting, ImageData, LayoutGrid, Node, NodeId, NodeKind}; -use figcraft_geom::Affine; +use figcraft_geom::{Affine, Point}; use serde_json::{Map, Value, json}; use super::{CommandSpec, ok}; @@ -616,7 +616,8 @@ fn delete(s: &mut Session, p: &Value) -> Result { /// Layers duplicated last (Duplicate or Alt-drag) and their copies, in the same order. While the /// copies are the selection, Duplicate places the next copies as far from them as they are from -/// their sources, measured then: so moving the copies first sets the step. +/// their sources, measured then (their move and turn, not their size): so moving or turning the +/// copies first sets the step. #[derive(Clone, Debug)] pub struct Duplicated { pub sources: Vec, @@ -629,9 +630,12 @@ impl Duplicated { !self.copies.is_empty() && set(&self.copies) == set(sel) } - /// The page offset from the sources to the copies, if both are still there and the copies move - /// freely (an auto layout places its own). - fn offset(&self, doc: &Document) -> Option<(f64, f64)> { + /// The step from the sources to the copies, if both are still there and the copies move freely + /// (an auto layout places its own): the mean move of the copies' own centres in the page frame + /// (less what a size change shifts them by), and the turn every copy has over its source (zero + /// unless they all agree, or when a flip differs). A turn is not counted as a move, whether each + /// copy turned about its own centre or the copies turned together about their shared centre. + fn step(&self, doc: &Document) -> Option { let free = self .copies .iter() @@ -639,19 +643,109 @@ impl Duplicated { if !free || self.sources.iter().chain(&self.copies).any(|i| !doc.contains(*i)) { return None; } - let (a, b) = (doc.bounds_of(&self.sources)?, doc.bounds_of(&self.copies)?); - let d = (b.x0 - a.x0, b.y0 - a.y0); - (d.0.is_finite() && d.1.is_finite() && (d.0 != 0.0 || d.1 != 0.0)).then_some(d) + // A flip reads as a half turn and was not measured: never repeat a turn across one. + let flips_differ = self + .sources + .iter() + .zip(&self.copies) + .any(|(s, c)| figcraft_geom::is_flipped(doc.world_transform(*s)) != figcraft_geom::is_flipped(doc.world_transform(*c))); + let turns: Vec = self + .sources + .iter() + .zip(&self.copies) + .map(|(s, c)| { + let d = figcraft_geom::rotation_degrees(doc.world_transform(*c)) - figcraft_geom::rotation_degrees(doc.world_transform(*s)); + let d = d.rem_euclid(360.0); + if d > 180.0 { d - 360.0 } else { d } + }) + .collect(); + let angle = match turns.first() { + Some(first) if !flips_differ && turns.iter().all(|t| (t - first).abs() < 1e-6) => *first, + _ => 0.0, + }; + // Per pair, where the copy's own centre is, less what its size change moved that centre by + // (a growing edge shifts it, in the source's frame), and where the source's centre is. + let mut pairs = Vec::new(); + for (s, c) in self.sources.iter().zip(&self.copies) { + let (sn, cn) = (doc.node(*s)?, doc.node(*c)?); + let (sw, cw) = (doc.world_transform(*s), doc.world_transform(*c)); + let (ps, pc) = (sw * Point::new(sn.width / 2.0, sn.height / 2.0), cw * Point::new(cn.width / 2.0, cn.height / 2.0)); + let grow = Point::new((cn.width - sn.width) / 2.0, (cn.height - sn.height) / 2.0); + let shift_in = |x: Affine| x * grow - x * Point::ORIGIN; + // The order of a turn and a resize isn't recorded. A resize then a turn shifts the centre + // along the source's axes; a turn then a resize, along the copy's. Take the copy's only + // when it alone makes this pair's own move zero: a pure resize plus turn, either order, + // with no move must give no move. Otherwise keep the source's. + let (by_source, by_copy) = (pc - shift_in(sw), pc - shift_in(cw)); + let still = |q: Point| (q.x - ps.x).hypot(q.y - ps.y) < 1e-6; + let corrected = if still(by_copy) && !still(by_source) { by_copy } else { by_source }; + pairs.push((ps, corrected)); + } + // The mean of the residuals, and whether they all agree (the copies fit that reading). + let fit = |res: &[(f64, f64)]| { + let n = res.len() as f64; + let mean = (res.iter().map(|m| m.0).sum::() / n, res.iter().map(|m| m.1).sum::() / n); + let agree = res.iter().all(|m| (m.0 - mean.0).hypot(m.1 - mean.1) < 1e-6); + (mean, agree) + }; + // Reading A, each copy turned about its own centre: the residual is the move of its centre. + let each: Vec<(f64, f64)> = pairs.iter().map(|(ps, pc)| (pc.x - ps.x, pc.y - ps.y)).collect(); + let (mut mv, each_fits) = fit(&each); + // Reading B, the copies turned together about the sources' centre (as a Rotate on several + // layers does): the residual is what is left once each source's centre is turned that way. + // The centre is `turn_centre`, never read from the copies: a turn about another point shifts + // every residual by the same vector, so where the copies are can't say which point they + // turned about. Such a turn reads as this one plus a move. + if angle != 0.0 + && pairs.len() > 1 + && !each_fits + && let Some(c) = turn_centre(doc, &self.sources) + { + let together: Vec<(f64, f64)> = pairs + .iter() + .map(|(ps, pc)| { + let q = figcraft_geom::translation(figcraft_geom::rotate_about(Affine::translate(ps.to_vec2()), c, angle)); + (pc.x - q.x, pc.y - q.y) + }) + .collect(); + let (m, together_fits) = fit(&together); + if together_fits { + mv = m; + } + } + let (dx, dy) = mv; + let step = Step { dx, dy, angle }; + (step.dx.is_finite() && step.dy.is_finite() && step.angle.is_finite() && (dx != 0.0 || dy != 0.0 || angle != 0.0)).then_some(step) } } +/// What Duplicate repeats: a move of the copies' centre in the page frame, then a turn about the +/// centre of the new copies. Size is not part of it. +#[derive(Clone, Copy, Debug)] +struct Step { + dx: f64, + dy: f64, + angle: f64, +} + +/// Where several layers turn, for the step and for its repeat: the centre of their handle box +/// (`selection_box`), the point the Rotate handle and the rotate keys turn a selection about. +/// One layer: its own centre. Several: their bounds centre, or the centre of the box turned +/// with them when they share a rotation. `transform.rotate` without a pivot turns about the +/// bounds centre instead, so its turn of layers that share a rotation repeats as a turn plus +/// a move. +fn turn_centre(doc: &Document, ids: &[NodeId]) -> Option { + let q = crate::tools::selection_box(doc, ids)?; + Some(Point::new(q.iter().map(|c| c.x).sum::() / 4.0, q.iter().map(|c| c.y).sum::() / 4.0)) +} + fn duplicate(s: &mut Session, p: &Value) -> Result { let ids = req_targets("edit.duplicate", s, p)?; let rename = s.prefs.rename_duplicates; let explicit = num(p, "dx").is_some() || num(p, "dy").is_some(); let ds = s.ds()?; let roots_now = z_sorted(&ds.doc, &roots(&ds.doc, &ids)); - let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.offset(&ds.doc)); + let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.step(&ds.doc)); let doc = s.doc_mut()?; let ids = roots_now; let mut out = Vec::new(); @@ -670,7 +764,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { _ => (0.0, 0.0), }; match repeat { - Some((rx, ry)) => super::arrange::move_world(doc, nid, rx, ry)?, + Some(st) => super::arrange::move_world(doc, nid, st.dx, st.dy)?, None => { let nn = doc.get_mut(nid)?; nn.transform = Affine::translate((dx, dy)) * nn.transform; @@ -683,6 +777,14 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { } out.push(nid); } + // A repeated turn is about the new copies' centre: one layer's own, several layers' shared one. + if let Some(st) = repeat.filter(|st| st.angle != 0.0) + && let Some(c) = turn_centre(doc, &out) + { + for nid in out.iter().copied() { + super::arrange::rotate_world(doc, nid, c, st.angle)?; + } + } crate::library::count_inserted(doc, &out); // Board connectors copied with what they join join the copies. let map = crate::board::copy_map(doc, &ids, &out); diff --git a/crates/engine/src/cmd/file/export.rs b/crates/engine/src/cmd/file/export.rs index bbc52e1b5..ac8353c30 100644 --- a/crates/engine/src/cmd/file/export.rs +++ b/crates/engine/src/cmd/file/export.rs @@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator)>, d if out.len() >= MAX_EXPORT_FILES { return out; } - let stem = format!("{base}{}", safe_file_name(&e.file_suffix())); + let stem = crate::file_access::escape_device_names(&format!("{base}{}", safe_file_name(&e.file_suffix()))); let ext = e.format.ext(); let file = (1..).map(|k| if k == 1 { format!("{stem}.{ext}") } else { format!("{stem} {k}.{ext}") }).find(|f| used.insert(f.to_lowercase())); @@ -439,3 +439,31 @@ pub(super) fn export_frames_pdf(s: &mut Session, p: &Value) -> Result { None => Ok(json!({"format": "pdf", "pages": pages, "data": base64::engine::general_purpose::STANDARD.encode(&bytes)})), } } + +#[cfg(test)] +mod filename_tests { + use super::*; + + #[test] + fn export_jobs_escape_device_names_after_suffixes_and_before_numbering() { + let mut doc = Document::new("Export names"); + let page = doc.first_page().unwrap(); + let cases = [ + ("C", "ON", "_CON.png"), + ("_con", "", "_con 2.png"), + ("CON/icon", "", "_CON/icon.png"), + ("Home", "CON", "HomeCON.png"), + ("COM", "1", "_COM1.png"), + ("COM1", "@2x", "COM1@2x.png"), + ]; + let items: Vec<_> = cases + .iter() + .map(|(name, suffix, _)| { + let id = doc.create(page, NodeKind::Frame, name, 0.0, 0.0, 10.0, 10.0).unwrap(); + (id, vec![ExportSetting { suffix: (*suffix).into(), ..Default::default() }]) + }) + .collect(); + let files: Vec<_> = jobs_for(items, &doc).into_iter().map(|job| job.file).collect(); + assert_eq!(files, cases.map(|(_, _, expected)| expected)); + } +} diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rs index 975976537..7cd01c2d2 100644 --- a/crates/engine/src/cmd/file/save.rs +++ b/crates/engine/src/cmd/file/save.rs @@ -85,7 +85,8 @@ impl FileSnapshot { /// files are from its folder. fn encode_at(&self, path: Option<&str>) -> Result> { let mut doc = (*self.doc).clone(); - doc.current_page = Some(self.page); + let opening = doc.pages.iter().copied().find(|&p| matches!(doc.get(p).map(|n| &n.kind), Ok(NodeKind::Page { opening: true, .. }))); + doc.current_page = Some(opening.unwrap_or(self.page)); if let Some(path) = path { crate::library::relate_links(&mut doc, path); } diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 458e7572c..3883c3f39 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -1,7 +1,7 @@ //! Pages. use figcraft_doc::proto::Flow; -use figcraft_doc::{Guide, NodeId, NodeKind}; +use figcraft_doc::{Document, Guide, NodeId, NodeKind}; use serde_json::{Value, json}; use super::{CommandSpec, ok}; @@ -53,9 +53,8 @@ pub fn specs() -> Vec { return Ok(json!({"id": id, "divider": true})); } let ds = s.ds_mut()?; - ds.page = id; + ds.open_page(id); ds.selection.clear(); - ds.zoom_to_fit(); Ok(json!({"id": id})) }), spec!("page.select", "Go to page", "{id | index}", false, |s, p| { @@ -74,10 +73,9 @@ pub fn specs() -> Vec { return Err(bad("page.select", "a divider isn't a page to open")); } let ds = s.ds_mut()?; - ds.page = id; + ds.open_page(id); ds.selection.clear(); ds.text_edit = None; - ds.zoom_to_fit(); ok() }), spec!("page.rename", "Rename page", "{id?, name} (an empty page named with a leading hyphen becomes a divider)", true, |s, p| { @@ -109,8 +107,8 @@ pub fn specs() -> Vec { // The copy keeps the page's colour, flows (pointing at the copied frames), prototype settings and guides. let guides = doc.get(src)?.guides.clone(); doc.get_mut(np)?.guides = guides; - if let NodeKind::Page { background, flows, prototype } = doc.get(src)?.kind.clone() - && let NodeKind::Page { background: b, flows: f, prototype: pr } = &mut doc.get_mut(np)?.kind + if let NodeKind::Page { background, flows, prototype, .. } = doc.get(src)?.kind.clone() + && let NodeKind::Page { background: b, flows: f, prototype: pr, .. } = &mut doc.get_mut(np)?.kind { *b = background; *f = flows @@ -147,6 +145,38 @@ pub fn specs() -> Vec { } ok() }), + spec!( + "page.setOpening", + "Set as opening page", + "{id?} (the page the file opens on, for everyone who opens or joins it; the current page when none is named)", + true, + |s, p| { + // A document property (#1817), so it syncs in a live session and undoes; nobody's + // own page moves (`page.select` is each viewer's). + let id = page_target(s, "page.setOpening", p)?; + if s.doc()?.is_divider(id) { + return Err(bad("page.setOpening", "a divider isn't a page to open on")); + } + let is_opening = |doc: &Document, p: NodeId| matches!(doc.get(p).map(|n| &n.kind), Ok(NodeKind::Page { opening: true, .. })); + if s.doc()?.current_page == Some(id) && is_opening(s.doc()?, id) { + // Already the opening page: nothing changes, so no undo step. + return ok(); + } + let doc = s.doc_mut()?; + doc.current_page = Some(id); + // The flag lives on the page node (so it syncs with the node's kind): one page has it. + for page in doc.pages.clone() { + let want = page == id; + if is_opening(doc, page) != want + && let NodeKind::Page { opening, .. } = &mut doc.get_mut(page)?.kind + { + *opening = want; + } + } + settle(s, "page.setOpening")?; + ok() + } + ), spec!("page.list", "List pages", "{}", false, |s, _| { let doc = s.doc()?; let cur = s.page()?; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 56f4aff27..7edf1372a 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result { } }; let ds = s.ds_mut()?; - ds.page = pg; + ds.open_page(pg); ds.selection.clear(); - ds.zoom_to_fit(); Ok(json!({"page": pg})) } diff --git a/crates/engine/src/collab_live_tests.rs b/crates/engine/src/collab_live_tests.rs index 7b1a08bc2..4788dfd05 100644 --- a/crates/engine/src/collab_live_tests.rs +++ b/crates/engine/src/collab_live_tests.rs @@ -552,3 +552,31 @@ fn leaving_the_session_goes_back_to_snapshot_undo() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().node(r).unwrap().name, "Live"); } + +/// #1817: the page a file opens on is a document property: setting it syncs to the server, so +/// everyone who joins afterwards lands on it, and moves nobody's own view. +#[test] +fn the_opening_page_syncs_and_moves_no_ones_view() { + let mut room = Room::new(base(), 2, 7); + let first = room.server.document().first_page().unwrap(); + let cover = NodeId(room.s(0).execute("page.add", &json!({"name": "Cover"})).unwrap()["id"].as_u64().unwrap()); + room.settle(); + room.check(); + assert_eq!(room.s(1).page().unwrap(), first, "another person's page is their own"); + room.s(0).execute("page.setOpening", &json!({"id": cover})).unwrap(); + room.settle(); + room.check(); + assert_eq!(room.server.document().current_page, Some(cover), "the server's file opens on it now"); + assert_eq!(room.s(1).page().unwrap(), first, "nobody's view moved"); + assert_eq!(Session::with_document(room.server.document().clone()).page().unwrap(), cover, "whoever joins next lands on it"); + // One undo step, the setter's. + assert_eq!(room.s(0).execute("edit.undo", &json!({})).unwrap()["undone"], true); + room.settle(); + room.check(); + assert_ne!(room.server.document().current_page, Some(cover), "undone for everyone"); + assert_eq!( + Session::with_document(room.server.document().clone()).page().unwrap(), + first, + "whoever joins after the undo lands on the restored page" + ); +} diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 3a1f72e50..12dfefe32 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -1,5 +1,7 @@ use super::view_state::ViewState; -use super::{Arc, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit}; +use super::{ + Arc, BTreeMap, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit, +}; /// One undo step. #[derive(Clone, Debug)] @@ -114,6 +116,9 @@ pub struct DocState { /// The file on disk as this tab last read or wrote it: a save refuses to replace what another /// app (figcraft-cli, say) wrote to it since (#1330). pub(crate) on_disk: Option, + /// Where each page's view was left in this session (its centre and zoom; see + /// [`Self::open_page`]; not saved). + page_views: BTreeMap, } /// A version shown on the canvas in place of the document: read-only until it's restored or the @@ -178,6 +183,7 @@ impl DocState { last_duplicate: None, images_left_in_file: None, on_disk: None, + page_views: BTreeMap::new(), }; st.zoom_to_fit(); st @@ -311,6 +317,21 @@ impl DocState { } /// Fit the current page's content (or centre on the origin when empty). + /// Show `page` at the view it was left at in this session, or one that fits its content the + /// first time; the page shown till now keeps its view for when it comes back. The page shown + /// already keeps its view. + pub fn open_page(&mut self, page: NodeId) { + if page == self.page { + return; + } + self.page_views.insert(self.page, (self.view.cx, self.view.cy, self.view.zoom)); + self.page = page; + match self.page_views.get(&page) { + Some(&(cx, cy, zoom)) => (self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom), + None => self.zoom_to_fit(), + } + } + pub fn zoom_to_fit(&mut self) { match self.doc.page_content_bounds(self.page) { Some(b) => self.view.fit(b, 1.0), diff --git a/crates/engine/src/duplicate_spacing_tests.rs b/crates/engine/src/duplicate_spacing_tests.rs index c46ab05c8..0f09a297d 100644 --- a/crates/engine/src/duplicate_spacing_tests.rs +++ b/crates/engine/src/duplicate_spacing_tests.rs @@ -255,3 +255,277 @@ fn duplicate_repeats_a_nudged_step() { let c2 = cmd_d(&mut s); assert_eq!(at(&s, c2), (80.0, 0.0), "the nudge is the step"); } + +fn centre(s: &Session, id: NodeId) -> (f64, f64) { + let c = s.doc().unwrap().world_bounds(id).unwrap().center(); + (c.x, c.y) +} + +fn turn(s: &Session, id: NodeId) -> f64 { + figcraft_geom::rotation_degrees(s.doc().unwrap().world_transform(id)) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +#[test] +fn duplicate_repeats_the_copys_move_and_rotation() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}})); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -15}})); + assert!(near(centre(&s, c1).0, 200.0) && near(centre(&s, c1).1, 50.0)); + for k in 1..=3 { + let c = cmd_d(&mut s); + let (x, y) = centre(&s, c); + let want = 200.0 + 150.0 * f64::from(k); + assert!(near(x, want) && near(y, 50.0), "repeat {k}: centre ({x}, {y})"); + assert!(near(turn(&s, c), -15.0 - 15.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c)); + } +} + +#[test] +fn duplicate_repeats_a_rotation_in_place() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": 30}})); + for k in 1..=3 { + let c = cmd_d(&mut s); + let (x, y) = centre(&s, c); + assert!(near(x, 50.0) && near(y, 50.0), "repeat {k}: centre ({x}, {y})"); + assert!(near(turn(&s, c), 30.0 + 30.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c)); + } +} + +#[test] +fn duplicate_does_not_step_the_size() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}})); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}})); + let c1_centre = centre(&s, c1); + for k in 1..=2 { + let c = cmd_d(&mut s); + let w = s.doc().unwrap().get(c).unwrap().width; + assert!(near(w, 120.0), "repeat {k}: width {w}"); + assert!(near(centre(&s, c).0, c1_centre.0 + 150.0 * f64::from(k)), "repeat {k}: centre {:?}", centre(&s, c)); + } +} + +#[test] +fn duplicate_turns_several_layers_about_their_selection_centre() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + let b = rect(&mut s, 150.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a, b]})); + let out = ex(&mut s, "edit.duplicate", json!({})); + let copies: Vec = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + ex(&mut s, "transform.nudge", json!({"dx": 150, "dy": 0})); + // Turn the pair -15 about its combined centre. + ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": -15})); + let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect(); + let pair_before = s.doc().unwrap().bounds_of(&copies).unwrap().center(); + let again = ex(&mut s, "edit.duplicate", json!({})); + let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + assert_eq!(next.len(), 2); + let after = s.doc().unwrap().bounds_of(&next).unwrap().center(); + assert!(near(after.x, pair_before.x + 150.0) && near(after.y, pair_before.y), "pair centre {after:?}"); + for (i, c) in next.iter().enumerate() { + assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c)); + // Expected: the layer's centre moved +150, then turned -15 about the moved pair's centre. + let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1)); + let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, after, -15.0)); + let got = centre(&s, *c); + assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); + } +} + +#[test] +fn a_deselect_forgets_the_duplicate_step() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}})); + ex(&mut s, "select.none", json!({})); + ex(&mut s, "select.set", json!({"ids": [c1]})); + let c2 = cmd_d(&mut s); + assert_eq!(at(&s, c2), (150.0, 0.0), "no step after a deselect: the copy lands in place"); +} + +#[test] +fn several_uneven_layers_turned_in_place_repeat_the_turn_without_a_move() { + let mut s = Session::new(); + let wide = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap(); + let ids = [rect(&mut s, 0.0, 200.0), wide]; + ex(&mut s, "select.set", json!({"ids": ids})); + let out = ex(&mut s, "edit.duplicate", json!({})); + let copies: Vec = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + for c in &copies { + ex(&mut s, "node.set", json!({"ids": [*c], "props": {"rotation": -45}})); + } + let pivot = handle_box_centre(&s, &copies); + let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect(); + let again = ex(&mut s, "edit.duplicate", json!({})); + let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + for (i, c) in next.iter().enumerate() { + assert!(near(turn(&s, *c), -90.0), "layer {i}: rotation {}", turn(&s, *c)); + // No move: each layer's centre only turned -45 about the copies' shared centre. + let want = + figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, -45.0)); + let got = centre(&s, *c); + assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); + } +} + +/// The uneven pair the collective-turn tests share: a square and a wide one, selected and duplicated. +fn uneven_pair_and_copies(s: &mut Session) -> Vec { + let wide = id_of(&ex(s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap(); + let ids = [rect(s, 0.0, 200.0), wide]; + ex(s, "select.set", json!({"ids": ids})); + let out = ex(s, "edit.duplicate", json!({})); + out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect() +} + +#[test] +fn several_uneven_layers_turned_together_repeat_the_turn_without_a_move() { + let mut s = Session::new(); + let copies = uneven_pair_and_copies(&mut s); + ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 90})); + let pivot = s.doc().unwrap().bounds_of(&copies).unwrap().center(); + let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect(); + let again = ex(&mut s, "edit.duplicate", json!({})); + let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + assert_eq!(next.len(), 2); + for (i, c) in next.iter().enumerate() { + assert!(near(turn(&s, *c).abs(), 180.0), "layer {i}: rotation {}", turn(&s, *c)); + let want = figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 90.0)); + let got = centre(&s, *c); + assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); + } +} + +#[test] +fn several_uneven_layers_moved_and_turned_together_repeat_both() { + let mut s = Session::new(); + let copies = uneven_pair_and_copies(&mut s); + ex(&mut s, "transform.nudge", json!({"dx": 150, "dy": 0})); + ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": -15})); + let pivot = handle_box_centre(&s, &copies); + let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect(); + let again = ex(&mut s, "edit.duplicate", json!({})); + let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + assert_eq!(next.len(), 2); + let moved_pivot = figcraft_geom::Point::new(pivot.x + 150.0, pivot.y); + for (i, c) in next.iter().enumerate() { + assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c)); + let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1)); + let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, moved_pivot, -15.0)); + let got = centre(&s, *c); + assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); + } +} + +#[test] +fn a_widened_copy_turned_in_place_repeats_the_turn_without_a_move() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}})); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -90}})); + let c1_centre = centre(&s, c1); + let c2 = cmd_d(&mut s); + let got = centre(&s, c2); + assert!(near(got.0, c1_centre.0) && near(got.1, c1_centre.1), "centre {got:?} vs {c1_centre:?}"); + assert!(near(turn(&s, c2).abs(), 180.0), "rotation {}", turn(&s, c2)); + assert!(near(s.doc().unwrap().get(c2).unwrap().width, 120.0)); +} + +#[test] +fn a_copy_turned_then_widened_repeats_the_turn_without_a_move() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -90}})); + ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}})); + let c1_centre = centre(&s, c1); + let c2 = cmd_d(&mut s); + let got = centre(&s, c2); + assert!(near(got.0, c1_centre.0) && near(got.1, c1_centre.1), "centre {got:?} vs {c1_centre:?}"); + assert!(near(turn(&s, c2).abs(), 180.0), "rotation {}", turn(&s, c2)); + assert!(near(s.doc().unwrap().get(c2).unwrap().width, 120.0)); +} + +/// The centre of the selection's handle box, which is what the Rotate handle turns about. +fn handle_box_centre(s: &Session, ids: &[NodeId]) -> figcraft_geom::Point { + let q = crate::tools::selection_box(s.doc().unwrap(), ids).unwrap(); + figcraft_geom::Point::new(q.iter().map(|c| c.x).sum::() / 4.0, q.iter().map(|c| c.y).sum::() / 4.0) +} + +#[test] +fn a_turned_pair_turned_again_about_its_handle_box_repeats_without_a_move() { + let mut s = Session::new(); + let wide = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap(); + let ids = [rect(&mut s, 0.0, 200.0), wide]; + ex(&mut s, "transform.rotate", json!({"ids": ids, "degrees": 60})); + ex(&mut s, "select.set", json!({"ids": ids})); + let out = ex(&mut s, "edit.duplicate", json!({})); + let copies: Vec = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + let p = handle_box_centre(&s, &copies); + ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 30, "cx": p.x, "cy": p.y})); + let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect(); + let again = ex(&mut s, "edit.duplicate", json!({})); + let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + assert_eq!(next.len(), 2); + let pivot = handle_box_centre(&s, &next); + for (i, c) in next.iter().enumerate() { + assert!(near(turn(&s, *c), 120.0), "layer {i}: rotation {}", turn(&s, *c)); + let want = figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 30.0)); + let got = centre(&s, *c); + assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}"); + } +} + +#[test] +fn several_uneven_layers_turned_together_repeat_about_one_centre_each_time() { + let mut s = Session::new(); + let mut copies = uneven_pair_and_copies(&mut s); + // Upright, the pair's handle box is its bounds: both centres are (250, 150), so this is also + // the Rotate handle's turn. Turned, the box keeps that centre; the bounds don't. + ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 30})); + let pivot = figcraft_geom::Point::new(250.0, 150.0); + for k in 1..=3 { + let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect(); + let again = ex(&mut s, "edit.duplicate", json!({})); + let next: Vec = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect(); + assert_eq!(next.len(), 2); + for (i, c) in next.iter().enumerate() { + assert!(near(turn(&s, *c), 30.0 + 30.0 * f64::from(k)), "repeat {k}, layer {i}: rotation {}", turn(&s, *c)); + let want = + figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 30.0)); + let got = centre(&s, *c); + assert!(near(got.0, want.x) && near(got.1, want.y), "repeat {k}, layer {i}: {got:?} vs {want:?}"); + } + copies = next; + } +} + +#[test] +fn a_flipped_copy_does_not_repeat_a_half_turn() { + let mut s = Session::new(); + let a = rect(&mut s, 0.0, 0.0); + ex(&mut s, "select.set", json!({"ids": [a]})); + let c1 = cmd_d(&mut s); + ex(&mut s, "object.flipH", json!({"ids": [c1]})); + let c2 = cmd_d(&mut s); + assert!(near(turn(&s, c2), turn(&s, c1)), "rotation {} vs {}", turn(&s, c2), turn(&s, c1)); +} diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index e3f4e79e9..52ca4fb1f 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -43,6 +43,8 @@ impl EngineError { match self { EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: format!("step {step}: {msg}") }, EngineError::Other(msg) => EngineError::Other(format!("step {step}: {msg}")), + EngineError::Disabled(cmd, msg) => EngineError::Disabled(cmd, format!("step {step}: {msg}")), + EngineError::Internal { cmd, msg } => EngineError::Internal { cmd, msg: format!("step {step}: {msg}") }, e => e, } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fc8ab8c4d..3c81b9147 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -460,6 +460,8 @@ mod page_clipboard_tests; #[cfg(test)] mod page_copy_navigation_tests; #[cfg(test)] +mod page_opening_tests; +#[cfg(test)] mod page_target_tests; #[cfg(test)] mod paint_index_tests; @@ -666,6 +668,8 @@ mod widget_shapes_tests; #[cfg(test)] mod widgets_tests; +#[cfg(test)] +mod page_view_tests; #[cfg(test)] mod selection_reorder_tests; #[cfg(test)] diff --git a/crates/engine/src/library_variables_tests.rs b/crates/engine/src/library_variables_tests.rs index bc82f7a94..67a2b2129 100644 --- a/crates/engine/src/library_variables_tests.rs +++ b/crates/engine/src/library_variables_tests.rs @@ -550,3 +550,55 @@ fn stored_variable_ids_keep_library_alias_dependencies() { assert!(copy.values.values().all(|v| *v == VariableValue::Alias(map.variables[target].clone()))); assert!(dest.variables.collections.iter().any(|c| c.name == "Base")); } + +/// A library with collection `coll` (Main/Alt), a colour variable `var` and a paint style `var` +/// bound to it, published to `path`; returns (the library session, its id). +fn styled_library(path: &str, coll: &str, var: &str, main: &str, alt: &str) -> (Session, String) { + let mut lib = Session::new(); + ex(&mut lib, "variable.createCollection", json!({"name": coll, "modes": ["Main", "Alt"]})); + let v = ex(&mut lib, "variable.create", json!({"collection": coll, "name": var, "type": "color", "values": {"Main": main, "Alt": alt}}))["id"] + .clone(); + let style = ex(&mut lib, "style.create", json!({"type": "paint", "name": var, "value": main}))["id"].clone(); + ex(&mut lib, "style.bind", json!({"style": style, "field": "fill", "variable": v})); + let lid = publish_to(&mut lib, path); + (lib, lid) +} + +#[test] +fn accepting_updates_keeps_variables_only_library_styles_use() { + let d = dir("accept-style-vars"); + let (pa, pb) = (path_str(&d.join("a.figcraft")), path_str(&d.join("b.figcraft"))); + let (mut a, la) = styled_library(&pa, "TokensA", "accent", "#1565c0", "#2e7d32"); + let (_b, lb) = styled_library(&pb, "TokensB", "primary", "#7b1fa2", "#00838f"); + + let mut s = Session::new(); + let frame = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 200}))); + let ra = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20, "parent": frame}))); + let rb = idv(&ex(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 20, "height": 20, "parent": frame}))); + ex(&mut s, "library.add", json!({"path": pa})); + ex(&mut s, "library.add", json!({"path": pb})); + ex(&mut s, "library.applyStyle", json!({"library": la, "style": "accent", "id": ra})); + ex(&mut s, "library.applyStyle", json!({"library": lb, "style": "primary", "id": rb})); + ex(&mut s, "library.setVariableMode", json!({"library": la, "collection": "TokensA", "mode": "Alt", "ids": [frame]})); + ex(&mut s, "library.setVariableMode", json!({"library": lb, "collection": "TokensB", "mode": "Alt", "ids": [frame]})); + assert_eq!(fill(&s, ra), "2E7D32"); + assert_eq!(fill(&s, rb), "00838F"); + healthy(&s); + + ex(&mut a, "variable.set", json!({"variable": "accent", "mode": "Alt", "value": "#ef6c00"})); + republish(&mut a); + let r = ex(&mut s, "library.acceptUpdates", json!({})); + assert_eq!(r["variables"], 1, "{r}"); + + let doc = s.doc().unwrap(); + for name in ["accent", "primary"] { + let v = doc.variables.variables.iter().find(|v| v.name == name && is_remote_variable(doc, &v.id)); + assert!(v.is_some(), "library variable copy `{name}` was deleted"); + let id = &v.unwrap().id; + assert!(doc.libraries.variables.iter().any(|r| &r.local == id), "record of `{name}` was deleted"); + } + assert_eq!(fill(&s, ra), "EF6C00"); + assert_eq!(fill(&s, rb), "00838F"); + healthy(&s); + let _ = std::fs::remove_dir_all(&d); +} diff --git a/crates/engine/src/page_opening_tests.rs b/crates/engine/src/page_opening_tests.rs new file mode 100644 index 000000000..aa9e6773c --- /dev/null +++ b/crates/engine/src/page_opening_tests.rs @@ -0,0 +1,175 @@ +//! `page.setOpening` (#1817): the page a file opens on, for everyone who opens or joins it, written +//! as a document change (so it syncs and undoes) without moving anyone's own view. + +use figcraft_doc::NodeId; +use serde_json::{Value, json}; + +use crate::Session; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// Setting the opening page writes the document, leaves this viewer where they are, is one undo +/// step, and a file opened from that document lands on it. +#[test] +fn the_opening_page_is_written_without_moving_the_view_and_a_reopened_file_lands_on_it() { + let mut s = Session::new(); + let first = s.page().unwrap(); + let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"}))); + ex(&mut s, "page.select", json!({"id": first})); + let depth = s.undo_depth().0; + ex(&mut s, "page.setOpening", json!({"id": cover})); + assert_eq!(s.doc().unwrap().current_page, Some(cover), "written to the document"); + assert_eq!(s.page().unwrap(), first, "the view stays where it was"); + assert_eq!(s.undo_depth().0, depth + 1, "one undo step"); + let reopened = Session::with_document(s.doc().unwrap().clone()); + assert_eq!(reopened.page().unwrap(), cover, "a file opened from this document lands on it"); + ex(&mut s, "edit.undo", json!({})); + assert_ne!(s.doc().unwrap().current_page, Some(cover), "undone"); + assert_eq!(Session::with_document(s.doc().unwrap().clone()).page().unwrap(), first); +} + +/// Without an id the current page is meant; a divider and a layer are refused and change nothing. +#[test] +fn the_current_page_is_the_default_and_dividers_and_layers_are_refused() { + let mut s = Session::new(); + let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"}))); + assert_eq!(s.page().unwrap(), two, "page.add goes to the new page"); + ex(&mut s, "page.setOpening", json!({})); + assert_eq!(s.doc().unwrap().current_page, Some(two), "the current page when none is named"); + let divider = id_of(&ex(&mut s, "page.add", json!({"name": "-"}))); + let r = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))); + let (view, depth) = (s.page().unwrap(), s.undo_depth()); + assert!(s.execute("page.setOpening", &json!({"id": divider})).is_err(), "a divider isn't a page to open on"); + assert!(s.execute("page.setOpening", &json!({"id": r})).is_err(), "a layer isn't a page"); + assert_eq!(s.doc().unwrap().current_page, Some(two), "refusals change nothing"); + assert_eq!(s.page().unwrap(), view, "the viewer's page is where it was"); + assert_eq!(s.undo_depth(), depth, "and no undo step was added"); +} + +/// An id that is no node at all errors and changes nothing. +#[test] +fn an_unknown_id_is_refused_and_changes_nothing() { + let mut s = Session::new(); + let first = s.page().unwrap(); + let depth = s.undo_depth(); + assert!(s.execute("page.setOpening", &json!({"id": 987_654_321u64})).is_err(), "no such node"); + assert_eq!(s.doc().unwrap().current_page, Some(first)); + assert_eq!(s.undo_depth(), depth); +} + +/// Setting the page that already is the opening page changes nothing and adds no undo step. +#[test] +fn setting_the_page_that_already_opens_the_file_adds_no_undo_step() { + let mut s = Session::new(); + let first = s.page().unwrap(); + assert_eq!(s.doc().unwrap().current_page, Some(first)); + ex(&mut s, "page.setOpening", json!({"id": first})); + let depth = s.undo_depth(); + ex(&mut s, "page.setOpening", json!({"id": first})); + assert_eq!(s.undo_depth(), depth, "already the opening page: no step"); + assert_eq!(s.doc().unwrap().current_page, Some(first)); +} + +/// Deleting the opening page leaves the file opening on a page that exists. +#[test] +fn deleting_the_opening_page_falls_back_to_a_page_that_exists() { + let mut s = Session::new(); + let first = s.page().unwrap(); + let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"}))); + ex(&mut s, "page.setOpening", json!({"id": cover})); + ex(&mut s, "page.delete", json!({"id": cover})); + let doc = s.doc().unwrap().clone(); + let now = doc.current_page.expect("an opening page remains"); + assert!(doc.pages.contains(&now) && now != cover, "a page that exists"); + assert_eq!(now, first); + assert_eq!(Session::with_document(doc).page().unwrap(), first, "a reopened file lands on it"); +} + +/// The file written by a real save (the serializer, not a cloned document), opened again. +fn saved_and_reopened(s: &Session) -> Session { + let bytes = crate::cmd::file::file_bytes(s.ds().unwrap()).unwrap(); + let (doc, _) = figcraft_format::load_bytes(&bytes).unwrap(); + Session::with_document(doc) +} + +/// Saving writes the chosen opening page, not the page the saver was viewing. +#[test] +fn the_opening_page_survives_a_save_and_reopen_from_another_page() { + let mut s = Session::new(); + let first = s.page().unwrap(); + let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"}))); + ex(&mut s, "page.select", json!({"id": first})); + ex(&mut s, "page.setOpening", json!({"id": cover})); + assert_eq!(s.page().unwrap(), first, "the saver stays on Page 1"); + assert_eq!(saved_and_reopened(&s).page().unwrap(), cover); +} + +/// With no opening page chosen, a file opens on the page it was saved on, as before. +#[test] +fn without_an_opening_page_a_file_reopens_on_the_page_it_was_saved_on() { + let mut s = Session::new(); + let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"}))); + assert_eq!(s.page().unwrap(), two); + assert_eq!(saved_and_reopened(&s).page().unwrap(), two); +} + +/// A deleted opening page no longer decides: the file opens where it was saved. +#[test] +fn deleting_the_opening_page_falls_back_to_the_saver_s_page() { + let mut s = Session::new(); + let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"}))); + let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"}))); + ex(&mut s, "page.setOpening", json!({"id": cover})); + ex(&mut s, "page.delete", json!({"id": cover})); + ex(&mut s, "page.select", json!({"id": two})); + assert_eq!(saved_and_reopened(&s).page().unwrap(), two); +} + +/// Undoing the choice puts the saver's page back in charge. +#[test] +fn undoing_the_opening_page_then_saving_reopens_on_the_saver_s_page() { + let mut s = Session::new(); + let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"}))); + let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"}))); + ex(&mut s, "page.setOpening", json!({"id": cover})); + ex(&mut s, "edit.undo", json!({})); + ex(&mut s, "page.select", json!({"id": two})); + assert_eq!(saved_and_reopened(&s).page().unwrap(), two); +} + +/// Choosing another opening page takes the choice off the first. +#[test] +fn setting_another_opening_page_clears_the_first() { + let mut s = Session::new(); + let a = id_of(&ex(&mut s, "page.add", json!({"name": "A"}))); + let b = id_of(&ex(&mut s, "page.add", json!({"name": "B"}))); + let c = id_of(&ex(&mut s, "page.add", json!({"name": "C"}))); + ex(&mut s, "page.setOpening", json!({"id": a})); + ex(&mut s, "page.setOpening", json!({"id": b})); + let flagged: Vec = s.doc().unwrap().pages.iter().copied().filter(|&p| opening(&s, p)).collect(); + assert_eq!(flagged, vec![b]); + ex(&mut s, "page.select", json!({"id": c})); + assert_eq!(saved_and_reopened(&s).page().unwrap(), b); +} + +/// A copy of the opening page is just a page. +#[test] +fn a_duplicated_opening_page_is_not_an_opening_page() { + let mut s = Session::new(); + let a = id_of(&ex(&mut s, "page.add", json!({"name": "A"}))); + ex(&mut s, "page.setOpening", json!({"id": a})); + let copy = id_of(&ex(&mut s, "page.duplicate", json!({"id": a}))); + assert_ne!(copy, a); + assert!(opening(&s, a)); + assert!(!opening(&s, copy)); +} + +fn opening(s: &Session, p: NodeId) -> bool { + matches!(s.doc().unwrap().get(p).map(|n| &n.kind), Ok(figcraft_doc::NodeKind::Page { opening: true, .. })) +} diff --git a/crates/engine/src/page_view_tests.rs b/crates/engine/src/page_view_tests.rs new file mode 100644 index 000000000..c08d6772f --- /dev/null +++ b/crates/engine/src/page_view_tests.rs @@ -0,0 +1,35 @@ +//! Each page keeps its view in a session: going back to a page shows it where it was left, not +//! fitted again (a new page is still fitted); going to the page shown changes nothing. + +use serde_json::{Value, json}; + +use crate::Session; + +fn view(s: &mut Session) -> (f64, f64, f64) { + let v: Value = s.execute("view.get", &json!({})).unwrap(); + (v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap(), v["zoom"].as_f64().unwrap()) +} + +#[test] +fn going_back_to_a_page_shows_it_where_it_was_left() { + let mut s = Session::new(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 400, "height": 300})).unwrap(); + let first = s.page().unwrap(); + s.execute("view.set", &json!({"zoom": 2.5, "cx": 1000, "cy": 500})).unwrap(); + let second = crate::params::id_of(&s.execute("page.add", &json!({})).unwrap()["id"]).unwrap(); + assert_ne!(view(&mut s), (1000.0, 500.0, 2.5), "a new page is fitted, not shown at the last page's view"); + s.execute("shape.ellipse", &json!({"x": 5000, "y": 5000, "width": 100, "height": 100})).unwrap(); + s.execute("view.set", &json!({"zoom": 0.5, "cx": -200, "cy": 40})).unwrap(); + + s.execute("page.select", &json!({"id": first})).unwrap(); + assert_eq!(view(&mut s), (1000.0, 500.0, 2.5), "the first page as it was left"); + s.execute("view.nextPage", &json!({})).unwrap(); + assert_eq!(s.page().unwrap(), second); + assert_eq!(view(&mut s), (-200.0, 40.0, 0.5), "the second page as it was left"); + // The page shown: nothing moves. + s.execute("view.set", &json!({"zoom": 3.0, "cx": 7, "cy": 8})).unwrap(); + s.execute("page.select", &json!({"id": second})).unwrap(); + assert_eq!(view(&mut s), (7.0, 8.0, 3.0)); + s.execute("view.prevPage", &json!({})).unwrap(); + assert_eq!(view(&mut s), (1000.0, 500.0, 2.5)); +} diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index e4a379e48..d988a7269 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -20,3 +20,8 @@ ruzstd = { workspace = true } sha1 = { workspace = true } sha2 = { workspace = true } image = { workspace = true } +craft-penpot = { workspace = true } +craft-sketch = { workspace = true } +craft-fig = { workspace = true } +craft-figcraft-format = { workspace = true } +craft-figma-rest = { workspace = true } diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 6b3d4efb2..033d4f22d 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -26,13 +26,11 @@ mod export; mod export_tests; #[cfg(test)] mod interop_tests; -pub mod kiwi; #[cfg(test)] mod layer_cap_tests; mod map; #[cfg(test)] mod missing_image_tests; -mod network; #[cfg(test)] mod paste_style_tests; #[cfg(test)] @@ -49,7 +47,6 @@ mod source_identity_tests; mod tests; #[cfg(test)] mod text_paragraph_tests; -mod text_path; #[cfg(test)] mod text_path_tests; #[cfg(test)] @@ -63,27 +60,22 @@ mod value_budget_tests; #[cfg(test)] mod vector_scale_tests; -use std::cell::Cell; use std::collections::BTreeMap; -use std::io::Read; -use std::sync::Arc; use figcraft_doc::{Document, FileKind}; pub use export::export; use crate::FormatError; -use kiwi::{Kv, Schema}; +#[cfg(test)] +use craft_fig::rest::MAX_FIG_NODES; +pub(crate) use craft_fig::rest::layer_budget; +use craft_fig::{Archive, Limits, decode_canvas, embedded_aliases, embedded_copies, kiwi}; +pub use craft_fig::{JAM_HEADER, is_fig}; +#[cfg(test)] +use craft_fig::{MAX_CANVAS, chunks, network}; +pub(crate) use craft_figma_rest::style_name; -/// Largest `canvas.fig` member read, and largest decompressed chunk. -const MAX_CANVAS: u64 = 256 * 1024 * 1024; -const MAX_CHUNK: u64 = 512 * 1024 * 1024; -/// Largest decompressed schema chunk: Figma's schema unpacks to well under 1 MB, so a schema that -/// inflates past this is refused before its definitions are decoded. -const MAX_SCHEMA: u64 = 16 * 1024 * 1024; -/// Longest image hash (bytes) an image is found by: `images/` names and embedded images both -/// stop at 64 bytes (128 hex digits). -pub(crate) const MAX_IMAGE_HASH: usize = 64; /// Largest image member read. const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES; /// Total decompressed ZIP image bytes read per import: the native image budget (`IMAGE_BUDGET`) on @@ -93,35 +85,6 @@ const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES; const MAX_IMAGE_BYTES: u64 = crate::IMAGE_BUDGET.bytes; #[cfg(target_pointer_width = "32")] const MAX_IMAGE_BYTES: u64 = 1024 * 1024 * 1024; -/// Most chunks read from `canvas.fig`. -const MAX_CHUNKS: usize = 16; -/// Most layers imported from a `.fig` file: one per [`PACKED_BYTES_PER_LAYER`] bytes of its -/// compressed canvas, at least the REST import's cap and at most [`MAX_FIG_NODES`]. Instances -/// expand into a layer per layer of their component, and chunks inflate up to [`MAX_CHUNK`], so the -/// budget follows what the file takes, not what it unpacks to: a small file can't claim a large -/// count, however it's built; a large one gets room. Design systems are mostly instances, which -/// pack tightly: a 7.8 MB canvas stopped at 244 248 layers at 32 bytes a layer (#981). At 8, files -/// under about 1.6 MB keep the floor and the ceiling comes at a 16 MB canvas (about 11 GB and 40 s -/// to import 2 million synthetic layers; memory grows with the count, about 5.4 KB a layer). -const PACKED_BYTES_PER_LAYER: usize = 8; -const MAX_FIG_NODES: usize = 2_000_000; - -/// Most layers imported from a `.fig` file whose compressed canvas is `packed` bytes. -pub(crate) fn layer_budget(packed: usize) -> usize { - (packed / PACKED_BYTES_PER_LAYER).clamp(crate::rest::MAX_NODES, MAX_FIG_NODES) -} - -/// The canvas header of a FigJam whiteboard (a `.jam`); a `.fig` has `fig-kiwi`. -pub const JAM_HEADER: &[u8] = b"fig-jam."; - -/// Whether `bytes` look like a `.fig` file: a zip holding `canvas.fig`, or a bare canvas. -pub fn is_fig(bytes: &[u8]) -> bool { - bytes.starts_with(b"fig-") || (bytes.starts_with(b"PK") && zip_has_canvas(bytes)) -} - -fn zip_has_canvas(bytes: &[u8]) -> bool { - zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| z.file_names().any(|n| n == "canvas.fig")) -} /// Import `bytes` when they are a `.fig` file; `None` when they are something else. pub fn try_import(bytes: &[u8], name: &str) -> Option), FormatError>> { @@ -135,24 +98,23 @@ pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec), Forma } fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result<(Document, Vec), FormatError> { - let mut archive = Archive::open(bytes)?; - archive.image_budget.remaining.set(image_limit); + let mut archive = Archive::open_with(bytes, Limits { max_image: MAX_IMAGE, max_image_total: image_limit }).map_err(fig_err)?; // The budgets follow the compressed canvas, which the file itself bounds (its zip member may // inflate too). let packed = archive.canvas.len().min(bytes.len()); // FigJam writes its whiteboards with this header: they open as boards. - let board = archive.canvas.starts_with(JAM_HEADER); + let board = archive.is_board(); // Each stage's input is dropped as soon as the next one is built: in a large file every one // of them takes gigabytes, and holding them all at once runs out of memory. - let (schema, message) = decode_canvas(&std::mem::take(&mut archive.canvas))?; + let (schema, message) = decode_canvas(&std::mem::take(&mut archive.canvas)).map_err(fig_err)?; let root = schema.find("Message").ok_or_else(|| corrupt("the schema has no Message definition"))?; - let msg = schema.decode_message_within(root, &message, kiwi::value_budget(packed)).map_err(|e| corrupt(e.to_string()))?; + let msg = schema.decode_message_within(root, &message, craft_fig::value_budget(packed)).map_err(|e| corrupt(e.to_string()))?; let max_nodes = layer_budget(packed); drop(message); let file_name = archive.file_name.as_deref().filter(|n| !n.trim().is_empty()).unwrap_or(name); let (mut json, mut warnings, networks) = map::to_rest_for(&msg, file_name, max_nodes, board); // The message goes before the layers are built, so the images it carries are copied out first. - let embedded = embedded_copies(&msg); + let embedded = embedded_copies(&msg, MAX_IMAGE); drop(msg); let aliases = embedded_aliases(&embedded, |hash| archive.has_image(hash)); if !aliases.is_empty() { @@ -160,7 +122,7 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result } let images = |r: &str| archive.image(r).or_else(|| embedded.get(r).map(|b| b.to_vec())); let (mut doc, more) = crate::rest::import_with_networks(&json, &images, networks, max_nodes)?; - let skipped = archive.image_budget.skipped.get(); + let skipped = archive.images_skipped(); if skipped > 0 { warnings.push(format!("{skipped} ZIP image(s) skipped by the total ZIP image byte budget ({image_limit} bytes)")); } @@ -177,87 +139,16 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result Ok((doc, warnings)) } -/// A font style under the name the format uses: the standard weight names as words ("SemiBold" -/// → "Semi Bold", "ExtraBoldItalic" → "Extra Bold Italic", "Regular Italic" → "Italic"). Other -/// names stay as they are. -pub(crate) fn style_name(style: &str) -> String { - const WEIGHTS: [&str; 12] = - ["Thin", "Extra Light", "Ultra Light", "Light", "Regular", "Medium", "Semi Bold", "Demi Bold", "Bold", "Extra Bold", "Ultra Bold", "Black"]; - let compact = |s: &str| s.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).flat_map(char::to_lowercase).collect::(); - let key = compact(style); - let (base, italic) = match key.strip_suffix("italic") { - Some(b) => (b, true), - None => (key.as_str(), false), - }; - let weight = if base.is_empty() && italic { Some("Regular") } else { WEIGHTS.into_iter().find(|w| compact(w) == base) }; - match (weight, italic) { - (None, _) => style.to_string(), - (Some("Regular"), true) => "Italic".into(), - (Some(w), true) => format!("{w} Italic"), - (Some(w), false) => w.into(), - } -} - fn corrupt(msg: impl Into) -> FormatError { FormatError::Corrupt(format!(".fig file: {}", msg.into())) } -/// Image bytes that travel inside the message, by image hash (lowercase hex): a paint's -/// `image.dataBlob` indexes the message's `blobs`. Copies written by plugins and other tools embed -/// their images this way, and a bare canvas (what the clipboard carries) has no `images/`. The -/// walk is iterative (no recursion on nested data) and skips blobs larger than [`MAX_IMAGE`]. -/// Returns the index of each hash's blob. -fn embedded_images(msg: &Kv) -> BTreeMap { - let blobs = msg.get("blobs").map(Kv::list).unwrap_or_default(); - let mut found = BTreeMap::new(); - let mut pending = vec![msg]; - while let Some(value) = pending.pop() { - match value { - Kv::Object(fields) => { - if let Some((hash, index)) = value.get("image").and_then(|image| embedded_image(image, blobs)) { - found.entry(hash).or_insert(index); - } - pending.extend(fields.iter().filter(|(name, _)| *name != "blobs").map(|(_, field)| field)); - } - Kv::Array(items) => pending.extend(items), - _ => {} - } +/// A `.fig` read or write failure as the app reports it (`Corrupt` already says `.fig file:`). +pub(crate) fn fig_err(e: craft_fig::Error) -> FormatError { + match e { + craft_fig::Error::Corrupt(_) => FormatError::Corrupt(e.to_string()), + craft_fig::Error::TooLarge | craft_fig::Error::Io(_) => FormatError::Io(e.to_string()), } - found -} - -/// The images that travel inside the message ([`embedded_images`]), copied out of it once per -/// blob: every hash naming the same blob shares its copy. A file can point any number of hashes -/// at one large blob, and a copy for each would multiply it (#1059). -fn embedded_copies(msg: &Kv) -> BTreeMap> { - let blobs = msg.get("blobs").map(Kv::list).unwrap_or_default(); - let mut copies: BTreeMap> = BTreeMap::new(); - let mut out = BTreeMap::new(); - for (hash, index) in embedded_images(msg) { - let Some(bytes) = blob(blobs, index) else { continue }; - out.insert(hash, Arc::clone(copies.entry(index).or_insert_with(|| Arc::from(bytes)))); - } - out -} - -/// Embedded images ([`embedded_copies`]) whose blob an earlier hash already names, each with that -/// hash. Hashes that also have an `images/` member keep their own name: the member is read first. -/// Pointing every alias at one name has the import copy and hash each blob once, however many -/// hashes a file points at it. -fn embedded_aliases(embedded: &BTreeMap>, in_zip: impl Fn(&str) -> bool) -> BTreeMap { - let mut first: BTreeMap = BTreeMap::new(); - let mut out = BTreeMap::new(); - for (hash, bytes) in embedded { - if in_zip(hash) { - continue; - } - // Hashes naming one blob share its copy, so the copy's address tells the blob. - let canonical = *first.entry(bytes.as_ptr() as usize).or_insert(hash); - if canonical != hash { - out.insert(hash.clone(), canonical.clone()); - } - } - out } /// Rename every `imageRef` in REST `json` found in `aliases` to the name it maps to. @@ -284,154 +175,6 @@ fn canonical_image_refs(json: &mut serde_json::Value, aliases: &BTreeMap Option<(String, usize)> { - let hash = image.get("hash").and_then(Kv::bytes).filter(|h| !h.is_empty() && h.len() <= MAX_IMAGE_HASH)?; - let Some(Kv::Uint(index)) = image.get("dataBlob") else { return None }; - let index = usize::try_from(*index).ok()?; - let bytes = blob(blobs, index)?; - if bytes.is_empty() || bytes.len() as u64 > MAX_IMAGE { - return None; - } - Some((hash.iter().map(|b| format!("{b:02x}")).collect(), index)) -} - -/// The bytes of blob `index`. -fn blob<'k>(blobs: &'k [Kv], index: usize) -> Option<&'k [u8]> { - blobs.get(index)?.get("bytes").and_then(Kv::bytes) -} - -/// Bytes left for ZIP image reads, including damaged images. The REST resolver caches references, -/// including failures, so each referenced member is read or counted as skipped only once. -struct ZipImageBudget { - remaining: Cell, - skipped: Cell, -} - -/// The parts of a `.fig` archive the import reads. -struct Archive<'b> { - canvas: Vec, - file_name: Option, - /// `images/` members (or nothing for a bare canvas). - zip: Option>>, - image_budget: ZipImageBudget, -} - -impl<'b> Archive<'b> { - fn open(bytes: &'b [u8]) -> Result { - let image_budget = ZipImageBudget { remaining: Cell::new(MAX_IMAGE_BYTES), skipped: Cell::new(0) }; - if bytes.starts_with(b"fig-") { - return Ok(Archive { canvas: bytes.to_vec(), file_name: None, zip: None, image_budget }); - } - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| corrupt(e.to_string()))?; - let canvas = crate::read_member(&mut z, "canvas.fig", MAX_CANVAS)?; - let file_name = crate::read_member(&mut z, "meta.json", 1 << 20) - .ok() - .and_then(|m| serde_json::from_slice::(&m).ok()) - .and_then(|m| m.get("file_name").and_then(serde_json::Value::as_str).map(str::to_string)); - Ok(Archive { canvas, file_name, zip: Some(z), image_budget }) - } - - /// Whether `images/` has a member for image `hash`. - fn has_image(&self, hash: &str) -> bool { - self.zip.as_ref().is_some_and(|z| z.index_for_name(&format!("images/{hash}")).is_some()) - } - - /// Bytes of image `hash` (lowercase hex) from `images/`. - fn image(&self, hash: &str) -> Option> { - let budget = &self.image_budget; - if hash.is_empty() || hash.len() > 2 * MAX_IMAGE_HASH || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - // A clone shares the parsed directory and the bytes; the resolver only has shared access. - let mut z = self.zip.clone()?; - let f = z.by_name(&format!("images/{hash}")).ok()?; - let size = f.size(); - if size > MAX_IMAGE { - return None; - } - let remaining = budget.remaining.get(); - if size > remaining { - budget.skipped.set(budget.skipped.get() + 1); - return None; - } - let checksum = f.crc32(); - let mut data = Vec::new(); - // Probe past the per-image cap only when the total budget has room. Even a dishonest - // size cannot make the read exceed the remaining total; failed reads keep their charge. - let limit = remaining.min(MAX_IMAGE + 1); - let read = f.take(limit).read_to_end(&mut data); - let used = data.len() as u64; - budget.remaining.set(remaining - used); - if used > size && used == remaining { - budget.skipped.set(budget.skipped.get() + 1); - } - if read.is_err() || used != size { - return None; - } - // `take` can stop exactly at the budget without asking ZIP for EOF (where it checks CRC). - // Check it here too, without spending an extra byte on an overflow probe. - if used == limit { - let mut crc = flate2::Crc::new(); - crc.update(&data); - if crc.sum() != checksum { - return None; - } - } - Some(data) - } -} - -/// The schema and the raw message of a `canvas.fig`. -fn decode_canvas(canvas: &[u8]) -> Result<(Schema, Vec), FormatError> { - let chunks = chunks(canvas)?; - let mut it = chunks.into_iter(); - let (Some(schema), Some(message)) = (it.next(), it.next()) else { - return Err(corrupt("canvas.fig needs a schema and a message chunk")); - }; - let schema = Schema::decode(&inflate_within(schema, MAX_SCHEMA)?).map_err(|e| corrupt(e.to_string()))?; - Ok((schema, inflate(message)?)) -} - -/// The length-prefixed chunks after the 12-byte header. -fn chunks(canvas: &[u8]) -> Result, FormatError> { - if canvas.len() < 12 || !canvas.starts_with(b"fig-") { - return Err(corrupt("canvas.fig has no header")); - } - let mut out = Vec::new(); - let mut pos = 12usize; - while pos < canvas.len() && out.len() < MAX_CHUNKS { - let len = canvas.get(pos..pos + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| corrupt("truncated chunk"))?; - let start = pos + 4; - let end = start.checked_add(len as usize).filter(|e| *e <= canvas.len()).ok_or_else(|| corrupt("truncated chunk"))?; - out.push(canvas.get(start..end).unwrap_or_default()); - pos = end; - } - Ok(out) -} - -/// Decompress a chunk: zstd (by its magic number), else raw deflate, else zlib. -fn inflate(data: &[u8]) -> Result, FormatError> { - inflate_within(data, MAX_CHUNK) -} - -/// [`inflate`] refusing a chunk that unpacks to more than `max` bytes. -fn inflate_within(data: &[u8], max: u64) -> Result, FormatError> { - let capped = |r: &mut dyn Read| -> Option> { - let mut out = Vec::new(); - r.take(max.saturating_add(1)).read_to_end(&mut out).ok()?; - (out.len() as u64 <= max).then_some(out) - }; - if data.starts_with(&[0x28, 0xB5, 0x2F, 0xFD]) { - let mut src = data; - let mut dec = ruzstd::decoding::StreamingDecoder::new(&mut src).map_err(|e| corrupt(format!("zstd: {e}")))?; - return capped(&mut dec).ok_or_else(|| corrupt("damaged or oversized zstd chunk")); - } - capped(&mut flate2::read::DeflateDecoder::new(data)) - .or_else(|| capped(&mut flate2::read::ZlibDecoder::new(data))) - .ok_or_else(|| corrupt("damaged or oversized deflate chunk")) -} - /// Decoded message `msg` as JSON (byte arrays as their length), for looking at files. #[cfg(test)] pub(crate) fn debug_json(v: &kiwi::Kv) -> serde_json::Value { diff --git a/crates/format/src/fig/connector_label_tests.rs b/crates/format/src/fig/connector_label_tests.rs index ca76c0b29..a0d60ba91 100644 --- a/crates/format/src/fig/connector_label_tests.rs +++ b/crates/format/src/fig/connector_label_tests.rs @@ -249,7 +249,7 @@ fn a_routed_connector_takes_its_line_style_from_the_generated_record() { assert_eq!(connector["strokeWeight"], 4.0); assert_eq!(connector["strokeDashes"], serde_json::json!([16.0, 10.0])); assert_eq!(connector["strokeCapEnd"], "ARROW"); - assert!(warnings.iter().any(|warning| warning.contains("follow FigCraft's own routing")), "{warnings:?}"); + assert!(warnings.iter().any(|warning| warning.contains("are routed afresh")), "{warnings:?}"); let (native, _) = crate::rest::import_fig(&rest, &|_| None).unwrap(); let node = find_node(&native, "synthetic connector"); diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index 8b3d0c649..c0de279c1 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -15,7 +15,6 @@ //! (`docs/file-format-parity.md` says what was checked); other apps may not open every file. use std::collections::BTreeMap; -use std::io::Write; use std::sync::Arc; use figcraft_doc::color::{BlendMode, Color, GradientKind, ImageScaleMode, Paint, PaintKind}; @@ -33,9 +32,9 @@ use figcraft_doc::{ use serde_json::Value; use sha1::Digest; -use super::kiwi::{Kv, Schema, encode}; -use super::network; use crate::FormatError; +use craft_fig::kiwi::{Kv, Schema, encode}; +use craft_fig::{network, path}; mod assets; mod common; @@ -50,18 +49,18 @@ mod shape; const MAX_NODES: usize = crate::rest::MAX_NODES; const MAX_DEPTH: usize = 256; /// Largest `canvas.fig` and image written (what the import reads). -const MAX_CANVAS: u64 = super::MAX_CANVAS; +const MAX_CANVAS: u64 = craft_fig::MAX_CANVAS; const MAX_IMAGE: u64 = super::MAX_IMAGE; -/// Largest whole file written. -const MAX_FILE: u64 = 2 * 1024 * 1024 * 1024; /// Most characters of one text layer, and vertices + segments + loop entries of one vector /// network (what the import reads). const MAX_CHARS: usize = 1 << 20; const MAX_NETWORK: usize = 200_000; /// Largest magnitude written for a float (the format stores 32-bit floats). const MAX_FLOAT: f64 = 1e30; -/// The version number in the `canvas.fig` header. -const VERSION: u32 = 101; +/// Grid track values, and the scale factor of a scaled instance, that the import follows. +const MAX_GRID_TRACK_VALUE: f64 = 1e6; +const MIN_SCALE_FACTOR: f64 = 1e-3; +const MAX_SCALE_FACTOR: f64 = 1e3; /// Session ids of the GUIDs: layers, and grid tracks and component properties. const LAYERS: u32 = 1; const AUX: u32 = 2; @@ -202,11 +201,11 @@ message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4 pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec), FormatError> { let mut x = Exporter::new(doc); let message = x.message(); - let fail = |e: super::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); + let fail = |e: craft_fig::kiwi::KiwiError| FormatError::Io(format!(".fig export: {e}")); let schema = Schema::parse(SCHEMA).map_err(fail)?; let root = schema.find("Message").ok_or_else(|| FormatError::Io(".fig export: the schema has no Message".into()))?; let body = encode::message(&schema, root, &message).map_err(fail)?; - let canvas = canvas(&encode::schema(&schema), &body)?; + let canvas = craft_fig::encode_canvas(&encode::schema(&schema), &body).map_err(super::fig_err)?; let background = doc.pages.first().and_then(|p| doc.node(*p)).and_then(|p| match &p.kind { NodeKind::Page { background, .. } => Some(*background), _ => None, @@ -215,28 +214,6 @@ pub fn export(doc: &Document, thumbnail: Option<&[u8]>) -> Result<(Vec, Vec< Ok((bytes, x.warnings)) } -fn too_large() -> FormatError { - FormatError::Io("the document is too large for a .fig file".into()) -} - -/// `canvas.fig`: the magic, the version and the two deflated chunks, each after its length. -pub(super) fn canvas(schema: &[u8], message: &[u8]) -> Result, FormatError> { - let mut out = b"fig-kiwi".to_vec(); - out.extend_from_slice(&VERSION.to_le_bytes()); - for chunk in [schema, message] { - let mut z = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); - z.write_all(chunk).map_err(crate::io_err)?; - let c = z.finish().map_err(crate::io_err)?; - let len = u32::try_from(c.len()).map_err(|_| too_large())?; - out.extend_from_slice(&len.to_le_bytes()); - out.extend_from_slice(&c); - } - if out.len() as u64 > MAX_CANVAS { - return Err(too_large()); - } - Ok(out) -} - /// The zip around `canvas.fig`. fn archive( name: &str, @@ -245,33 +222,9 @@ fn archive( images: &[(String, Arc>)], thumbnail: Option<&[u8]>, ) -> Result, FormatError> { - let mut buf = std::io::Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - crate::put(&mut z, "canvas.fig", stored, canvas)?; - if let Some(t) = thumbnail { - crate::put(&mut z, "thumbnail.png", stored, t)?; - } - let mut client = serde_json::json!({"background_color": {"r": background.r, "g": background.g, "b": background.b, "a": background.a}}); - // A PNG says its size right after its signature and header chunk name. - let be = |at: usize| thumbnail.and_then(|t| t.get(at..at + 4)).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); - if let (Some(w), Some(h)) = (be(16), be(20)) { - client["thumbnail_size"] = serde_json::json!({"width": w, "height": h}); - } - let meta = serde_json::to_vec(&serde_json::json!({"client_meta": client, "file_name": name})).map_err(crate::io_err)?; - crate::put(&mut z, "meta.json", crate::json_options(), &meta)?; - let mut total = canvas.len() as u64; - for (hash, bytes) in images { - total += bytes.len() as u64; - if total > MAX_FILE { - return Err(too_large()); - } - crate::put(&mut z, &format!("images/{hash}"), stored, bytes)?; - } - z.finish().map_err(crate::io_err)?; - } - Ok(buf.into_inner()) + let images: Vec<(&str, &[u8])> = images.iter().map(|(hash, bytes)| (hash.as_str(), bytes.as_slice())).collect(); + let background = [background.r, background.g, background.b, background.a].map(f64::from); + craft_fig::write_archive(&craft_fig::Package { file_name: name, background, canvas, images: &images, thumbnail }).map_err(super::fig_err) } type Fields = Vec<(&'static str, Kv<'static>)>; @@ -306,7 +259,7 @@ fn b(x: bool) -> Kv<'static> { /// importer keeps only those). `None`: the format has no name for it, so an equal track stands in. fn grid_track_size(track: &GridTrack) -> Option<(&'static str, f64)> { let value = track.value; - let fits = value.is_finite() && (0.0..=crate::fig::map::MAX_GRID_TRACK_VALUE).contains(&value); + let fits = value.is_finite() && (0.0..=MAX_GRID_TRACK_VALUE).contains(&value); match track.sizing { Sizing::Fixed if fits => Some(("FIXED", value)), Sizing::Fill if fits && value > 0.0 => Some(("FLEX", value)), @@ -419,27 +372,21 @@ fn join_name(j: StrokeJoin) -> &'static str { } } -/// A geometry blob (the import's `svg_path` reads it): commands `0` close, `1` move, `2` line, -/// `3` quadratic, `4` cubic, each followed by its points as little-endian `f32` pairs. +/// A geometry blob (`craft_fig::path`), with every value finite. fn path_blob(p: &BezPath) -> Vec { - let mut out = Vec::new(); - let mut put = |cmd: u8, pts: &[figcraft_doc::geom::Point]| { - out.push(cmd); - for q in pts { - out.extend_from_slice(&(finite(q.x) as f32).to_le_bytes()); - out.extend_from_slice(&(finite(q.y) as f32).to_le_bytes()); - } - }; - for el in p.elements() { - match *el { - PathEl::MoveTo(a) => put(1, &[a]), - PathEl::LineTo(a) => put(2, &[a]), - PathEl::QuadTo(a, c) => put(3, &[a, c]), - PathEl::CurveTo(a, c, d) => put(4, &[a, c, d]), - PathEl::ClosePath => put(0, &[]), - } - } - out + let pt = |q: figcraft_doc::geom::Point| [finite(q.x) as f32, finite(q.y) as f32]; + let commands: Vec = p + .elements() + .iter() + .map(|el| match *el { + PathEl::MoveTo(a) => path::Command::Move(pt(a)), + PathEl::LineTo(a) => path::Command::Line(pt(a)), + PathEl::QuadTo(a, c) => path::Command::Quad(pt(a), pt(c)), + PathEl::CurveTo(a, c, d) => path::Command::Cubic(pt(a), pt(c), pt(d)), + PathEl::ClosePath => path::Command::Close, + }) + .collect(); + path::encode(&commands) } /// Settings an overlay's destination carries. diff --git a/crates/format/src/fig/export/component.rs b/crates/format/src/fig/export/component.rs index f43e1d3ac..416a99610 100644 --- a/crates/format/src/fig/export/component.rs +++ b/crates/format/src/fig/export/component.rs @@ -1,9 +1,9 @@ -use super::super::map::{MAX_SCALE_FACTOR, MIN_SCALE_FACTOR}; 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::{MAX_SCALE_FACTOR, MIN_SCALE_FACTOR}; /// A changed effect/grid style, and a payload only when it differs from that style's values. struct ListStyleOverride { diff --git a/crates/format/src/fig/kiwi.rs b/crates/format/src/fig/kiwi.rs deleted file mode 100644 index 382311b40..000000000 --- a/crates/format/src/fig/kiwi.rs +++ /dev/null @@ -1,690 +0,0 @@ -//! A generic decoder and encoder for the kiwi binary schema format (an open, MIT-licensed message -//! format with a public specification). A binary schema lists definitions (enums, structs and messages, each -//! with typed fields); a message is then decoded with it into a [`Kv`] tree keyed by field name, -//! and encoded back from one ([`encode`]). -//! -//! Everything here reads untrusted bytes: reads are bounds-checked, nesting is capped, array -//! counts can't exceed the bytes left, and the total number of decoded values is capped. - -use std::collections::HashMap; -use std::fmt; - -/// Deepest struct/message nesting decoded. -const MAX_DEPTH: usize = 64; -/// Most values decoded from one message (every scalar, array element and field counts): at least -/// [`MIN_VALUES`], and [`VALUES_PER_PACKED_BYTE`] per byte of the file's compressed canvas up to -/// [`MAX_VALUES`], so a large real file decodes while a small one can't expand into a huge tree, -/// however far its chunks inflate. 32-bit targets (wasm32) have a 4 GB address space in all, so -/// their ceiling is lower: past it the file is refused cleanly instead of running out of memory. -const MIN_VALUES: usize = 20_000_000; -/// Value budget per compressed canvas byte. The real files measured in -/// `large_files_get_a_larger_value_budget` hold up to 0.75 values per compressed byte without their -/// single scalar fields; counting those too adds 15–43% on the generated files in -/// `value_budget_tests` and up to 3.2 times on a rectangle carrying only geometry and paint, so a -/// dense file may reach about 2.4 per byte. Four leaves two-thirds more room than that. The -/// trade-off: from 32 MiB of canvas (8 MiB on 32-bit targets) a file gets all of [`MAX_VALUES`], -/// and above the floor it may decode four values for every byte it carries; [`MIN_VALUES`] and -/// [`MAX_VALUES`] still bound every file. -const VALUES_PER_PACKED_BYTE: usize = 4; -#[cfg(not(target_pointer_width = "32"))] -const MAX_VALUES: usize = 128 << 20; -#[cfg(target_pointer_width = "32")] -const MAX_VALUES: usize = 32 << 20; -/// Most definitions in a schema, and fields in one definition. -const MAX_DEFS: usize = 10_000; -const MAX_FIELDS: usize = 10_000; -/// Most fields in a schema, every definition together: Figma's own schema has a few thousand, and -/// without a total a schema of [`MAX_DEFS`] wide definitions could hold 100 million field records. -const MAX_SCHEMA_FIELDS: usize = 200_000; - -#[derive(Debug, PartialEq, Eq)] -pub struct KiwiError(pub String); - -impl fmt::Display for KiwiError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -fn err(msg: impl Into) -> Result { - Err(KiwiError(msg.into())) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Kind { - Enum, - Struct, - Message, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Type { - Bool, - Byte, - Int, - Uint, - Float, - Str, - Int64, - Uint64, - /// Index of a definition in the schema. - Def(usize), -} - -/// Built-in types in their schema order (encoded as `!index`). -const BUILTINS: [Type; 8] = [Type::Bool, Type::Byte, Type::Int, Type::Uint, Type::Float, Type::Str, Type::Int64, Type::Uint64]; - -#[derive(Clone, Debug)] -pub struct Field { - pub name: String, - /// `None` for enum values. - pub ty: Option, - pub array: bool, - /// The field id (messages) or the value (enums). - pub value: u32, -} - -#[derive(Clone, Debug)] -pub struct Def { - pub name: String, - pub kind: Kind, - pub fields: Vec, -} - -#[derive(Clone, Debug, Default)] -pub struct Schema { - pub defs: Vec, -} - -/// A decoded value. Field and enum names borrow from the schema. -#[derive(Clone, Debug, PartialEq)] -pub enum Kv<'s> { - Bool(bool), - Int(i64), - Uint(u64), - Float(f32), - Str(String), - /// A `byte[]` field. - Bytes(Vec), - Enum(&'s str), - Array(Vec>), - /// A struct or message: its fields in the order read. - Object(Vec<(&'s str, Kv<'s>)>), -} - -impl<'s> Kv<'s> { - /// Field `name` of an object. - pub fn get(&self, name: &str) -> Option<&Kv<'s>> { - match self { - Kv::Object(f) => f.iter().find(|(n, _)| *n == name).map(|(_, v)| v), - _ => None, - } - } - - pub fn f64(&self) -> Option { - let v = match self { - Kv::Float(f) => f64::from(*f), - Kv::Int(i) => *i as f64, - Kv::Uint(u) => *u as f64, - Kv::Bool(b) => f64::from(u8::from(*b)), - _ => return None, - }; - v.is_finite().then_some(v) - } - - pub fn bool(&self) -> Option { - match self { - Kv::Bool(b) => Some(*b), - _ => None, - } - } - - pub fn str(&self) -> Option<&str> { - match self { - Kv::Str(s) => Some(s), - Kv::Enum(s) => Some(s), - _ => None, - } - } - - pub fn list(&self) -> &[Kv<'s>] { - match self { - Kv::Array(a) => a, - _ => &[], - } - } - - pub fn bytes(&self) -> Option<&[u8]> { - match self { - Kv::Bytes(b) => Some(b), - _ => None, - } - } -} - -/// A bounds-checked reader over kiwi bytes. -struct Reader<'b> { - data: &'b [u8], - pos: usize, -} - -impl<'b> Reader<'b> { - fn left(&self) -> usize { - self.data.len().saturating_sub(self.pos) - } - - fn byte(&mut self) -> Result { - let b = *self.data.get(self.pos).ok_or_else(|| KiwiError("unexpected end of data".into()))?; - self.pos += 1; - Ok(b) - } - - fn take(&mut self, n: usize) -> Result<&'b [u8], KiwiError> { - let end = self.pos.checked_add(n).filter(|e| *e <= self.data.len()).ok_or_else(|| KiwiError("unexpected end of data".into()))?; - let s = self.data.get(self.pos..end).ok_or_else(|| KiwiError("unexpected end of data".into()))?; - self.pos = end; - Ok(s) - } - - fn var_uint(&mut self) -> Result { - let mut value = 0u32; - let mut shift = 0; - loop { - let b = self.byte()?; - let part = b & 127; - if shift == 28 && (part > 0x0f || b & 128 != 0) { - return err("u32 varint overflow"); - } - value |= u32::from(part) << shift; - shift += 7; - if b & 128 == 0 { - return Ok(value); - } - } - } - - fn var_int(&mut self) -> Result { - let v = self.var_uint()?; - Ok(if v & 1 != 0 { !((v >> 1) as i32) } else { (v >> 1) as i32 }) - } - - fn var_uint64(&mut self) -> Result { - let mut value = 0u64; - let mut shift = 0u32; - loop { - let b = self.byte()?; - if shift == 56 { - // The ninth byte carries a full eight bits. - return Ok(value | (u64::from(b) << 56)); - } - value |= u64::from(b & 127) << shift; - shift += 7; - if b & 128 == 0 { - return Ok(value); - } - } - } - - fn var_int64(&mut self) -> Result { - let v = self.var_uint64()?; - Ok(if v & 1 != 0 { !((v >> 1) as i64) } else { (v >> 1) as i64 }) - } - - fn var_float(&mut self) -> Result { - if self.data.get(self.pos) == Some(&0) { - self.pos += 1; - return Ok(0.0); - } - let b = self.take(4)?; - let bits = u32::from_le_bytes([b[0], b[1], b[2], b[3]]); - // The exponent is stored first so zero fits one byte; move it back into place. - Ok(f32::from_bits(bits.rotate_left(23))) - } - - fn string(&mut self) -> Result { - let rest = self.data.get(self.pos..).unwrap_or_default(); - let len = rest.iter().position(|b| *b == 0).ok_or_else(|| KiwiError("unterminated string".into()))?; - let s = String::from_utf8_lossy(self.take(len)?).into_owned(); - self.pos += 1; - Ok(s) - } -} - -impl Schema { - /// Decode a binary schema. - pub fn decode(data: &[u8]) -> Result { - let mut r = Reader { data, pos: 0 }; - let count = r.var_uint()? as usize; - if count > MAX_DEFS || count > r.left() { - return err("schema: too many definitions"); - } - let mut defs = Vec::with_capacity(count); - let mut raw_types = Vec::new(); - let mut total_fields = 0usize; - for _ in 0..count { - let name = r.string()?; - let kind = match r.byte()? { - 0 => Kind::Enum, - 1 => Kind::Struct, - 2 => Kind::Message, - k => return err(format!("schema: unknown definition kind {k}")), - }; - let n = r.var_uint()? as usize; - total_fields = total_fields.saturating_add(n); - if n > MAX_FIELDS || n > r.left() || total_fields > MAX_SCHEMA_FIELDS { - return err("schema: too many fields"); - } - let mut fields = Vec::with_capacity(n); - for _ in 0..n { - let fname = r.string()?; - let ty = r.var_int()?; - let array = r.byte()? & 1 != 0; - let value = r.var_uint()?; - if kind == Kind::Message && fields.iter().any(|f: &Field| f.value == value) { - return err(format!("schema: duplicate field id {value} in {name}")); - } - raw_types.push(ty); - fields.push(Field { name: fname, ty: None, array, value }); - } - defs.push(Def { name, kind, fields }); - } - let total = defs.len(); - let mut types = raw_types.into_iter(); - for d in &mut defs { - for f in &mut d.fields { - let raw = types.next().unwrap_or(0); - if d.kind == Kind::Enum { - continue; - } - f.ty = Some(if raw < 0 { - *BUILTINS.get((!raw) as usize).ok_or_else(|| KiwiError(format!("schema: unknown type {raw}")))? - } else { - let i = raw as usize; - if i >= total { - return err(format!("schema: field {} names missing definition {i}", f.name)); - } - Type::Def(i) - }); - } - } - Ok(Schema { defs }) - } - - pub fn find(&self, name: &str) -> Option { - self.defs.iter().position(|d| d.name == name) - } - - /// Decode a message of definition `root`, within [`MIN_VALUES`] values. - pub fn decode_message<'s>(&'s self, root: usize, data: &[u8]) -> Result, KiwiError> { - self.decode_message_within(root, data, MIN_VALUES) - } - - /// [`Self::decode_message`] within `budget` values (see [`value_budget`]). - pub fn decode_message_within<'s>(&'s self, root: usize, data: &[u8], budget: usize) -> Result, KiwiError> { - let mut d = Decoder { schema: self, r: Reader { data, pos: 0 }, budget, ids: vec![None; self.defs.len()] }; - d.def(root, 0) - } -} - -/// Most values decoded from a file whose compressed canvas is `packed` bytes. -pub(crate) fn value_budget(packed: usize) -> usize { - packed.saturating_mul(VALUES_PER_PACKED_BYTE).clamp(MIN_VALUES, MAX_VALUES) -} - -struct Decoder<'s, 'b> { - schema: &'s Schema, - r: Reader<'b>, - budget: usize, - /// Per definition, the index of the first field with each id (message field ids, enum - /// values), built the first time the definition is decoded: a message can carry many tags - /// against a wide definition, and a scan per tag would multiply the two. - ids: Vec>>, -} - -impl<'s> Decoder<'s, '_> { - fn spend(&mut self, n: usize) -> Result<(), KiwiError> { - self.budget = self.budget.checked_sub(n).ok_or_else(|| KiwiError("message: too many values".into()))?; - Ok(()) - } - - /// The first field of definition `i` with id (or enum value) `id`. - fn field_by_id(&mut self, i: usize, id: u32) -> Option<&'s Field> { - let fields = &self.schema.defs.get(i)?.fields; - let ids = self.ids.get_mut(i)?.get_or_insert_with(|| { - let mut m = HashMap::with_capacity(fields.len()); - for (j, f) in fields.iter().enumerate() { - m.entry(f.value).or_insert(j); - } - m - }); - fields.get(*ids.get(&id)?) - } - - fn def(&mut self, i: usize, depth: usize) -> Result, KiwiError> { - if depth > MAX_DEPTH { - return err("message: nested too deeply"); - } - self.spend(1)?; - let schema = self.schema; - let d = schema.defs.get(i).ok_or_else(|| KiwiError("message: missing definition".into()))?; - match d.kind { - Kind::Enum => { - let v = self.r.var_uint()?; - Ok(self.field_by_id(i, v).map_or(Kv::Uint(u64::from(v)), |f| Kv::Enum(f.name.as_str()))) - } - Kind::Struct => { - let mut out = Vec::with_capacity(d.fields.len()); - for f in &d.fields { - out.push((f.name.as_str(), self.field(f, depth)?)); - } - Ok(Kv::Object(out)) - } - Kind::Message => { - let mut out = Vec::new(); - loop { - let id = self.r.var_uint()?; - if id == 0 { - // Grown by doubling: trimmed, a large file's tree takes a good part less. - out.shrink_to_fit(); - return Ok(Kv::Object(out)); - } - let f = self.field_by_id(i, id).ok_or_else(|| KiwiError(format!("message: {} has no field {id}", d.name)))?; - out.push((f.name.as_str(), self.field(f, depth)?)); - } - } - } - } - - fn field(&mut self, f: &Field, depth: usize) -> Result, KiwiError> { - let ty = f.ty.ok_or_else(|| KiwiError("message: untyped field".into()))?; - if !f.array { - // A nested definition spends its own value in `def`. - if !matches!(ty, Type::Def(_)) { - self.spend(1)?; - } - return self.value(ty, depth); - } - let n = self.r.var_uint()? as usize; - // Every element takes at least one byte. - if n > self.r.left() { - return err("message: array longer than the data"); - } - // The field itself counts, so empty arrays can't pile up for free. - self.spend(1)?; - if ty == Type::Byte { - return Ok(Kv::Bytes(self.r.take(n)?.to_vec())); - } - self.spend(n)?; - let mut out = Vec::with_capacity(n); - for _ in 0..n { - out.push(self.value(ty, depth)?); - } - Ok(Kv::Array(out)) - } - - fn value(&mut self, ty: Type, depth: usize) -> Result, KiwiError> { - Ok(match ty { - Type::Bool => Kv::Bool(self.r.byte()? != 0), - Type::Byte => Kv::Uint(u64::from(self.r.byte()?)), - Type::Int => Kv::Int(i64::from(self.r.var_int()?)), - Type::Uint => Kv::Uint(u64::from(self.r.var_uint()?)), - Type::Float => Kv::Float(self.r.var_float()?), - Type::Str => Kv::Str(self.r.string()?), - Type::Int64 => Kv::Int(self.r.var_int64()?), - Type::Uint64 => Kv::Uint(self.r.var_uint64()?), - Type::Def(i) => self.def(i, depth + 1)?, - }) - } -} - -/// An encoder for the same format: the `.fig` export writes its schema and message with it (and -/// test fixtures are built with it). Values are checked against the schema; it never panics. -pub mod encode { - use super::{BUILTINS, Field, Kind, KiwiError, Kv, MAX_DEPTH, Schema, Type, err}; - - #[derive(Default)] - pub struct Writer(pub Vec); - - impl Writer { - pub fn byte(&mut self, b: u8) { - self.0.push(b); - } - - pub fn var_uint(&mut self, mut v: u32) { - loop { - let b = (v & 127) as u8; - v >>= 7; - if v == 0 { - self.0.push(b); - return; - } - self.0.push(b | 128); - } - } - - pub fn var_int(&mut self, v: i32) { - self.var_uint(((v << 1) ^ (v >> 31)) as u32); - } - - pub fn var_uint64(&mut self, mut v: u64) { - for _ in 0..8 { - let b = (v & 127) as u8; - v >>= 7; - if v == 0 { - self.0.push(b); - return; - } - self.0.push(b | 128); - } - self.0.push(v as u8); - } - - pub fn var_int64(&mut self, v: i64) { - self.var_uint64(((v << 1) ^ (v >> 63)) as u64); - } - - pub fn var_float(&mut self, f: f32) { - let bits = f.to_bits().rotate_right(23); - if bits & 255 == 0 { - self.0.push(0); - } else { - self.0.extend_from_slice(&bits.to_le_bytes()); - } - } - - /// A NUL-terminated string (NULs inside are dropped: they would end it early). - pub fn string(&mut self, s: &str) { - self.0.extend(s.bytes().filter(|b| *b != 0)); - self.0.push(0); - } - } - - pub fn schema(s: &Schema) -> Vec { - let mut w = Writer::default(); - w.var_uint(s.defs.len() as u32); - for d in &s.defs { - w.string(&d.name); - w.byte(match d.kind { - Kind::Enum => 0, - Kind::Struct => 1, - Kind::Message => 2, - }); - w.var_uint(d.fields.len() as u32); - for f in &d.fields { - w.string(&f.name); - w.var_int(match f.ty { - None => 0, - Some(Type::Def(i)) => i32::try_from(i).unwrap_or(i32::MAX), - Some(t) => !(BUILTINS.iter().position(|b| *b == t).unwrap_or(0) as i32), - }); - w.byte(u8::from(f.array)); - w.var_uint(f.value); - } - } - w.0 - } - - /// Encode `v` as definition `def` (objects may leave message fields out; struct fields are - /// required, in order). Fails on what doesn't fit the schema: unknown fields or enum names, - /// missing struct fields, wrong types, numbers out of range, non-finite floats. - pub fn message(s: &Schema, def: usize, v: &Kv) -> Result, KiwiError> { - let mut w = Writer::default(); - encode_def(s, def, v, &mut w, 0)?; - Ok(w.0) - } - - fn encode_def(s: &Schema, i: usize, v: &Kv, w: &mut Writer, depth: usize) -> Result<(), KiwiError> { - if depth > MAX_DEPTH { - return err("encode: nested too deeply"); - } - let d = s.defs.get(i).ok_or_else(|| KiwiError("encode: missing definition".into()))?; - match d.kind { - Kind::Enum => { - let value = match v { - Kv::Uint(u) => u32::try_from(*u).ok(), - _ => v.str().and_then(|name| d.fields.iter().find(|f| f.name == name)).map(|f| f.value), - }; - w.var_uint(value.ok_or_else(|| KiwiError(format!("encode: {v:?} is not a value of {}", d.name)))?); - } - Kind::Struct => { - for f in &d.fields { - let fv = v.get(&f.name).ok_or_else(|| KiwiError(format!("encode: {} needs field {}", d.name, f.name)))?; - encode_field(s, f, fv, w, depth)?; - } - } - Kind::Message => { - let Kv::Object(fields) = v else { return err(format!("encode: {} needs an object", d.name)) }; - for (name, fv) in fields { - let f = d.fields.iter().find(|f| f.name == *name).ok_or_else(|| KiwiError(format!("encode: {} has no field {name}", d.name)))?; - w.var_uint(f.value); - encode_field(s, f, fv, w, depth)?; - } - w.var_uint(0); - } - } - Ok(()) - } - - fn encode_field(s: &Schema, f: &Field, v: &Kv, w: &mut Writer, depth: usize) -> Result<(), KiwiError> { - let ty = f.ty.ok_or_else(|| KiwiError("encode: untyped field".into()))?; - if !f.array { - return encode_value(s, ty, v, w, depth); - } - let len = |n: usize| u32::try_from(n).map_err(|_| KiwiError(format!("encode: {} is too long", f.name))); - if let (Type::Byte, Kv::Bytes(b)) = (ty, v) { - w.var_uint(len(b.len())?); - w.0.extend_from_slice(b); - return Ok(()); - } - let Kv::Array(items) = v else { return err(format!("encode: {} needs a list", f.name)) }; - w.var_uint(len(items.len())?); - for it in items { - encode_value(s, ty, it, w, depth)?; - } - Ok(()) - } - - /// An integer value (whole finite floats count). - fn int(v: &Kv) -> Option { - match v { - Kv::Int(i) => Some(i128::from(*i)), - Kv::Uint(u) => Some(i128::from(*u)), - Kv::Bool(b) => Some(i128::from(*b)), - Kv::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f as i128), - _ => None, - } - } - - fn encode_value(s: &Schema, ty: Type, v: &Kv, w: &mut Writer, depth: usize) -> Result<(), KiwiError> { - let bad = || KiwiError(format!("encode: {v:?} is not a {ty:?}")); - let ranged = |lo: i128, hi: i128| int(v).filter(|i| (lo..=hi).contains(i)).ok_or_else(bad); - match ty { - Type::Bool => w.byte(u8::from(v.bool().ok_or_else(bad)?)), - Type::Byte => w.byte(ranged(0, 255)? as u8), - Type::Int => w.var_int(ranged(i32::MIN.into(), i32::MAX.into())? as i32), - Type::Uint => w.var_uint(ranged(0, u32::MAX.into())? as u32), - // Infinity is a value of its own (an axis with no maximum size); NaN is not. - Type::Float => w.var_float(match v { - Kv::Float(f) if f.is_infinite() => *f, - _ => v.f64().map(|x| x as f32).filter(|x| x.is_finite()).ok_or_else(bad)?, - }), - Type::Str => w.string(v.str().ok_or_else(bad)?), - Type::Int64 => w.var_int64(ranged(i64::MIN.into(), i64::MAX.into())? as i64), - Type::Uint64 => w.var_uint64(ranged(0, u64::MAX.into())? as u64), - Type::Def(i) => encode_def(s, i, v, w, depth + 1)?, - } - Ok(()) - } -} - -/// The built-in type names, in [`BUILTINS`] order. -const BUILTIN_NAMES: [&str; 8] = ["bool", "byte", "int", "uint", "float", "string", "int64", "uint64"]; - -impl Schema { - /// A schema from a compact text form, one definition per line: `enum Name A B …` (values from - /// 0), `struct Name type field, type field[] …` or `message Name …` (field ids from 1), the - /// types being built-in names or other definitions'. `A=3` or `type field=7` gives a value or - /// a field its own number. - pub fn parse(text: &str) -> Result { - let lines: Vec> = text.lines().map(|l| l.split_whitespace().collect::>()).filter(|l| !l.is_empty()).collect(); - let index = |name: &str| lines.iter().position(|l| l.get(1) == Some(&name)); - let mut defs = Vec::with_capacity(lines.len()); - for l in &lines { - let (Some(kind), Some(name)) = (l.first(), l.get(1)) else { return err("schema text: a definition needs a kind and a name") }; - let rest = l.get(2..).unwrap_or_default(); - let (kind, fields) = match *kind { - "enum" => { - let mut fields = Vec::new(); - for (n, i) in rest.iter().zip(0..) { - let (name, value) = numbered(n, i)?; - fields.push(Field { name, ty: None, array: false, value }); - } - (Kind::Enum, fields) - } - "struct" | "message" => { - let mut fields = Vec::new(); - for (f, id) in rest.join(" ").split(',').zip(1..) { - let Some((t, n)) = f.trim().split_once(' ') else { return err(format!("schema text: bad field `{f}` in {name}")) }; - let base = t.trim_end_matches("[]"); - let ty = match BUILTIN_NAMES.iter().position(|b| *b == base) { - Some(i) => BUILTINS.get(i).copied(), - None => index(base).map(Type::Def), - } - .ok_or_else(|| KiwiError(format!("schema text: unknown type {base}")))?; - let (name, value) = numbered(n.trim(), id)?; - if *kind == "message" && fields.iter().any(|f: &Field| f.value == value) { - return err(format!("schema text: duplicate field id {value} in {name}")); - } - fields.push(Field { name, ty: Some(ty), array: t.ends_with("[]"), value }); - } - (if *kind == "struct" { Kind::Struct } else { Kind::Message }, fields) - } - k => return err(format!("schema text: unknown kind {k}")), - }; - defs.push(Def { name: name.to_string(), kind, fields }); - } - Ok(Schema { defs }) - } -} - -/// `name=number` as its parts, or `name` with `default`. -fn numbered(token: &str, default: u32) -> Result<(String, u32), KiwiError> { - match token.split_once('=') { - None => Ok((token.to_string(), default)), - Some((name, n)) => Ok((name.to_string(), n.parse().map_err(|_| KiwiError(format!("schema text: bad number in `{token}`")))?)), - } -} - -#[cfg(test)] -mod tests { - use super::Reader; - - #[test] - fn overflowing_u32_varint_is_rejected() { - let mut boundary = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x0f], pos: 0 }; - assert_eq!(boundary.var_uint(), Ok(u32::MAX)); - - let mut overflowing = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x7f], pos: 0 }; - assert!(overflowing.var_uint().is_err(), "overflowing u32 varint was accepted"); - } -} diff --git a/crates/format/src/fig/map.rs b/crates/format/src/fig/map.rs index 5e4ab7e9d..f075c1526 100644 --- a/crates/format/src/fig/map.rs +++ b/crates/format/src/fig/map.rs @@ -1,56 +1,66 @@ -//! Decoded `.fig` message → REST API file JSON, which [`crate::rest`] then imports. -//! -//! The message lists node changes; each names its id (`guid`), its parent and its position among -//! the siblings (`parentIndex`). Nodes are read by field name, so files written with newer -//! schemas still import what is understood. Instances carry only their overrides: their layers -//! are expanded here from the main component (overrides and derived layout matched by id path, -//! component property values applied) so the import looks as saved. +//! Decoded `.fig` message → REST API file JSON, which [`crate::rest`] then imports. The mapping +//! is `craft_fig::rest`; FigCraft gives it its own connector routing and text measure, so an +//! imported connector runs as one drawn here, and takes the networks it hands over. -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::rc::Rc; - -use figcraft_doc::VectorNetwork; -use figcraft_doc::geom::{Affine, Point}; -use figcraft_doc::proto::{MAX_ACTION_DEPTH, MAX_EXPR_DEPTH}; -use serde_json::{Map, Value, json}; +use craft_fig::rest::{self, Geometry, RouteEnd, Routing, SavedRuns, Side}; +use figcraft_doc::geom::{Point, measure}; +use figcraft_doc::{BoardShape, ConnectorPath, VectorNetwork}; +use serde_json::Value; use super::kiwi::Kv; -use super::network; -mod board; -mod component; -mod connector; -mod document; -mod layer; -mod layout; -mod paint; -mod proto; -mod text; -mod variables; +/// FigCraft's board routing and text measure, for the mapping. +struct FigGeometry; -#[cfg(test)] -pub(super) use board::board_shape; +fn end(e: RouteEnd) -> figcraft_doc::RouteEnd { + match e { + RouteEnd::Point(p) => figcraft_doc::RouteEnd::Point(p), + RouteEnd::Box(b, s) => figcraft_doc::RouteEnd::Box(b, side(s)), + } +} -use component::OverrideScope; -#[cfg(test)] -use paint::paint; +fn side(s: Side) -> figcraft_doc::Side { + match s { + Side::Auto => figcraft_doc::Side::Auto, + Side::Top => figcraft_doc::Side::Top, + Side::Right => figcraft_doc::Side::Right, + Side::Bottom => figcraft_doc::Side::Bottom, + Side::Left => figcraft_doc::Side::Left, + } +} -type Obj = Map; +fn side_back(s: figcraft_doc::Side) -> Side { + match s { + figcraft_doc::Side::Auto => Side::Auto, + figcraft_doc::Side::Top => Side::Top, + figcraft_doc::Side::Right => Side::Right, + figcraft_doc::Side::Bottom => Side::Bottom, + figcraft_doc::Side::Left => Side::Left, + } +} -/// Deepest nesting followed. -const MAX_DEPTH: usize = 256; -/// Most path commands read from one geometry blob. -const MAX_COMMANDS: usize = 200_000; -const MAX_GRID_TRACKS: usize = 1_000; -pub(super) const MAX_GRID_TRACK_VALUE: f64 = 1e6; -/// Smallest and largest scale factor of a scaled instance (`symbolData.uniformScaleFactor`, times -/// those of the instances around it) that is followed: a junk factor changes nothing. -pub(super) const MIN_SCALE_FACTOR: f64 = 1e-3; -pub(super) const MAX_SCALE_FACTOR: f64 = 1e3; -/// Id of "no style". -const NO_STYLE: &str = "4294967295:4294967295"; -/// Longest asset `key` or `version` kept for resolving references given as assets. -const MAX_ASSET_PART: usize = 256; +impl Geometry for FigGeometry { + fn route(&self, from: RouteEnd, to: RouteEnd, routing: Routing, saved: Option<&SavedRuns>) -> Option> { + let routing = match routing { + Routing::Straight => figcraft_doc::Routing::Straight, + Routing::Elbow => figcraft_doc::Routing::Elbow, + Routing::Curved => figcraft_doc::Routing::Curved, + }; + let path = saved.map(|s| ConnectorPath::Runs { across: s.across, at: s.at.clone() }); + figcraft_doc::route_along(end(from), end(to), routing, path.as_ref()) + } + + fn attach(&self, from: RouteEnd, to: RouteEnd) -> ((Point, Option), (Point, Option)) { + let (a, b) = (end(from), end(to)); + let ((p0, p1), (s0, s1)) = (figcraft_doc::attach_points(a, b), figcraft_doc::attached_sides(a, b)); + ((p0, s0.map(side_back)), (p1, s1.map(side_back))) + } + + fn text_path_measurable(&self, d: &str) -> bool { + let path = figcraft_doc::geom::svg_path(d).unwrap_or_default(); + measure::polylines(&path).and_then(|lines| lines.first().map(|line| line.length() > 1e-9)).unwrap_or(false) + } +} /// The REST API file JSON for message `msg`, with the warnings about what was skipped and the /// vector networks its layers name by `vectorNetworkRef` (for [`crate::rest::import_with_networks`]). @@ -59,49 +69,189 @@ pub(super) fn to_rest(msg: &Kv, name: &str, max_nodes: usize) -> (Value, Vec (Value, Vec, Vec>) { - let mut m = Mapper::new(msg, max_nodes); - m.board = board; - let _canon = VarCanon::install(&m); - let doc = m.document(); - // Large values are moved in, never passed through `json!`, which serialises its arguments: - // a deep copy of the whole tree, briefly holding it twice. - let mut out = json!({"name": name}); - out["document"] = doc; - if !m.library_contexts.is_empty() { - out[crate::rest::FIG_LIBRARY_CONTEXTS_FIELD] = Value::Array(std::mem::take(&mut m.library_contexts)); + let options = rest::Options { max_nodes, geometry: &FigGeometry, outlined_stroke: Some(super::export::STASH), board }; + let mut mapped = rest::to_rest(msg, name, &options); + // Each network passes the importer's own checks, as the JSON's `vectorNetwork` does. + let networks: Vec> = + mapped.networks.into_iter().map(|n| serde_json::to_value(n?).ok().and_then(|v| crate::rest::network(&v))).collect(); + if board { + native_board_shapes(msg, &mut mapped.json, &mut mapped.warnings); } - // Mains in the file that the layer cap kept out: their instances are told apart from those of - // components the file doesn't have (#981). - if m.count >= m.max_nodes { - let capped: Vec = m.referenced_mains.difference(&m.mapped_mains).map(|id| json!(id)).collect(); - if !capped.is_empty() { - out[crate::rest::FIG_CAPPED_MAINS_FIELD] = Value::Array(capped); - } - } - if !m.styles.is_empty() { - out["styles"] = Value::Object(std::mem::take(&mut m.styles)); - } - if !m.components.is_empty() { - out["components"] = Value::Object(std::mem::take(&mut m.components)); - } - if !m.sets.is_empty() { - out["componentSets"] = Value::Object(std::mem::take(&mut m.sets)); - } - if let Some(vars) = m.variables() { - out["meta"] = vars; - } - let styles = m.style_definitions(); - if !styles.is_empty() { - out["styleDefinitions"] = Value::Array(styles); - } - (out, m.warnings.finish(), m.networks) + (mapped.json, mapped.warnings, networks) } -#[cfg(test)] -mod image_filter_tests; +/// FigJam shapes whose generated records are complete are native board items in FigCraft. The +/// shared mapper owns the neutral generated layers; this adapter supplies only FigCraft's board +/// shape model, outline, and layout semantics. +fn native_board_shapes(msg: &Kv, json: &mut Value, warnings: &mut Vec) { + let Some(changes) = msg.get("nodeChanges") else { return }; + let mut shapes = std::collections::HashMap::new(); + for node in changes.list() { + if node.get("type").and_then(Kv::str) != Some("SHAPE_WITH_TEXT") { + continue; + } + let Some(guid) = node.get("guid") else { continue }; + let Some(origin) = guid + .get("sessionID") + .and_then(Kv::f64) + .zip(guid.get("localID").and_then(Kv::f64)) + .map(|(session, local)| format!("{}:{}", session as u64, local as u64)) + else { + continue; + }; + let kind = node.get("shapeWithTextType").and_then(Kv::str).unwrap_or("SQUARE"); + let Some(shape) = board_shape(kind) else { + warnings.push(format!("shape with text kind {} has no FigCraft outline; kept as a frame", crate::rest::props::clip_str(kind))); + continue; + }; + // An outer text fallback means the generated body was absent or invalid. Keep the shared + // mapper's editable generated layers in that case, matching the older FigJam adapter. + if node.get("textData").and_then(|t| t.get("characters")).and_then(Kv::str).is_some_and(|s| !s.trim().is_empty()) { + continue; + } + shapes.insert(origin, (shape, generated_empty_body(node))); + } + apply_native_board_shapes(json, &shapes); +} + +/// Traverse only the mapped REST tree (already bounded by `max_nodes`) and adapt each source +/// origin at most once. The origin index avoids rescanning the tree for every source record. +fn apply_native_board_shapes(json: &mut Value, shapes: &std::collections::HashMap) { + fn visit(json: &mut Value, shapes: &std::collections::HashMap, visited: &mut std::collections::HashSet) { + if let Some(origin) = json.get(craft_fig::rest::FIG_SOURCE_FIELD).and_then(|s| s.get("origin")).and_then(Value::as_str).map(str::to_owned) + && visited.insert(origin.clone()) + && let Some((shape, empty_body)) = shapes.get(&origin).copied() + { + apply_native_board_shape(json, &origin, shape, empty_body); + } + match json { + Value::Object(fields) => fields.values_mut().for_each(|child| visit(child, shapes, visited)), + Value::Array(items) => items.iter_mut().for_each(|child| visit(child, shapes, visited)), + _ => {} + } + } + visit(json, shapes, &mut std::collections::HashSet::new()); +} + +fn apply_native_board_shape(rest_node: &mut Value, origin: &str, shape: BoardShape, empty_body: bool) { + let Some(children) = rest_node.get("children").and_then(Value::as_array) else { return }; + let has_generated_outline = !children.is_empty() && children[0]["type"] == "VECTOR"; + let has_generated_label = children.len() == 2 && children[1]["type"] == "TEXT"; + if !has_generated_outline || !(has_generated_label || (children.len() == 1 && empty_body)) { + return; + } + let (Some(width), Some(height)) = ( + rest_node.get("size").and_then(|s| s.get("x")).and_then(Value::as_f64), + rest_node.get("size").and_then(|s| s.get("y")).and_then(Value::as_f64), + ) else { + return; + }; + if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) { + return; + } + let (width, height) = (width.min(crate::rest::props::MAX_SIZE), height.min(crate::rest::props::MAX_SIZE)); + let Some(network) = serde_json::to_value(VectorNetwork::from_path(&shape.path(width, height))).ok() else { return }; + + rest_node["board"] = serde_json::json!({"type": "shape", "shape": shape.id()}); + rest_node["fills"] = serde_json::json!([]); + rest_node["strokes"] = serde_json::json!([]); + rest_node["clipsContent"] = serde_json::json!(false); + rest_node["layoutMode"] = serde_json::json!("VERTICAL"); + rest_node["primaryAxisAlignItems"] = serde_json::json!("CENTER"); + rest_node["counterAxisAlignItems"] = serde_json::json!("CENTER"); + rest_node["primaryAxisSizingMode"] = serde_json::json!("FIXED"); + rest_node["counterAxisSizingMode"] = serde_json::json!("FIXED"); + let [top, right, bottom, left] = shape.text_insets(); + rest_node["paddingTop"] = serde_json::json!(top * height); + rest_node["paddingRight"] = serde_json::json!(right * width); + rest_node["paddingBottom"] = serde_json::json!(bottom * height); + rest_node["paddingLeft"] = serde_json::json!(left * width); + + let Some(children) = rest_node.get_mut("children").and_then(Value::as_array_mut) else { return }; + if children.len() == 1 { + children.push(serde_json::json!({ + "id": format!("{origin};generated1"), + "type": "TEXT", + "name": "", + "characters": "", + "size": {"x": width, "y": height}, + "relativeTransform": [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + "style": {"textAutoResize": "HEIGHT", "textAlignHorizontal": "CENTER"}, + "layoutSizingHorizontal": "FILL" + })); + } + let outline = &mut children[0]; + outline["name"] = serde_json::json!("Outline"); + outline["vectorNetwork"] = network; + outline["size"] = serde_json::json!({"x": width, "y": height}); + outline["relativeTransform"] = serde_json::json!([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]); + outline["layoutPositioning"] = serde_json::json!("ABSOLUTE"); + outline["constraints"] = serde_json::json!({"horizontal": "SCALE", "vertical": "SCALE"}); + outline.as_object_mut().map(|o| o.remove("cornerRadius")); + + let label = &mut children[1]; + label["layoutSizingHorizontal"] = serde_json::json!("FILL"); + if let Some(style) = label.get_mut("style").and_then(Value::as_object_mut) { + style.insert("textAutoResize".into(), serde_json::json!("HEIGHT")); + style.insert("textAlignHorizontal".into(), serde_json::json!("CENTER")); + } +} + +/// The shared snapshot mapper omits a generated text child whose characters are empty. FigCraft +/// still keeps that empty child on a native shape, matching its prior mapper behavior. +fn generated_empty_body(node: &Kv) -> bool { + fn record<'a, 's>(node: &'a Kv<'s>, field: &str) -> Option<&'a Kv<'s>> { + node.get(field)?.get("overrides")?.list().iter().find(|record| { + let Some(guids) = record.get("guidPath").and_then(|path| path.get("guids")).map(Kv::list) else { return false }; + if guids.len() != 1 { + return false; + } + let session = guids[0].get("sessionID").and_then(Kv::f64); + let local = guids[0].get("localID").and_then(Kv::f64); + session == Some(40_000_000.0) && local == Some(1.0) + }) + } + let bounds = node.get("derivedImmutableFrameData"); + let version = bounds.and_then(|v| v.get("version")).and_then(Kv::f64); + if version != Some(1.0) { + return false; + } + let Some(style) = record(node, "nodeGenerationData") else { return false }; + let Some(_) = record(node, "derivedImmutableFrameData") else { return false }; + style.get("textData").and_then(|v| v.get("characters")).and_then(Kv::str) == Some("") +} + +/// FigJam's `shapeWithTextType` values that have a corresponding FigCraft board outline. +pub(super) fn board_shape(kind: &str) -> Option { + Some(match kind { + "SQUARE" => BoardShape::Rectangle, + "ROUNDED_RECTANGLE" => BoardShape::RoundedRectangle, + "ELLIPSE" => BoardShape::Ellipse, + "DIAMOND" => BoardShape::Diamond, + "TRIANGLE_UP" => BoardShape::Triangle, + "TRIANGLE_DOWN" => BoardShape::TriangleDown, + "PARALLELOGRAM_RIGHT" => BoardShape::ParallelogramRight, + "PARALLELOGRAM_LEFT" => BoardShape::ParallelogramLeft, + "TRAPEZOID" => BoardShape::Trapezoid, + "PENTAGON" => BoardShape::Pentagon, + "HEXAGON" => BoardShape::Hexagon, + "OCTAGON" => BoardShape::Octagon, + "STAR" => BoardShape::Star, + "PLUS" => BoardShape::Plus, + "ARROW_LEFT" => BoardShape::ArrowLeft, + "ARROW_RIGHT" => BoardShape::ArrowRight, + "CHEVRON" => BoardShape::Chevron, + "SPEECH_BUBBLE" => BoardShape::SpeechBubble, + "ENG_DATABASE" => BoardShape::Database, + "DOCUMENT_SINGLE" => BoardShape::Document, + "PREDEFINED_PROCESS" => BoardShape::PredefinedProcess, + "MANUAL_INPUT" => BoardShape::ManualInput, + "INTERNAL_STORAGE" => BoardShape::InternalStorage, + _ => return None, + }) +} /// REST importer warnings reworded for a `.fig` import (`None`: drop it). pub(super) fn adapt_warning(w: String) -> Option { @@ -110,538 +260,3 @@ pub(super) fn adapt_warning(w: String) -> Option { } Some(w.replace("the variables JSON", "the file").replace("the file JSON", "the file")) } - -// ---- small readers ---- - -/// A generated child is identified by one exact template GUID, not its array position. -fn generated_record<'a>(v: &View<'a>, field: &str, local_id: u32) -> Option<&'a Kv<'a>> { - v.get(field)?.get("overrides")?.list().iter().find(|row| { - row.get("guidPath").and_then(|path| path.get("guids")).map(Kv::list).is_some_and(|guids| { - guids.len() == 1 && num(&guids[0], "sessionID") == Some(40_000_000.0) && num(&guids[0], "localID") == Some(f64::from(local_id)) - }) - }) -} - -fn num(n: &Kv, k: &str) -> Option { - n.get(k).and_then(Kv::f64) -} - -fn guid(v: &Kv) -> Option { - Some(format!("{}:{}", num(v, "sessionID")? as u64, num(v, "localID")? as u64)) -} - -#[cfg(test)] -mod connector_snapshot_budget_tests; - -/// A `GUID`-holding reference (`StyleId`, `VariableID`, …): its `guid`. -fn ref_guid(v: &Kv) -> Option { - v.get("guid").and_then(guid).filter(|g| g != NO_STYLE) -} - -fn vec2(v: &Kv) -> Option { - Some(json!({"x": num(v, "x")?, "y": num(v, "y")?})) -} - -fn size(v: &Kv) -> Option<(f64, f64)> { - Some((num(v, "x")?, num(v, "y")?)) -} - -fn matrix(m: &Kv) -> Option { - let c = |k: &str| num(m, k); - let a = Affine::new([c("m00")?, c("m10")?, c("m01")?, c("m11")?, c("m02")?, c("m12")?]); - a.as_coeffs().iter().all(|x| x.is_finite()).then_some(a) -} - -fn rows(a: Affine) -> Value { - let [a, b, c, d, e, f] = a.as_coeffs(); - json!([[a, c, e], [b, d, f]]) -} - -fn copy_num(o: &mut Obj, n: &View, from: &str, to: &str) { - if let Some(x) = n.num(from) { - o.insert(to.into(), json!(x)); - } -} - -/// [`copy_num`] for a length: the layers of a scaled instance give it at the instance's scale. -fn copy_len(o: &mut Obj, n: &View, from: &str, to: &str) { - if let Some(x) = n.len(from) { - o.insert(to.into(), json!(x)); - } -} - -/// `x` at scale `k`; `None` when the result is not finite. -fn scaled(x: f64, k: f64) -> Option { - if k == 1.0 { - return Some(x); - } - let r = x * k; - r.is_finite().then_some(r) -} - -fn copy_str(o: &mut Obj, n: &View, from: &str, to: &str) { - if let Some(s) = n.str(from) { - o.insert(to.into(), json!(s)); - } -} - -/// A node seen through override layers: the last layer with a field wins. -#[derive(Clone)] -struct View<'a> { - layers: Vec<&'a Kv<'a>>, - /// The factor each layer's lengths take (`scales[i]` is for `layers[i]`): the layers of a main - /// inside a scaled instance have the instance's, the override and derived rows of the instance - /// 1, being at the instance's scale already (#2091). - scales: Vec, - /// Size and transform worked out from the constraints, over the layers' own. - fitted: Option<((f64, f64), Affine)>, -} - -impl<'a> View<'a> { - fn of(n: &'a Kv<'a>) -> Self { - Self::of_scaled(n, 1.0) - } - - /// A node of a main inside an instance scaled by `k`: its lengths read `k` times as long. - fn of_scaled(n: &'a Kv<'a>, k: f64) -> Self { - Self { layers: vec![n], scales: vec![k], fitted: None } - } - - /// This view with the layers of `upper` over it (`upper`'s fitted size and place). - fn over(&self, upper: &Self) -> Self { - let mut v = self.clone(); - v.layers.extend(upper.layers.iter().copied()); - v.scales.extend(upper.scales.iter().copied()); - v.fitted = upper.fitted; - v - } - - /// The factor of the lowest layer (the layer's own main), for values a style gives. - fn base_scale(&self) -> f64 { - self.scales.first().copied().unwrap_or(1.0) - } - - fn size(&self) -> Option<(f64, f64)> { - self.fitted.map(|f| f.0).or_else(|| { - let (v, k) = self.find("size")?; - let (x, y) = size(v)?; - Some((scaled(x, k)?, scaled(y, k)?)) - }) - } - - fn transform(&self) -> Option { - self.fitted.map(|f| f.1).or_else(|| { - let (v, k) = self.find("transform")?; - let m = matrix(v)?; - if k == 1.0 { - return Some(m); - } - let [a, b, c, d, e, f] = m.as_coeffs(); - let m = Affine::new([a, b, c, d, scaled(e, k)?, scaled(f, k)?]); - Some(m) - }) - } - - /// This view with `top` over it, each layer with the factor its lengths take. - fn with(&self, top: impl IntoIterator, f64)>) -> Self { - let mut v = self.clone(); - for (layer, scale) in top { - v.layers.push(layer); - v.scales.push(scale); - } - v - } - - /// The factor of the layer that links a style in `key` (or `legacy`), the lowest layer's when - /// none does: what the linked style's lengths take. - fn link_scale(&self, key: &str, legacy: &str) -> f64 { - self.find(key).or_else(|| self.find(legacy)).map_or_else(|| self.base_scale(), |f| f.1) - } - - /// This view with `style` just above the layer that links it in `key` (or `legacy`): the style - /// beats that layer's and lower layers' copies of its fields (stale when the style changed - /// since, or written for the style linked before), and override rows above the link beat it. - fn styled(&self, style: Option<&'a Kv<'a>>, key: &str, legacy: &str) -> Self { - let mut v = self.clone(); - if let Some(s) = style { - let linked_in = |k: &str| v.layers.iter().rposition(|l| l.get(k).is_some()); - let at = linked_in(key).or_else(|| linked_in(legacy)).map_or(1, |i| i + 1); - let at = at.min(v.layers.len()); - // The style is at the scale of the layer that links it. - let k = at.checked_sub(1).and_then(|i| v.scales.get(i)).copied().unwrap_or(1.0); - v.layers.insert(at, s); - v.scales.insert(at, k); - } - v - } - - /// An effect/grid list follows the same precedence as text styles: an override above the - /// style link wins, while the style beats stale copies on and below its linking row. A style - /// without the list is empty; it must not expose a stale list from a lower row. - fn styled_list(&self, style: &'a Kv<'a>, list: &str, key: &str, legacy: &str) -> (&'a [Kv<'a>], f64) { - let linked_in = |k: &str| self.layers.iter().rposition(|l| l.get(k).is_some()); - let above = linked_in(key).or_else(|| linked_in(legacy)).map_or(1, |i| i + 1); - self.layers - .iter() - .zip(&self.scales) - .skip(above) - .rev() - .find_map(|(row, scale)| row.get(list).map(|v| (v.list(), *scale))) - .unwrap_or_else(|| (style.get(list).map(Kv::list).unwrap_or_default(), self.link_scale(key, legacy))) - } - - fn get(&self, k: &str) -> Option<&'a Kv<'a>> { - self.layers.iter().rev().find_map(|l| l.get(k)) - } - - /// [`Self::get`], and the factor of the layer that has it. - fn find(&self, k: &str) -> Option<(&'a Kv<'a>, f64)> { - self.layers.iter().zip(&self.scales).rev().find_map(|(l, s)| l.get(k).map(|v| (v, *s))) - } - - /// A length: the number `k` holds at the scale of the layer that has it. - fn len(&self, k: &str) -> Option { - let (v, s) = self.find(k)?; - scaled(v.f64()?, s) - } - - /// [`Self::list`], and the factor of the layer that has it. - fn list_scaled(&self, k: &str) -> (&'a [Kv<'a>], f64) { - self.find(k).map_or((&[], 1.0), |(v, s)| (v.list(), s)) - } - - fn num(&self, k: &str) -> Option { - self.get(k).and_then(Kv::f64) - } - - fn str(&self, k: &str) -> Option<&'a str> { - self.get(k).and_then(Kv::str) - } - - fn flag(&self, k: &str) -> Option { - self.get(k).and_then(Kv::bool) - } - - fn list(&self, k: &str) -> &'a [Kv<'a>] { - self.get(k).map(Kv::list).unwrap_or_default() - } -} - -struct Mapper<'a> { - nodes: BTreeMap>, - kids: BTreeMap>, - blobs: Vec<&'a [u8]>, - /// Component property definitions: id → (REST name "Name#id", type). - prop_defs: BTreeMap, - /// The copies of a set's definitions each variant keeps (no name or type of their own; the - /// variant's layers and its instances' assignments use them): copy id → the definition's id. - prop_parents: BTreeMap, - /// File nodes by asset `key` and `version`: references can name a collection, variable or - /// style as the asset instead of the guid, and the file carries the resources to resolve - /// them (the collection node itself says the same `key`). - assets: BTreeMap>, - styles: Obj, - /// Descriptions of components and component sets (REST `components` / `componentSets`). - components: Obj, - sets: Obj, - /// Layers and keys of each main, built when an instance of it first needs them. - override_scopes: BTreeMap>, - /// Entries held by `override_scopes` (bounded by `max_nodes` together). - override_scope_entries: usize, - /// Component-bearing branches of the file's internal canvases (cached library definitions). - library_contexts: Vec, - /// Layers visited while scanning internal canvases, across all of them. - library_scan_count: usize, - warnings: crate::rest::Warnings, - count: usize, - /// The mains in the file that instances or instance swap defaults name, and the mains mapped - /// as layers: the difference is what the layer cap kept out. - referenced_mains: BTreeSet, - mapped_mains: BTreeSet, - /// Most layers produced or scanned, instance expansion included; the one place the cap comes - /// from (see [`super::layer_budget`]). - max_nodes: usize, - /// Layers kept back for the visible pages' top level while library copies are mapped, so the - /// copies can't take the whole budget and leave the pages empty. - reserved: usize, - /// Vector networks, each built once: the layers that show one (every instance of a main - /// holding it) name it by `vectorNetworkRef`. Kept out of the JSON, where a large file's - /// networks took gigabytes. - networks: Vec>, - /// Index in `networks` by its blob, position scale, style table, point-radius scale and the - /// layer's corner radius (which points without one of their own take). - network_ids: HashMap<(usize, u64, u64, usize, u64, u64), usize>, - /// Region paint elements (paints and gradient stops) read so far: one budget for the whole - /// file, since layers with region paints don't share their network. - region_paint_elements: usize, - /// The file is a FigJam whiteboard: its objects are built as native board items. - board: bool, -} - -impl<'a> Mapper<'a> { - fn new(msg: &'a Kv<'a>, max_nodes: usize) -> Self { - let mut nodes = BTreeMap::new(); - let mut kids: BTreeMap> = BTreeMap::new(); - let mut prop_defs = BTreeMap::new(); - let mut prop_parents = BTreeMap::new(); - let changes = msg.get("nodeChanges").map(Kv::list).unwrap_or_default(); - // The last change of a GUID wins; a REMOVED change deletes what came before it. - for n in changes { - let Some(id) = n.get("guid").and_then(guid) else { continue }; - if n.get("phase").and_then(Kv::str) == Some("REMOVED") { - nodes.remove(&id); - } else { - nodes.insert(id, n); - } - } - for n in changes { - let Some(id) = n.get("guid").and_then(guid) else { continue }; - if !nodes.get(&id).is_some_and(|latest| std::ptr::eq(*latest, n)) { - continue; - } - // Variables and their collections are read from the node list (`of_type`), never - // as layers: out of the layer tree, an instance's expansion doesn't walk them again for - // every instance without counting them (#1077). - if let Some(p) = n.get("parentIndex") - && let Some(parent) = p.get("guid").and_then(guid) - && !matches!(n.get("type").and_then(Kv::str), Some("VARIABLE" | "VARIABLE_SET")) - { - kids.entry(parent).or_default().push((p.get("position").and_then(Kv::str).unwrap_or(""), id.clone())); - } - for d in n.get("componentPropDefs").map(Kv::list).unwrap_or_default() { - let Some(did) = d.get("id").and_then(guid) else { continue }; - if let (Some(name), Some(ty)) = (d.get("name").and_then(Kv::str), d.get("type").and_then(Kv::str)) { - prop_defs.insert(did.clone(), (format!("{name}#{did}"), ty)); - } else if let Some(parent) = d.get("parentPropDefId").and_then(guid) { - prop_parents.insert(did, parent); - } - } - } - for list in kids.values_mut() { - list.sort(); - list.dedup_by(|a, b| a.1 == b.1); - } - let blobs = - msg.get("blobs").map(Kv::list).unwrap_or_default().iter().map(|b| b.get("bytes").and_then(Kv::bytes).unwrap_or_default()).collect(); - let mut assets: BTreeMap> = BTreeMap::new(); - for n in msg.get("nodeChanges").map(Kv::list).unwrap_or_default() { - let (Some(key), Some(id)) = (n.get("key").and_then(Kv::str), n.get("guid").and_then(guid)) else { continue }; - if key.is_empty() || key.len() > MAX_ASSET_PART { - continue; - } - let version = n.get("version").and_then(Kv::str).filter(|v| !v.is_empty() && v.len() <= MAX_ASSET_PART).unwrap_or(""); - assets.entry(key.to_string()).or_default().entry(version.to_string()).or_insert(id); - } - Self { - nodes, - kids, - blobs, - prop_defs, - prop_parents, - assets, - styles: Obj::new(), - components: Obj::new(), - sets: Obj::new(), - override_scopes: BTreeMap::new(), - override_scope_entries: 0, - library_contexts: Vec::new(), - library_scan_count: 0, - warnings: crate::rest::Warnings::default(), - count: 0, - referenced_mains: BTreeSet::new(), - mapped_mains: BTreeSet::new(), - max_nodes, - reserved: 0, - networks: Vec::new(), - board: false, - network_ids: HashMap::new(), - region_paint_elements: 0, - } - } - - /// The id of the resource a `VariableSetID` (or `VariableID`, `StyleId`) names: its `guid`, - /// else the file node its asset `key` and `version` names (a collection from a library is - /// referenced as the asset, and the file's own node for it says the same `key`). `None` when - /// the reference has neither or the asset names nothing (or ambiguously) in the file. - /// Original code for this importer: the field names are those of the schema each file embeds. - fn resource_id(&self, v: &Kv) -> Option { - // A guid names the resource when this file holds a node by it. One from another file (the - // library a style or collection came from, as a paste carries) names nothing here: the - // asset it also names finds the file's copy (#1638). - if let Some(g) = v.get("guid").and_then(guid).filter(|g| *g != NO_STYLE && self.nodes.contains_key(g)) { - return Some(g); - } - let asset = v.get("assetRef")?; - let key = asset.get("key").and_then(Kv::str)?; - let versions = self.assets.get(key)?; - let version = asset.get("version").and_then(Kv::str); - match version { - Some(v) => versions.get(v), - // Without a version: an unversioned record, else the file's only one. - None => versions.get("").or_else(|| (versions.len() == 1).then(|| versions.values().next()).flatten()), - } - .cloned() - } - - /// The collection a `VariableSetID` names, as one collection per library asset: a file that - /// took several updates of a library holds a copy of the collection for each version it met, - /// all with the same asset `key`. Variables and explicit modes may name any of those copies, - /// while the mode ids stay the same across them, so every copy maps to the newest one (the - /// one [`Self::variables`] keeps, with the modes of the others added). Without this, a page set - /// to a mode an older copy didn't have yet lost its mode, and the layers fell back to the - /// default mode of the newest copy. A reference by asset that names no copy by itself (no - /// version, or a version the file doesn't hold, while it holds several) still names the asset: - /// its newest live copy. - pub(super) fn collection_id(&self, v: &Kv) -> Option { - let by_asset = || v.get("assetRef")?.get("key").and_then(Kv::str).and_then(VarCanon::newest_set); - match self.resource_id(v) { - Some(id) if self.nodes.contains_key(&id) => Some(self.canonical_collection(&id).unwrap_or(id)), - // The asset index can name a node a later change removed: the asset's live copy instead. - Some(id) => by_asset().or(Some(id)), - None => by_asset(), - } - } - - /// The newest live copy of collection node `id`'s library asset, when it has a key. - pub(super) fn canonical_collection(&self, id: &str) -> Option { - let key = self.nodes.get(id)?.get("key").and_then(Kv::str).filter(|k| !k.is_empty())?; - VarCanon::newest_set(key) - } - - /// A note about what this file's mapping left out or changed. Counted, as the REST importer - /// counts its own: these notes are met once per layer, so the kinds were named once each with - /// no sign of how much of the file they covered -- a file whose every text layer lost a - /// setting read the same as one where a single layer did (#467). The collector keeps the - /// first-seen order and the same cap, since some notes name fields of the file (image - /// filters). - fn warn(&mut self, w: impl Into) { - self.warnings.add(w.into()); - } - - fn children(&self, id: &str) -> Vec { - self.kids.get(id).map(|k| k.iter().map(|(_, c)| c.clone()).collect()).unwrap_or_default() - } - - /// How many layers may be produced now: the cap, less what is kept for the visible pages. - fn budget(&self) -> usize { - self.max_nodes.saturating_sub(self.reserved) - } -} - -/// A library version (`"40727:1183"`) as numbers to order by; unparsable parts rank lowest. -fn version_rank(v: &str) -> (u64, u64) { - let mut parts = v.split(':').map(|p| p.trim().parse::().unwrap_or(0)); - (parts.next().unwrap_or(0), parts.next().unwrap_or(0)) -} - -/// Library variables, one per asset. A file that took several updates of a library keeps a copy -/// of a variable for each version it met (same `key`, another `version`), and layers and other -/// variables name them by that asset (`assetRef {key, version}`) rather than by guid. Each -/// reference goes to the newest copy: it has the values of every mode the library has now, where -/// an older one lacks the modes added since (a layer under a page set to such a mode fell back to -/// the default one). Kept per thread while a file is mapped: the paint and variable readers that -/// meet references are free functions. -#[derive(Default)] -pub(super) struct VarCanon { - by_key: HashMap, - by_id: HashMap, - /// Every live variable node of the file, with a key or not. - local: BTreeSet, - /// The newest live copy of each library collection, by asset key. Read from the file's live - /// nodes (the last change of each guid, REMOVED ones gone), not from the asset index, which - /// keeps the first node it met for a key and version even when a later change removed it. - sets_by_key: HashMap, -} - -thread_local! { - static VAR_CANON: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; -} - -/// Removes the thread's table when the mapping is done. -pub(super) struct VarCanonGuard; - -impl Drop for VarCanonGuard { - /// Clears the thread's table, so a later file on this thread starts without it. - fn drop(&mut self) { - VAR_CANON.with(|c| c.borrow_mut().take()); - } -} - -impl VarCanon { - /// Builds the table from mapper `m`'s live nodes (newest copy per asset key, for variables and - /// for collections) and installs it for this thread until the returned guard is dropped. - fn install(m: &Mapper) -> VarCanonGuard { - let mut newest: HashMap = HashMap::new(); - let mut copies: Vec<(String, String)> = Vec::new(); - let mut local = BTreeSet::new(); - let mut sets: HashMap = HashMap::new(); - for (id, n) in &m.nodes { - let ty = n.get("type").and_then(Kv::str); - if !matches!(ty, Some("VARIABLE" | "VARIABLE_SET")) || n.get("isSoftDeleted").and_then(Kv::bool) == Some(true) { - continue; - } - if ty == Some("VARIABLE_SET") { - if let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) { - let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); - let e = sets.entry(key.to_string()).or_insert_with(|| (rank, id.clone())); - if rank > e.0 || (rank == e.0 && *id > e.1) { - *e = (rank, id.clone()); - } - } - continue; - } - local.insert(id.clone()); - let Some(key) = n.get("key").and_then(Kv::str).filter(|k| !k.is_empty()) else { continue }; - let rank = version_rank(n.get("version").and_then(Kv::str).unwrap_or("")); - copies.push((id.clone(), key.to_string())); - let e = newest.entry(key.to_string()).or_insert_with(|| (rank, id.clone())); - if rank > e.0 || (rank == e.0 && *id > e.1) { - *e = (rank, id.clone()); - } - } - let mut t = VarCanon::default(); - for (id, key) in copies { - if let Some((_, canon)) = newest.get(&key) { - t.by_id.insert(id, canon.clone()); - } - } - t.by_key = newest.into_iter().map(|(k, (_, id))| (k, id)).collect(); - t.local = local; - t.sets_by_key = sets.into_iter().map(|(k, (_, id))| (k, id)).collect(); - VAR_CANON.with(|c| *c.borrow_mut() = Some(t)); - VarCanonGuard - } - - /// The variable a reference (`{guid}` or `{assetRef}`) names, as its newest copy. A guid - /// counts when this file holds a variable by it; one from another file (a paste carries the - /// library's own guids) names nothing here, so the asset it also names is tried before it is - /// kept as it is. - pub(super) fn resolve(r: &Kv) -> Option { - let by_guid = r.get("guid").and_then(guid).filter(|g| g != NO_STYLE); - VAR_CANON.with(|c| { - let c = c.borrow(); - let Some(t) = c.as_ref() else { return by_guid.clone() }; - if let Some(g) = by_guid.as_ref().filter(|g| t.local.contains(*g)) { - return Some(t.by_id.get(g).cloned().unwrap_or_else(|| g.clone())); - } - let by_asset = r.get("assetRef").and_then(|a| a.get("key")).and_then(Kv::str).and_then(|k| t.by_key.get(k)).cloned(); - by_asset.or(by_guid) - }) - } - - /// The newest live copy of the library collection with asset key `key`. - pub(super) fn newest_set(key: &str) -> Option { - VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.sets_by_key.get(key).cloned())) - } - - /// Whether a table is installed on this thread (for tests: none outlives the mapping). - #[cfg(test)] - pub(crate) fn installed() -> bool { - VAR_CANON.with(|c| c.borrow().is_some()) - } - - /// Whether variable node `id` is an older copy another one replaces. - pub(super) fn superseded(id: &str) -> bool { - VAR_CANON.with(|c| c.borrow().as_ref().and_then(|t| t.by_id.get(id)).is_some_and(|canon| canon != id)) - } -} diff --git a/crates/format/src/fig/map/board.rs b/crates/format/src/fig/map/board.rs deleted file mode 100644 index 723c490bd..000000000 --- a/crates/format/src/fig/map/board.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! FigJam whiteboard objects as native board items: what a `.jam` import builds in place of the -//! generated frames a `.fig` keeps. The REST JSON carries them as a `board` field -//! ([`crate::rest`] reads it). - -use super::layer::{own_text, valid_size}; -use super::paint::paint; -use super::{Affine, Kv, MAX_DEPTH, Mapper, Obj, Value, View, generated_record, json, num}; -use figcraft_doc::BoardShape; - -impl<'a> Mapper<'a> { - /// A sticky as a native board sticky: its frame (size, place, opacity and shadows as saved, - /// the saved colour) holding the note and, when saved, the author line. `None` (nothing - /// changed) unless every generated record is complete: then the caller keeps the generated - /// layers. - pub(super) fn native_sticky(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { - if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) { - return None; - } - let record = |id: u32| { - let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?); - let view = View::of(style).with([(bounds, 1.0)]); - (valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view) - }; - let background = record(0)?; - let fills = background.list("fillPaints"); - let solid = matches!(fills, [p] if p.get("type").and_then(Kv::str) == Some("SOLID") && p.get("visible").and_then(Kv::bool) != Some(false)); - if !solid || !background.list("strokePaints").is_empty() { - return None; - } - let note = record(1).filter(|n| own_text(n).is_some())?; - let author = record(2).filter(|a| a.flag("visible") != Some(false) && own_text(a).is_some()); - let wanted = 1 + usize::from(author.is_some()); - if depth >= MAX_DEPTH || self.count.saturating_add(wanted) > self.budget() { - return None; - } - let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?; - let at = note.transform().unwrap_or_default().as_coeffs(); - let pad = |x: f64| if x.is_finite() { x.clamp(0.0, (w.min(h) / 2.0).max(0.0)) } else { 0.0 }; - let (pad_x, pad_y) = (pad(at[4]), pad(at[5])); - // Everything is valid: build. - let paints: Vec = fills.iter().filter_map(|p| paint(p, &mut |m| self.warn(m))).collect(); - o.insert("fills".into(), Value::Array(paints)); - o.insert("strokes".into(), json!([])); - o.insert("clipsContent".into(), json!(false)); - match background.len("cornerRadius") { - Some(r) => o.insert("cornerRadius".into(), json!(r)), - None => o.remove("cornerRadius"), - }; - for (k, val) in [ - ("layoutMode", json!("VERTICAL")), - ("primaryAxisAlignItems", json!("SPACE_BETWEEN")), - ("counterAxisAlignItems", json!("MIN")), - ("primaryAxisSizingMode", json!("AUTO")), - ("counterAxisSizingMode", json!("FIXED")), - ("minHeight", json!(h)), - ("itemSpacing", json!(8.0)), - ("paddingTop", json!(pad_y)), - ("paddingBottom", json!(pad_y)), - ("paddingLeft", json!(pad_x)), - ("paddingRight", json!(pad_x)), - ] { - o.insert(k.into(), val); - } - let mut kids = Vec::new(); - let mut written = String::new(); - for (local, view) in [(1, Some(note)), (2, author)] { - let Some(view) = view else { continue }; - let chars = own_text(&view).unwrap_or_default(); - let mut layer = Obj::new(); - layer.insert("id".into(), json!(format!("{rest_id};generated{local}"))); - layer.insert("type".into(), json!("TEXT")); - layer.insert("name".into(), json!(if local == 1 { chars.chars().take(40).collect::() } else { "Author".to_string() })); - self.common(&mut layer, &view, "TEXT", Affine::IDENTITY, None); - self.text(&mut layer, &view); - if let Some(Value::Object(style)) = layer.get_mut("style") { - style.insert("textAutoResize".into(), json!("HEIGHT")); - style.insert("textAlignHorizontal".into(), json!("LEFT")); - } - layer.insert("layoutSizingHorizontal".into(), json!("FILL")); - if local == 2 { - written = chars.trim().to_string(); - } - self.count += 1; - kids.push(Value::Object(layer)); - } - o.insert("board".into(), json!({"type": "sticky", "author": written})); - Some(kids) - } -} - -impl<'a> Mapper<'a> { - /// A sticky or shape with text as a native board item, or `None` with the note that it is - /// a frame with its generated layers. - pub(super) fn native_board_item(&mut self, own: &str, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { - let native = if own == "STICKY" { self.native_sticky(o, v, rest_id, depth) } else { self.native_shape(o, v, rest_id, depth) }; - if native.is_none() && own == "STICKY" { - self.warn("sticky layers import as frames with their text"); - } else if native.is_none() { - self.warn("shape with text layers import as frames with their text"); - } - native - } -} - -impl<'a> Mapper<'a> { - /// A shape with text as a native board shape: an empty frame holding FigCraft's own outline - /// (the file's paints and weight) and the text, centred. `None` (nothing changed) when the kind - /// has no FigCraft outline or a generated record is damaged: then the caller keeps the - /// generated layers. - pub(super) fn native_shape(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option> { - let kind = v.str("shapeWithTextType").unwrap_or("SQUARE"); - let Some(shape) = board_shape(kind) else { - self.warn(format!("shape with text kind {} has no FigCraft outline; kept as a frame", crate::rest::props::clip_str(kind))); - return None; - }; - if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) { - return None; - } - let record = |id: u32| { - let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?); - let view = View::of(style).with([(bounds, 1.0)]); - (valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view) - }; - let background = record(0)?; - let body = record(1)?; - // Blank generated text must not hide text the outer node still carries (#1397): the - // generated layers keep it. - if own_text(&body).is_none() && own_text(v).is_some() { - return None; - } - if depth >= MAX_DEPTH || self.count.saturating_add(2) > self.budget() { - return None; - } - let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?; - if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { - return None; - } - // The REST reader caps every size; the outline is drawn at the capped size too, so it - // stays inside its frame. - let (w, h) = (w.min(crate::rest::props::MAX_SIZE), h.min(crate::rest::props::MAX_SIZE)); - // Everything is valid: build the outline from the record's paints, then the frame. - let mut outline = Obj::new(); - outline.insert("id".into(), json!(format!("{rest_id};generated0"))); - outline.insert("type".into(), json!("VECTOR")); - outline.insert("name".into(), json!("Outline")); - self.common(&mut outline, &background, "VECTOR", Affine::IDENTITY, None); - outline.insert("size".into(), json!({"x": w, "y": h})); - outline.insert("relativeTransform".into(), json!([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])); - outline.insert("vectorNetwork".into(), serde_json::to_value(figcraft_doc::VectorNetwork::from_path(&shape.path(w, h))).ok()?); - outline.insert("layoutPositioning".into(), json!("ABSOLUTE")); - outline.insert("constraints".into(), json!({"horizontal": "SCALE", "vertical": "SCALE"})); - outline.remove("cornerRadius"); - let mut label = Obj::new(); - label.insert("id".into(), json!(format!("{rest_id};generated1"))); - label.insert("type".into(), json!("TEXT")); - label.insert("name".into(), json!(own_text(&body).map_or_else(|| "Text".to_string(), |c| c.chars().take(40).collect()))); - self.common(&mut label, &body, "TEXT", Affine::IDENTITY, None); - self.text(&mut label, &body); - if let Some(Value::Object(style)) = label.get_mut("style") { - style.insert("textAutoResize".into(), json!("HEIGHT")); - style.insert("textAlignHorizontal".into(), json!("CENTER")); - } - label.insert("layoutSizingHorizontal".into(), json!("FILL")); - o.insert("fills".into(), json!([])); - o.insert("strokes".into(), json!([])); - o.insert("clipsContent".into(), json!(false)); - o.remove("cornerRadius"); - let [top, right, bottom, left] = shape.text_insets(); - for (k, val) in [ - ("layoutMode", json!("VERTICAL")), - ("primaryAxisAlignItems", json!("CENTER")), - ("counterAxisAlignItems", json!("CENTER")), - ("primaryAxisSizingMode", json!("FIXED")), - ("counterAxisSizingMode", json!("FIXED")), - ("paddingTop", json!(top * h)), - ("paddingRight", json!(right * w)), - ("paddingBottom", json!(bottom * h)), - ("paddingLeft", json!(left * w)), - ] { - o.insert(k.into(), val); - } - self.count += 2; - o.insert("board".into(), json!({"type": "shape", "shape": shape.id()})); - Some(vec![Value::Object(outline), Value::Object(label)]) - } -} - -/// FigJam's `shapeWithTextType` as the outline FigCraft draws for it; `None` for the kinds it has none for. -pub(in crate::fig) fn board_shape(kind: &str) -> Option { - Some(match kind { - "SQUARE" => BoardShape::Rectangle, - "ROUNDED_RECTANGLE" => BoardShape::RoundedRectangle, - "ELLIPSE" => BoardShape::Ellipse, - "DIAMOND" => BoardShape::Diamond, - "TRIANGLE_UP" => BoardShape::Triangle, - "TRIANGLE_DOWN" => BoardShape::TriangleDown, - "PARALLELOGRAM_RIGHT" => BoardShape::ParallelogramRight, - "PARALLELOGRAM_LEFT" => BoardShape::ParallelogramLeft, - "TRAPEZOID" => BoardShape::Trapezoid, - "PENTAGON" => BoardShape::Pentagon, - "HEXAGON" => BoardShape::Hexagon, - "OCTAGON" => BoardShape::Octagon, - "STAR" => BoardShape::Star, - "PLUS" => BoardShape::Plus, - "ARROW_LEFT" => BoardShape::ArrowLeft, - "ARROW_RIGHT" => BoardShape::ArrowRight, - "CHEVRON" => BoardShape::Chevron, - "SPEECH_BUBBLE" => BoardShape::SpeechBubble, - "ENG_DATABASE" => BoardShape::Database, - "DOCUMENT_SINGLE" => BoardShape::Document, - "PREDEFINED_PROCESS" => BoardShape::PredefinedProcess, - "MANUAL_INPUT" => BoardShape::ManualInput, - "INTERNAL_STORAGE" => BoardShape::InternalStorage, - _ => return None, - }) -} diff --git a/crates/format/src/fig/map/component.rs b/crates/format/src/fig/map/component.rs deleted file mode 100644 index 76e8b861a..000000000 --- a/crates/format/src/fig/map/component.rs +++ /dev/null @@ -1,506 +0,0 @@ -use super::layer::own_text; -use super::text::char_styles; -use super::{BTreeMap, BTreeSet, Kv, MAX_DEPTH, MAX_SCALE_FACTOR, MIN_SCALE_FACTOR, Mapper, Obj, Rc, Value, View, guid, json}; - -/// An override row names a layer of the main by its current GUID or by the `overrideKey` the -/// layer had when the row was written: the key becomes the current GUID, unless the layer is -/// current already or the key is ambiguous. -fn normalize_override_segment(path: &mut [String], index: usize, scope: &OverrideScope) { - let Some(segment) = path.get(index) else { return }; - if scope.current.contains(segment) { - return; - } - if let Some(Some(current)) = scope.aliases.get(segment) { - path[index] = current.clone(); - } -} - -/// Overrides and derived layout by id path. -type Overrides<'a> = BTreeMap, Vec>>; - -/// Where an override entry comes from. -#[derive(Clone, Copy, PartialEq)] -pub(super) enum Entry { - Override, - Derived, - /// Derived layout of a nested instance for a size it no longer has: its size and place no - /// longer hold, the rest (resolved colours, text) still does. - Stale, -} - -/// One override or derived-layout row addressed to a layer. -#[derive(Clone)] -pub(super) struct OverrideRow<'a> { - pub(super) row: &'a Kv<'a>, - pub(super) entry: Entry, - /// How many mains are being expanded around the instance that wrote the row: the rows of - /// the enclosing (outer) instances win over those of the inner ones. - source_depth: usize, - /// How many levels below the writing instance the row restates (`overrideLevel`; 0 for the - /// instance's own rows). - level: usize, - /// Position among the rows of the instance that wrote it; later rows win. - ordinal: usize, - /// The factor the row's lengths take: 1 for the rows of an instance in the document, the - /// factor of the layer of the enclosing main that holds the rows for a nested instance's own - /// (they are written in that main's space, #2091). - pub(super) scale: f64, -} - -/// The nested level an override row restates: its `overrideLevel`, capped; 0 when it has none. -fn override_level(row: &Kv) -> usize { - row.get("overrideLevel").and_then(Kv::f64).filter(|l| l.is_finite() && *l > 0.0).map_or(0, |l| l.min(MAX_DEPTH as f64) as usize) -} - -/// The layers of a main by current GUID, and the old `overrideKey` of each that has one -/// (`None` when two layers claim the same key). -pub(super) struct OverrideScope { - current: BTreeSet, - aliases: BTreeMap>, -} - -/// Values by key that nested instances add to their outer instances' (property values, slot -/// contents): an outer instance's value wins. Each instance keeps only what it adds and shares the -/// rest, instead of copying every outer value (#1077); lookups walk at most the nesting depth. -pub(super) struct Chain { - own: BTreeMap, - outer: Option>>, -} - -impl Chain { - /// `outer`'s values, then `own`'s for keys `outer` lacks (shared as it is when `own` adds nothing). - fn over(outer: Option<&Rc>>, own: BTreeMap) -> Rc { - match outer { - Some(o) if own.is_empty() => Rc::clone(o), - _ => Rc::new(Self { own, outer: outer.cloned() }), - } - } - - pub(super) fn get(&self, key: &str) -> Option<&V> { - self.outer.as_ref().and_then(|o| o.get(key)).or_else(|| self.own.get(key)) - } -} - -/// Where an instance's expanded layers are: the overrides and derived layout of the outermost -/// instance (by id path), the path of the instance being expanded, and the property values. -#[derive(Clone)] -pub(super) struct Inst<'a> { - pub(super) root: String, - pub(super) path: Vec, - pub(super) overrides: Rc>, - /// Property values with the factor their lengths take (the layer of the writing instance's - /// node that holds the assignment, as for override rows). - props: Rc, f64)>>, - /// Slot property GUID → private slot-content node GUID. - pub(super) slot_contents: Rc>, - /// Layers imported from a slot's independent content subtree. - pub(super) slot_content: bool, - /// Mains being expanded (an instance inside its own main stops there). - symbols: Vec, - /// The factor the lengths of the expanded layers take: the instance's `uniformScaleFactor` - /// times those of the instances around it (#2091). Override and derived rows are already at - /// the instance's scale and take none. - pub(super) scale: f64, -} - -impl<'a> Mapper<'a> { - /// The layers of main `main` by current GUID and by `overrideKey`. An instance nested in the - /// main is not entered: its layers belong to another main. - fn override_scope(&mut self, main: &str) -> Rc { - if let Some(scope) = self.override_scopes.get(main) { - return Rc::clone(scope); - } - let mut current = BTreeSet::new(); - let mut aliases: BTreeMap> = BTreeMap::new(); - let mut visited = BTreeSet::new(); - let mut pending: Vec<(String, usize)> = self.children(main).into_iter().map(|id| (id, 1)).collect(); - let mut complete = true; - while let Some((id, depth)) = pending.pop() { - if depth > MAX_DEPTH || visited.len() >= self.max_nodes { - complete = false; - break; - } - if !visited.insert(id.clone()) { - continue; - } - let Some(node) = self.nodes.get(&id) else { continue }; - current.insert(id.clone()); - if let Some(alias) = node.get("overrideKey").and_then(guid) { - let target = aliases.entry(alias).or_insert_with(|| Some(id.clone())); - if target.as_deref().is_some_and(|target| target != id) { - *target = None; - } - } - if node.get("type").and_then(Kv::str) != Some("INSTANCE") { - pending.extend(self.children(&id).into_iter().map(|child| (child, depth + 1))); - } - } - // A scope cut short could name the wrong layer for a key: use none of the keys. - if !complete { - aliases.clear(); - } - let scope = Rc::new(OverrideScope { current, aliases }); - let cost = scope.current.len() + scope.aliases.len(); - if cost <= self.max_nodes.saturating_sub(self.override_scope_entries) { - self.override_scope_entries += cost; - self.override_scopes.insert(main.to_string(), Rc::clone(&scope)); - } - scope - } - - pub(super) fn is_instance_swap(&self, def: &Kv) -> Option<()> { - matches!(self.prop_def(&guid(def)?), Some((_, "INSTANCE_SWAP"))).then_some(()) - } - - /// The definition a copy of it was made from, followed to the original: the values an instance - /// sets are kept under it, since an assignment and the layers that read it may name different - /// copies of one definition. - pub(super) fn prop_root(&self, def: &str) -> String { - let mut def = def; - for _ in 0..=MAX_DEPTH { - let Some(parent) = self.prop_parents.get(def) else { break }; - def = parent; - } - def.to_string() - } - - /// The definition `def` names: its own, or the set's for a variant's copy of it. - fn prop_def(&self, def: &str) -> Option<&(String, &'a str)> { - let mut def = def; - for _ in 0..=MAX_DEPTH { - if let Some(found) = self.prop_defs.get(def) { - return Some(found); - } - def = self.prop_parents.get(def)?; - } - None - } - - /// Component property definitions and description. - pub(super) fn component(&mut self, o: &mut Obj, v: &View<'a>, id: &str) { - let mut defs = Obj::new(); - for d in v.list("componentPropDefs") { - if d.get("isDeleted").and_then(Kv::bool) == Some(true) { - continue; - } - let Some((name, ty)) = d.get("id").and_then(guid).and_then(|i| self.prop_defs.get(&i).cloned()) else { continue }; - let init = d.get("initialValue"); - let def = match ty { - "BOOL" => json!({"type": "BOOLEAN", "defaultValue": init.and_then(|i| i.get("boolValue")).and_then(Kv::bool).unwrap_or(true)}), - "TEXT" => json!({"type": "TEXT", "defaultValue": init.and_then(prop_text).unwrap_or("")}), - "INSTANCE_SWAP" => match init.and_then(|i| i.get("guidValue")).and_then(guid) { - Some(g) => { - if self.nodes.contains_key(&g) { - self.referenced_mains.insert(g.clone()); - } - json!({"type": "INSTANCE_SWAP", "defaultValue": g}) - } - None => continue, - }, - "VARIANT" => json!({"type": "VARIANT"}), - "SLOT" => { - self.warn_non_default_slot_config(d); - self.warn_dropped_slot_preferred_values(d); - json!({"type": "SLOT"}) - } - _ => { - self.warn(format!("{} component properties are not supported and were skipped", ty.to_ascii_lowercase())); - continue; - } - }; - defs.insert(name, def); - } - if !defs.is_empty() { - o.insert("componentPropertyDefinitions".into(), Value::Object(defs)); - } - if let Some(d) = v.str("symbolDescription").or_else(|| v.str("description")).filter(|d| !d.is_empty()) { - let into = if o.get("type").and_then(Value::as_str) == Some("COMPONENT_SET") { &mut self.sets } else { &mut self.components }; - into.insert(id.to_string(), json!({"description": d})); - } - } - - /// Preferred slot values are source component keys, but this mapper has no proven way to map - /// those keys to file GUIDs. They are dropped instead of guessing native NodeIds. - fn warn_dropped_slot_preferred_values(&mut self, def: &Kv<'a>) { - let entries = def.get("preferredValues").and_then(|v| v.get("instanceSwapValues")).map(Kv::list).unwrap_or_default(); - if !entries.is_empty() { - self.warn("preferred slot component keys cannot be resolved to file nodes and were skipped"); - } - } - - fn warn_non_default_slot_config(&mut self, def: &Kv<'a>) { - let Some(config) = def.get("slotPropConfig") else { return }; - let non_default = [ - ("stretchChildOnInsert", Some(false)), - ("displayByDefault", Some(false)), - ("minChildren", None), - ("maxChildren", None), - ("allowPreferredValuesOnly", Some(false)), - ] - .into_iter() - .any(|(field, bool_default)| { - let Some(value) = config.get(field) else { return false }; - if let Some(default) = bool_default { value.bool() != Some(default) } else { value.f64() != Some(0.0) } - }); - if non_default { - self.warn("non-default slot settings are not represented and were skipped"); - } - } - - /// A layer's component property references, and inside an instance the values they take. - pub(super) fn prop_refs(&mut self, o: &mut Obj, v: &View<'a>, inst: Option<&Inst<'a>>) { - let mut refs = Obj::new(); - for e in v.get("parameterConsumptionMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() { - let field = match e.get("variableField").and_then(Kv::str) { - Some("VISIBLE") => "visible", - Some("TEXT_DATA") => "characters", - Some("OVERRIDDEN_SYMBOL_ID") => "mainComponent", - Some("SLOT_CONTENT_ID") => "slot", - _ => continue, - }; - let Some(def) = - e.get("variableData").and_then(|d| d.get("value")).and_then(|x| x.get("propRefValue")).and_then(|p| p.get("defId")).and_then(guid) - else { - continue; - }; - // Expanded frames must follow their main frame's source link. A direct slot reference - // makes the engine resolve ownership against the instance, where the property is not defined. - if !(field == "slot" && inst.is_some()) - && let Some((name, _)) = self.prop_def(&def) - { - refs.insert(field.into(), json!(name)); - } - let Some(&(val, val_scale)) = inst.and_then(|i| i.props.get(&self.prop_root(&def))) else { continue }; - match field { - "visible" => { - if let Some(b) = val.get("boolValue").and_then(Kv::bool) { - o.insert("visible".into(), json!(b)); - } - } - "characters" => { - if let Some(t) = prop_text(val) { - o.insert("characters".into(), json!(t)); - // Run styles count the chars they were made for: for other chars only - // the value's own apply. - if own_text(v) != Some(t) { - o.remove("characterStyleOverrides"); - o.remove("styleOverrideTable"); - o.remove("_figLineStarts"); - if let Some(tv) = prop_text_data(val) { - let size = o.get("style").and_then(|s| s.get("fontSize")).and_then(Value::as_f64); - char_styles(o, tv, val_scale, size, &mut |w| self.warn(w)); - } - } - } - } - _ => {} - } - } - if !refs.is_empty() { - o.insert("componentPropertyReferences".into(), Value::Object(refs)); - } - } - - /// An instance's main and properties; the context its expanded layers are built in. - pub(super) fn instance(&mut self, o: &mut Obj, v: &View<'a>, id: &str, outer: Option<&Inst<'a>>, rest_id: &str) -> Option<(Inst<'a>, String)> { - let sd = v.get("symbolData"); - let mut sym = v.get("overriddenSymbolID").and_then(guid).or_else(|| sd.and_then(|s| s.get("symbolID")).and_then(guid)); - // An instance swap property value picks the main. - if let Some(i) = outer - && let Some(def) = prop_ref(v, "OVERRIDDEN_SYMBOL_ID") - && let Some(g) = i.props.get(&self.prop_root(&def)).and_then(|(p, _)| prop_guid(p)) - { - sym = Some(g); - } - let Some(sym) = sym else { - self.warn("instances without a main component were imported as empty frames"); - return None; - }; - o.insert("componentId".into(), json!(sym)); - let assignments = v.list("componentPropAssignments"); - let mut props = Obj::new(); - for a in assignments { - let Some((name, ty)) = a.get("defID").and_then(guid).and_then(|d| self.prop_def(&d).cloned()) else { continue }; - let val = assigned(a); - let p = match ty { - "BOOL" => val.and_then(|x| x.get("boolValue")).and_then(Kv::bool).map(|b| json!({"type": "BOOLEAN", "value": b})), - "TEXT" => val.and_then(prop_text).map(|t| json!({"type": "TEXT", "value": t})), - "INSTANCE_SWAP" => val.and_then(prop_guid).map(|g| json!({"type": "INSTANCE_SWAP", "value": g})), - _ => None, - }; - if let Some(p) = p { - props.insert(name, p); - } - } - if !props.is_empty() { - o.insert("componentProperties".into(), Value::Object(props)); - } - if !self.nodes.contains_key(&sym) { - self.warn("instances of components that aren't in the file show no layers"); - return None; - } - if !self.referenced_mains.contains(&sym) { - self.referenced_mains.insert(sym.clone()); - } - if outer.is_some_and(|i| i.symbols.contains(&sym)) { - return None; - } - // Overrides by id path below this instance (the instance itself is addressed by its main's id). - let own_path: Vec = outer.map(|i| [i.path.as_slice(), &[id.to_string()]].concat()).unwrap_or_default(); - let scope = self.override_scope(&sym); - let mut overrides: Overrides<'a> = BTreeMap::new(); - if let Some(inherited) = outer { - // Only rows addressed below this instance can apply inside it (every path looked up in - // it starts with `own_path`); they sort together, so the others aren't even visited. A - // nested instance used to copy all of its outer instance's rows (#1077). - let below = inherited.overrides.range(own_path.clone()..).take_while(|(path, _)| path.starts_with(&own_path)); - for (path, rows) in below.filter(|(path, _)| path.len() > own_path.len()) { - let mut path = path.clone(); - // Rows an outer instance wrote for this instance's layers may use their old keys. - normalize_override_segment(&mut path, own_path.len(), &scope); - overrides.entry(path).or_default().extend(rows.iter().cloned()); - } - } - // A nested instance's derived layout is for the size it has in its main: resized here, the - // sizes and places in it no longer hold and its layers follow their constraints instead. - // A scaled size is the factor's product, rounded to a float: a looser match. - let tolerance = if outer.is_some_and(|i| i.scale != 1.0) { 1e-4 } else { 1e-6 }; - let differs = |a: f64, b: f64| (a - b).abs() > tolerance * a.abs().max(b.abs()).max(1.0); - let outer_scale = outer.map_or(1.0, |i| i.scale); - let resized = outer.is_some() - && match (self.nodes.get(id).and_then(|b| View::of_scaled(b, outer_scale).size()), v.size()) { - (Some(a), Some(b)) => differs(a.0, b.0) || differs(a.1, b.1), - (a, b) => a.is_some() != b.is_some(), - }; - let mut local: Overrides<'a> = BTreeMap::new(); - // The lists are at the scale of the layer of this node that holds them. - let scale_of = |k: &str| v.find(k).map_or(1.0, |f| f.1); - let lists = [ - (sd.and_then(|s| s.get("symbolOverrides")).map(Kv::list).unwrap_or_default(), scale_of("symbolData")), - (v.list("derivedSymbolData"), scale_of("derivedSymbolData")), - ]; - let source_depth = outer.map_or(0, |i| i.symbols.len()); - let mut ordinal = 0; - for (layer, (list, row_scale)) in lists.into_iter().enumerate() { - for ov in list { - let row_ordinal = ordinal; - ordinal += 1; - let mut rel: Vec = - ov.get("guidPath").and_then(|g| g.get("guids")).map(Kv::list).unwrap_or_default().iter().filter_map(guid).collect(); - if rel.is_empty() || rel == [sym.clone()] { - continue; - } - normalize_override_segment(&mut rel, 0, &scope); - // Explicit overrides, then derived layout (stale once the instance is resized). - let entry = match (layer, resized) { - (0, _) => Entry::Override, - (_, false) => Entry::Derived, - (_, true) => Entry::Stale, - }; - local.entry([own_path.as_slice(), &rel].concat()).or_default().push(OverrideRow { - row: ov, - entry, - source_depth, - level: override_level(ov), - ordinal: row_ordinal, - scale: row_scale, - }); - } - } - for (path, rows) in local { - overrides.entry(path).or_default().extend(rows); - } - for rows in overrides.values_mut() { - // Deeper rows apply first and outer rows win: a row restating a nested level counts at - // that level's depth, wherever it sits on the wire. Equal depths keep the outer source - // last, then wire order. - rows.sort_by_key(|row| (std::cmp::Reverse(row.source_depth + row.level), std::cmp::Reverse(row.source_depth), row.ordinal)); - } - // This instance's own property values and slot contents; the outer instances' win. - let assignment_scale = v.find("componentPropAssignments").map_or(1.0, |f| f.1); - let mut all_props: BTreeMap, f64)> = BTreeMap::new(); - let mut slot_contents: BTreeMap = BTreeMap::new(); - for a in assignments { - if let (Some(d), Some(val)) = (a.get("defID").and_then(guid), assigned(a)) { - all_props.entry(self.prop_root(&d)).or_insert((val, assignment_scale)); - } - let Some(def) = a.get("defID").and_then(guid) else { continue }; - if self.prop_def(&def).is_none_or(|(_, ty)| *ty != "SLOT") { - continue; - } - let var_value = a.get("varValue"); - if var_value.and_then(|v| v.get("dataType")).and_then(Kv::str) != Some("SLOT_CONTENT_ID") { - self.warn("malformed slot content assignment was skipped"); - continue; - } - let target = var_value.and_then(|v| v.get("value")).and_then(|v| v.get("slotContentIdValue")).and_then(|v| v.get("guid")).and_then(guid); - let Some(target) = target else { - self.warn("malformed slot content assignment was skipped"); - continue; - }; - if target == "4294967295:4294967295" { - self.warn("slot content assignment uses the empty GUID sentinel and was skipped"); - continue; - } - if self.nodes.get(&target).is_none_or(|n| n.get("isSlotContent").and_then(Kv::bool) != Some(true)) { - self.warn("slot content assignment target is missing or is not slot content"); - continue; - } - slot_contents.entry(self.prop_root(&def)).or_insert(target); - } - let mut symbols = outer.map(|i| i.symbols.clone()).unwrap_or_default(); - symbols.push(sym.clone()); - let root = outer.map_or_else(|| rest_id.to_string(), |i| i.root.clone()); - // The scale the Scale tool gave the instance; a junk factor changes nothing. - let factor = sd - .and_then(|s| s.get("uniformScaleFactor")) - .and_then(Kv::f64) - .filter(|k| (MIN_SCALE_FACTOR..=MAX_SCALE_FACTOR).contains(k)) - .unwrap_or(1.0); - let scale = (outer_scale * factor).clamp(MIN_SCALE_FACTOR, MAX_SCALE_FACTOR); - Some(( - Inst { - root, - path: own_path, - overrides: Rc::new(overrides), - props: Chain::over(outer.map(|i| &i.props), all_props), - slot_contents: Chain::over(outer.map(|i| &i.slot_contents), slot_contents), - slot_content: false, - symbols, - scale, - }, - sym, - )) - } -} - -/// The text of a component property value. -fn prop_text<'k>(v: &'k Kv) -> Option<&'k str> { - prop_text_data(v).and_then(|t| t.get("characters")).and_then(Kv::str) -} - -/// The text data of a component property value: `textValue`, or `textDataValue` in the variable form. -fn prop_text_data<'k, 's>(v: &'k Kv<'s>) -> Option<&'k Kv<'s>> { - v.get("textValue").or_else(|| v.get("textDataValue")) -} - -/// The main an instance swap value names: `guidValue`, or `symbolIdValue` in the variable form. -pub(super) fn prop_guid(v: &Kv) -> Option { - v.get("guidValue").and_then(guid).or_else(|| v.get("symbolIdValue")?.get("guid").and_then(guid)) -} - -/// The value a component property assignment sets: `value`, or the variable form `varValue` holds -/// when `value` is empty, as current files write many booleans and instance swaps. -pub(super) fn assigned<'k, 's>(assignment: &'k Kv<'s>) -> Option<&'k Kv<'s>> { - assignment.get("value").filter(|v| !matches!(v, Kv::Object(fields) if fields.is_empty())).or_else(|| assignment.get("varValue")?.get("value")) -} - -/// The property a layer's `field` is bound to (`parameterConsumptionMap`). -pub(super) fn prop_ref(v: &View, field: &str) -> Option { - v.get("parameterConsumptionMap")?.get("entries")?.list().iter().find_map(|e| { - if e.get("variableField").and_then(Kv::str) != Some(field) { - return None; - } - e.get("variableData")?.get("value")?.get("propRefValue")?.get("defId").and_then(guid) - }) -} diff --git a/crates/format/src/fig/map/connector.rs b/crates/format/src/fig/map/connector.rs deleted file mode 100644 index 22514e5b6..000000000 --- a/crates/format/src/fig/map/connector.rs +++ /dev/null @@ -1,521 +0,0 @@ -use super::layer::{cap_name, own_text, svg_path, valid_size}; -use super::paint::{paint, stroke}; -use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, generated_record, guid, json, matrix, network, num, rows}; -use figcraft_doc::geom::kurbo::{BezPath, PathEl, Rect, Shape}; -use figcraft_doc::{ConnectorPath, MAX_RUNS, RouteEnd, Routing, Side, attach_points, attached_sides, route_along}; - -/// How a connector imports: from its saved snapshot (`terminal`: as one vector, no room for its -/// label), or drawn from its ends, as a frame with its line and `label` when it has one. -#[derive(Clone, Copy)] -pub(super) struct ConnectorShape { - pub snapshot: bool, - pub terminal: bool, - pub label: bool, -} - -impl<'a> Mapper<'a> { - /// A connector's own properties on `o`; returns the children it adds (a line and a label). - pub(super) fn connector_layer(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, space: Affine, shape: ConnectorShape) -> Vec { - if shape.snapshot { - if shape.terminal { - self.connector_snapshot_flatten(o, v, rest_id, space); - } else { - o.insert("fills".into(), json!([])); - o.insert("strokes".into(), json!([])); - for key in ["styles", "strokeWeight", "strokeAlign", "strokeJoin", "strokeDashes", "strokeCap"] { - o.remove(key); - } - o.insert("clipsContent".into(), json!(false)); - } - return Vec::new(); - } - let mid = self.connector(o, v, space); - self.connector_line_style(o, v); - if shape.label { - return self.connector_label(o, v, rest_id, mid); - } - if connector_has_saved_label(v) { - self.warn("connector labels were skipped"); - } - Vec::new() - } - - /// Whether a connector without a snapshot keeps its label: it has text of its own and there is - /// room for its two children under the depth and layer limits. - pub(super) fn connector_label_fits(&self, v: &View<'a>, depth: usize) -> bool { - own_text(v).is_some() && depth < super::MAX_DEPTH && self.count.saturating_add(2) < self.budget() - } - - /// A connector's end caps, and when it has no saved outline or network its line between its - /// ends (free points, or a sibling layer): straight to the point given on the layer (its - /// centre unless given), or elbowed or curved from a side of it, as a board connector runs; - /// an elbow saved with its path (FigJam's control points) runs along it (#1910). - /// Returns the middle of that line by length, in the connector's own coordinates. - pub(super) fn connector(&mut self, o: &mut Obj, v: &View<'a>, space: Affine) -> Option { - for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] { - if let Some(c) = v.str(from) { - o.insert(to.into(), json!(cap_name(c))); - } - } - if ["vectorNetwork", "vectorNetworkRef", "fillGeometry", "strokeGeometry"].iter().any(|k| o.contains_key(*k)) { - return None; - } - let routing = match v.str("connectorLineStyle") { - Some("ELBOWED") => Routing::Elbow, - Some("CURVED") => Routing::Curved, - _ => Routing::Straight, - }; - let parent = v.get("parentIndex").and_then(|p| p.get("guid")).and_then(guid); - let end = |k: &str| -> Option { - let e = v.get(k)?; - let end = match e.get("endpointNodeID").and_then(guid).filter(|g| g != NO_STYLE) { - Some(id) => { - let n = *self.nodes.get(&id)?; - // Only siblings share the connector's coordinates. - if n.get("parentIndex").and_then(|p| p.get("guid")).and_then(guid) != parent { - return None; - } - let (w, h) = n.get("size").map_or((0.0, 0.0), |s| (num(s, "x").unwrap_or(0.0), num(s, "y").unwrap_or(0.0))); - let at = e.get("relativePosition").and_then(|r| Some((num(r, "x")?, num(r, "y")?))); - let t = n.get("transform").and_then(matrix).unwrap_or_default(); - // An automatic magnet (`AUTO`: the side is picked when the connector is drawn; - // `CENTER`: the end aims at the layer's middle) attaches to the side facing the - // other end, as a board connector drawn here does; the file's `relativePosition` - // is not where such an end sits (#1909). - let automatic = matches!(e.get("magnet").and_then(Kv::str), Some("AUTO" | "CENTER")); - match routing { - Routing::Straight if !automatic => { - let (rx, ry) = at.unwrap_or((0.5, 0.5)); - RouteEnd::Point(t * Point::new(w * rx, h * ry)) - } - _ => RouteEnd::Box(t.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), side(e, at)), - } - } - None => RouteEnd::Point(e.get("position").and_then(|p| Some(Point::new(num(p, "x")?, num(p, "y")?)))?), - }; - let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); - let ok = match end { - RouteEnd::Point(p) | RouteEnd::On(_, _, p) => finite(p), - RouteEnd::Box(b, _) => finite(b.origin()) && finite(Point::new(b.x1, b.y1)), - }; - ok.then_some(end) - }; - let ends = end("connectorStart").zip(end("connectorEnd")); - let path = ends.filter(|_| routing == Routing::Elbow).and_then(|(a, b)| saved_runs(v, a, b)); - let Some(pts) = ends.and_then(|(a, b)| route_along(a, b, routing, path.as_ref())) else { - self.warn("connectors whose ends can't be placed are empty"); - return None; - }; - if routing != Routing::Straight && path.is_none() { - self.warn("elbowed and curved connectors without a saved path follow FigCraft's own routing"); - } - // A curved route is one curve: its ends and the two control points between them. - let (path, vertices) = match (routing, pts.as_slice()) { - (Routing::Curved, [p0, c0, c1, p1]) => { - let mut path = BezPath::new(); - path.move_to(*p0); - path.curve_to(*c0, *c1, *p1); - (path, vec![*p0, *p1]) - } - _ => (pts.iter().enumerate().map(|(i, p)| if i == 0 { PathEl::MoveTo(*p) } else { PathEl::LineTo(*p) }).collect(), pts.clone()), - }; - let b = path.bounding_box(); - let (x0, y0) = (b.x0, b.y0); - o.insert("relativeTransform".into(), rows(space * Affine::translate((x0, y0)))); - o.insert("size".into(), json!({"x": b.width(), "y": b.height()})); - let segments: Vec = match (routing, pts.as_slice()) { - (Routing::Curved, [p0, c0, c1, p1]) => vec![json!({"a": 0, "b": 1, "ta": [c0.x - p0.x, c0.y - p0.y], "tb": [c1.x - p1.x, c1.y - p1.y]})], - _ => (1..vertices.len()).map(|i| json!({"a": i - 1, "b": i})).collect(), - }; - let vertices: Vec = vertices.iter().map(|p| json!({"x": p.x - x0, "y": p.y - y0})).collect(); - o.insert("vectorNetwork".into(), json!({"vertices": vertices, "segments": segments})); - middle(&path).map(|m| m - b.origin().to_vec2()) - } - - /// The line's paint, weight, cap and dashes, which a connector keeps in its generated line - /// record rather than on itself: without a saved snapshot the routed line took none of them and - /// drew nothing (#1807). The connector's own values, when it has any, win. - fn connector_line_style(&mut self, o: &mut Obj, v: &View<'a>) { - let Some(line_style) = generated_record(v, "nodeGenerationData", 0) else { return }; - let style = View::of(line_style); - // A connector that writes its own (even empty) paints or dash pattern keeps them: an empty - // list is no stroke, or a solid line, not a missing value. - if v.get("strokePaints").is_none() && o.get("strokes").and_then(Value::as_array).is_none_or(Vec::is_empty) { - let strokes: Vec = style.list("strokePaints").iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect(); - if !strokes.is_empty() { - o.insert("strokes".into(), Value::Array(strokes)); - } - } - let mut line = Obj::new(); - stroke(&mut line, &style); - if v.get("dashPattern").is_some() { - line.remove("strokeDashes"); - } - for (key, value) in line { - o.entry(key).or_insert(value); - } - } - - /// A connector with a label but no saved snapshot of it, as the frame a saved one imports as: - /// `o` keeps the connector's place and size and gives its line to a vector child, and the - /// label is a text child centred on `mid` (the line's middle; the frame's centre when the line - /// came saved). Returns the two children. - pub(super) fn connector_label(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, mid: Option) -> Vec { - let (w, h) = o.get("size").map_or((0.0, 0.0), |s| (s["x"].as_f64().unwrap_or(0.0), s["y"].as_f64().unwrap_or(0.0))); - let mut line = Obj::new(); - line.insert("id".into(), json!(format!("{rest_id};line"))); - line.insert("type".into(), json!("VECTOR")); - line.insert("name".into(), json!(format!("{} line", v.str("name").unwrap_or("Connector")))); - line.insert("size".into(), json!({"x": w, "y": h})); - line.insert("relativeTransform".into(), rows(Affine::IDENTITY)); - // The connector's fill paints colour its label; the line is only stroked. - let label_fills = o.remove("fills").filter(|f| f.as_array().is_some_and(|a| !a.is_empty())); - for key in LINE_KEYS { - if let Some(value) = o.remove(*key) { - line.insert((*key).into(), value); - } - } - o.insert("fills".into(), json!([])); - o.insert("strokes".into(), json!([])); - o.insert("clipsContent".into(), json!(false)); - - let mut text = Obj::new(); - text.insert("id".into(), json!(format!("{rest_id};label"))); - text.insert("type".into(), json!("TEXT")); - self.text(&mut text, v); - let characters = text.get("characters").and_then(Value::as_str).unwrap_or_default().to_string(); - text.insert("name".into(), json!(characters)); - text.insert("fills".into(), label_fills.unwrap_or_else(|| json!([{"type": "SOLID", "color": {"r": 0, "g": 0, "b": 0, "a": 1}}]))); - // Centred on the line's middle in a box of the label's width, as tall as its lines (laid out - // again with the fonts at hand, so the box only centres it). - let size = text.get("style").and_then(|s| s["fontSize"].as_f64()).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(16.0); - let lines = characters.lines().count().max(1) as f64; - let (bw, bh) = (LABEL_WIDTH, lines * size * 1.4); - if let Some(style) = text.get_mut("style").and_then(Value::as_object_mut) { - style.insert("textAlignHorizontal".into(), json!("CENTER")); - style.insert("textAlignVertical".into(), json!("CENTER")); - style.insert("textAutoResize".into(), json!("NONE")); - } - let at = mid.unwrap_or(Point::new(w / 2.0, h / 2.0)); - text.insert("size".into(), json!({"x": bw, "y": bh})); - text.insert("relativeTransform".into(), rows(Affine::translate((at.x - bw / 2.0, at.y - bh / 2.0)))); - self.count += 2; - self.warn("connector labels without a saved snapshot are centred on the line, without their background"); - vec![Value::Object(line), Value::Object(text)] - } - - pub(super) fn connector_snapshot_supported(&self, v: &View<'a>) -> bool { - if v.str("connectorType") != Some("MANUAL") - || v.get("connectorVersion").and_then(Kv::f64) != Some(1.0) - || v.str("connectorLineStyle") != Some("STRAIGHT") - || v.get("derivedImmutableFrameData").and_then(|data| data.get("version")).and_then(Kv::f64) != Some(1.0) - { - return false; - } - let Some(line) = generated_record(v, "derivedImmutableFrameData", 0) else { return false }; - if line.get("transform").and_then(matrix).is_none() || valid_size(line.get("size")).is_none() { - return false; - } - let geometry = ["fillGeometry", "strokeGeometry"].iter().any(|key| { - line.get(key).map(Kv::list).unwrap_or_default().iter().any(|path| { - num(path, "commandsBlob") - .and_then(|index| self.blobs.get(index as usize)) - .and_then(|blob| svg_path(blob)) - .is_some_and(|data| !data.is_empty()) - }) - }); - let network = line - .get("vectorData") - .and_then(|data| num(data, "vectorNetworkBlob")) - .and_then(|index| self.blobs.get(index as usize)) - .and_then(|blob| network::decode(blob)) - .is_some_and(|network| !network.segments.is_empty()); - (geometry || network) && generated_record(v, "nodeGenerationData", 0).is_some() - } - - pub(super) fn connector_snapshot_flatten(&mut self, out: &mut Obj, v: &View<'a>, rest_id: &str, space: Affine) { - let parent = space * v.get("transform").and_then(matrix).unwrap_or_default(); - let Some(vector) = self.connector_snapshot_vector(v, rest_id, parent, false) else { - self.warn("connector snapshot vector data is missing; connector was left empty"); - return; - }; - for key in [ - "size", - "relativeTransform", - "fills", - "strokes", - "strokeWeight", - "strokeAlign", - "strokeJoin", - "strokeDashes", - "strokeCap", - "strokeCapStart", - "strokeCapEnd", - "styles", - "fillGeometry", - "strokeGeometry", - "vectorNetwork", - ] { - if let Some(value) = vector.get(key) { - out.insert(key.to_string(), value.clone()); - } - } - if vector.get("visible").and_then(Value::as_bool) == Some(false) { - out.insert("visible".into(), json!(false)); - } - if let Some(line_opacity) = vector.get("opacity").and_then(Value::as_f64) { - let root_opacity = out.get("opacity").and_then(Value::as_f64).unwrap_or(1.0); - out.insert("opacity".into(), json!(root_opacity * line_opacity)); - } - if connector_has_saved_label(v) { - let reason = if self.count >= self.budget() { "node budget" } else { "depth limit" }; - self.warn(format!("connector label was skipped: {reason} prevents nested snapshot children")); - } - } - - /// Build the saved vector child or flattened terminal connector from the same child-only view. - fn connector_snapshot_vector(&mut self, v: &View<'a>, rest_id: &str, space: Affine, nested: bool) -> Option { - let (Some(line), Some(line_style)) = (generated_record(v, "derivedImmutableFrameData", 0), generated_record(v, "nodeGenerationData", 0)) - else { - return None; - }; - let mut vector = Obj::new(); - vector.insert("id".into(), json!(if nested { format!("{rest_id};vector") } else { rest_id.to_string() })); - vector.insert("type".into(), json!("VECTOR")); - if let Some(name) = v.str("name") { - vector.insert("name".into(), json!(if nested { format!("{name} vector") } else { name.to_string() })); - } - let line_view = View::of(line).with([(line_style, 1.0)]); - self.common(&mut vector, &line_view, "VECTOR", space, None); - self.geometry(&mut vector, &line_view); - for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] { - if let Some(cap) = v.str(from) { - vector.entry(to).or_insert_with(|| json!(cap_name(cap))); - } - } - Some(vector) - } - - /// Snapshot the straight, manual connector contract carried by its generated children. - pub(crate) fn connector_snapshot_children(&mut self, v: &View<'a>, rest_id: &str) -> Vec { - if self.count >= self.budget() { - self.warn(format!("the file has more than {} layers; connector snapshot children were skipped", self.max_nodes)); - return Vec::new(); - } - let Some(vector) = self.connector_snapshot_vector(v, rest_id, Affine::IDENTITY, true) else { - self.warn("connector snapshot vector data is missing; connector was left empty"); - return Vec::new(); - }; - let mut children = Vec::new(); - children.push(Value::Object(vector)); - self.count += 1; - - let Some(text_frame) = generated_record(v, "derivedImmutableFrameData", 1) else { - if connector_has_saved_label(v) { - self.warn("connector label was skipped: derived text bounds are missing"); - } - return children; - }; - let Some(background) = generated_record(v, "derivedImmutableFrameData", 2) else { - if connector_has_saved_label(v) || valid_size(text_frame.get("size")).is_some_and(|(w, h)| w > 0.0 && h > 0.0) { - self.warn("connector label was skipped: derived background bounds are missing"); - } - return children; - }; - let Some(text_style) = generated_record(v, "nodeGenerationData", 1) else { - if valid_size(text_frame.get("size")).is_some_and(|(w, h)| w > 0.0 && h > 0.0) { - self.warn("connector label was skipped: text style data is missing"); - } - return children; - }; - let text_view = View::of(text_frame).with([(text_style, 1.0)]); - let Some(characters) = text_view.get("textData").and_then(|d| d.get("characters")).and_then(Kv::str).filter(|s| !s.trim().is_empty()) else { - return children; - }; - let Some(text_transform) = text_frame.get("transform").and_then(matrix) else { - self.warn("connector label was skipped: text transform is invalid"); - return children; - }; - let Some(background_transform) = background.get("transform").and_then(matrix) else { - self.warn("connector label was skipped: background transform is invalid"); - return children; - }; - let Some(text_size) = valid_size(text_frame.get("size")) else { - self.warn("connector label was skipped: text bounds are invalid"); - return children; - }; - let Some(background_size) = valid_size(background.get("size")) else { - self.warn("connector label was skipped: background bounds are invalid"); - return children; - }; - let composed_text_transform = background_transform * text_transform; - if !composed_text_transform.as_coeffs().iter().all(|coefficient| coefficient.is_finite()) { - self.warn("connector label was skipped: composed text transform is invalid"); - return children; - } - - let Some(background_style) = generated_record(v, "nodeGenerationData", 2) else { - self.warn("connector label background was skipped: style data is missing"); - self.add_connector_text(&mut children, rest_id, characters, text_size, composed_text_transform, &text_view); - return children; - }; - let background_view = View::of(background).with([(background_style, 1.0)]); - if !background_view.list("fillPaints").is_empty() { - if self.count >= self.budget() { - self.warn(format!("the file has more than {} layers; connector label background was skipped", self.max_nodes)); - } else { - let mut rect = Obj::new(); - rect.insert("id".into(), json!(format!("{rest_id};label-background"))); - rect.insert("type".into(), json!("RECTANGLE")); - rect.insert("name".into(), json!("connector label background")); - self.common(&mut rect, &background_view, "RECTANGLE", Affine::IDENTITY, None); - rect.insert("size".into(), json!({"x": background_size.0, "y": background_size.1})); - rect.insert("relativeTransform".into(), rows(background_transform)); - rect.insert("clipsContent".into(), json!(false)); - children.push(Value::Object(rect)); - self.count += 1; - } - } - self.add_connector_text(&mut children, rest_id, characters, text_size, composed_text_transform, &text_view); - children - } - - fn add_connector_text( - &mut self, - children: &mut Vec, - rest_id: &str, - characters: &str, - size: (f64, f64), - transform: Affine, - view: &View<'a>, - ) { - if self.count >= self.budget() { - self.warn(format!("the file has more than {} layers; connector label was skipped", self.max_nodes)); - return; - } - let mut text = Obj::new(); - text.insert("id".into(), json!(format!("{rest_id};label-text"))); - text.insert("type".into(), json!("TEXT")); - text.insert("name".into(), json!(characters)); - text.insert("size".into(), json!({"x": size.0, "y": size.1})); - self.common(&mut text, view, "TEXT", Affine::IDENTITY, None); - text.insert("relativeTransform".into(), rows(transform)); - self.text(&mut text, view); - children.push(Value::Object(text)); - self.count += 1; - } -} - -pub(super) fn connector_has_saved_label(v: &View<'_>) -> bool { - own_text(v).is_some() - || generated_record(v, "nodeGenerationData", 1) - .and_then(|r| r.get("textData")) - .and_then(|d| d.get("characters")) - .and_then(Kv::str) - .is_some_and(|s| !s.trim().is_empty()) -} - -/// The path a FigJam elbow connector was saved with: its `connectorControlPoints`, one per run -/// between the first and the last, each a point on its run (in the connector's parent's -/// coordinates, like its ends) with the run's axis; the first run leaves the start's side and the -/// last arrives at the end's, so neither is saved. `None` without any, or when they don't make -/// such a path: a point off both axes, two runs in a row the same way, a first or last run that -/// would leave or arrive sideways to its side, or more runs than a hand could make here. -fn saved_runs(v: &View<'_>, from: RouteEnd, to: RouteEnd) -> Option { - let saved = v.list("connectorControlPoints"); - if saved.is_empty() || saved.len() + 2 > MAX_RUNS { - return None; - } - let (p0, p1) = attach_points(from, to); - let mid = p0.midpoint(p1); - let mut at = Vec::with_capacity(saved.len()); - let (mut first, mut last) = (None, None); - for p in saved { - let pos = p.get("position").and_then(|q| Some(Point::new(num(q, "x")?, num(q, "y")?)))?; - let (ax, ay) = p.get("axis").and_then(|q| Some((num(q, "x")?, num(q, "y")?)))?; - let sideways = match (ax != 0.0, ay != 0.0) { - (true, false) => true, - (false, true) => false, - _ => return None, - }; - if last == Some(sideways) { - return None; - } - first.get_or_insert(!sideways); - last = Some(sideways); - at.push(if sideways { pos.y - mid.y } else { pos.x - mid.x }); - } - // The run through each end goes the way its side faces, out of the object: the first leaves - // the start's side for the first saved run, the last arrives at the end's from the last saved - // run. One along the side, or back into the object, doesn't. - let (across, last) = (first?, last?); - let (&a0, &a1) = (at.first()?, at.last()?); - // Where the run from `p` (`sideways`: going across) meets the saved run at `v`. - let onto = |sideways: bool, p: Point, v: f64| if sideways { Point::new(mid.x + v, p.y) } else { Point::new(p.x, mid.y + v) }; - let out_of = |s: Option, p: Point, q: Point| s.is_none_or(|s| (q - p).dot(s.normal()) > 0.0); - let (s0, s1) = attached_sides(from, to); - let fits = out_of(s0, p0, onto(across, p0, a0)) && out_of(s1, p1, onto(!last, p1, a1)); - fits.then_some(ConnectorPath::Runs { across, at }) -} - -/// The side of its layer a connector end leaves from: the `magnet` the file names (`AUTO` and -/// `CENTER`: the side facing the other end, whatever `relativePosition` says; #1909), else the edge -/// its point on the layer (`relativePosition`, 0–1) lies on, else the side facing the other end. -fn side(e: &Kv<'_>, at: Option<(f64, f64)>) -> Side { - match e.get("magnet").and_then(Kv::str) { - Some("TOP") => Side::Top, - Some("RIGHT") => Side::Right, - Some("BOTTOM") => Side::Bottom, - Some("LEFT") => Side::Left, - Some("AUTO" | "CENTER") => Side::Auto, - _ => match at { - Some((x, _)) if x <= 0.0 => Side::Left, - Some((x, _)) if x >= 1.0 => Side::Right, - Some((_, y)) if y <= 0.0 => Side::Top, - Some((_, y)) if y >= 1.0 => Side::Bottom, - _ => Side::Auto, - }, - } -} - -/// What a connector's line carries, moved to the line child when the connector becomes a frame. -const LINE_KEYS: &[&str] = &[ - "vectorNetwork", - "vectorNetworkRef", - "fillGeometry", - "strokeGeometry", - "fills", - "strokes", - "strokeWeight", - "strokeAlign", - "strokeJoin", - "strokeDashes", - "strokeCap", - "strokeCapStart", - "strokeCapEnd", - "strokeWidthProfile", - "styles", -]; - -/// How wide a label without a saved snapshot is laid out, centred on its connector. -const LABEL_WIDTH: f64 = 200.0; - -/// The point halfway along `path` by length. -fn middle(path: &BezPath) -> Option { - let mut pts: Vec = Vec::new(); - figcraft_doc::geom::kurbo::flatten(path.iter(), 0.25, |el| { - if let PathEl::MoveTo(p) | PathEl::LineTo(p) = el { - pts.push(p); - } - }); - let total: f64 = pts.windows(2).map(|s| (s[1] - s[0]).hypot()).sum(); - let mut left = total / 2.0; - for s in pts.windows(2) { - let l = (s[1] - s[0]).hypot(); - if l >= left && l > 0.0 { - return Some(s[0].lerp(s[1], left / l)); - } - left -= l; - } - pts.first().copied() -} diff --git a/crates/format/src/fig/map/connector_snapshot_budget_tests.rs b/crates/format/src/fig/map/connector_snapshot_budget_tests.rs deleted file mode 100644 index 8727c31b7..000000000 --- a/crates/format/src/fig/map/connector_snapshot_budget_tests.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! Connector snapshot flattening stays within the node and depth budgets. - -use super::{MAX_DEPTH, Mapper, View}; -use crate::fig::kiwi::Kv; -use crate::rest::MAX_NODES; -use figcraft_doc::geom::Affine; - -fn obj(fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { - Kv::Object(fields) -} - -fn guid(local_id: u64) -> Kv<'static> { - obj(vec![("sessionID", Kv::Uint(40_000_000)), ("localID", Kv::Uint(local_id))]) -} - -fn path_blob() -> Vec { - let mut bytes = vec![1]; - bytes.extend(0.0f32.to_le_bytes()); - bytes.extend(0.0f32.to_le_bytes()); - bytes.push(2); - bytes.extend(20.0f32.to_le_bytes()); - bytes.extend(10.0f32.to_le_bytes()); - bytes -} - -fn record(local_id: u64, mut fields: Vec<(&'static str, Kv<'static>)>) -> Kv<'static> { - fields.push(("guidPath", obj(vec![("guids", Kv::Array(vec![guid(local_id)]))]))); - obj(fields) -} - -fn message() -> Kv<'static> { - let line = record( - 0, - vec![ - ( - "transform", - obj(vec![ - ("m00", Kv::Float(1.0)), - ("m01", Kv::Float(0.0)), - ("m02", Kv::Float(0.0)), - ("m10", Kv::Float(0.0)), - ("m11", Kv::Float(1.0)), - ("m12", Kv::Float(0.0)), - ]), - ), - ("size", obj(vec![("x", Kv::Float(20.0)), ("y", Kv::Float(10.0))])), - ("fillGeometry", Kv::Array(vec![obj(vec![("commandsBlob", Kv::Uint(0))])])), - ], - ); - let text = record( - 1, - vec![ - ( - "transform", - obj(vec![ - ("m00", Kv::Float(1.0)), - ("m01", Kv::Float(0.0)), - ("m02", Kv::Float(0.0)), - ("m10", Kv::Float(0.0)), - ("m11", Kv::Float(1.0)), - ("m12", Kv::Float(0.0)), - ]), - ), - ("size", obj(vec![("x", Kv::Float(50.0)), ("y", Kv::Float(20.0))])), - ], - ); - let background = record( - 2, - vec![ - ( - "transform", - obj(vec![ - ("m00", Kv::Float(1.0)), - ("m01", Kv::Float(0.0)), - ("m02", Kv::Float(0.0)), - ("m10", Kv::Float(0.0)), - ("m11", Kv::Float(1.0)), - ("m12", Kv::Float(0.0)), - ]), - ), - ("size", obj(vec![("x", Kv::Float(60.0)), ("y", Kv::Float(30.0))])), - ], - ); - let line_style = record(0, vec![]); - let text_style = record(1, vec![("textData", obj(vec![("characters", Kv::Str("budget label".into()))]))]); - let background_style = record(2, vec![("fillPaints", Kv::Array(vec![]))]); - obj(vec![ - ( - "nodeChanges", - Kv::Array(vec![obj(vec![ - ("guid", obj(vec![("sessionID", Kv::Uint(1)), ("localID", Kv::Uint(123))])), - ("type", Kv::Enum("CONNECTOR")), - ("name", Kv::Str("budget connector".into())), - ("connectorType", Kv::Enum("MANUAL")), - ("connectorVersion", Kv::Float(1.0)), - ("connectorLineStyle", Kv::Enum("STRAIGHT")), - ("derivedImmutableFrameData", obj(vec![("version", Kv::Float(1.0)), ("overrides", Kv::Array(vec![line, text, background]))])), - ("nodeGenerationData", obj(vec![("overrides", Kv::Array(vec![line_style, text_style, background_style]))])), - ])]), - ), - ("blobs", Kv::Array(vec![obj(vec![("bytes", Kv::Bytes(path_blob()))])])), - ]) -} - -#[test] -fn connector_snapshot_respects_last_and_zero_child_slots() { - let message = message(); - let node = message.get("nodeChanges").unwrap().list().first().unwrap(); - let view = View::of(node); - let mut mapper = Mapper::new(&message, MAX_NODES); - mapper.count = MAX_NODES - 1; - let children = mapper.connector_snapshot_children(&view, "1:123"); - assert_eq!(children.len(), 1, "the final available slot preserves the saved vector"); - assert_eq!(children[0]["type"], "VECTOR"); - assert!(!children[0]["fillGeometry"].as_array().unwrap().is_empty(), "saved outline survives the budget limit"); - assert_eq!(children[0]["fillGeometry"][0]["path"], "M 0 0 L 20 10"); - assert_eq!(mapper.count, MAX_NODES); - assert!(mapper.warnings.seen().any(|warning| warning == format!("the file has more than {MAX_NODES} layers; connector label was skipped"))); - - let mut mapper = Mapper::new(&message, MAX_NODES); - mapper.count = MAX_NODES; - let children = mapper.connector_snapshot_children(&view, "1:123"); - assert!(children.is_empty()); - assert_eq!(mapper.count, MAX_NODES, "the node budget is never exceeded"); - assert!(mapper.warnings.seen().any(|warning| warning.contains("connector snapshot children were skipped"))); -} - -#[test] -fn connector_snapshot_flattens_vector_at_depth_and_node_limits() { - let message = message(); - let mut mapper = Mapper::new(&message, MAX_NODES); - let depth_limited = mapper.layer("1:123", None, Affine::IDENTITY, None, None, MAX_DEPTH).expect("terminal connector"); - assert_eq!(depth_limited["type"], "VECTOR"); - assert!(!depth_limited["fillGeometry"].as_array().unwrap().is_empty()); - assert!(depth_limited.get("children").is_none()); - assert!(mapper.warnings.seen().any(|warning| warning == "connector label was skipped: depth limit prevents nested snapshot children")); - - let mut mapper = Mapper::new(&message, MAX_NODES); - mapper.count = MAX_NODES - 1; - let budget_limited = mapper.layer("1:123", None, Affine::IDENTITY, None, None, 0).expect("last allowed connector"); - assert_eq!(budget_limited["type"], "VECTOR"); - assert!(!budget_limited["fillGeometry"].as_array().unwrap().is_empty()); - assert!(budget_limited.get("children").is_none()); - assert_eq!(mapper.count, MAX_NODES); - assert!(mapper.warnings.seen().any(|warning| warning == "connector label was skipped: node budget prevents nested snapshot children")); -} - -/// A mapper note is met once per layer, so the kinds were named once each with no sign of how much -/// of the file they covered: a file whose every layer lost a setting read the same as one where a -/// single layer did (#467). They are counted now, with the `(×n)` the REST importer already uses -/// and the import report already reads back off before translating a note. -#[test] -fn a_note_met_more_than_once_carries_its_count() { - let message = message(); - - let mut mapper = Mapper::new(&message, MAX_NODES); - for _ in 0..2 { - mapper.layer("1:123", None, Affine::IDENTITY, None, None, MAX_DEPTH).expect("terminal connector"); - } - let notes = std::mem::take(&mut mapper.warnings).finish(); - let counted: Vec<&String> = notes.iter().filter(|n| n.contains("(×")).collect(); - assert!( - counted.iter().any(|n| n.ends_with("(×2)") && n.contains("connector label was skipped: depth limit")), - "the note met twice says so: {notes:?}" - ); - assert!(notes.iter().all(|n| !n.ends_with("(×1)")), "a count of one is left off: {notes:?}"); - - // One layer, and the same notes have no count at all. - let mut mapper = Mapper::new(&message, MAX_NODES); - mapper.layer("1:123", None, Affine::IDENTITY, None, None, MAX_DEPTH).expect("terminal connector"); - let once = std::mem::take(&mut mapper.warnings).finish(); - assert!(once.iter().all(|n| !n.contains("(×")), "{once:?}"); - assert_eq!( - once.len(), - counted.len() + notes.iter().filter(|n| !n.contains("(×")).count(), - "the same kinds, counted or not: {once:?} vs {notes:?}" - ); -} diff --git a/crates/format/src/fig/map/document.rs b/crates/format/src/fig/map/document.rs deleted file mode 100644 index 6868de485..000000000 --- a/crates/format/src/fig/map/document.rs +++ /dev/null @@ -1,333 +0,0 @@ -use super::component::{assigned, prop_guid}; -use super::paint::color; -use super::variables::variable_value; -use super::{Affine, BTreeMap, BTreeSet, Kv, MAX_DEPTH, Mapper, Obj, Value, View, copy_str, guid, json, rows}; - -impl<'a> Mapper<'a> { - /// The DOCUMENT with its pages. - pub(super) fn document(&mut self) -> Value { - let doc_id = self.nodes.iter().find(|(_, n)| n.get("type").and_then(Kv::str) == Some("DOCUMENT")).map(|(id, _)| id.clone()); - let pages: Vec = match &doc_id { - Some(d) => self.children(d), - None => self.nodes.iter().filter(|(_, n)| n.get("type").and_then(Kv::str) == Some("CANVAS")).map(|(id, _)| id.clone()).collect(), - }; - let mut internal = Vec::new(); - let mut visible = Vec::new(); - for p in pages { - let Some(&n) = self.nodes.get(&p) else { continue }; - if n.get("type").and_then(Kv::str) != Some("CANVAS") { - self.warn("document children other than pages were skipped"); - continue; - } - // The hidden page that holds styles, variables and library copies. - if n.get("internalOnly").and_then(Kv::bool) == Some(true) { - internal.push((p, n)); - } else { - visible.push((p, n)); - } - } - // The library copies the pages use come first: in a file past the layer cap, the pages' - // last layers are skipped rather than the mains every instance of them needs (#981). - let visible_pages: Vec = visible.iter().map(|(p, _)| p.clone()).collect(); - let required_mains = self.referenced_component_mains(&visible_pages); - // The pages and their top-level layers, up to half the cap, stay for the pages. - let top: usize = visible_pages.iter().map(|p| 1 + self.children(p).len()).sum(); - self.reserved = top.min(self.max_nodes / 2); - for (id, canvas) in internal { - if let Some(context) = self.library_context(&id, canvas, &required_mains) { - self.library_contexts.push(context); - } - } - self.reserved = 0; - let out: Vec = visible.into_iter().map(|(p, n)| self.page(&p, n)).collect(); - if out.is_empty() { - self.warn("the file has no pages"); - } - let mut doc = json!({"id": doc_id.unwrap_or_else(|| "0:0".into()), "type": "DOCUMENT"}); - doc["children"] = Value::Array(out); - doc - } - - /// The ids of the components the visible pages use, directly or through the components they - /// use in turn (nested instances, swap targets, overrides naming another main). - fn referenced_component_mains(&mut self, visible_pages: &[String]) -> BTreeSet { - let mut mains = BTreeSet::new(); - let mut visited = BTreeSet::new(); - let mut pending: Vec<(String, usize)> = visible_pages.iter().flat_map(|page| self.children(page)).map(|id| (id, 1)).collect(); - while let Some((id, depth)) = pending.pop() { - if depth > MAX_DEPTH { - self.warn(format!("component references below {MAX_DEPTH} layer levels were skipped")); - continue; - } - if !visited.insert(id.clone()) { - continue; - } - if visited.len() > self.max_nodes { - let max = self.max_nodes; - self.warn(format!("the component reference scan reached the {max}-layer limit")); - break; - } - let Some(node) = self.nodes.get(&id) else { continue }; - for target in self.component_main_targets(node) { - if mains.insert(target.clone()) { - pending.push((target, 1)); - } - } - pending.extend(self.children(&id).into_iter().map(|child| (child, depth + 1))); - } - mains - } - - /// The mains a layer names: an instance's own, the ones its overrides swap in, the instance-swap - /// defaults and values of component properties. - fn component_main_targets(&self, node: &Kv<'a>) -> Vec { - let mut targets: Vec = node - .get("componentPropDefs") - .map(Kv::list) - .unwrap_or_default() - .iter() - .filter_map(|definition| { - self.is_instance_swap(definition.get("id")?)?; - definition.get("initialValue")?.get("guidValue").and_then(guid) - }) - .collect(); - if node.get("type").and_then(Kv::str) != Some("INSTANCE") { - return targets; - } - // The instance and the override rows below it (rows carry the same fields, nested). - let mut pending: Vec<(&Kv<'a>, usize)> = vec![(node, 0)]; - let mut rows = 0usize; - while let Some((row, depth)) = pending.pop() { - rows += 1; - if depth > MAX_DEPTH || rows > self.max_nodes { - break; - } - let data = row.get("symbolData"); - targets.extend(row.get("overriddenSymbolID").and_then(guid)); - targets.extend(data.and_then(|d| d.get("symbolID")).and_then(guid)); - for assignment in row.get("componentPropAssignments").map(Kv::list).unwrap_or_default() { - if assignment.get("defID").is_some_and(|def| self.is_instance_swap(def).is_some()) { - targets.extend(assigned(assignment).and_then(prop_guid)); - } - } - let overrides = data.and_then(|d| d.get("symbolOverrides")).map(Kv::list).unwrap_or_default(); - let derived = row.get("derivedSymbolData").map(Kv::list).unwrap_or_default(); - pending.extend(overrides.iter().chain(derived).map(|row| (row, depth + 1))); - } - targets - } - - /// The branches of the internal canvas `id` that hold the `required_mains` (with the frames - /// they sit in), as a frame of its own: the cached definitions of components that come from a - /// library. `None` when it holds none. - fn library_context(&mut self, id: &str, canvas: &'a Kv<'a>, required_mains: &BTreeSet) -> Option { - let mut included = BTreeSet::new(); - let mut parents: BTreeMap = BTreeMap::new(); - // The canvas itself is never a layer of the walk, whatever the parent links say. - let mut visited = BTreeSet::from([id.to_string()]); - // Each entry: layer, depth, inside a required definition. - let mut pending: Vec<(String, usize, bool)> = self.children(id).into_iter().map(|child| (child, 1, false)).collect(); - while let Some((node_id, depth, in_definition)) = pending.pop() { - if depth > MAX_DEPTH { - self.warn(format!("internal library branches deeper than {MAX_DEPTH} levels were skipped")); - continue; - } - if !visited.insert(node_id.clone()) { - continue; - } - self.library_scan_count += 1; - if self.library_scan_count > self.max_nodes { - let max = self.max_nodes; - self.warn(format!("the internal library scan reached the {max}-layer limit; the remaining branches were skipped")); - break; - } - let Some(node) = self.nodes.get(&node_id) else { continue }; - let kind = node.get("type").and_then(Kv::str); - let definition = (kind == Some("SYMBOL") || (kind == Some("FRAME") && node.get("isStateGroup").and_then(Kv::bool) == Some(true))) - && required_mains.contains(&node_id); - let in_definition = in_definition || definition; - if in_definition { - included.insert(node_id.clone()); - } - if definition { - // The frames around it keep the path its layers are addressed by. - let mut ancestor = parents.get(&node_id); - for _ in 0..=MAX_DEPTH { - let Some(parent) = ancestor else { break }; - if !included.insert(parent.clone()) { - break; - } - ancestor = parents.get(parent); - } - } - for child in self.children(&node_id).into_iter().rev() { - // A layer reached again keeps the parent it was first reached by, so the parents - // lead back to the canvas. - if visited.contains(&child) { - continue; - } - parents.entry(child.clone()).or_insert_with(|| node_id.clone()); - pending.push((child, depth + 1, in_definition)); - } - } - if included.is_empty() { - return None; - } - let mut context = Obj::new(); - context.insert("id".into(), json!(id)); - context.insert("type".into(), json!("FRAME")); - copy_str(&mut context, &View::of(canvas), "name", "name"); - context.insert("size".into(), json!({"x": 0.0, "y": 0.0})); - context.insert("relativeTransform".into(), rows(Affine::IDENTITY)); - context.insert(crate::rest::FIG_SOURCE_FIELD.into(), json!({"origin": id, "expanded": false, "wireFrame": true, "wireInstance": false})); - self.variable_bindings(&mut context, &View::of(canvas)); - let mut children = Vec::new(); - for child in self.children(id) { - children.extend(self.layer_filtered(&child, None, Affine::IDENTITY, None, None, 0, Some(&included))); - } - if !children.is_empty() { - context.insert("children".into(), Value::Array(children)); - } - Some(Value::Object(context)) - } - - fn page(&mut self, id: &str, n: &'a Kv<'a>) -> Value { - let v = View::of(n); - let mut o = Obj::new(); - o.insert("id".into(), json!(id)); - o.insert("type".into(), json!("CANVAS")); - copy_str(&mut o, &v, "name", "name"); - if let Some(c) = v.get("backgroundColor") { - o.insert("backgroundColor".into(), color(c)); - } - if let Some(c) = v.get("prototypeBackgroundColor") { - o.insert("prototypeBackgrounds".into(), json!([color(c)])); - } - self.variable_bindings(&mut o, &v); - let mut flows: Vec<(&str, Value)> = Vec::new(); - let mut kids = Vec::new(); - for c in self.children(id) { - if let Some(sp) = self.nodes.get(&c).and_then(|k| k.get("prototypeStartingPoint")) { - let name = sp.get("name").and_then(Kv::str).filter(|s| !s.is_empty()).unwrap_or("Flow"); - flows.push((sp.get("position").and_then(Kv::str).unwrap_or(""), json!({"nodeId": c, "name": name}))); - } - kids.extend(self.layer(&c, None, Affine::IDENTITY, None, None, 0)); - } - flows.sort_by(|a, b| a.0.cmp(b.0)); - if !flows.is_empty() { - o.insert("flowStartingPoints".into(), Value::Array(flows.into_iter().map(|f| f.1).collect())); - } - o.insert("children".into(), Value::Array(kids)); - Value::Object(o) - } - - /// The shared styles the file defines, in their order: each with the sample layer that holds - /// its values (`styleDefinitions`, our extension of the file JSON; the REST importer reads it). - pub(super) fn style_definitions(&mut self) -> Vec { - let mut found: Vec<(&'a str, String, &'a Kv<'a>)> = Vec::new(); - for (id, n) in &self.nodes { - let live = n.get("isSoftDeleted").and_then(Kv::bool) != Some(true) && n.get("isSoftDeletedStyle").and_then(Kv::bool) != Some(true); - if live && n.get("styleType").and_then(Kv::str).is_some_and(|t| matches!(t, "FILL" | "TEXT" | "EFFECT" | "GRID")) { - found.push((n.get("sortPosition").and_then(Kv::str).unwrap_or(""), id.clone(), n)); - } - } - found.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1))); - let mut out = Vec::new(); - for (_, id, n) in found { - let Some(node) = self.layer(&id, None, Affine::IDENTITY, None, None, 0) else { break }; - let name = n.get("name").and_then(Kv::str).unwrap_or("Style"); - let desc = n.get("styleDescription").or_else(|| n.get("description")).and_then(Kv::str).unwrap_or(""); - let ty = n.get("styleType").and_then(Kv::str).unwrap_or(""); - out.push(json!({"id": id, "name": name, "description": desc, "styleType": ty, "node": node})); - } - out - } - - /// Collections and variables, as the local variables response's `meta`, with their ids in the - /// file's order (`collectionOrder` and `variableOrder`, our extensions). - pub(super) fn variables(&self) -> Option { - let of_type = |t: &'static str, key: &'static str| { - let live = move |n: &Kv| n.get("type").and_then(Kv::str) == Some(t) && n.get("isSoftDeleted").and_then(Kv::bool) != Some(true); - let mut list: Vec<(&str, &String, &'a Kv<'a>)> = self - .nodes - .iter() - .filter(|(_, n)| live(n)) - .map(|(id, n)| (n.get(key).and_then(|p| p.get("position").or(Some(p))).and_then(Kv::str).unwrap_or(""), id, *n)) - .collect(); - list.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1))); - list.into_iter().map(|(_, id, n)| (id, n)) - }; - let mut order = Vec::new(); - let mut collections = Obj::new(); - // Copies of one library collection (one per version the file met) become one: the newest - // keeps its modes in its order, the others add the modes it no longer has. - let mut extra: BTreeMap> = BTreeMap::new(); - for (id, n) in of_type("VARIABLE_SET", "parentIndex") { - let modes = sorted_modes(n); - match self.canonical_collection(id).filter(|c| c != id) { - Some(canonical) => extra.entry(canonical).or_default().extend(modes), - None => { - order.push(json!(id)); - let default = modes.first().map_or(Value::Null, |m| m.1["modeId"].clone()); - let name = n.get("name").and_then(Kv::str).unwrap_or("Collection"); - let modes: Vec = modes.into_iter().map(|m| m.1).collect(); - collections.insert(id.clone(), json!({"id": id, "name": name, "modes": modes, "defaultModeId": default})); - } - } - } - for (canonical, more) in extra { - let Some(modes) = collections.get_mut(&canonical).and_then(|c| c.get_mut("modes")).and_then(Value::as_array_mut) else { continue }; - for (_, m) in more { - if !modes.iter().any(|x| x["modeId"] == m["modeId"]) { - modes.push(m); - } - } - } - let mut variable_order = Vec::new(); - let mut variables = Obj::new(); - for (id, n) in of_type("VARIABLE", "sortPosition") { - if super::VarCanon::superseded(id) { - continue; - } - let Some(set) = n.get("variableSetID").and_then(|s| self.collection_id(s)).filter(|s| collections.contains_key(s)) else { continue }; - let ty = n.get("variableResolvedType").and_then(Kv::str).unwrap_or(""); - if !matches!(ty, "BOOLEAN" | "FLOAT" | "STRING" | "COLOR") { - continue; - } - let mut values = Obj::new(); - for e in n.get("variableDataValues").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() { - if let (Some(mode), Some(val)) = (e.get("modeID").and_then(guid), e.get("variableData").and_then(variable_value)) { - values.insert(mode, val); - } - } - let name = n.get("name").and_then(Kv::str).unwrap_or("Variable"); - let desc = n.get("description").and_then(Kv::str).unwrap_or(""); - let mut var = - json!({"id": id, "name": name, "variableCollectionId": set, "resolvedType": ty, "valuesByMode": values, "description": desc}); - // The properties pickers offer the variable for, under the REST names. - if let Some(scopes) = n.get("variableScopes") { - var["scopes"] = scopes.list().iter().filter_map(Kv::str).map(|s| if s == "STROKE" { "STROKE_COLOR" } else { s }).collect(); - } - variable_order.push(json!(id)); - variables.insert(id.clone(), var); - } - (!collections.is_empty()) - .then(|| json!({"variableCollections": collections, "variables": variables, "collectionOrder": order, "variableOrder": variable_order})) - } -} - -/// A collection node's modes in their order (`sortPosition`), as `(position, {modeId, name})`. -fn sorted_modes(n: &Kv) -> Vec<(String, Value)> { - let mut modes: Vec<(String, Value)> = n - .get("variableSetModes") - .map(Kv::list) - .unwrap_or_default() - .iter() - .filter_map(|m| { - let mode = json!({"modeId": m.get("id").and_then(guid)?, "name": m.get("name").and_then(Kv::str).unwrap_or("Mode")}); - Some((m.get("sortPosition").and_then(Kv::str).unwrap_or("").to_string(), mode)) - }) - .collect(); - modes.sort_by(|a, b| a.0.cmp(&b.0)); - modes -} diff --git a/crates/format/src/fig/map/image_filter_tests.rs b/crates/format/src/fig/map/image_filter_tests.rs deleted file mode 100644 index e13a56e32..000000000 --- a/crates/format/src/fig/map/image_filter_tests.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! Malformed image paint filters are skipped with a warning, and image hashes too long to name -//! an image aren't spelled out. - -use super::*; - -#[test] -fn malformed_non_finite_filter_is_skipped_with_warning() { - let paint = Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("paintFilter", Kv::Object(vec![("exposure", Kv::Float(f32::NAN))]))]); - let mut warnings = Vec::new(); - let value = super::paint(&paint, &mut |warning| warnings.push(warning)).unwrap(); - assert!(value.get("filters").is_none(), "{value}"); - assert!(warnings.iter().any(|warning| warning.contains("malformed image filter `exposure`")), "{warnings:?}"); -} - -#[test] -fn boolean_filter_values_are_malformed_even_when_false() { - for (field, value, expected_warning) in [ - ("exposure", Kv::Bool(true), "malformed image filter `exposure`"), - ("exposure", Kv::Bool(false), "malformed image filter `exposure`"), - ("mystery", Kv::Bool(false), "malformed unsupported image filter `mystery`"), - ] { - let paint = Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("paintFilter", Kv::Object(vec![(field, value)]))]); - let mut warnings = Vec::new(); - let value = super::paint(&paint, &mut |warning| warnings.push(warning)).unwrap(); - assert!(value.get("filters").is_none(), "{value}"); - assert!(warnings.iter().any(|warning| warning.contains(expected_warning)), "{warnings:?}"); - } -} - -#[test] -fn an_oversized_image_hash_is_not_spelled_out() { - let paint = |len: usize| Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("image", Kv::Object(vec![("hash", Kv::Bytes(vec![0xab; len]))]))]); - let image_ref = |len: usize| super::paint(&paint(len), &mut |_| {}).and_then(|p| p.get("imageRef").cloned()); - assert_eq!(image_ref(20), Some(Value::String("ab".repeat(20)))); - assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH), Some(Value::String("ab".repeat(crate::fig::MAX_IMAGE_HASH)))); - assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH + 1), Some(Value::String(String::new()))); -} diff --git a/crates/format/src/fig/map/layer.rs b/crates/format/src/fig/map/layer.rs deleted file mode 100644 index a2bc20ad0..000000000 --- a/crates/format/src/fig/map/layer.rs +++ /dev/null @@ -1,927 +0,0 @@ -use super::component::{Entry, Inst, OverrideRow, prop_ref}; -use super::connector::{ConnectorShape, connector_has_saved_label}; -use super::layout::{layout_grid, tracks}; -use super::paint::{effect, export_setting, has_bound_variables, paint, paint_bound, stroke}; -use super::{ - Affine, BTreeMap, BTreeSet, Kv, MAX_COMMANDS, MAX_DEPTH, Mapper, Obj, Value, View, copy_len, copy_num, copy_str, generated_record, guid, json, - matrix, network, num, rows, scaled, size, -}; - -/// How the layers of a resized container follow it when the file gives no derived layout for -/// them: a frame's by their constraints, from its main's size to its own; a group's scale with it. -#[derive(Clone, Copy)] -pub(super) enum Fit { - Frame { from: (f64, f64), to: (f64, f64) }, - Scale(f64, f64), -} - -impl Fit { - fn frame(from: Option<(f64, f64)>, to: Option<(f64, f64)>) -> Option { - let (from, to) = (from?, to?); - ((from.0 - to.0).abs() > 1e-9 || (from.1 - to.1).abs() > 1e-9).then_some(Fit::Frame { from, to }) - } - - fn scale(from: Option<(f64, f64)>, to: Option<(f64, f64)>) -> Option { - let (from, to) = (from?, to?); - let k = |a: f64, b: f64| if a > 1e-9 { b / a } else { 1.0 }; - let (kx, ky) = (k(from.0, to.0), k(from.1, to.1)); - ((kx - 1.0).abs() > 1e-9 || (ky - 1.0).abs() > 1e-9).then_some(Fit::Scale(kx, ky)) - } - - /// The size and transform (in the parent's coordinates) of a `w` × `h` layer at `t` with - /// constraints `h_con`, `v_con`. Like the editor's constraint solver, a layer keeps its - /// rotation and flip and stretches along its own axes. - fn apply(self, w: f64, h: f64, t: Affine, h_con: Option<&str>, v_con: Option<&str>) -> ((f64, f64), Affine) { - let [a, b, c, d, _, _] = t.as_coeffs(); - let lin = Affine::new([a, b, c, d, 0.0, 0.0]); - let bb = figcraft_doc::geom::transform_rect_bbox(t, figcraft_doc::geom::Rect::new(0.0, 0.0, w, h)); - // Where the new box goes: its top-left (constraints) or its centre (a group's scale). - let (kx, ky, x0, y0, centred) = match self { - Fit::Frame { from, to } => { - let axis = |con: Option<&str>, lo: f64, hi: f64, old: f64, new: f64| match con { - Some("MAX" | "FIXED_MAX") => (lo + new - old, hi + new - old), - Some("STRETCH") => (lo, hi + new - old), - Some("CENTER") => (lo + (new - old) / 2.0, hi + (new - old) / 2.0), - Some("SCALE") if old > 1e-9 => (lo * new / old, hi * new / old), - _ => (lo, hi), - }; - let (x0, x1) = axis(h_con, bb.x0, bb.x1, from.0, to.0); - let (y0, y1) = axis(v_con, bb.y0, bb.y1, from.1, to.1); - let k = |new: f64, old: f64| if old > 1e-9 { (new / old).max(0.0) } else { 1.0 }; - (k(x1 - x0, bb.width()), k(y1 - y0, bb.height()), x0, y0, false) - } - Fit::Scale(kx, ky) => (kx, ky, bb.center().x * kx, bb.center().y * ky, true), - }; - let along = |x: f64, y: f64, fallback: f64| { - let len = x.hypot(y); - let k = (kx * x).hypot(ky * y) / len; - if len > 1e-12 && k.is_finite() { k } else { fallback } - }; - let size = (w * along(a, b, kx), h * along(c, d, ky)); - let nb = figcraft_doc::geom::transform_rect_bbox(lin, figcraft_doc::geom::Rect::new(0.0, 0.0, size.0, size.1)); - let at = if centred { nb.center() } else { figcraft_doc::geom::Point::new(nb.x0, nb.y0) }; - (size, Affine::translate((x0 - at.x, y0 - at.y)) * lin) - } -} - -struct LayerChildren<'s, 'a> { - id: &'s str, - inst: Option<&'s Inst<'a>>, - base: &'s Kv<'a>, - child_space: Affine, - view: &'s View<'a>, - object: &'s mut Obj, - ty: &'s str, - rest_id: &'s str, - connector_snapshot: bool, - connector_terminal: bool, - depth: usize, - included: Option<&'s BTreeSet>, - slot_content: Option, -} - -impl<'a> Mapper<'a> { - /// Layer `id` (inside instance `inst` when expanding one) and its subtree. `space`: from the - /// parent's coordinates to the enclosing frame's (groups and booleans place their children in - /// the frame's space, like the REST JSON). `parent`: the parent's view (grid tracks). - pub(crate) fn layer( - &mut self, - id: &str, - inst: Option<&Inst<'a>>, - space: Affine, - parent: Option<&View<'a>>, - fit: Option, - depth: usize, - ) -> Option { - self.layer_filtered(id, inst, space, parent, fit, depth, None) - } - - /// [`Self::layer`], keeping only the layers in `included` (all when `None`) below the - /// top-level one: the cached library definitions of an internal canvas. - pub(super) fn layer_filtered( - &mut self, - id: &str, - inst: Option<&Inst<'a>>, - space: Affine, - parent: Option<&View<'a>>, - fit: Option, - depth: usize, - included: Option<&BTreeSet>, - ) -> Option { - if included.is_some_and(|ids| !ids.contains(id)) { - return None; - } - if depth > MAX_DEPTH { - self.warn(format!("layers nested deeper than {MAX_DEPTH} levels were skipped")); - return None; - } - if self.count >= self.budget() { - let max = self.max_nodes; - self.warn(format!("the file has more than {max} layers; the rest were skipped")); - return None; - } - let base = *self.nodes.get(id)?; - let path = inst.map(|i| [i.path.as_slice(), &[id.to_string()]].concat()); - let entries: &[OverrideRow<'a>] = match (inst, &path) { - (Some(i), Some(p)) => i.overrides.get(p).map(Vec::as_slice).unwrap_or_default(), - _ => &[], - }; - // Inside a scaled instance the main's lengths are the factor times as long; the rows of - // the instance are at its scale already (#2091). - let scale = inst.map_or(1.0, |i| i.scale); - let mut view = View::of_scaled(base, scale).with(entries.iter().map(|e| (e.row, e.scale))); - // A layer of a resized instance the file gives no derived layout for follows its - // constraints from the main's geometry, then takes the size and place overridden on it - // (auto layout places the others, as in the editor). - let derived = entries.iter().any(|e| e.entry == Entry::Derived && (e.row.get("size").is_some() || e.row.get("transform").is_some())); - let stacked = parent.and_then(|p| p.str("stackMode")).is_some_and(|m| matches!(m, "HORIZONTAL" | "VERTICAL" | "GRID")) - && view.str("stackPositioning") != Some("ABSOLUTE"); - let main = View::of_scaled(base, scale); - // The size and place a row gives, at the scale of the row (a nested instance's own rows - // are at its enclosing main's scale). - let set = |k: &str| entries.iter().rev().filter(|e| e.entry != Entry::Stale).find_map(|e| e.row.get(k).map(|r| (r, e.scale))); - let set_size = || { - let (r, k) = set("size")?; - let (x, y) = size(r)?; - Some((scaled(x, k)?, scaled(y, k)?)) - }; - let set_transform = || { - let (r, k) = set("transform")?; - let m = matrix(r)?; - let [a, b, c, d, e, f] = m.as_coeffs(); - Some(Affine::new([a, b, c, d, scaled(e, k)?, scaled(f, k)?])) - }; - if let (Some(f), false, false, Some((w, h))) = (fit, derived, stacked, main.size()) { - let t = main.transform().unwrap_or_default(); - let (fw, ft) = f.apply(w, h, t, view.str("horizontalConstraint"), view.str("verticalConstraint")); - view.fitted = Some((set_size().unwrap_or(fw), set_transform().unwrap_or(ft))); - } else if entries.iter().any(|e| e.entry == Entry::Stale && (e.row.get("size").is_some() || e.row.get("transform").is_some())) - && let Some(s) = set_size().or_else(|| main.size()) - { - view.fitted = Some((s, set_transform().or_else(|| main.transform()).unwrap_or_default())); - } - let rest_id = match (inst, &path) { - (Some(i), Some(p)) => format!("I{};{}", i.root, p.join(";")), - _ => id.to_string(), - }; - let own = view.str("type").unwrap_or(""); - let connector_snapshot = own == "CONNECTOR" && self.connector_snapshot_supported(&view); - // Only a connector with a saved label needs the frame wrapper; an unlabelled one stays a single vector. - let connector_terminal = - connector_snapshot && (!connector_has_saved_label(&view) || depth >= MAX_DEPTH || self.count.saturating_add(1) >= self.budget()); - // A supported connector snapshot has its own note below instead of the generic stand-in one. - let stand = stand_in(own).filter(|_| !connector_snapshot); - // A label without a snapshot: the connector becomes a frame holding its line and its label. - let connector_label = own == "CONNECTOR" && !connector_snapshot && self.connector_label_fits(&view, depth); - let ty = if connector_label { "FRAME" } else { Self::mapped_type(own, &view, connector_snapshot, connector_terminal, stand)? }; - // A whiteboard's sticky or shape with text says it imports as a frame only when it can't be a native one. - let native_board = self.board && matches!(own, "STICKY" | "SHAPE_WITH_TEXT"); - if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_board) { - self.warn(format!("{} layers import as {what}", own.to_ascii_lowercase().replace('_', " "))); - } - if connector_snapshot { - self.warn("connector layers import as static frame/vector snapshots with labels when present; live endpoint bindings are not retained"); - } - self.count += 1; - if own == "SYMBOL" && inst.is_none() { - self.mapped_mains.insert(id.to_string()); - } - let mut o = Obj::new(); - o.insert("id".into(), json!(rest_id)); - // Private provenance for the .fig importer; ordinary REST import ignores it. - o.insert( - crate::rest::FIG_SOURCE_FIELD.into(), - json!({ - "origin": id, - "expanded": inst.is_some(), - "wireFrame": own == "FRAME", - "wireInstance": own == "INSTANCE", - "slotContent": inst.is_some_and(|i| i.slot_content), - // A size the instance gives this layer itself (kept when the instance relays out). - "sizeOverride": entries.iter().any(|e| e.entry == Entry::Override && e.row.get("size").is_some()), - }), - ); - o.insert("type".into(), json!(ty)); - copy_str(&mut o, &view, "name", "name"); - self.common(&mut o, &view, ty, space, parent); - match ty { - "TEXT" => { - self.text(&mut o, &view); - if own == "TEXT_PATH" { - self.text_path(&mut o, &view); - } - } - "VECTOR" | "STAR" | "REGULAR_POLYGON" => self.geometry(&mut o, &view), - "ELLIPSE" => { - if let Some(a) = view.get("arcData") { - let arc: Obj = - ["startingAngle", "endingAngle", "innerRadius"].iter().filter_map(|k| Some((k.to_string(), json!(num(a, k)?)))).collect(); - o.insert("arcData".into(), Value::Object(arc)); - } - } - "BOOLEAN_OPERATION" => { - if let Some(op) = view.str("booleanOperation") { - o.insert("booleanOperation".into(), json!(if op == "XOR" { "EXCLUDE" } else { op })); - } - } - _ => {} - } - let connector_kids = if own == "CONNECTOR" { - let shape = ConnectorShape { snapshot: connector_snapshot, terminal: connector_terminal, label: connector_label }; - self.connector_layer(&mut o, &view, &rest_id, space, shape) - } else { - Vec::new() - }; - if ty == "COMPONENT" || ty == "COMPONENT_SET" { - self.component(&mut o, &view, &rest_id); - } - self.prop_refs(&mut o, &view, inst); - let slot_content = if own == "FRAME" { - prop_ref(&view, "SLOT_CONTENT_ID").and_then(|def| inst.and_then(|i| i.slot_contents.get(&self.prop_root(&def)).cloned())) - } else { - None - }; - if slot_content.is_some() - && let Some(source) = o.get_mut(crate::rest::FIG_SOURCE_FIELD).and_then(Value::as_object_mut) - { - source.insert("slotOverride".into(), json!(true)); - } - let child_space = if matches!(ty, "GROUP" | "BOOLEAN_OPERATION") { space * view.transform().unwrap_or_default() } else { Affine::IDENTITY }; - let mut kids = self.map_layer_children(LayerChildren { - id, - inst, - base, - child_space, - view: &view, - object: &mut o, - ty, - rest_id: &rest_id, - connector_snapshot, - connector_terminal, - depth, - included, - slot_content, - }); - kids.splice(0..0, connector_kids); - if stand.is_some_and(|s| s.0 == "FRAME") { - let native = if native_board { self.native_board_item(own, &mut o, &view, &rest_id, depth) } else { None }; - if let Some(native) = native { - kids.splice(0..0, native); - } else if let Some(snapshot) = self.board_snapshot(&mut o, &view, own, &rest_id, depth) { - kids.splice(0..0, snapshot); - } else { - kids.splice(0..0, self.shape_with_text(&mut o, &view, own, &rest_id)); - kids.extend(self.inner_text(&o, &view, &rest_id, own == "STICKY")); - } - } - if !kids.is_empty() { - o.insert("children".into(), Value::Array(kids)); - } - Some(Value::Object(o)) - } - - fn map_layer_children(&mut self, context: LayerChildren<'_, 'a>) -> Vec { - let LayerChildren { - id, - inst, - base, - child_space, - view, - object: o, - ty, - rest_id, - connector_snapshot, - connector_terminal, - depth, - included, - slot_content, - } = context; - let mut kids = if connector_snapshot && !connector_terminal { self.connector_snapshot_children(view, rest_id) } else { Vec::new() }; - if connector_terminal { - // The saved vector is flattened into the connector node when no child slot remains. - } else if ty == "INSTANCE" { - if let Some((sub, sym)) = self.instance(o, view, id, inst, rest_id) { - let main = self.nodes.get(&sym).map(|m| View::of_scaled(m, sub.scale)); - // A scaled main's size is the factor's product, rounded to a float: it matches an - // instance of that size without a fit that would round the layers again. - let near = |a: f64, b: f64| (a - b).abs() <= 1e-4 * a.abs().max(b.abs()).max(1.0); - let fit = match (main.as_ref().and_then(View::size), view.size()) { - (Some(a), Some(b)) if sub.scale != 1.0 && near(a.0, b.0) && near(a.1, b.1) => None, - (a, b) => Fit::frame(a, b), - }; - // An instance that records no auto layout of its own has its main's. - let view = match main { - Some(m) if view.get("stackMode").is_none() && m.get("stackMode").is_some() => { - let layered = m.over(view); - self.auto_layout(o, &layered); - layered - } - _ => view.clone(), - }; - for c in self.children(&sym) { - // The main's branch can live outside the cached context being mapped. - kids.extend(self.layer_filtered(&c, Some(&sub), child_space, Some(&view), fit, depth + 1, None)); - } - } - } else if let Some(content) = slot_content { - let mut content_inst = inst.cloned(); - if let Some(content_inst) = &mut content_inst { - content_inst.slot_content = true; - } - for c in self.children(&content) { - kids.extend(self.layer_filtered(&c, content_inst.as_ref(), child_space, Some(view), None, depth + 1, included)); - } - } else { - // Inside an instance a layer's children are its main's: they follow it from the main's - // size to its own. - let fit = match (inst, ty) { - (None, _) => None, - (Some(i), "GROUP" | "BOOLEAN_OPERATION") => Fit::scale(View::of_scaled(base, i.scale).size(), view.size()), - (Some(i), _) => Fit::frame(View::of_scaled(base, i.scale).size(), view.size()), - }; - for c in self.children(id) { - kids.extend(self.layer_filtered(&c, inst, child_space, Some(view), fit, depth + 1, included)); - } - } - kids - } - - fn mapped_type<'s>( - own: &'s str, - view: &View<'a>, - connector_snapshot: bool, - connector_terminal: bool, - stand: Option<(&'static str, &'static str)>, - ) -> Option<&'s str> { - match own { - "ROUNDED_RECTANGLE" => Some("RECTANGLE"), - "SYMBOL" => Some("COMPONENT"), - "FRAME" if view.flag("isStateGroup") == Some(true) => Some("COMPONENT_SET"), - "FRAME" if view.flag("resizeToFit") == Some(true) => Some("GROUP"), - "VARIABLE" | "VARIABLE_SET" => None, - "CONNECTOR" if connector_snapshot && connector_terminal => Some("VECTOR"), - "CONNECTOR" if connector_snapshot => Some("FRAME"), - t => Some(stand.map_or(t, |s| s.0)), - } - } - - /// FigJam notes and shapes keep their paints and text on generated template children, - /// not on the outer node. Keep the saved layout as ordinary editable layers (including a - /// note's author), without applying the background's opacity or transform to the wrapper. - /// When no generated body survives, retain usable outer text alongside successful children. - fn board_snapshot(&mut self, o: &mut Obj, v: &View<'a>, own: &str, rest_id: &str, depth: usize) -> Option> { - if !matches!(own, "STICKY" | "SHAPE_WITH_TEXT") || v.get("nodeGenerationData").is_none() { - return None; - } - if v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) { - self.warn("note or shape generated layout is missing or unsupported; using its outer frame"); - return None; - } - let mut children = Vec::new(); - let mut has_body = false; - for local_id in 0..if own == "STICKY" { 3 } else { 2 } { - let style = generated_record(v, "nodeGenerationData", local_id); - let bounds = generated_record(v, "derivedImmutableFrameData", local_id); - let (Some(style), Some(bounds)) = (style, bounds) else { - if style.is_some() || bounds.is_some() { - self.warn("note or shape generated child is missing its style or bounds; child skipped"); - } - continue; - }; - let child = View::of(style).with([(bounds, 1.0)]); - let chars = own_text(&child); - if local_id != 0 && chars.is_none() { - continue; - } - if valid_size(child.get("size")).is_none() || child.transform().is_none() { - self.warn("note or shape generated child has invalid bounds; child skipped"); - continue; - } - if self.count >= self.budget() || depth >= MAX_DEPTH { - self.warn("note or shape generated children exceed the layer or nesting limit; remaining children skipped"); - break; - } - let mut layer = Obj::new(); - let ty = if local_id == 0 { "RECTANGLE" } else { "TEXT" }; - layer.insert("id".into(), json!(format!("{rest_id};generated{local_id}"))); - layer.insert("type".into(), json!(ty)); - layer.insert("name".into(), json!(chars.map_or_else(|| "Background".into(), |c| c.chars().take(40).collect::()))); - self.common(&mut layer, &child, ty, Affine::IDENTITY, None); - if local_id == 0 { - // Network decoding is only enabled for vectors; choose that type before - // geometry sees a saved network, then restore the rectangle if it is unusable. - if child.get("vectorData").is_some() { - layer.insert("type".into(), json!("VECTOR")); - } - self.geometry(&mut layer, &child); - let outlined = |layer: &Obj| ["fillGeometry", "strokeGeometry", "vectorNetworkRef"].iter().any(|key| layer.contains_key(*key)); - if own == "SHAPE_WITH_TEXT" && !outlined(&layer) { - self.geometry(&mut layer, v); - } - if outlined(&layer) { - layer.insert("type".into(), json!("VECTOR")); - } else { - layer.insert("type".into(), json!("RECTANGLE")); - if own == "SHAPE_WITH_TEXT" && !matches!(v.str("shapeWithTextType"), None | Some("SQUARE" | "ROUNDED_RECTANGLE")) { - self.warn("shape generated outline is missing or damaged; using its rectangle"); - } - } - o.insert("fills".into(), json!([])); - o.insert("strokes".into(), json!([])); - } else { - self.text(&mut layer, &child); - if let Some(Value::Object(style)) = layer.get_mut("style") { - style.insert("textAutoResize".into(), json!("NONE")); - } - } - self.count += 1; - has_body |= local_id == 1; - children.push(Value::Object(layer)); - } - if depth < MAX_DEPTH && !has_body { - children.extend(self.inner_text(o, v, rest_id, own == "STICKY")); - } - Some(children) - } - - /// A non-rectangular shape-with-text's shape, as a vector under its frame (which gives up its - /// paints to it). - fn shape_with_text(&mut self, o: &mut Obj, v: &View<'a>, own: &str, rest_id: &str) -> Option { - let shape = v.str("shapeWithTextType").unwrap_or("SQUARE"); - let outlined = !v.list("fillGeometry").is_empty() || !v.list("strokeGeometry").is_empty(); - if own != "SHAPE_WITH_TEXT" || matches!(shape, "SQUARE" | "ROUNDED_RECTANGLE") || !outlined || self.count >= self.budget() { - return None; - } - let mut s = Obj::new(); - s.insert("id".into(), json!(format!("{rest_id};shape"))); - s.insert("type".into(), json!("VECTOR")); - s.insert("name".into(), json!(shape.to_ascii_lowercase().replace('_', " "))); - for k in ["size", "strokeWeight", "strokeAlign", "strokeJoin", "strokeDashes"] { - if let Some(x) = o.get(k) { - s.insert(k.into(), x.clone()); - } - } - for k in ["fills", "strokes"] { - s.insert(k.into(), o.insert(k.into(), json!([])).unwrap_or_else(|| json!([]))); - } - s.insert("relativeTransform".into(), rows(Affine::IDENTITY)); - self.geometry(&mut s, v); - if !s.contains_key("fillGeometry") && !s.contains_key("strokeGeometry") { - // Damaged outlines: the frame keeps its paints and box. - for k in ["fills", "strokes"] { - o.insert(k.into(), s.remove(k).unwrap_or_else(|| json!([]))); - } - return None; - } - self.count += 1; - Some(Value::Object(s)) - } - - /// The text a stand-in frame holds (a sticky note's, a shape's, a table cell's) as a text - /// layer filling it, inset a little; centred unless it's a note. - fn inner_text(&mut self, o: &Obj, v: &View<'a>, rest_id: &str, note: bool) -> Option { - let chars = own_text(v)?; - if self.count >= self.budget() { - return None; - } - self.count += 1; - let size = |k: &str| o.get("size").and_then(|s| s.get(k)).and_then(Value::as_f64).unwrap_or(0.0); - let (w, h) = (size("x"), size("y")); - let pad = (w.min(h) / 4.0).clamp(0.0, 16.0); - let mut t = Obj::new(); - t.insert("id".into(), json!(format!("{rest_id};text"))); - t.insert("type".into(), json!("TEXT")); - t.insert("name".into(), json!(chars.chars().take(40).collect::())); - t.insert("size".into(), json!({"x": (w - 2.0 * pad).max(1.0), "y": (h - 2.0 * pad).max(1.0)})); - t.insert("relativeTransform".into(), rows(Affine::translate((pad, pad)))); - self.text(&mut t, v); - if let Some(Value::Object(st)) = t.get_mut("style") { - let (hor, ver) = if note { ("LEFT", "TOP") } else { ("CENTER", "CENTER") }; - st.entry("textAlignHorizontal").or_insert_with(|| json!(hor)); - st.entry("textAlignVertical").or_insert_with(|| json!(ver)); - st.insert("textAutoResize".into(), json!("NONE")); - } - Some(Value::Object(t)) - } - - /// Fields every layer type shares. - pub(super) fn common(&mut self, o: &mut Obj, v: &View<'a>, ty: &str, space: Affine, parent: Option<&View<'a>>) { - for (from, to) in [("visible", "visible"), ("locked", "locked"), ("mask", "isMask")] { - if let Some(b) = v.flag(from) { - o.insert(to.into(), json!(b)); - } - } - if let Some(m) = v.str("maskType") { - o.insert("maskType".into(), json!(if m == "OUTLINE" { "VECTOR" } else { m })); - } - copy_num(o, v, "opacity", "opacity"); - if let Some(b) = v.str("blendMode").filter(|b| *b != "UNSET") { - o.insert("blendMode".into(), json!(b)); - } - if let Some((x, y)) = v.size() { - o.insert("size".into(), json!({"x": x, "y": y})); - } - let t = v.transform().unwrap_or_default(); - o.insert("relativeTransform".into(), rows(space * t)); - // Paints, from the shared style when one is linked (the layer's own copy can be stale), - // unless the layer's own paints are bound to variables: those bindings must not be lost. - let mut styles = Obj::new(); - let own = |k: &str| Some(v.list(k)).filter(|l| l.iter().any(paint_bound)); - let fill_style = self.style(v, "styleIdForFill", "inheritFillStyleID", "fill", &mut styles); - let fills = own("fillPaints") - .unwrap_or_else(|| fill_style.map_or_else(|| v.list("fillPaints"), |s| s.get("fillPaints").map(Kv::list).unwrap_or_default())); - o.insert("fills".into(), Value::Array(fills.iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect())); - let stroke_style = self.style(v, "styleIdForStrokeFill", "inheritFillStyleIDForStroke", "stroke", &mut styles); - let strokes = own("strokePaints") - .unwrap_or_else(|| stroke_style.map_or_else(|| v.list("strokePaints"), |s| s.get("fillPaints").map(Kv::list).unwrap_or_default())); - o.insert("strokes".into(), Value::Array(strokes.iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect())); - let effect_style = self.style(v, "styleIdForEffect", "inheritEffectStyleID", "effect", &mut styles); - let (effects, effects_scale) = - effect_style.map_or_else(|| v.list_scaled("effects"), |s| v.styled_list(s, "effects", "styleIdForEffect", "inheritEffectStyleID")); - if !effects.is_empty() { - o.insert("effects".into(), Value::Array(effects.iter().filter_map(|e| effect(e, effects_scale)).collect())); - } - let grid_style = self.style(v, "styleIdForGrid", "inheritGridStyleID", "grid", &mut styles); - let (grids, grids_scale) = - grid_style.map_or_else(|| v.list_scaled("layoutGrids"), |s| v.styled_list(s, "layoutGrids", "styleIdForGrid", "inheritGridStyleID")); - if !grids.is_empty() { - o.insert("layoutGrids".into(), Value::Array(grids.iter().map(|g| layout_grid(g, grids_scale)).collect())); - } - if ty == "TEXT" { - self.style(v, "styleIdForText", "inheritTextStyleID", "text", &mut styles); - } - if !styles.is_empty() { - o.insert("styles".into(), Value::Object(styles)); - } - stroke(o, v); - copy_len(o, v, "cornerRadius", "cornerRadius"); - copy_num(o, v, "cornerSmoothing", "cornerSmoothing"); - if v.flag("rectangleCornerRadiiIndependent") == Some(true) { - let r = |k: &str| v.len(k).unwrap_or(0.0); - o.insert( - "rectangleCornerRadii".into(), - json!([ - r("rectangleTopLeftCornerRadius"), - r("rectangleTopRightCornerRadius"), - r("rectangleBottomRightCornerRadius"), - r("rectangleBottomLeftCornerRadius") - ]), - ); - } - let constraint = |k: &str, min: &'static str, max: &'static str, both: &'static str| match v.str(k) { - Some("CENTER") => "CENTER", - Some("MAX" | "FIXED_MAX") => max, - Some("STRETCH") => both, - Some("SCALE") => "SCALE", - _ => min, - }; - o.insert( - "constraints".into(), - json!({ - "horizontal": constraint("horizontalConstraint", "LEFT", "RIGHT", "LEFT_RIGHT"), - "vertical": constraint("verticalConstraint", "TOP", "BOTTOM", "TOP_BOTTOM"), - }), - ); - if matches!(ty, "FRAME" | "COMPONENT" | "COMPONENT_SET" | "INSTANCE" | "SECTION") { - o.insert("clipsContent".into(), json!(!v.flag("frameMaskDisabled").unwrap_or(false))); - self.auto_layout(o, v); - } - child_layout(o, v, parent); - let exports: Vec = v.list("exportSettings").iter().map(export_setting).collect(); - if !exports.is_empty() { - o.insert("exportSettings".into(), Value::Array(exports)); - } - if let Some(b) = v.flag("sectionContentsHidden") { - o.insert("sectionContentsHidden".into(), json!(b)); - } - self.prototype(o, v); - self.variable_bindings(o, v); - } - - /// `fillGeometry` / `strokeGeometry` as SVG path data, and star/polygon parameters. - pub(super) fn geometry(&mut self, o: &mut Obj, v: &View<'a>) { - for key in ["fillGeometry", "strokeGeometry"] { - let mut out = Vec::new(); - for p in v.list(key) { - let Some(blob) = num(p, "commandsBlob").and_then(|i| self.blobs.get(i as usize)).copied() else { continue }; - let Some(d) = svg_path(blob) else { - self.warn("damaged vector geometry was skipped"); - continue; - }; - if d.is_empty() { - continue; - } - let winding = if p.get("windingRule").and_then(Kv::str) == Some("ODD") { "EVENODD" } else { "NONZERO" }; - out.push(json!({"path": d, "windingRule": winding})); - } - if !out.is_empty() { - o.insert(key.into(), Value::Array(out)); - } - } - let vector = o.get("type").and_then(Value::as_str) == Some("VECTOR"); - if vector && !self.network(o, v) && !o.contains_key("fillGeometry") && !o.contains_key("strokeGeometry") && v.str("type") != Some("CONNECTOR") - { - self.warn("vectors without geometry are empty"); - } - if !vector { - copy_num(o, v, "count", "pointCount"); - copy_num(o, v, "starInnerScale", "innerRadius"); - } - } - - /// The editable network of `vectorData` as `vectorNetwork` (the REST importer's extension), - /// scaled to the layer's size, with per-point corner radii, handle mirroring and end caps. - /// False when there's none or it's damaged (the outlines stand in). - fn network(&mut self, o: &mut Obj, v: &View<'a>) -> bool { - let Some((vd, radius_scale)) = v.find("vectorData") else { return false }; - let Some(blob_id) = num(vd, "vectorNetworkBlob").map(|i| i as usize) else { return false }; - let Some(blob) = self.blobs.get(blob_id).copied() else { return false }; - let Some(net) = network::decode(blob) else { - self.warn("damaged vector networks import as outlines"); - return false; - }; - let styles: BTreeMap = - vd.get("styleOverrideTable").map(Kv::list).unwrap_or_default().iter().filter_map(|s| Some((num(s, "styleID")? as u64, s))).collect(); - let mut has_uninterpreted = false; - let mut has_missing = false; - for segment in &net.segments { - if segment.style == 0 { - continue; - } - if styles.contains_key(&u64::from(segment.style)) { - has_uninterpreted = true; - } else { - has_missing = true; - } - } - if has_uninterpreted { - self.warn("style settings of some vector segments aren't supported; those segments use the layer's stroke"); - } - if has_missing { - self.warn("some vector segments refer to style settings missing from the file; they use the layer's stroke"); - } - // An open path shows its fill, which regions can't hold: the outline keeps the look. - let fills_shown = - o.get("fills").and_then(Value::as_array).is_some_and(|f| f.iter().any(|p| p.get("visible").and_then(Value::as_bool) != Some(false))); - if net.segments.is_empty() || (net.regions.is_empty() && fills_shown && o.contains_key("fillGeometry")) { - return false; - } - let style = |id: u32| styles.get(&u64::from(id)).copied().filter(|_| id != 0); - let scale = |k: &str| { - let size = v.size().map(|s| if k == "x" { s.0 } else { s.1 }); - let norm = vd.get("normalizedSize").and_then(|s| num(s, k)); - size.zip(norm).filter(|(s, n)| s.is_finite() && *n > 1e-9).map_or(1.0, |(s, n)| s / n) - }; - let (sx, sy) = (scale("x"), scale("y")); - // A point whose style doesn't set a radius takes the layer's, as the editor draws it. - let layer_radius = v.len("cornerRadius"); - let vertices: Vec = net - .vertices - .iter() - .map(|p| { - let mut out = json!({"x": p.x * sx, "y": p.y * sy}); - let st = style(p.style); - // Point radii are lengths in this row's space, unlike the normalized positions. - // An override/derived row already carries the instance's scale. - if let Some(r) = st.and_then(|s| num(s, "cornerRadius")).and_then(|r| scaled(r, radius_scale)).or(layer_radius).filter(|r| *r > 0.0) { - out["radius"] = json!(r); - } - match st.and_then(|s| s.get("handleMirroring")).and_then(Kv::str) { - Some("ANGLE") => out["mirror"] = json!("angle"), - Some("ANGLE_AND_LENGTH") => out["mirror"] = json!("angleAndLength"), - Some("NONE") => out["mirror"] = json!("none"), - _ => {} - } - if let Some(join @ ("MITER" | "BEVEL" | "ROUND")) = st.and_then(|s| s.get("strokeJoin")).and_then(Kv::str) { - out["join"] = json!(join.to_ascii_lowercase()); - } - out - }) - .collect(); - let segments: Vec = - net.segments.iter().map(|s| json!({"a": s.a, "b": s.b, "ta": [s.ta.0 * sx, s.ta.1 * sy], "tb": [s.tb.0 * sx, s.tb.1 * sy]})).collect(); - let regions: Vec = net - .regions - .iter() - .map(|r| { - let mut region = json!({"loops": r.loops, "winding": if r.non_zero { "nonZero" } else { "evenOdd" }}); - if r.style != 0 { - match style(r.style) { - Some(s) => { - let fills = s.get("fillPaints").and_then(|own_fills| { - if own_fills.list().iter().any(paint_bound) { - return Some(own_fills); - } - let linked_style = self - .style_link(&View::of(s), "styleIdForFill", "inheritFillStyleID") - .and_then(|id| self.nodes.get(&id).copied()) - .filter(|style| style.get("styleType").and_then(Kv::str) == Some("FILL")); - match linked_style { - Some(style) => style.get("fillPaints"), - None => Some(own_fills), - } - }); - if let Some(fills) = fills { - if let Kv::Array(source_paints) = fills { - let paint_cost = source_paints.iter().fold(source_paints.len(), |cost, paint| { - cost.saturating_add(paint.get("stops").map(Kv::list).unwrap_or_default().len()) - }); - let oversized_stops = - source_paints.iter().any(|paint| paint.get("stops").map(Kv::list).unwrap_or_default().len() > 256); - if source_paints.len() > 256 || oversized_stops || self.region_paint_elements.saturating_add(paint_cost) > 200_000 - { - self.warn("vector region paint data exceeded import limits and was skipped"); - return region; - } - self.region_paint_elements += paint_cost; - let paints: Vec = source_paints.iter().filter_map(|p| paint(p, &mut |w| self.warn(w))).collect(); - if paints.len() != source_paints.len() { - self.warn("invalid vector region paints were skipped"); - } - if paints.iter().any(has_bound_variables) { - self.warn("variable-bound vector region paints keep resolved appearance; live bindings were left out"); - } - if s.get("styleIdForFill").is_some() { - self.warn("linked vector region fill styles keep resolved appearance; live style links were left out"); - } - region["_figRegionFills"] = Value::Array(paints); - } else { - self.warn("invalid vector region fill paint list; layer fill used"); - } - } - } - None => self.warn("vector region references a missing fill style; layer fill used"), - } - } - region - }) - .collect(); - // An absent layer join is the source default. - let layer_join = v.str("strokeJoin").unwrap_or("MITER"); - let point_join = |p: &network::Vertex| style(p.style).and_then(|s| s.get("strokeJoin")); - let known = |j: &str| matches!(j, "MITER" | "BEVEL" | "ROUND"); - let unresolved_style = net.vertices.iter().any(|p| p.style != 0 && style(p.style).is_none()); - let unknown_join = net.vertices.iter().any(|p| point_join(p).is_some_and(|j| !j.str().is_some_and(known))); - let unsupported_join = net.vertices.iter().any(|p| point_join(p).and_then(Kv::str).is_some_and(|j| known(j) && j != layer_join)); - if unresolved_style { - self.warn("some vector points refer to point settings missing from the file; they use the layer's joins and plain corners"); - } - if unknown_join { - self.warn("vector points with unknown stroke joins use the layer join"); - } - if unsupported_join && (o.contains_key("strokeDashes") || o.contains_key("strokeWidthProfile")) { - self.warn("point stroke joins were preserved; dashed or variable-width strokes render with the layer join"); - } - // The stroke starts at the first end point and stops at the last (as the editor draws it). - let mut degree = vec![0usize; net.vertices.len()]; - for s in &net.segments { - for i in [s.a, s.b] { - if let Some(d) = degree.get_mut(i) { - *d += 1; - } - } - } - let ends: Vec = (0..degree.len()).filter(|i| degree.get(*i) == Some(&1)).collect(); - let cap = - |i: Option<&usize>| i.and_then(|i| net.vertices.get(*i)).and_then(|p| style(p.style)).and_then(|s| s.get("strokeCap")).and_then(Kv::str); - let (first, last) = (cap(ends.first()), cap(ends.last())); - if first.is_some() || last.is_some() { - let node = v.str("strokeCap").unwrap_or("NONE"); - o.insert("strokeCapStart".into(), json!(cap_name(first.unwrap_or(node)))); - o.insert("strokeCapEnd".into(), json!(cap_name(last.unwrap_or(node)))); - } - // Every instance of a main shows the same network: it is written once and shared. - let mut entry = json!({}); - entry["vertices"] = Value::Array(vertices); - entry["segments"] = Value::Array(segments); - entry["regions"] = Value::Array(regions.clone()); - if regions.iter().any(|r| r.get("_figRegionFills").is_some()) { - o.insert("vectorNetwork".into(), entry); - return true; - } - // A resized instance and a K-scaled one can have the same box but different radii. - let key = - (blob_id, sx.to_bits(), sy.to_bits(), std::ptr::from_ref(vd) as usize, radius_scale.to_bits(), layer_radius.unwrap_or(0.0).to_bits()); - let id = match self.network_ids.get(&key) { - Some(id) => *id, - None => { - self.networks.push(crate::rest::network(&entry)); - self.network_ids.insert(key, self.networks.len() - 1); - self.networks.len() - 1 - } - }; - o.insert("vectorNetworkRef".into(), json!(id)); - true - } -} - -/// The text a layer that isn't a text layer carries (a note's, a shape's), unless blank. -pub(super) fn own_text<'a>(v: &View<'a>) -> Option<&'a str> { - v.get("textData").and_then(|t| t.get("characters")).and_then(Kv::str).filter(|c| !c.trim().is_empty()) -} - -pub(super) fn valid_size(value: Option<&Kv<'_>>) -> Option<(f64, f64)> { - let x = num(value?, "x")?; - let y = num(value?, "y")?; - (x.is_finite() && y.is_finite() && x >= 0.0 && y >= 0.0).then_some((x, y)) -} - -/// The REST name of a stroke cap. -pub(super) fn cap_name(cap: &str) -> &str { - match cap { - "ARROW_LINES" => "LINE_ARROW", - "ARROW_EQUILATERAL" => "TRIANGLE_ARROW", - c => c, - } -} - -/// The layer kind (and how the warning names it) that a layer the editor has no counterpart for -/// imports as: frames for notes, shapes, tables, slides and the like (their text as a text layer), -/// vectors for connectors and marker strokes, plain text for text on a path. -fn stand_in(ty: &str) -> Option<(&'static str, &'static str)> { - Some(match ty { - "STICKY" - | "SHAPE_WITH_TEXT" - | "CODE_BLOCK" - | "TABLE" - | "TABLE_CELL" - | "STAMP" - | "MEDIA" - | "WIDGET" - | "SLIDE" - | "SLIDE_GRID" - | "SLIDE_ROW" - | "INTERACTIVE_SLIDE_ELEMENT" - | "MODULE" => ("FRAME", "frames with their text"), - "CONNECTOR" | "HIGHLIGHT" | "WASHI_TAPE" => ("VECTOR", "vectors"), - "TEXT_PATH" => ("TEXT", "text off its path"), - _ => return None, - }) -} - -/// How a layer sizes and sits in an auto layout parent. -fn child_layout(o: &mut Obj, v: &View, parent: Option<&View>) { - copy_num(o, v, "stackChildPrimaryGrow", "layoutGrow"); - if v.str("stackChildAlignSelf") == Some("STRETCH") { - o.insert("layoutAlign".into(), json!("STRETCH")); - } - if v.str("stackPositioning") == Some("ABSOLUTE") { - o.insert("layoutPositioning".into(), json!("ABSOLUTE")); - } - for (k, w, h) in [("minSize", "minWidth", "minHeight"), ("maxSize", "maxWidth", "maxHeight")] { - if let Some((val, scale)) = v.find(k).and_then(|(s, scale)| Some((s.get("value")?, scale))) { - for (axis, to) in [("x", w), ("y", h)] { - if let Some(x) = num(val, axis).and_then(|x| scaled(x, scale)).filter(|x| *x > 0.0 && *x < 1e9) { - o.insert(to.into(), json!(x)); - } - } - } - } - if let Some(p) = parent.filter(|p| p.str("stackMode") == Some("GRID")) { - for (anchor, list, to) in [("gridColumnAnchor", "gridColumns", "gridColumnAnchorIndex"), ("gridRowAnchor", "gridRows", "gridRowAnchorIndex")] - { - if let Some(i) = v.get(anchor).and_then(guid).and_then(|g| tracks(p, list).iter().position(|t| *t == g)) { - o.insert(to.into(), json!(i)); - } - } - copy_num(o, v, "gridColumnSpan", "gridColumnSpan"); - copy_num(o, v, "gridRowSpan", "gridRowSpan"); - } -} - -/// SVG path data of a geometry blob: commands `0` close, `1` move, `2` line, `3` quadratic and -/// `4` cubic, each followed by its points as little-endian `f32` pairs. `None` when damaged. -pub(super) fn svg_path(b: &[u8]) -> Option { - let mut out = String::new(); - let mut i = 0usize; - let mut n = 0usize; - while i < b.len() { - n += 1; - if n > MAX_COMMANDS { - return None; - } - let (letter, points) = match *b.get(i)? { - 0 => ('Z', 0), - 1 => ('M', 1), - 2 => ('L', 1), - 3 => ('Q', 2), - 4 => ('C', 3), - _ => return None, - }; - i += 1; - if !out.is_empty() { - out.push(' '); - } - out.push(letter); - for _ in 0..points * 2 { - let bytes: [u8; 4] = b.get(i..i + 4)?.try_into().ok()?; - let x = f32::from_le_bytes(bytes); - if !x.is_finite() { - return None; - } - out.push_str(&format!(" {x}")); - i += 4; - } - } - Some(out) -} diff --git a/crates/format/src/fig/map/layout.rs b/crates/format/src/fig/map/layout.rs deleted file mode 100644 index 28fb801a2..000000000 --- a/crates/format/src/fig/map/layout.rs +++ /dev/null @@ -1,190 +0,0 @@ -use super::paint::{bound, color}; -use super::{BTreeMap, BTreeSet, Kv, MAX_GRID_TRACK_VALUE, MAX_GRID_TRACKS, Mapper, Obj, Value, View, copy_len, guid, json, num, scaled}; - -impl<'a> Mapper<'a> { - pub(super) fn auto_layout(&mut self, o: &mut Obj, v: &View<'a>) { - let Some(mode) = v.str("stackMode").filter(|m| matches!(*m, "HORIZONTAL" | "VERTICAL" | "GRID")) else { return }; - o.insert("layoutMode".into(), json!(mode)); - copy_len(o, v, "stackSpacing", "itemSpacing"); - copy_len(o, v, "stackCounterSpacing", "counterAxisSpacing"); - if v.str("stackWrap") == Some("WRAP") { - o.insert("layoutWrap".into(), json!("WRAP")); - } - if v.str("stackCounterAlignContent") == Some("SPACE_BETWEEN") { - o.insert("counterAxisAlignContent".into(), json!("SPACE_BETWEEN")); - } - let (h, vert) = (v.len("stackHorizontalPadding").unwrap_or(0.0), v.len("stackVerticalPadding").unwrap_or(0.0)); - o.insert("paddingLeft".into(), json!(h)); - o.insert("paddingTop".into(), json!(vert)); - o.insert("paddingRight".into(), json!(v.len("stackPaddingRight").unwrap_or(h))); - o.insert("paddingBottom".into(), json!(v.len("stackPaddingBottom").unwrap_or(vert))); - let main = match v.str("stackPrimaryAlignItems").or_else(|| v.str("stackJustify")) { - Some("CENTER") => "CENTER", - Some("MAX") => "MAX", - Some("SPACE_AROUND") => "SPACE_AROUND", - // `SPACE_EVENLY` is the format's older name for equal gaps without edge space. - Some("SPACE_EVENLY_CSS") => "SPACE_EVENLY", - Some("SPACE_BETWEEN" | "SPACE_EVENLY") => "SPACE_BETWEEN", - _ => "MIN", - }; - o.insert("primaryAxisAlignItems".into(), json!(main)); - let cross = match v.str("stackCounterAlignItems").or_else(|| v.str("stackAlign")) { - Some("CENTER") => "CENTER", - Some("MAX") => "MAX", - Some("BASELINE") => "BASELINE", - _ => "MIN", - }; - o.insert("counterAxisAlignItems".into(), json!(cross)); - let sizing = |k: &str| if v.str(k).is_some_and(|s| s.starts_with("RESIZE_TO_FIT")) { "AUTO" } else { "FIXED" }; - // A flow that records no sizing for its primary axis sizes it by its content: auto layout - // did before that axis could be fixed. - let primary = if v.get("stackPrimarySizing").is_none() && mode != "GRID" { "AUTO" } else { sizing("stackPrimarySizing") }; - o.insert("primaryAxisSizingMode".into(), json!(primary)); - o.insert("counterAxisSizingMode".into(), json!(sizing("stackCounterSizing"))); - if let Some(b) = v.flag("bordersTakeSpace") { - o.insert("strokesIncludedInLayout".into(), json!(b)); - } - if let Some(b) = v.flag("stackReverseZIndex") { - o.insert("itemReverseZIndex".into(), json!(b)); - } - if mode == "GRID" { - copy_len(o, v, "gridColumnGap", "gridColumnGap"); - copy_len(o, v, "gridRowGap", "gridRowGap"); - o.insert("gridColumnCount".into(), json!(tracks(v, "gridColumns").len())); - o.insert("gridRowCount".into(), json!(tracks(v, "gridRows").len())); - let track_data = [("columnTracks", "gridColumns", "gridColumnsSizing"), ("rowTracks", "gridRows", "gridRowsSizing")] - .into_iter() - .filter_map(|(out_key, order_key, sizing_key)| { - self.map_grid_tracks(v, order_key, sizing_key).map(|mapped| (out_key.to_string(), mapped)) - }) - .collect::(); - if !track_data.is_empty() { - let source = o.entry(crate::rest::FIG_SOURCE_FIELD).or_insert_with(|| json!({})); - if let Some(source) = source.as_object_mut() { - source.insert("gridTracks".into(), Value::Object(track_data)); - } - } - } - } - - /// Track sizing maps are keyed by GUID; their order comes from the separate track list. - fn map_grid_tracks(&mut self, v: &View<'a>, order_key: &str, sizing_key: &str) -> Option { - let track_entries = v.get(order_key).and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default(); - let sizes = v.get(sizing_key).and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default(); - if track_entries.len() > MAX_GRID_TRACKS { - self.warn("grid track list exceeds 1000 entries; the tracks use the default equal sizing"); - return None; - } - if sizes.is_empty() { - return None; - } - if sizes.len() > MAX_GRID_TRACKS { - self.warn("grid track sizing list exceeds 1000 entries; the tracks use the default equal sizing"); - return None; - } - let ordered = tracks(v, order_key); - let ordered_ids: BTreeSet<&str> = ordered.iter().map(String::as_str).collect(); - let mut size_by_id: BTreeMap>> = BTreeMap::new(); - for entry in sizes { - let Some(id) = entry.get("id").and_then(guid) else { - self.warn("stale or invalid grid track sizing entries were ignored"); - continue; - }; - if !ordered_ids.contains(id.as_str()) { - self.warn("stale or invalid grid track sizing entries were ignored"); - continue; - } - match size_by_id.entry(id) { - std::collections::btree_map::Entry::Vacant(slot) => { - slot.insert(Some(entry)); - } - std::collections::btree_map::Entry::Occupied(mut slot) => { - slot.insert(None); - self.warn("duplicate grid track sizing entries use equal tracks"); - } - } - } - let mut mapped = Vec::with_capacity(ordered.len()); - for id in ordered { - if let Some(Some(entry)) = size_by_id.get(&id) { - match grid_track_sizing(entry.get("trackSize")) { - Some(track) => mapped.push(track), - None => { - self.warn("grid track sizing is unsupported or malformed; affected tracks use equal sizing"); - mapped.push(json!({"sizing": "fill", "value": 1.0})); - } - } - } else { - mapped.push(json!({"sizing": "fill", "value": 1.0})); - } - } - Some(Value::Array(mapped)) - } -} - -/// The track ids of a grid's columns or rows, in order. -pub(super) fn tracks(v: &View, key: &str) -> Vec { - let mut t: Vec<(&str, String)> = v - .get(key) - .and_then(|m| m.get("entries")) - .map(Kv::list) - .unwrap_or_default() - .iter() - .filter_map(|e| Some((e.get("position").and_then(Kv::str).unwrap_or(""), e.get("id").and_then(guid)?))) - .collect(); - t.sort(); - t.into_iter().map(|e| e.1).collect() -} - -/// Convert only unconstrained tracks, whose min and max sizing functions agree. -fn grid_track_sizing(size: Option<&Kv<'_>>) -> Option { - let size = size?; - let min = size.get("minSizing")?; - let max = size.get("maxSizing")?; - let min_type = min.get("type").and_then(Kv::str)?; - let max_type = max.get("type").and_then(Kv::str)?; - if min_type != max_type { - return None; - } - match min_type { - "FIXED" => { - let px = num(min, "value")?; - let max_px = num(max, "value")?; - (px == max_px && px.is_finite() && (0.0..=MAX_GRID_TRACK_VALUE).contains(&px)).then(|| json!({"sizing": "fixed", "value": px})) - } - "FLEX" => { - let fr = num(min, "value")?; - let max_fr = num(max, "value")?; - (fr == max_fr && fr.is_finite() && fr > 0.0 && fr <= MAX_GRID_TRACK_VALUE).then(|| json!({"sizing": "fill", "value": fr})) - } - "HUG" => Some(json!({"sizing": "hug", "value": 0.0})), - _ => None, - } -} - -/// A layout grid; `k`: the factor its lengths take (a scaled instance's layer). -pub(super) fn layout_grid(g: &Kv, k: f64) -> Value { - let pattern = match (g.get("pattern").and_then(Kv::str), g.get("axis").and_then(Kv::str)) { - (Some("GRID"), _) => "GRID", - (_, Some("Y")) => "ROWS", - _ => "COLUMNS", - }; - let mut o = json!({"pattern": pattern, "alignment": g.get("type").and_then(Kv::str).unwrap_or("STRETCH")}); - for (from, to) in [("sectionSize", "sectionSize"), ("numSections", "count"), ("gutterSize", "gutterSize"), ("offset", "offset")] { - let length = from != "numSections"; - if let Some(x) = num(g, from).and_then(|x| scaled(x, if length { k } else { 1.0 })) { - o[to] = json!(x); - } - } - if let Some(c) = g.get("color") { - o["color"] = color(c); - } - if let Some(b) = g.get("visible").and_then(Kv::bool) { - o["visible"] = json!(b); - } - let vars = [("numSectionsVar", "count"), ("offsetVar", "offset"), ("sectionSizeVar", "sectionSize"), ("gutterSizeVar", "gutterSize")]; - if let Some(b) = bound(Some(g), &vars) { - o["boundVariables"] = b; - } - o -} diff --git a/crates/format/src/fig/map/paint.rs b/crates/format/src/fig/map/paint.rs deleted file mode 100644 index f672c1b6c..000000000 --- a/crates/format/src/fig/map/paint.rs +++ /dev/null @@ -1,337 +0,0 @@ -use super::layer::cap_name; -use super::variables::alias; -use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, copy_len, copy_str, guid, json, matrix, num, rows, scaled, vec2}; - -fn filter_number(value: &Kv) -> Option { - let number = match value { - Kv::Float(value) => f64::from(*value), - Kv::Int(value) => *value as f64, - Kv::Uint(value) => *value as f64, - _ => return None, - }; - number.is_finite().then_some(number) -} - -pub(super) fn color(c: &Kv) -> Value { - let ch = |k: &str| num(c, k).unwrap_or(0.0); - json!({"r": ch("r"), "g": ch("g"), "b": ch("b"), "a": num(c, "a").unwrap_or(1.0)}) -} - -impl<'a> Mapper<'a> { - /// The style a layer links in `key`, by guid or by library asset (the file's copy of a library - /// style), or in the older `legacy` field when `key` names none. An explicit NO_STYLE guid in - /// `key` with no asset is a detach and wins over the legacy field. - pub(super) fn style_link(&self, v: &View, key: &str, legacy: &str) -> Option { - let fallback = || v.get(legacy).and_then(guid).filter(|g| g != NO_STYLE); - let Some(link) = v.get(key) else { return fallback() }; - match (self.resource_id(link), link.get("guid").and_then(guid)) { - (Some(id), _) => Some(id), - (None, Some(_)) => None, - (None, None) => fallback(), - } - } - - /// The style node a layer links in `key` (or the older `legacy` field), recorded for the REST - /// `styles` map under `slot`. - /// A link to a style the file doesn't hold leaves the layer its own values (the colours it - /// stored with it), with a note. - pub(super) fn style(&mut self, v: &View<'a>, key: &str, legacy: &str, slot: &str, out: &mut Obj) -> Option<&'a Kv<'a>> { - let found = self.style_link(v, key, legacy).and_then(|id| Some((self.nodes.get(&id).copied()?, id))); - let Some((node, id)) = found.filter(|(n, _)| n.get("styleType").and_then(Kv::str).is_some()) else { - let named = |l: &Kv| l.get("assetRef").is_some() || l.get("guid").and_then(guid).is_some_and(|g| g != NO_STYLE); - if v.get(key).is_some_and(named) || v.get(legacy).and_then(guid).is_some_and(|g| g != NO_STYLE) { - self.warn("links to shared styles that aren't in the file kept the layers' own values"); - } - return None; - }; - out.insert(slot.into(), json!(id)); - if !self.styles.contains_key(&id) { - let name = node.get("name").and_then(Kv::str).unwrap_or("Style"); - let desc = node.get("styleDescription").or_else(|| node.get("description")).and_then(Kv::str).unwrap_or(""); - self.styles.insert(id, json!({"name": name, "description": desc})); - } - Some(node) - } -} - -pub(super) fn stroke(o: &mut Obj, v: &View) { - copy_len(o, v, "strokeWeight", "strokeWeight"); - if let Some(a) = v.str("strokeAlign").filter(|a| *a != "OFFSET") { - o.insert("strokeAlign".into(), json!(a)); - } - copy_str(o, v, "strokeJoin", "strokeJoin"); - if let Some(cap) = v.str("strokeCap") { - o.insert("strokeCap".into(), json!(cap_name(cap))); - } - // A layer written as the outline of its stroke keeps what it was as plugin data - // (`outlinedStroke`, our extension of the file JSON). - let (id, key) = crate::fig::export::STASH; - let kept = v.list("pluginData").iter().find(|p| p.get("pluginID").and_then(Kv::str) == Some(id) && p.get("key").and_then(Kv::str) == Some(key)); - if let Some(original) = kept.and_then(|p| p.get("value")).and_then(Kv::str).and_then(|s| serde_json::from_str::(s).ok()) { - o.insert("outlinedStroke".into(), original); - } - // A variable width: each point's reach on the two sides of the path (shares of the stroke - // weight), as `[t, scale, bias]` (`strokeWidthProfile`, our extension of the file JSON). - let profile: Vec = v - .list("variableWidthPoints") - .iter() - .filter_map(|p| { - let (left, right) = (num(p, "ascent")?.max(0.0), num(p, "descent")?.max(0.0)); - let bias = if left + right > 0.0 { (right - left) / (left + right) } else { 0.0 }; - Some(json!([num(p, "position")?, left + right, bias])) - }) - .collect(); - if !profile.is_empty() { - o.insert("strokeWidthProfile".into(), Value::Array(profile)); - } - let (dash_list, dash_scale) = v.list_scaled("dashPattern"); - let dashes: Vec = dash_list.iter().filter_map(Kv::f64).filter_map(|d| scaled(d, dash_scale)).collect(); - if !dashes.is_empty() { - o.insert("strokeDashes".into(), json!(dashes)); - } - // A miter limit L bevels joins sharper than 2·asin(1/L). - if let Some(l) = v.num("miterLimit").filter(|l| *l > 1.0) { - o.insert("strokeMiterAngle".into(), json!((2.0 * (1.0 / l).asin()).to_degrees())); - } - if v.flag("borderStrokeWeightsIndependent") == Some(true) { - // A side that isn't written has no border. - let side = |k: &str| v.len(k).unwrap_or(0.0); - o.insert( - "individualStrokeWeights".into(), - json!({"top": side("borderTopWeight"), "right": side("borderRightWeight"), "bottom": side("borderBottomWeight"), "left": side("borderLeftWeight")}), - ); - } -} - -/// Whether a paint's colour or one of its gradient stops is bound to a variable. -pub(super) fn paint_bound(p: &Kv) -> bool { - alias(p.get("colorVar")).is_some() || p.get("stopsVar").map(Kv::list).unwrap_or_default().iter().any(|s| alias(s.get("colorVar")).is_some()) -} - -pub(crate) fn paint(p: &Kv, warn: &mut dyn FnMut(String)) -> Option { - let ty = p.get("type").and_then(Kv::str)?; - let mut o = Obj::new(); - o.insert("type".into(), json!(ty)); - if let Some(x) = num(p, "opacity") { - o.insert("opacity".into(), json!(x)); - } - if let Some(b) = p.get("visible").and_then(Kv::bool) { - o.insert("visible".into(), json!(b)); - } - if let Some(b) = p.get("blendMode").and_then(Kv::str) { - o.insert("blendMode".into(), json!(b)); - } - let t = p.get("transform").and_then(matrix); - match ty { - "SOLID" => { - if let Some(c) = p.get("color") { - o.insert("color".into(), color(c)); - } - if let Some(var) = alias(p.get("colorVar")) { - o.insert("boundVariables".into(), json!({"color": {"type": "VARIABLE_ALIAS", "id": var}})); - } - } - _ if ty.starts_with("GRADIENT_") => { - // The paint transform maps the layer's unit box to gradient space, where a linear - // gradient runs from (0, ½) to (1, ½) and the others are centred on (½, ½). - let inv = t.filter(|t| t.determinant().abs() > 1e-12).map_or(Affine::IDENTITY, Affine::inverse); - let pts = if ty == "GRADIENT_LINEAR" { [(0.0, 0.5), (1.0, 0.5), (0.0, 1.0)] } else { [(0.5, 0.5), (1.0, 0.5), (0.5, 1.0)] }; - let handles: Vec = pts - .iter() - .map(|(x, y)| { - let q = inv * Point::new(*x, *y); - json!({"x": q.x, "y": q.y}) - }) - .collect(); - o.insert("gradientHandlePositions".into(), Value::Array(handles)); - // Stops bound to variables are listed again, each with its variable. - let vars = p.get("stopsVar").map(Kv::list).unwrap_or_default(); - let stops: Vec = p - .get("stops") - .map(Kv::list) - .unwrap_or_default() - .iter() - .enumerate() - .map(|(i, s)| { - let mut stop = json!({"position": num(s, "position").unwrap_or(0.0), "color": s.get("color").map_or(Value::Null, color)}); - if let Some(b) = bound(vars.get(i), &[("colorVar", "color")]) { - stop["boundVariables"] = b; - } - stop - }) - .collect(); - o.insert("gradientStops".into(), Value::Array(stops)); - } - "IMAGE" => { - // A hash longer than any the file's images can be named by resolves to nothing: it - // isn't spelled out, which a shared style would repeat for every layer using it. - let hash: String = p - .get("image") - .and_then(|i| i.get("hash")) - .and_then(Kv::bytes) - .filter(|h| h.len() <= crate::fig::MAX_IMAGE_HASH) - .unwrap_or_default() - .iter() - .map(|b| format!("{b:02x}")) - .collect(); - o.insert("imageRef".into(), json!(hash)); - let mode = p.get("imageScaleMode").and_then(Kv::str).unwrap_or("FILL"); - o.insert("scaleMode".into(), json!(mode)); - if let (Some(t), "STRETCH") = (t, mode) { - o.insert("imageTransform".into(), rows(t)); - } - if let Some(s) = num(p, "scale") { - o.insert("scalingFactor".into(), json!(s)); - } - if let Some(r) = num(p, "rotation") { - o.insert("rotation".into(), json!(r)); - } - match (p.get("filterColorAdjust"), p.get("paintFilter")) { - (Some(_), Some(_)) => { - warn("image filters are ambiguous because both filter containers are present; filter conversion was skipped".into()) - } - (Some(_), None) => warn("legacy image filter container is unsupported; filter conversion was skipped".into()), - (None, Some(filters)) => { - let mut mapped = Obj::new(); - let fields = [ - ("exposure", "exposure"), - ("contrast", "contrast"), - ("vibrance", "saturation"), - ("temperature", "temperature"), - ("tint", "tint"), - ("highlights", "highlights"), - ("shadows", "shadows"), - ]; - if let Kv::Object(values) = filters { - for (source, target) in fields { - if let Some(value) = filters.get(source) { - match filter_number(value) { - Some(value) => { - mapped.insert(target.into(), json!(value)); - } - None => warn(format!("malformed image filter `{source}` was skipped")), - } - } - } - for (name, value) in values { - if fields.iter().any(|(known, _)| *known == *name) { - continue; - } - match filter_number(value) { - Some(0.0) => {} - Some(_) => warn(format!("nonzero unsupported image filter `{}` was skipped", crate::rest::props::clip_str(name))), - None => warn(format!("malformed unsupported image filter `{}` was skipped", crate::rest::props::clip_str(name))), - } - } - } else { - warn("malformed image paintFilter container was skipped".into()); - } - if !mapped.is_empty() { - o.insert("filters".into(), Value::Object(mapped)); - } - } - (None, None) => {} - } - } - _ => {} - } - Some(Value::Object(o)) -} - -pub(super) fn has_bound_variables(value: &Value) -> bool { - match value { - Value::Object(object) => object.contains_key("boundVariables") || object.values().any(has_bound_variables), - Value::Array(values) => values.iter().any(has_bound_variables), - _ => false, - } -} - -/// The variables bound to the fields of a paint stop, an effect or a layout grid, as its REST -/// `boundVariables`: `fields` pairs the format's field with the REST name. -pub(super) fn bound(v: Option<&Kv>, fields: &[(&str, &str)]) -> Option { - let v = v?; - let found: Obj = - fields.iter().filter_map(|(from, to)| Some((to.to_string(), json!({"type": "VARIABLE_ALIAS", "id": alias(v.get(from))?})))).collect(); - (!found.is_empty()).then_some(Value::Object(found)) -} - -/// A layer effect; `k`: the factor its lengths take (a scaled instance's layer). -pub(super) fn effect(e: &Kv, k: f64) -> Option { - let ty = match e.get("type").and_then(Kv::str)? { - "FOREGROUND_BLUR" => "LAYER_BLUR", - "GRAIN" => "TEXTURE", - t => t, - }; - let mut o = Obj::new(); - o.insert("type".into(), json!(ty)); - for key in ["radius", "spread", "startRadius", "density", "opacity"] { - let length = matches!(key, "radius" | "spread" | "startRadius"); - if let Some(x) = num(e, key).and_then(|x| scaled(x, if length { k } else { 1.0 })) { - o.insert(key.into(), json!(x)); - } - } - for k in ["visible", "showShadowBehindNode", "clipToShape"] { - if let Some(b) = e.get(k).and_then(Kv::bool) { - o.insert(k.into(), json!(b)); - } - } - for k in ["blendMode", "noiseType"] { - if let Some(s) = e.get(k).and_then(Kv::str) { - o.insert(k.into(), json!(s)); - } - } - for k in ["color", "secondaryColor"] { - if let Some(c) = e.get(k) { - o.insert(k.into(), color(c)); - } - } - // `startOffset` and `endOffset` are positions in the layer's unit box, not lengths: they stay. - for (from, to) in [("offset", "offset"), ("noiseSize", "noiseSizeVector")] { - if let Some(p) = e.get(from).and_then(vec2) { - o.insert(to.into(), scale_vec2(p, k)); - } - } - for key in ["startOffset", "endOffset"] { - if let Some(p) = e.get(key).and_then(vec2) { - o.insert(key.into(), p); - } - } - if e.get("blurOpType").and_then(Kv::str) == Some("PROGRESSIVE") { - o.insert("blurType".into(), json!("PROGRESSIVE")); - } - let vars = [ - ("colorVar", "color"), - ("radiusVar", "radius"), - ("spreadVar", "spread"), - ("xVar", "offsetX"), - ("yVar", "offsetY"), - ("startRadiusVar", "startRadius"), - ]; - if let Some(b) = bound(Some(e), &vars) { - o.insert("boundVariables".into(), b); - } - Some(Value::Object(o)) -} - -/// A `{"x", "y"}` vector at scale `k` (unchanged when that is not finite). -fn scale_vec2(p: Value, k: f64) -> Value { - let axis = |name: &str| p.get(name).and_then(Value::as_f64).and_then(|x| scaled(x, k)); - match (axis("x"), axis("y")) { - (Some(x), Some(y)) => json!({"x": x, "y": y}), - _ => p, - } -} - -pub(super) fn export_setting(e: &Kv) -> Value { - let c = e.get("constraint"); - let ty = match c.and_then(|c| c.get("type")).and_then(Kv::str) { - Some("CONTENT_WIDTH") => "WIDTH", - Some("CONTENT_HEIGHT") => "HEIGHT", - _ => "SCALE", - }; - json!({ - "format": e.get("imageType").and_then(Kv::str).unwrap_or("PNG"), - "suffix": e.get("suffix").and_then(Kv::str).unwrap_or(""), - "constraint": {"type": ty, "value": c.and_then(|c| num(c, "value")).unwrap_or(1.0)}, - }) -} diff --git a/crates/format/src/fig/map/proto.rs b/crates/format/src/fig/map/proto.rs deleted file mode 100644 index 9238cafb6..000000000 --- a/crates/format/src/fig/map/proto.rs +++ /dev/null @@ -1,179 +0,0 @@ -use super::paint::color; -use super::variables::variable_data; -use super::{Kv, MAX_ACTION_DEPTH, Mapper, Obj, Value, View, copy_str, guid, json, num, ref_guid}; - -impl<'a> Mapper<'a> { - pub(super) fn prototype(&mut self, o: &mut Obj, v: &View<'a>) { - let mut list = Vec::new(); - for it in v.list("prototypeInteractions") { - if it.get("isDeleted").and_then(Kv::bool) == Some(true) { - continue; - } - if let Some(i) = self.interaction(it) { - list.push(i); - } - } - if !list.is_empty() { - o.insert("interactions".into(), Value::Array(list)); - } - let overflow = match v.str("scrollDirection") { - Some("HORIZONTAL") => Some("HORIZONTAL_SCROLLING"), - Some("VERTICAL") => Some("VERTICAL_SCROLLING"), - Some("BOTH") => Some("HORIZONTAL_AND_VERTICAL_SCROLLING"), - _ => None, - }; - if let Some(d) = overflow { - o.insert("overflowDirection".into(), json!(d)); - } - let behavior = match v.str("scrollBehavior") { - Some("FIXED_WHEN_CHILD_OF_SCROLLING_FRAME") => Some("FIXED"), - Some("STICKY_SCROLLS") => Some("STICKY_SCROLLS"), - _ => None, - }; - if let Some(b) = behavior { - o.insert("scrollBehavior".into(), json!(b)); - } - copy_str(o, v, "overlayPositionType", "overlayPositionType"); - copy_str(o, v, "overlayBackgroundInteraction", "overlayBackgroundInteraction"); - if let Some(a) = v.get("overlayBackgroundAppearance") { - let ty = a.get("backgroundType").and_then(Kv::str).unwrap_or("NONE"); - o.insert("overlayBackground".into(), json!({"type": ty, "color": a.get("backgroundColor").map_or(Value::Null, color)})); - } - } - - fn interaction(&mut self, it: &Kv) -> Option { - let ev = it.get("event"); - let ty = match ev.and_then(|e| e.get("interactionType")).and_then(Kv::str).unwrap_or("ON_CLICK") { - "DRAG" => "ON_DRAG", - "MOUSE_IN" => "MOUSE_ENTER", - "MOUSE_OUT" => "MOUSE_LEAVE", - t => t, - }; - let mut trigger = json!({"type": ty}); - if let Some(t) = ev.and_then(|e| num(e, "transitionTimeout")) { - // Seconds as 32-bit floats: whole milliseconds. - trigger["timeout"] = json!((t * 1000.0).round()); - } - if let Some(k) = ev.and_then(|e| e.get("keyTrigger")) { - let codes: Vec = k.get("keyCodes").map(Kv::list).unwrap_or_default().iter().filter_map(Kv::f64).collect(); - trigger["keyCodes"] = json!(codes); - if let Some(d) = k.get("triggerDevice").and_then(Kv::str) { - trigger["device"] = json!(if d.contains("KEYBOARD") { "KEYBOARD" } else { d }); - } - } - let actions: Vec = it.get("actions").map(Kv::list).unwrap_or_default().iter().filter_map(|a| self.action(a, 0)).collect(); - (!actions.is_empty()).then(|| json!({"trigger": trigger, "actions": actions})) - } - - /// One prototype action in the REST shape (`depth`: conditionals it's nested in). - fn action(&mut self, a: &Kv, depth: usize) -> Option { - Some(match a.get("connectionType").and_then(Kv::str) { - Some("INTERNAL_NODE") | None => { - let dest = a.get("transitionNodeID").and_then(guid)?; - let nav = match a.get("navigationType").and_then(Kv::str) { - Some("SWAP_STATE") => "CHANGE_TO", - Some(n) => n, - None => "NAVIGATE", - }; - let mut act = json!({"type": "NODE", "destinationId": dest, "navigation": nav}); - if let Some(t) = transition(a) { - act["transition"] = t; - } - if let Some(b) = a.get("transitionPreserveScroll").and_then(Kv::bool) { - act["preserveScrollPosition"] = json!(b); - } - if let Some(p) = a.get("overlayRelativePosition") { - act["overlayRelativePosition"] = json!({"x": num(p, "x"), "y": num(p, "y")}); - } - act - } - Some("URL") => json!({"type": "URL", "url": a.get("connectionURL").and_then(Kv::str)?}), - Some("BACK") => json!({"type": "BACK"}), - Some("CLOSE") => json!({"type": "CLOSE"}), - Some("NONE") => return None, - Some("SET_VARIABLE") => { - let var = a.get("targetVariable").and_then(|t| t.get("id")).and_then(ref_guid).or_else(|| a.get("targetVariableID").and_then(guid)); - // Missing parts are left out: the REST importer skips the action with a warning. - let mut act = json!({"type": "SET_VARIABLE", "variableId": var}); - if let Some(d) = a.get("targetVariableData").and_then(|d| variable_data(d, 0)) { - act["variableValue"] = d; - } - act - } - Some("SET_VARIABLE_MODE") => json!({ - "type": "SET_VARIABLE_MODE", - "variableCollectionId": a.get("targetVariableSetID").and_then(ref_guid), - "variableModeId": a.get("targetVariableModeID").and_then(guid), - }), - Some("CONDITIONAL") if depth < MAX_ACTION_DEPTH => { - let mut blocks = Vec::new(); - for b in a.get("conditionalActions").map(Kv::list).unwrap_or_default() { - let actions: Vec = - b.get("actions").map(Kv::list).unwrap_or_default().iter().filter_map(|x| self.action(x, depth + 1)).collect(); - let mut block = json!({"actions": actions}); - // A condition that can't be read must not turn the block into an "else". - if let Some(c) = b.get("condition") { - block["condition"] = variable_data(c, 0).unwrap_or_else(|| json!({})); - } - blocks.push(block); - } - json!({"type": "CONDITIONAL", "conditionalBlocks": blocks}) - } - Some(other) => { - self.warn(format!("{} prototype actions are not imported from .fig files yet", other.to_ascii_lowercase().replace('_', " "))); - return None; - } - }) - } -} - -/// A prototype action's transition (`None`: instant). -fn transition(a: &Kv) -> Option { - let ty = a.get("transitionType").and_then(Kv::str)?; - // Directions name where the incoming screen moves (SLIDE_FROM_LEFT moves right). - let (kind, dir) = match ty { - "INSTANT_TRANSITION" => return None, - "DISSOLVE" | "FADE" => ("DISSOLVE", None), - "SMART_ANIMATE" | "MAGIC_MOVE" => ("SMART_ANIMATE", None), - "SCROLL_ANIMATE" => ("SCROLL_ANIMATE", None), - t => { - let prefixes = [ - ("SLIDE_FROM_", "SLIDE_IN"), - ("PUSH_FROM_", "PUSH"), - ("MOVE_FROM_", "MOVE_IN"), - ("SLIDE_OUT_TO_", "SLIDE_OUT"), - ("MOVE_OUT_TO_", "MOVE_OUT"), - ]; - let (kind, side) = prefixes.iter().find_map(|(p, k)| t.strip_prefix(p).map(|r| (*k, r)))?; - let incoming = matches!(kind, "SLIDE_IN" | "PUSH" | "MOVE_IN"); - let dir = match (side, incoming) { - ("LEFT", true) | ("RIGHT", false) => "RIGHT", - ("RIGHT", true) | ("LEFT", false) => "LEFT", - ("TOP", true) | ("BOTTOM", false) => "BOTTOM", - _ => "TOP", - }; - (kind, Some(dir)) - } - }; - let easing = match a.get("easingType").and_then(Kv::str) { - Some("IN_CUBIC" | "EASE_IN") => "EASE_IN", - Some("INOUT_CUBIC") => "EASE_IN_AND_OUT", - Some("LINEAR") => "LINEAR", - Some("IN_BACK_CUBIC") => "EASE_IN_BACK", - Some("OUT_BACK_CUBIC") => "EASE_OUT_BACK", - Some("INOUT_BACK_CUBIC") => "EASE_IN_AND_OUT_BACK", - Some("GENTLE_SPRING") => "GENTLE", - Some("CUSTOM_CUBIC") => "CUSTOM_CUBIC_BEZIER", - _ => "EASE_OUT", - }; - let mut e = json!({"type": easing}); - let f: Vec = a.get("easingFunction").map(Kv::list).unwrap_or_default().iter().filter_map(Kv::f64).collect(); - if let (true, [x1, y1, x2, y2, ..]) = (easing == "CUSTOM_CUBIC_BEZIER", f.as_slice()) { - e["easingFunctionCubicBezier"] = json!({"x1": x1, "y1": y1, "x2": x2, "y2": y2}); - } - let mut t = json!({"type": kind, "duration": (num(a, "transitionDuration").unwrap_or(0.3) * 1000.0).round(), "easing": e}); - if let Some(d) = dir { - t["direction"] = json!(d); - } - Some(t) -} diff --git a/crates/format/src/fig/map/text.rs b/crates/format/src/fig/map/text.rs deleted file mode 100644 index d41b85185..000000000 --- a/crates/format/src/fig/map/text.rs +++ /dev/null @@ -1,323 +0,0 @@ -use super::paint::paint; -use super::{Kv, Mapper, Obj, Value, View, copy_len, copy_str, json, network, num, scaled}; - -/// The value from the last override layer holding a valid one for an optional text setting; invalid instance rows fall through. -/// `length`: the setting is a length, at the scale of the layer that has it. -fn text_num(v: &View, key: &str, length: bool) -> Option { - v.layers.iter().zip(&v.scales).rev().find_map(|(layer, k)| { - layer.get(key).and_then(|value| match value { - Kv::Bool(_) => None, - _ => scaled(value.f64()?, if length { *k } else { 1.0 }), - }) - }) -} - -fn text_flag(v: &View, key: &str) -> Option { - v.layers.iter().rev().find_map(|layer| layer.get(key).and_then(Kv::bool)) -} - -fn insert_text_options(style: &mut Obj, v: &View) { - if let Some(value) = text_num(v, "listSpacing", true) { - style.insert("listSpacing".into(), json!(value)); - } - for k in ["hangingList", "hangingPunctuation"] { - if let Some(value) = text_flag(v, k) { - style.insert(k.into(), json!(value)); - } - } - if let Some(value) = leading_trim(v) { - style.insert("leadingTrim".into(), json!(value)); - } -} - -fn leading_trim<'a>(v: &View<'a>) -> Option<&'a str> { - v.layers.iter().rev().find_map(|layer| match layer.get("leadingTrim").and_then(Kv::str) { - Some(value @ ("NONE" | "CAP_HEIGHT")) => Some(value), - _ => None, - }) -} - -/// The chars that start a wrapped line in the layout the file saved with the text -/// (`derivedTextData`'s `baselines`, each line's `firstCharacter` in UTF-16 units), when that layout -/// is for these characters; lines after a hard break are left out (empty: it wraps nowhere). None -/// when the saved layout is missing, for other text or inconsistent. -fn saved_line_starts(v: &View, chars: &str) -> Option> { - // Derived data from below the layer that set the characters was laid out for other text. - let top = |k: &str| v.layers.iter().rposition(|l| l.get(k).is_some()); - if top("derivedTextData")? < top("textData")? { - return None; - } - let baselines = v.get("derivedTextData")?.get("baselines")?.list(); - // UTF-16 offset of each char, and of the end. - let mut offsets: Vec = Vec::with_capacity(chars.len() + 1); - let mut unit = 0; - for c in chars.chars() { - offsets.push(unit); - unit += c.len_utf16(); - } - offsets.push(unit); - let list: Vec = chars.chars().collect(); - let mut starts = Vec::new(); - let mut prev = None; - for b in baselines { - let u = num(b, "firstCharacter").filter(|u| *u >= 0.0 && u.fract() == 0.0 && *u < unit as f64)? as usize; - let c = offsets.binary_search(&u).ok()?; - // Lines start at the first char, then further on each time. - if !prev.map_or(c == 0, |p| c > p) { - return None; - } - prev = Some(c); - if c > 0 && !list.get(c - 1).is_some_and(|ch| matches!(ch, '\n' | '\u{2028}')) { - starts.push(c); - } - } - prev.map(|_| starts) -} - -impl<'a> Mapper<'a> { - pub(super) fn text(&mut self, o: &mut Obj, v: &View<'a>) { - let (key, legacy) = ("styleIdForText", "inheritTextStyleID"); - let style_node = self.style_link(v, key, legacy).and_then(|s| self.nodes.get(&s).copied()); - // Overrides above the one that links the style beat it; it beats the copies below. - let sv = v.styled(style_node.filter(|s| s.get("styleType").and_then(Kv::str) == Some("TEXT")), key, legacy); - let found = v.find("textData"); - let (td, td_scale) = (found.map(|f| f.0), found.map_or(1.0, |f| f.1)); - let chars = td.and_then(|t| t.get("characters")).and_then(Kv::str).unwrap_or(""); - o.insert("characters".into(), json!(chars)); - // Where the file's own layout wrapped the lines (not a REST field). - if let Some(starts) = saved_line_starts(v, chars) { - o.insert("_figLineStarts".into(), json!(starts)); - } - let mut style = text_style(&sv, None); - // The style's typography beats the layer's own copy of it (the copy is stale when the style - // changed). The file cannot tell a stale copy of these four values from a deliberate local - // one, and "original", "none" and 0 could never be set locally if the style always won, so - // a value the layer or an override sets itself is taken as deliberate. - if let Some(decoration @ ("NONE" | "UNDERLINE" | "STRIKETHROUGH")) = v.str("textDecoration") { - style.insert("textDecoration".into(), json!(decoration)); - } - if let Some(skip_ink) = v.flag("textDecorationSkipInk") { - style.insert("textDecorationSkipInk".into(), json!(skip_ink)); - } - if let Some(case @ ("ORIGINAL" | "UPPER" | "LOWER" | "TITLE" | "SMALL_CAPS" | "SMALL_CAPS_FORCED")) = v.str("textCase") { - style.insert("textCase".into(), json!(case)); - } - for k in ["textAlignHorizontal", "textAlignVertical", "textAutoResize", "textTruncation"] { - copy_str(&mut style, v, k, k); - } - // Paragraph settings belong to the effective text layer, including explicit zero clears. - for k in ["paragraphSpacing", "paragraphIndent"] { - copy_len(&mut style, v, k, k); - } - insert_text_options(&mut style, v); - if let Some(n) = v.num("maxLines").filter(|n| *n >= 1.0) { - style.insert("maxLines".into(), json!(n)); - } - let size = sv.len("fontSize"); - if let Some(b) = o.get_mut("style").and_then(|s| s.get_mut("boundVariables")).map(Value::take) { - style.insert("boundVariables".into(), b); - } - o.insert("style".into(), Value::Object(style)); - let Some(td) = td else { return }; - char_styles(o, td, td_scale, size, &mut |w| self.warn(w)); - let raw = td.get("lines").map(Kv::list).unwrap_or_default(); - let lines: Vec<&str> = raw - .iter() - .map(|l| match l.get("lineType").and_then(Kv::str) { - Some("ORDERED_LIST") => "ORDERED", - Some("UNORDERED_LIST") => "UNORDERED", - _ => "NONE", - }) - .collect(); - if lines.iter().any(|l| *l != "NONE") { - o.insert("lineTypes".into(), json!(lines)); - } - // A forced base direction per paragraph (`sourceDirectionality`; not a REST field). - let dirs: Vec<&str> = raw - .iter() - .map(|l| match l.get("sourceDirectionality").and_then(Kv::str) { - Some("LTR") => "LTR", - Some("RTL") => "RTL", - _ => "AUTO", - }) - .collect(); - if dirs.iter().any(|d| *d != "AUTO") { - o.insert("lineDirections".into(), json!(dirs)); - } - // Where a numbered list starts counting, less one (not a REST field). - let starts: Vec = - raw.iter().map(|l| num(l, "listStartOffset").filter(|n| n.is_finite()).map_or(0, |n| n.clamp(0.0, f64::from(u32::MAX)) as u32)).collect(); - if starts.iter().any(|n| *n > 0) { - o.insert("listStartOffsets".into(), json!(starts)); - } - } - - /// Carry supported text-path data through the private .fig REST ingress only. - pub(super) fn text_path(&mut self, o: &mut Obj, v: &View<'a>) { - let fail = |this: &mut Self, reason: &str| { - this.warn(format!("text path {reason}; text imports off its path")); - }; - let Some(start) = v.get("textPathStart") else { - fail(self, "has no start data"); - return; - }; - let (Some(t), Some(forward)) = (num(start, "tValue"), start.get("forward").and_then(Kv::bool)) else { - fail(self, "has invalid start data"); - return; - }; - let Some(vd) = v.get("vectorData") else { - fail(self, "has no vector data"); - return; - }; - let Some(blob) = num(vd, "vectorNetworkBlob") - .filter(|i| i.is_finite() && *i >= 0.0 && i.fract() == 0.0) - .and_then(|i| usize::try_from(i as u64).ok()) - .and_then(|i| self.blobs.get(i)) - .copied() - else { - fail(self, "has no vector network"); - return; - }; - let Some(net) = network::decode(blob) else { - fail(self, "has damaged vector data"); - return; - }; - let Some(norm) = vd.get("normalizedSize") else { - fail(self, "has invalid normalized size"); - return; - }; - let (Some(nx), Some(ny), Some((w, h))) = (num(norm, "x"), num(norm, "y"), v.size()) else { - fail(self, "has invalid dimensions"); - return; - }; - let axis_scale = |size: f64, normalized: f64, values: &[f64]| -> Option { - if !size.is_finite() || size < 0.0 || !normalized.is_finite() || normalized < 0.0 { - return None; - } - if normalized > 1e-9 { - if size <= 0.0 { - return None; - } - return Some(size / normalized); - } - (size == 0.0 && values.iter().all(|v| *v == 0.0)).then_some(1.0) - }; - let xs: Vec = net.vertices.iter().map(|p| p.x).chain(net.segments.iter().flat_map(|s| [s.ta.0, s.tb.0])).collect(); - let ys: Vec = net.vertices.iter().map(|p| p.y).chain(net.segments.iter().flat_map(|s| [s.ta.1, s.tb.1])).collect(); - let sx = axis_scale(w, nx, &xs); - let sy = axis_scale(h, ny, &ys); - let (Some(sx), Some(sy)) = (sx, sy) else { - fail(self, "has invalid path scale"); - return; - }; - if v.str("textAlignVertical").is_some_and(|x| x != "TOP") { - fail(self, "uses unsupported vertical placement"); - return; - } - if v.get("textData").and_then(|td| td.get("characters")).and_then(Kv::str).is_some_and(|s| s.chars().any(|c| matches!(c, '\n' | '\r'))) { - fail(self, "contains multiple lines"); - return; - } - let path = match crate::fig::text_path::from_network(&net, sx, sy, t, forward) { - Ok(path) => path, - Err(reason) => { - fail(self, reason); - return; - } - }; - let has_decoration = |style: &Value| style.get("textDecoration").and_then(Value::as_str).is_some_and(|x| x != "NONE"); - let decorated = o.get("style").is_some_and(has_decoration) - || o.get("styleOverrideTable").and_then(Value::as_object).into_iter().flat_map(|styles| styles.values()).any(has_decoration); - if decorated { - self.warn("text path underline or strikethrough decoration is not rendered"); - } - o.insert("_figTextPath".into(), json!({"d": path.d, "start": path.start, "flip": path.flip})); - } -} - -/// Per-character styles of text data `td` (`characterStyleIDs` + `styleOverrideTable`) as REST -/// `characterStyleOverrides` + `styleOverrideTable`; `scale`: the factor the lengths of `td` take -/// (a scaled instance's layer); `size`: the base font size. -pub(super) fn char_styles(o: &mut Obj, td: &Kv, scale: f64, size: Option, warn: &mut dyn FnMut(String)) { - let ids: Vec = td.get("characterStyleIDs").map(Kv::list).unwrap_or_default().iter().filter_map(Kv::f64).map(|i| i as u64).collect(); - if ids.iter().all(|i| *i == 0) { - return; - } - let mut table = Obj::new(); - for e in td.get("styleOverrideTable").map(Kv::list).unwrap_or_default() { - let Some(sid) = num(e, "styleID") else { continue }; - let mut s = text_style(&View::of_scaled(e, scale), size); - if let Some(fills) = e.get("fillPaints") { - s.insert("fills".into(), Value::Array(fills.list().iter().filter_map(|p| paint(p, warn)).collect())); - } - table.insert((sid as u64).to_string(), Value::Object(s)); - } - o.insert("characterStyleOverrides".into(), json!(ids)); - o.insert("styleOverrideTable".into(), Value::Object(table)); -} - -/// The REST TypeStyle fields a node (or text override entry) sets. `size`: the font size that -/// letter spacing in percent refers to when the entry doesn't set one. -fn text_style(v: &View, size: Option) -> Obj { - let mut s = Obj::new(); - if let Some(f) = v.get("fontName") { - for (from, to) in [("family", "fontFamily"), ("style", "fontStyle"), ("postscript", "fontPostScriptName")] { - if let Some(x) = f.get(from).and_then(Kv::str).filter(|x| !x.is_empty()) { - // Compact and spaced style names ("SemiBold", "Semi Bold") are the same style. - s.insert(to.into(), if from == "style" { json!(crate::fig::style_name(x)) } else { json!(x) }); - } - } - } - copy_len(&mut s, v, "fontSize", "fontSize"); - copy_len(&mut s, v, "paragraphSpacing", "paragraphSpacing"); - copy_len(&mut s, v, "paragraphIndent", "paragraphIndent"); - insert_text_options(&mut s, v); - copy_str(&mut s, v, "textCase", "textCase"); - copy_str(&mut s, v, "textDecoration", "textDecoration"); - if let Some(skip_ink) = v.flag("textDecorationSkipInk") { - s.insert("textDecorationSkipInk".into(), json!(skip_ink)); - } - copy_str(&mut s, v, "leadingTrim", "leadingTrim"); - let font_size = v.len("fontSize").or(size).unwrap_or(12.0); - if let Some((ls, k)) = v.find("letterSpacing") { - let val = num(ls, "value").unwrap_or(0.0); - let px = match ls.get("units").and_then(Kv::str) { - Some("PIXELS") => scaled(val, k).unwrap_or(val), - Some("PERCENT") => { - // Private (read by `rest/text.rs`): REST spacing is in pixels; keep the percent. - s.insert("_letterSpacingPercent".into(), json!(val)); - val / 100.0 * font_size - } - _ => val * font_size, - }; - s.insert("letterSpacing".into(), json!(px)); - } - if let Some((lh, k)) = v.find("lineHeight") { - let val = num(lh, "value").unwrap_or(100.0); - match lh.get("units").and_then(Kv::str) { - Some("PIXELS") => { - s.insert("lineHeightUnit".into(), json!("PIXELS")); - s.insert("lineHeightPx".into(), json!(scaled(val, k).unwrap_or(val))); - } - // shortcut: percent units count from the font's own line height (100 % is "auto"), which - // the document can only say for 100 %; other values read as % of the font size. Upgrade - // when line heights can be a share of the font's own. - Some("PERCENT") if (val - 100.0).abs() < 1e-6 => { - s.insert("lineHeightUnit".into(), json!("INTRINSIC_%")); - } - Some("PERCENT") => { - s.insert("lineHeightUnit".into(), json!("FONT_SIZE_%")); - s.insert("lineHeightPercentFontSize".into(), json!(val)); - } - _ => { - s.insert("lineHeightUnit".into(), json!("FONT_SIZE_%")); - s.insert("lineHeightPercentFontSize".into(), json!(val * 100.0)); - } - } - } - // An empty URL is kept: on an override entry it clears the text's own link. - if let Some(u) = v.get("hyperlink").and_then(|h| h.get("url")).and_then(Kv::str) { - s.insert("hyperlink".into(), json!({"type": "URL", "url": u})); - } - s -} diff --git a/crates/format/src/fig/map/variables.rs b/crates/format/src/fig/map/variables.rs deleted file mode 100644 index 0794ef155..000000000 --- a/crates/format/src/fig/map/variables.rs +++ /dev/null @@ -1,168 +0,0 @@ -use super::paint::color; -use super::{Kv, MAX_EXPR_DEPTH, Mapper, Obj, Value, View, guid, json, num, ref_guid}; - -impl<'a> Mapper<'a> { - /// Layer `v`'s variable bindings (`boundVariables`, and the text style's) and its explicitly - /// set modes (`explicitVariableModes`) into `o`, in the REST shape. Variables and collections - /// named by library asset resolve to their newest copy in the file. - pub(super) fn variable_bindings(&mut self, o: &mut Obj, v: &View<'a>) { - let mut bound = Obj::new(); - let mut text_bound = Obj::new(); - for e in v.get("variableConsumptionMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() { - let Some(var) = alias(e.get("variableData")) else { continue }; - let a = json!({"type": "VARIABLE_ALIAS", "id": var}); - let field = e.get("variableField").and_then(Kv::str).unwrap_or(""); - match (binding_key(field), text_binding_key(field)) { - (Some(k), _) => { - bound.insert(k.into(), a); - } - (_, Some(k)) => { - text_bound.insert(k.into(), a); - } - _ if field == "CORNER_RADIUS" => { - for k in ["topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius"] { - bound.insert(k.into(), a.clone()); - } - } - _ if field.starts_with("BORDER_") => { - let side = match field { - "BORDER_TOP_WEIGHT" => "strokeTopWeight", - "BORDER_RIGHT_WEIGHT" => "strokeRightWeight", - "BORDER_BOTTOM_WEIGHT" => "strokeBottomWeight", - _ => "strokeLeftWeight", - }; - bound.insert(side.into(), a); - } - _ if field == "WIDTH" || field == "HEIGHT" => { - let axis = if field == "WIDTH" { "x" } else { "y" }; - let size = bound.entry("size").or_insert_with(|| json!({})); - size[axis] = a; - } - _ => self.warn(format!("variables bound to {} are not imported from .fig files yet", field.to_ascii_lowercase().replace('_', " "))), - } - } - if !bound.is_empty() { - o.insert("boundVariables".into(), Value::Object(bound)); - } - // (The text style itself is added after this: it keeps these.) - if !text_bound.is_empty() { - o.insert("style".into(), json!({"boundVariables": text_bound})); - } - let mut modes = Obj::new(); - let mut lost = false; - for e in v.get("variableModeBySetMap").and_then(|m| m.get("entries")).map(Kv::list).unwrap_or_default() { - let (Some(set), Some(mode)) = (e.get("variableSetID"), e.get("variableModeID").and_then(guid)) else { continue }; - match self.collection_id(set) { - Some(id) => { - modes.insert(id, json!(mode)); - } - // A mode of a collection neither named by guid nor resolvable in the file. - None if set.get("guid").is_some() || set.get("assetRef").is_some() => lost = true, - None => {} - } - } - if lost { - self.warn("variable modes of collections that aren't in the file were skipped"); - } - if !modes.is_empty() { - o.insert("explicitVariableModes".into(), Value::Object(modes)); - } - } -} - -/// The REST `boundVariables` key of a bound layer field. -fn binding_key(field: &str) -> Option<&'static str> { - Some(match field { - "STROKE_WEIGHT" => "strokeWeight", - "STACK_SPACING" => "itemSpacing", - "STACK_COUNTER_SPACING" => "counterAxisSpacing", - "STACK_PADDING_LEFT" => "paddingLeft", - "STACK_PADDING_TOP" => "paddingTop", - "STACK_PADDING_RIGHT" => "paddingRight", - "STACK_PADDING_BOTTOM" => "paddingBottom", - "VISIBLE" => "visible", - "TEXT_DATA" => "characters", - "OPACITY" => "opacity", - "MIN_WIDTH" => "minWidth", - "MAX_WIDTH" => "maxWidth", - "MIN_HEIGHT" => "minHeight", - "MAX_HEIGHT" => "maxHeight", - "RECTANGLE_TOP_LEFT_CORNER_RADIUS" => "topLeftRadius", - "RECTANGLE_TOP_RIGHT_CORNER_RADIUS" => "topRightRadius", - "RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS" => "bottomLeftRadius", - "RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS" => "bottomRightRadius", - _ => return None, - }) -} - -/// The REST text style `boundVariables` key of a bound text field. -fn text_binding_key(field: &str) -> Option<&'static str> { - Some(match field { - "FONT_SIZE" => "fontSize", - "FONT_FAMILY" => "fontFamily", - "FONT_STYLE" => "fontStyle", - "LETTER_SPACING" => "letterSpacing", - "LINE_HEIGHT" => "lineHeight", - "PARAGRAPH_SPACING" => "paragraphSpacing", - "PARAGRAPH_INDENT" => "paragraphIndent", - _ => return None, - }) -} - -/// A `VariableData` (literal, variable reference or expression) in the REST shape; `None` for -/// kinds a prototype can't evaluate. -pub(super) fn variable_data(d: &Kv, depth: usize) -> Option { - let v = d.get("value")?; - let ty = d.get("dataType").and_then(Kv::str)?; - let value = match ty { - "ALIAS" => json!({"type": "VARIABLE_ALIAS", "id": v.get("alias").and_then(ref_guid)?}), - "EXPRESSION" if depth < MAX_EXPR_DEPTH => { - let e = v.get("expressionValue")?; - let function = match e.get("expressionFunction").and_then(Kv::str)? { - "MULTIPLY" => "MULTIPLICATION", - "DIVIDE" => "DIVISION", - f => f, - }; - let args = e.get("expressionArguments").map(Kv::list).unwrap_or_default(); - let args = args.iter().map(|x| variable_data(x, depth + 1)).collect::>>()?; - json!({"expressionFunction": function, "expressionArguments": args}) - } - "BOOLEAN" => json!(v.get("boolValue").and_then(Kv::bool)?), - "FLOAT" => json!(num(v, "floatValue").filter(|x| x.is_finite())?), - "STRING" => json!(v.get("textValue").and_then(Kv::str)?), - "COLOR" => color(v.get("colorValue")?), - _ => return None, - }; - let mut out = json!({"type": ty, "value": value}); - if let Some(r) = d.get("resolvedDataType").and_then(Kv::str) { - out["resolvedType"] = json!(r); - } - Some(out) -} - -/// The variable an `ALIAS` variable data points at: by guid, or by library asset (the newest copy -/// of it in the file). -pub(super) fn alias(d: Option<&Kv>) -> Option { - let d = d?; - if d.get("dataType").and_then(Kv::str) != Some("ALIAS") { - return None; - } - d.get("value").and_then(|v| v.get("alias")).and_then(super::VarCanon::resolve) -} - -pub(super) fn variable_value(d: &Kv) -> Option { - if let Some(a) = alias(Some(d)) { - return Some(json!({"type": "VARIABLE_ALIAS", "id": a})); - } - let v = d.get("value")?; - if let Some(c) = v.get("colorValue") { - return Some(color(c)); - } - if let Some(b) = v.get("boolValue").and_then(Kv::bool) { - return Some(json!(b)); - } - if let Some(x) = num(v, "floatValue") { - return Some(json!(x)); - } - v.get("textValue").and_then(Kv::str).map(|s| json!(s)) -} diff --git a/crates/format/src/fig/network.rs b/crates/format/src/fig/network.rs deleted file mode 100644 index ccb5c2913..000000000 --- a/crates/format/src/fig/network.rs +++ /dev/null @@ -1,133 +0,0 @@ -//! Vector network blobs: the editable form of a vector layer (`vectorData.vectorNetworkBlob`). -//! -//! Little-endian throughout: `u32` counts of vertices, segments and regions; each vertex a style -//! id (`u32`) and its position (`f32` x, y); each segment a style id, its start vertex (`u32`) and -//! tangent (`f32` x, y), then its end vertex and tangent; each region a `u32` holding its style id -//! shifted left once with the winding rule in the low bit (set: non-zero, clear: even-odd), a loop -//! count, and per loop a segment count and the segment indices. Positions are in the space of -//! `vectorData.normalizedSize`. Style ids point into `vectorData.styleOverrideTable` (0: none). - -/// Most vertices, segments, regions or loop entries read from one blob. -const MAX_ITEMS: usize = 200_000; - -pub(super) struct Vertex { - pub style: u32, - pub x: f64, - pub y: f64, -} - -pub(super) struct Segment { - pub style: u32, - pub a: usize, - pub ta: (f64, f64), - pub b: usize, - pub tb: (f64, f64), -} - -pub(super) struct Region { - pub style: u32, - pub non_zero: bool, - pub loops: Vec>, -} - -#[derive(Default)] -pub(super) struct Network { - pub vertices: Vec, - pub segments: Vec, - pub regions: Vec, -} - -struct Reader<'b> { - b: &'b [u8], - pos: usize, -} - -impl Reader<'_> { - fn u32(&mut self) -> Option { - let v = u32::from_le_bytes(self.b.get(self.pos..self.pos + 4)?.try_into().ok()?); - self.pos += 4; - Some(v) - } - - fn f32(&mut self) -> Option { - Some(f64::from(f32::from_bits(self.u32()?))).filter(|x| x.is_finite()) - } - - /// An index below `len`. - fn index(&mut self, len: usize) -> Option { - Some(self.u32()? as usize).filter(|i| *i < len) - } - - /// A count of items of at least `size` bytes each that the rest of the blob can hold. - fn count(&mut self, size: usize) -> Option { - let n = self.u32()? as usize; - (n <= MAX_ITEMS && n * size <= self.b.len().saturating_sub(self.pos)).then_some(n) - } -} - -/// The network in blob `b`; `None` when it's truncated, out of range or not finite. -pub(super) fn decode(b: &[u8]) -> Option { - let mut r = Reader { b, pos: 0 }; - let (nv, ns, nr) = (r.u32()? as usize, r.u32()? as usize, r.u32()? as usize); - if nv > MAX_ITEMS || ns > MAX_ITEMS || nr > MAX_ITEMS || nv * 12 + ns * 28 + nr * 8 > b.len().saturating_sub(12) { - return None; - } - let mut net = Network::default(); - for _ in 0..nv { - net.vertices.push(Vertex { style: r.u32()?, x: r.f32()?, y: r.f32()? }); - } - for _ in 0..ns { - let style = r.u32()?; - net.segments.push(Segment { style, a: r.index(nv)?, ta: (r.f32()?, r.f32()?), b: r.index(nv)?, tb: (r.f32()?, r.f32()?) }); - } - let mut entries = 0usize; - for _ in 0..nr { - let sw = r.u32()?; - let mut loops = Vec::new(); - for _ in 0..r.count(4)? { - let n = r.count(4)?; - entries += n; - if entries > MAX_ITEMS { - return None; - } - loops.push((0..n).map(|_| r.index(ns)).collect::>>()?); - } - net.regions.push(Region { style: sw >> 1, non_zero: sw & 1 == 1, loops }); - } - Some(net) -} - -/// The blob of `net` (the export writes it; so do test fixtures). Callers pass finite values. -pub(super) fn encode(net: &Network) -> Vec { - let mut out = Vec::new(); - let u = |v: u32, out: &mut Vec| out.extend_from_slice(&v.to_le_bytes()); - let fl = |v: f64, out: &mut Vec| out.extend_from_slice(&(v as f32).to_le_bytes()); - for n in [net.vertices.len(), net.segments.len(), net.regions.len()] { - u(n as u32, &mut out); - } - for v in &net.vertices { - u(v.style, &mut out); - fl(v.x, &mut out); - fl(v.y, &mut out); - } - for s in &net.segments { - u(s.style, &mut out); - u(s.a as u32, &mut out); - fl(s.ta.0, &mut out); - fl(s.ta.1, &mut out); - u(s.b as u32, &mut out); - fl(s.tb.0, &mut out); - fl(s.tb.1, &mut out); - } - for r in &net.regions { - u((r.style << 1) | u32::from(r.non_zero), &mut out); - u(r.loops.len() as u32, &mut out); - for l in &r.loops { - u(l.len() as u32, &mut out); - for i in l { - u(*i as u32, &mut out); - } - } - } - out -} diff --git a/crates/format/src/fig/tail_tests.rs b/crates/format/src/fig/tail_tests.rs index 264216bcc..af4ad840e 100644 --- a/crates/format/src/fig/tail_tests.rs +++ b/crates/format/src/fig/tail_tests.rs @@ -775,7 +775,7 @@ fn connectors_without_a_saved_path_follow_their_line_style() { let line: Vec<_> = network_of(&doc, "Line").vertices.iter().map(|v| world("Line") * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect(); assert_eq!(line, [(100.0, 650.0), (300.0, 650.0)]); - assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("are routed afresh")), "{warnings:?}"); } /// #1909: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER` @@ -1055,7 +1055,7 @@ fn an_elbow_connector_saved_with_its_path_keeps_it() { // Each end starts `END_GAP` (4) outside its side's border. assert_eq!(line, [(50.0, 704.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (296.0, 850.0)]); // The fixture's own Link, saved without a path, is routed here: the note counts it alone. - let routed: Vec<_> = warnings.iter().filter(|w| w.contains("FigCraft's own routing")).collect(); + let routed: Vec<_> = warnings.iter().filter(|w| w.contains("are routed afresh")).collect(); assert_eq!(routed.len(), 1, "{warnings:?}"); assert!(!routed[0].contains('×'), "a connector with its path isn't counted among those routed here: {routed:?}"); } @@ -1103,5 +1103,5 @@ fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() { for name in ["Sideways", "Askew", "Repeated", "Backwards", "Inside"] { assert_eq!(line(name), plain, "{name} is routed as one without a path"); } - assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("are routed afresh")), "{warnings:?}"); } diff --git a/crates/format/src/fig/tests.rs b/crates/format/src/fig/tests.rs index e024920a7..1399e171f 100644 --- a/crates/format/src/fig/tests.rs +++ b/crates/format/src/fig/tests.rs @@ -795,11 +795,11 @@ fn hashes_naming_one_blob_share_one_copy_of_it() { ("blobs", Kv::Array(vec![o(vec![("bytes", Kv::Bytes(png()))]), o(vec![("bytes", Kv::Bytes(vec![7; 16]))])])), ("nodeChanges", Kv::Array((1..=50).map(|h| image(h, 0)).chain([image(99, 1), image(98, 2)]).collect())), ]); - let copies = embedded_copies(&msg); + let copies = embedded_copies(&msg, MAX_IMAGE); assert_eq!(copies.len(), 51, "the hash naming no blob is left out"); let first = &copies[&"01".repeat(20)]; assert_eq!(**first, *png()); - assert_eq!(copies.values().filter(|c| Arc::ptr_eq(c, first)).count(), 50); + assert_eq!(copies.values().filter(|c| std::sync::Arc::ptr_eq(c, first)).count(), 50); assert_eq!(*copies[&"63".repeat(20)], [7; 16]); } @@ -814,7 +814,7 @@ fn hashes_naming_one_blob_are_imported_once() { let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])]; nodes.extend((2..42).map(|i| rect(i, i as u8, 0))); let msg = o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(png()))])]))]); - let copies = embedded_copies(&msg); + let copies = embedded_copies(&msg, MAX_IMAGE); let aliases = embedded_aliases(&copies, |_| false); assert_eq!(aliases.len(), 39); assert!(aliases.values().all(|c| *c == "02".repeat(20))); @@ -974,13 +974,13 @@ mod image_budget { // Shorten the first member's compressed size, cutting its deflate stream mid-image. change_member_field(&mut zip, 1, 20, 15); let limit = members[0].1.len() as u64; - let archive = Archive::open(&zip).unwrap(); - archive.image_budget.remaining.set(limit); + let archive = Archive::open_with(&zip, Limits { max_image: MAX_IMAGE, max_image_total: limit }).unwrap(); assert!(archive.image(&"01".repeat(20)).is_none()); - let remaining = archive.image_budget.remaining.get(); - assert!(remaining > 0 && remaining < limit, "partial read left {remaining} of {limit} bytes"); + // The failed read keeps its charge (craft-fig charges the declared size). + let remaining = archive.image_bytes_left(); + assert!(remaining < limit, "partial read left {remaining} of {limit} bytes"); assert!(archive.image(&"02".repeat(20)).is_none()); - assert_eq!(archive.image_budget.remaining.get(), remaining); + assert_eq!(archive.image_bytes_left(), remaining); let (doc, warnings) = import_with_image_limit(&zip, "Images", limit).unwrap(); assert_ne!(bytes(&doc, 1), members[1].1); assert_eq!(budget_warnings(&warnings).len(), 1, "{warnings:?}"); @@ -1013,14 +1013,13 @@ mod image_budget { let members = [(1, image(1)), (2, image(2))]; let mut zip = file(&[1, 2], &members); change_member_field(&mut zip, 1, 24, 1); - let archive = Archive::open(&zip).unwrap(); - archive.image_budget.remaining.set(members[0].1.len() as u64 - 1); + let archive = Archive::open_with(&zip, Limits { max_image: MAX_IMAGE, max_image_total: members[0].1.len() as u64 - 1 }).unwrap(); + // Whether the ZIP reader refuses the mismatch or reads on, the member is not returned + // and the budget is never overdrawn. assert!(archive.image(&"01".repeat(20)).is_none()); - assert_eq!(archive.image_budget.remaining.get(), 0); - assert_eq!(archive.image_budget.skipped.get(), 1); + assert!(archive.image_bytes_left() < members[0].1.len() as u64); assert!(archive.image(&"02".repeat(20)).is_none()); - assert_eq!(archive.image_budget.remaining.get(), 0); - assert_eq!(archive.image_budget.skipped.get(), 2); + assert!(archive.images_skipped() >= 1); } #[test] @@ -1153,23 +1152,23 @@ fn mangled_kiwi_never_panics() { #[test] fn large_files_get_a_larger_value_budget() { // Small files keep the fixed floor: a few bytes can't expand into a huge tree. - assert_eq!(kiwi::value_budget(0), 20_000_000); - assert_eq!(kiwi::value_budget(1 << 20), 20_000_000); + assert_eq!(craft_fig::value_budget(0), 20_000_000); + assert_eq!(craft_fig::value_budget(1 << 20), 20_000_000); // A real 400 000-layer file: an 83.5 MB canvas whose message unpacks to 334 MB and holds // 30.5 million values was refused as "too many values". - assert!(kiwi::value_budget(83_491_232) > 30_514_899); + assert!(craft_fig::value_budget(83_491_232) > 30_514_899); // A real 194 MB design-system file (UX4G): a 39.5 MB canvas holding 29.7 million values. - assert!(kiwi::value_budget(39_528_420) > 29_703_730); + assert!(craft_fig::value_budget(39_528_420) > 29_703_730); // Still bounded by the largest canvas read. - assert!(kiwi::value_budget(MAX_CANVAS as usize) <= 128 << 20); + assert!(craft_fig::value_budget(MAX_CANVAS as usize) <= 128 << 20); // Counting every scalar field, a dense file may reach about 2.4 values per compressed byte (the // 15 MB text-heavy fixture in `value_budget_tests` measures 1.8): below the ceiling the budget must // cover that, the floor still holds up to 5 MB of canvas, and 32 MiB is enough for the ceiling. - assert!(kiwi::value_budget(8 << 20) >= (8 << 20) * 12 / 5); + assert!(craft_fig::value_budget(8 << 20) >= (8 << 20) * 12 / 5); #[cfg(not(target_pointer_width = "32"))] - assert!(kiwi::value_budget(30_000_000) >= 30_000_000 * 12 / 5); - assert_eq!(kiwi::value_budget(5_000_000), 20_000_000); - assert_eq!(kiwi::value_budget(32 << 20), kiwi::value_budget(MAX_CANVAS as usize)); + assert!(craft_fig::value_budget(30_000_000) >= 30_000_000 * 12 / 5); + assert_eq!(craft_fig::value_budget(5_000_000), 20_000_000); + assert_eq!(craft_fig::value_budget(32 << 20), craft_fig::value_budget(MAX_CANVAS as usize)); } #[test] @@ -1822,7 +1821,6 @@ fn same_version_library_copies_resolve_deterministically_and_leave_no_table() { let page = doc.nodes().find(|n| n.name == "Page").unwrap(); assert_eq!(page.var_modes.get(&id).map(String::as_str), Some("1:90")); picked.push(id); - assert!(!super::map::VarCanon::installed()); } assert_eq!(picked, ["1:6", "1:6"]); } diff --git a/crates/format/src/fig/text_path.rs b/crates/format/src/fig/text_path.rs deleted file mode 100644 index 90c631514..000000000 --- a/crates/format/src/fig/text_path.rs +++ /dev/null @@ -1,316 +0,0 @@ -//! Convert the simple vector network used by text-on-path layers in `.fig` files into a native text path. - -use figcraft_doc::{ - TextPath, - geom::{ - BezPath, - kurbo::{CubicBez, Line, ParamCurve, ParamCurveArclen, Point}, - }, -}; - -use super::network::{Network, Segment}; - -const START_SEGMENT_STYLE: u32 = 0x01ff_ffff; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Use { - segment: usize, - forward: bool, -} - -/// Build a native path from a validated connected chain or cycle. The marked source segment is -/// oriented a→b; `t` is local to that line/cubic. Coordinates are scaled into layer space. -pub(super) fn from_network(net: &Network, sx: f64, sy: f64, t: f64, forward: bool) -> Result { - if !t.is_finite() || !(0.0..=1.0).contains(&t) { - return Err("invalid start parameter"); - } - if !sx.is_finite() || !sy.is_finite() || sx <= 0.0 || sy <= 0.0 { - return Err("invalid path scale"); - } - let markers: Vec = net.segments.iter().enumerate().filter_map(|(i, s)| (s.style == START_SEGMENT_STYLE).then_some(i)).collect(); - let [marked] = markers.as_slice() else { - return Err("missing or ambiguous start segment marker"); - }; - - let (uses, closed) = ordered_chain(net, *marked)?; - let mut d = BezPath::new(); - let mut total = 0.0; - let mut prefix = 0.0; - let mut start_segment_length = 0.0; - for use_ in &uses { - let (p0, p1, p2, p3) = cubic(net, *use_, sx, sy)?; - if d.elements().is_empty() { - d.move_to((p0.0, p0.1)); - } - let line = p1 == p0 && p2 == p3; - let (length, partial) = if line { - d.line_to((p3.0, p3.1)); - let line = Line::new(Point::new(p0.0, p0.1), Point::new(p3.0, p3.1)); - (line.arclen(1e-9), line.arclen(1e-9) * t) - } else { - d.curve_to((p1.0, p1.1), (p2.0, p2.1), (p3.0, p3.1)); - let curve = CubicBez::new((p0.0, p0.1), (p1.0, p1.1), (p2.0, p2.1), (p3.0, p3.1)); - let partial = if t <= 0.0 { 0.0 } else { curve.subsegment(0.0..t).arclen(1e-9) }; - (curve.arclen(1e-9), partial) - }; - if !length.is_finite() || length <= 1e-10 { - return Err("zero-length path segment"); - } - if use_.segment == *marked { - start_segment_length = partial; - if !start_segment_length.is_finite() { - return Err("invalid path length"); - } - prefix = total; - } - total += length; - } - if closed { - d.close_path(); - } - if !total.is_finite() || total <= 1e-10 { - return Err("zero-length path"); - } - let mut start = ((prefix + start_segment_length) / total).clamp(0.0, 1.0); - let flip = !forward; - if flip { - start = 1.0 - start; - } - let path = TextPath { d: d.to_svg(), start, flip }; - let lines = figcraft_doc::geom::measure::polylines(&path.path()).ok_or("cannot be measured by text renderer")?; - if lines.first().is_none_or(|line| line.length() <= 1e-9) { - return Err("cannot be measured by text renderer"); - } - Ok(path) -} - -/// Return every segment in chain order. Open chains are oriented so the marked segment runs a→b; -/// cycles start at the marked segment's a vertex and traverse it first. -fn ordered_chain(net: &Network, marked: usize) -> Result<(Vec, bool), &'static str> { - let marker = net.segments.get(marked).ok_or("invalid start segment index")?; - let mut adjacency = vec![Vec::::new(); net.vertices.len()]; - for (i, s) in net.segments.iter().enumerate() { - if s.a >= adjacency.len() || s.b >= adjacency.len() { - return Err("invalid path vertex index"); - } - if s.a == s.b { - return Err("path contains a segment that starts and ends at the same vertex"); - } - adjacency[s.a].push(i); - adjacency[s.b].push(i); - } - let mut endpoints = Vec::new(); - for edges in &adjacency { - if edges.len() > 2 { - return Err("branched path network"); - } - if edges.len() == 1 { - endpoints.push(edges[0]); - } - } - if !endpoints.is_empty() && endpoints.len() != 2 { - return Err("disconnected or malformed path network"); - } - let cycle = endpoints.is_empty(); - let mut used = vec![false; net.segments.len()]; - let mut out = Vec::with_capacity(net.segments.len()); - if cycle { - out.push(Use { segment: marked, forward: true }); - used[marked] = true; - let mut at = marker.b; - let mut visited = vec![false; net.vertices.len()]; - visited[marker.a] = true; - visited[marker.b] = true; - while at != marker.a { - let next = adjacency[at].iter().copied().find(|i| !used[*i]).ok_or("disconnected path cycle")?; - used[next] = true; - let s = &net.segments[next]; - let is_forward = s.a == at; - at = if is_forward { s.b } else { s.a }; - if at != marker.a && std::mem::replace(&mut visited[at], true) { - return Err("path cycle is not simple"); - } - out.push(Use { segment: next, forward: is_forward }); - if out.len() > net.segments.len() { - return Err("invalid path cycle"); - } - } - } else { - let endpoint = adjacency.iter().position(|e| e.len() == 1).ok_or("missing path endpoint")?; - let mut at = endpoint; - while let Some(next) = adjacency[at].iter().copied().find(|i| !used[*i]) { - used[next] = true; - let s = &net.segments[next]; - let is_forward = s.a == at; - at = if is_forward { s.b } else { s.a }; - out.push(Use { segment: next, forward: is_forward }); - } - let Some(marker_use) = out.iter().find(|u| u.segment == marked) else { return Err("disconnected start segment") }; - if !marker_use.forward { - out.reverse(); - for u in &mut out { - u.forward = !u.forward; - } - } - } - if !used.iter().all(|x| *x) { - return Err("disconnected path network"); - } - Ok((out, cycle)) -} - -type P = (f64, f64); - -fn cubic(net: &Network, use_: Use, sx: f64, sy: f64) -> Result<(P, P, P, P), &'static str> { - let s: &Segment = net.segments.get(use_.segment).ok_or("invalid path segment index")?; - let a = net.vertices.get(s.a).ok_or("invalid path vertex index")?; - let b = net.vertices.get(s.b).ok_or("invalid path vertex index")?; - let p0 = (a.x * sx, a.y * sy); - let p3 = (b.x * sx, b.y * sy); - let ta = (s.ta.0 * sx, s.ta.1 * sy); - let tb = (s.tb.0 * sx, s.tb.1 * sy); - if [p0.0, p0.1, p3.0, p3.1, ta.0, ta.1, tb.0, tb.1].iter().any(|x| !x.is_finite()) { - return Err("invalid path coordinates"); - } - let (p0, p1, p2, p3) = - if ta == (0.0, 0.0) && tb == (0.0, 0.0) { (p0, p0, p3, p3) } else { (p0, (p0.0 + ta.0, p0.1 + ta.1), (p3.0 + tb.0, p3.1 + tb.1), p3) }; - if use_.forward { Ok((p0, p1, p2, p3)) } else { Ok((p3, p2, p1, p0)) } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::fig::network::{Segment, Vertex}; - use figcraft_doc::geom::kurbo::PathEl; - - fn vertex(x: f64, y: f64) -> Vertex { - Vertex { style: 0, x, y } - } - - fn segment(style: u32, a: usize, b: usize, ta: (f64, f64), tb: (f64, f64)) -> Segment { - Segment { style, a, ta, b, tb } - } - - fn curved() -> Network { - Network { - vertices: vec![vertex(0.0, 82.5), vertex(300.0, 82.5), vertex(600.0, 82.5)], - segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (70.0, -110.0), (-70.0, -110.0)), segment(0, 1, 2, (70.0, 110.0), (-70.0, 110.0))], - ..Network::default() - } - } - - #[test] - fn local_cubic_parameter_converts_to_path_distance() { - let path = from_network(&curved(), 1.0, 1.0, 0.0086954795, true).unwrap(); - assert!((path.start - 0.004744078).abs() < 0.00001); - // Cubic t is not its fraction of total path length. - assert!((path.start - 0.0086954795).abs() > 0.003); - let elements = path.path().elements().to_vec(); - assert!(matches!(elements.first(), Some(PathEl::MoveTo(p)) if p.x == 0.0 && p.y == 82.5)); - assert!(matches!(elements.get(1), Some(PathEl::CurveTo(..)))); - } - - #[test] - fn second_segment_marker_and_t_are_respected() { - let mut net = curved(); - net.segments[0].style = 0; - net.segments[1].style = START_SEGMENT_STYLE; - let path = from_network(&net, 1.0, 1.0, 0.49800667, true).unwrap(); - assert!((path.start - 0.7490379757).abs() < 0.00002); - } - - #[test] - fn reverse_direction_inverts_normalized_start() { - let net = Network { - vertices: vec![vertex(0.0, 0.0), vertex(600.0, 0.0)], - segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))], - ..Network::default() - }; - let path = from_network(&net, 1.0, 1.0, 0.83986014, false).unwrap(); - assert!(path.flip); - assert!((path.start - 0.16013986).abs() < 1e-8); - assert!(matches!(path.path().elements().get(1), Some(PathEl::LineTo(p)) if p.x == 600.0 && p.y == 0.0)); - } - - #[test] - fn rejects_missing_duplicate_and_zero_length_segments() { - let mut net = curved(); - net.segments[0].style = 0; - assert_eq!(from_network(&net, 1.0, 1.0, 0.5, true), Err("missing or ambiguous start segment marker")); - net.segments[1].style = START_SEGMENT_STYLE; - net.segments[0].style = START_SEGMENT_STYLE; - assert_eq!(from_network(&net, 1.0, 1.0, 0.5, true), Err("missing or ambiguous start segment marker")); - let zero = Network { - vertices: vec![vertex(0.0, 0.0), vertex(0.0, 0.0)], - segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))], - ..Network::default() - }; - assert_eq!(from_network(&zero, 1.0, 1.0, 0.5, true), Err("zero-length path segment")); - } - - #[test] - fn rejects_branching_and_disconnected_segments() { - let branch = Network { - vertices: vec![vertex(0.0, 0.0), vertex(1.0, 0.0), vertex(2.0, 0.0), vertex(1.0, 1.0)], - segments: vec![ - segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0)), - segment(0, 1, 2, (0.0, 0.0), (0.0, 0.0)), - segment(0, 1, 3, (0.0, 0.0), (0.0, 0.0)), - ], - ..Network::default() - }; - assert_eq!(from_network(&branch, 1.0, 1.0, 0.5, true), Err("branched path network")); - let disconnected = Network { - vertices: vec![vertex(0.0, 0.0), vertex(1.0, 0.0), vertex(2.0, 0.0), vertex(3.0, 0.0)], - segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0)), segment(0, 2, 3, (0.0, 0.0), (0.0, 0.0))], - ..Network::default() - }; - assert_eq!(from_network(&disconnected, 1.0, 1.0, 0.5, true), Err("disconnected or malformed path network")); - } - - #[test] - fn scales_geometry_and_accepts_closed_cycles() { - let cycle = Network { - vertices: vec![vertex(0.0, 0.0), vertex(100.0, 0.0), vertex(100.0, 100.0)], - segments: vec![ - segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0)), - segment(0, 1, 2, (0.0, 0.0), (0.0, 0.0)), - segment(0, 2, 0, (0.0, 0.0), (0.0, 0.0)), - ], - ..Network::default() - }; - let path = from_network(&cycle, 2.0, 3.0, 0.5, true).unwrap(); - let elements = path.path().elements().to_vec(); - assert!(matches!(elements.first(), Some(PathEl::MoveTo(p)) if p.x == 0.0 && p.y == 0.0)); - assert!(matches!(elements.get(1), Some(PathEl::LineTo(p)) if p.x == 200.0 && p.y == 0.0)); - let total = 200.0 + 300.0 + 130_000.0_f64.sqrt(); - assert!((path.start - 100.0 / total).abs() < 1e-8); - assert!(matches!(elements.last(), Some(PathEl::ClosePath))); - } - - #[test] - fn rejects_paths_the_native_renderer_cannot_measure() { - let count = 40_000usize; - let many_lines = Network { - vertices: (0..=count).map(|i| vertex(i as f64, 0.0)).collect(), - segments: (0..count).map(|i| segment(if i == 0 { START_SEGMENT_STYLE } else { 0 }, i, i + 1, (0.0, 0.0), (0.0, 0.0))).collect(), - ..Network::default() - }; - assert_eq!(from_network(&many_lines, 1.0, 1.0, 0.5, true), Err("cannot be measured by text renderer")); - - // Past the cap the builders hold their sizes to (`figcraft_geom::MAX_COORD`, inclusive). - let huge = Network { - vertices: vec![vertex(0.0, 0.0), vertex(2e9, 0.0)], - segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))], - ..Network::default() - }; - assert_eq!(from_network(&huge, 1.0, 1.0, 0.5, true), Err("cannot be measured by text renderer")); - - let tiny = Network { - vertices: vec![vertex(0.0, 0.0), vertex(5e-10, 0.0)], - segments: vec![segment(START_SEGMENT_STYLE, 0, 1, (0.0, 0.0), (0.0, 0.0))], - ..Network::default() - }; - assert_eq!(from_network(&tiny, 1.0, 1.0, 0.5, true), Err("cannot be measured by text renderer")); - } -} diff --git a/crates/format/src/fig/value_budget_tests.rs b/crates/format/src/fig/value_budget_tests.rs index 7046b1d50..8cdf208e6 100644 --- a/crates/format/src/fig/value_budget_tests.rs +++ b/crates/format/src/fig/value_budget_tests.rs @@ -4,7 +4,7 @@ use super::kiwi::{Kv, Schema, encode}; use super::tests::{Lcg, arr, at, f, g, node, o, s, schema, solid, u, xy}; -use super::{decode_canvas, export, import, kiwi}; +use super::{decode_canvas, import}; fn frac(r: &mut Lcg, hi: f64) -> f64 { (r.next() % 100_000) as f64 / 100_000.0 * hi @@ -84,7 +84,7 @@ fn one_list_canvas(sc: &Schema, count: u32, elements: impl IntoIterator) -> std::fmt::Result { - match self { - FormatError::Io(e) => write!(f, "{e}"), - FormatError::Corrupt(e) => write!(f, "not a valid FigCraft file: {e}"), - FormatError::Newer(v) => write!(f, "this file was saved by a newer FigCraft (format version {v})"), - } - } -} - -impl std::error::Error for FormatError {} /// One entry of a file's version history: a named snapshot of the document. #[derive(Clone, Debug)] @@ -191,16 +142,6 @@ pub struct Branch { pub versions: Vec, } -/// Whether `id` can name a version (and its archive entry). -pub fn is_valid_version_id(id: &str) -> bool { - (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') -} - -/// `s` cut to at most `max` chars. -pub fn clip(s: &str, max: usize) -> String { - s.chars().take(max).collect() -} - /// A file as read: the document, the repairs made (and versions skipped), and its version /// history, oldest first. #[derive(Debug)] @@ -243,33 +184,14 @@ pub(crate) fn image_data(data: Vec) -> ImageData { ImageData { bytes: Arc::new(data), width: w, height: h } } -/// `document.json`: the format header, the image index and the document's own fields, written -/// straight from the document (no intermediate JSON tree). -#[derive(Serialize)] -struct DocumentJson<'a> { - format: &'static str, - version: u32, - #[serde(rename = "imageIndex", serialize_with = "image_index")] - images: &'a BTreeMap, - #[serde(flatten)] - doc: &'a Document, -} +/// The image hashes a `document.json` lists in its `imageIndex` (`None` without one). +type ImageIndex = Option>; -impl<'a> DocumentJson<'a> { - fn new(doc: &'a Document) -> Self { - Self { format: FORMAT, version: VERSION, images: &doc.images, doc } - } -} - -/// The `imageIndex`: `[{hash, width, height}]` for every image the document holds. -fn image_index(images: &&BTreeMap, s: S) -> Result { - #[derive(Serialize)] - struct Entry<'a> { - hash: &'a str, - width: u32, - height: u32, - } - s.collect_seq(images.iter().map(|(hash, i)| Entry { hash, width: i.width, height: i.height })) +fn native_image_index(doc: &Document) -> Vec { + doc.images + .iter() + .map(|(hash, image)| craft_figcraft_format::ImageIndexEntry { hash: hash.clone(), width: image.width, height: image.height }) + .collect() } /// A serializer adapter that writes `0` in place of every NaN or infinite float. JSON has no such @@ -452,13 +374,17 @@ impl serde::ser::SerializeStructVariant f /// Serialize the document (without images) to the JSON value stored in `document.json`. /// NaN and infinite numbers are written as `0`. pub fn to_json(doc: &Document) -> Result { - DocumentJson::new(doc).serialize(Finite(serde_json::value::Serializer)).map_err(io_err) + { + let mut bytes = Vec::new(); + craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), &mut bytes).map_err(io_err)?; + serde_json::from_slice(&bytes).map_err(io_err) + } } /// Write the document (without images) as `document.json` content to `w`. /// NaN and infinite numbers are written as `0`. pub fn write_json(doc: &Document, w: impl Write) -> Result<(), FormatError> { - DocumentJson::new(doc).serialize(Finite(&mut serde_json::Serializer::new(w))).map_err(io_err) + craft_figcraft_format::write_document_json(&FiniteValue(doc), &native_image_index(doc), w).map_err(io_err) } /// Parse `document.json` content. @@ -466,109 +392,56 @@ pub fn from_json(text: &str) -> Result<(Document, Vec), FormatError> { parse_json(text).map(|(doc, issues, _)| (doc, issues)) } -/// The image hashes a `document.json` lists in its `imageIndex` (`None` without one). -type ImageIndex = Option>; - -/// The header of a `document.json` (its format version and image index), read in a pass that -/// skips over everything else without building it. -#[derive(Default)] -struct Header { - version: Option, - images: ImageIndex, -} - -impl<'de> Deserialize<'de> for Header { - fn deserialize>(d: D) -> Result { - struct HeaderVisitor; - impl<'de> Visitor<'de> for HeaderVisitor { - type Value = Header; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - f.write_str("a FigCraft document object") - } - fn visit_map>(self, mut map: A) -> Result { - let mut h = Header::default(); - while let Some(key) = map.next_key::()? { - match key.as_str() { - "version" => h.version = map.next_value::()?.as_u64(), - "imageIndex" => { - h.images = map - .next_value::()? - .as_array() - .map(|a| a.iter().filter_map(|i| i.get("hash").and_then(Value::as_str).map(str::to_string)).collect()); - } - _ => { - map.next_value::()?; - } - } - } - Ok(h) - } - } - d.deserialize_map(HeaderVisitor) - } -} - /// Parse `document.json` content; also returns its [`ImageIndex`]. The header is checked first /// (a newer file is refused before its document is read), then the document is deserialized /// straight from the text. fn parse_json(text: &str) -> Result<(Document, Vec, ImageIndex), FormatError> { - let corrupt = |e: serde_json::Error| FormatError::Corrupt(e.to_string()); - let header: Header = serde_json::from_str(text).map_err(corrupt)?; - if let Some(ver) = header.version - && ver > u64::from(VERSION) - { - return Err(FormatError::Newer(u32::try_from(ver).unwrap_or(u32::MAX))); - } - let mut doc: Document = serde_json::from_str(text).map_err(corrupt)?; + let (mut doc, header) = craft_figcraft_format::read_document_json::(text).map_err(|e| match e { + craft_figcraft_format::ReadDocumentError::Json(error) => FormatError::Corrupt(error.to_string()), + craft_figcraft_format::ReadDocumentError::NewerVersion(error) => FormatError::Newer(error.0), + })?; + let images = header.images.map(|hashes| hashes.into_iter().collect()); let issues = doc.validate(); if !issues.is_empty() { doc.repair(); } - Ok((doc, issues, header.images)) + Ok((doc, issues, images)) } pub(crate) fn io_err(e: impl std::fmt::Display) -> FormatError { FormatError::Io(e.to_string()) } -/// Add one member to the archive. -pub(crate) fn put( - z: &mut zip::ZipWriter, +/// JSON compression for legacy Penpot test fixtures. +#[cfg(test)] +pub(crate) fn json_options() -> zip::write::SimpleFileOptions { + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL)) +} + +/// Add one member to the native archive. +pub(crate) fn put( + z: &mut craft_figcraft_format::ArchiveWriter, name: &str, - opts: zip::write::SimpleFileOptions, + compression: craft_figcraft_format::Compression, bytes: &[u8], ) -> Result<(), FormatError> { - z.start_file(name, opts).map_err(io_err)?; - z.write_all(bytes).map_err(io_err) + z.add(name, bytes, compression).map_err(io_err) } /// `files` (name, bytes; a `/` in a name makes a folder) as one zip archive: several exports /// delivered as a single download (#969). pub fn zip_files<'a>(files: impl IntoIterator) -> Result, FormatError> { - let mut buf = std::io::Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - for (name, bytes) in files { - put(&mut z, name, zip::write::SimpleFileOptions::default(), bytes)?; - } - z.finish().map_err(io_err)?; - } - Ok(buf.into_inner()) + craft_figcraft_format::write_archive(files.into_iter().map(|(name, bytes)| craft_figcraft_format::Member { + name, + bytes, + compression: craft_figcraft_format::Compression::Deflated, + })) + .map_err(io_err) } /// Add `doc` as a `document.json`-style member, serialized straight into the compressor. -fn put_json(z: &mut zip::ZipWriter, name: &str, doc: &Document) -> Result<(), FormatError> { - z.start_file(name, json_options()).map_err(io_err)?; - // The serializer writes many small pieces: batch them before they reach the compressor. - let mut w = std::io::BufWriter::with_capacity(1 << 16, z); - write_json(doc, &mut w)?; - w.flush().map_err(io_err) -} - -/// How JSON members are compressed. Document JSON is very repetitive: a fast level compresses it -/// nearly as well as the default one (about 15% larger) in half the time. -pub(crate) fn json_options() -> zip::write::SimpleFileOptions { - zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).compression_level(Some(JSON_LEVEL)) +fn put_json(z: &mut craft_figcraft_format::ArchiveWriter, name: &str, doc: &Document) -> Result<(), FormatError> { + z.add_document_json(name, &FiniteValue(doc), &native_image_index(doc)).map_err(io_err) } /// Write a `.figcraft` archive to bytes. @@ -588,50 +461,62 @@ pub fn save_bytes_with_history( versions: &[Version], branches: &[Branch], ) -> Result, FormatError> { - let mut buf = std::io::Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - put_json(&mut z, "document.json", doc)?; - // Every image once, whether the document, a version or a branch uses it. - let mut written = BTreeSet::new(); - let branch_images = branches.iter().flat_map(|b| [&b.base.images, &b.head.images].into_iter().chain(b.versions.iter().map(Version::images))); - for (hash, img) in std::iter::once(&doc.images).chain(versions.iter().map(Version::images)).chain(branch_images).flatten() { - if written.insert(hash) { - put(&mut z, &format!("images/{hash}"), stored, &img.bytes)?; - } + let mut z = craft_figcraft_format::ArchiveWriter::new(); + let stored = craft_figcraft_format::Compression::Stored; + put_json(&mut z, "document.json", doc)?; + // Every image once, whether the document, a version or a branch uses it. + let mut written = BTreeSet::new(); + let branch_images = branches.iter().flat_map(|b| [&b.base.images, &b.head.images].into_iter().chain(b.versions.iter().map(Version::images))); + for (hash, img) in std::iter::once(&doc.images).chain(versions.iter().map(Version::images)).chain(branch_images).flatten() { + if written.insert(hash) { + put(&mut z, &format!("images/{hash}"), stored, img.bytes.as_slice())?; } - if let Some(t) = thumbnail_png { - put(&mut z, "thumbnail.png", stored, t)?; - } - put_versions(&mut z, "versions", versions)?; - if !branches.is_empty() { - let mut ids = BTreeSet::new(); - let mut index = Vec::with_capacity(branches.len()); - for b in branches { - if !is_valid_version_id(&b.id) || !ids.insert(b.id.as_str()) { - return Err(FormatError::Io(format!("invalid or duplicate branch id `{}`", b.id))); - } - put_json(&mut z, &format!("branches/{}/base.json", b.id), &b.base)?; - put_json(&mut z, &format!("branches/{}/head.json", b.id), &b.head)?; - put_versions(&mut z, &format!("branches/{}/versions", b.id), &b.versions)?; - let images = |d: &Document| d.images.keys().cloned().collect::>(); - index.push(json!({"id": b.id, "name": b.name, "time": b.time, "client": b.client, "state": b.state, - "baseImages": images(&b.base), "headImages": images(&b.head)})); - } - put(&mut z, BRANCH_INDEX, json_options(), &serde_json::to_vec(&json!({"branches": index})).map_err(io_err)?)?; - } - if let Some(lib) = &doc.published { - library::write(&mut z, lib, &written)?; - } - z.finish().map_err(io_err)?; } - Ok(buf.into_inner()) + if let Some(t) = thumbnail_png { + put(&mut z, "thumbnail.png", stored, t)?; + } + put_versions(&mut z, "versions", versions)?; + if !branches.is_empty() { + let mut ids = BTreeSet::new(); + let mut index = Vec::with_capacity(branches.len()); + for b in branches { + if !is_valid_version_id(&b.id) || !ids.insert(b.id.as_str()) { + return Err(FormatError::Io(format!("invalid or duplicate branch id `{}`", b.id))); + } + put_json(&mut z, &format!("branches/{}/base.json", b.id), &b.base)?; + put_json(&mut z, &format!("branches/{}/head.json", b.id), &b.head)?; + put_versions(&mut z, &format!("branches/{}/versions", b.id), &b.versions)?; + let images = |d: &Document| d.images.keys().cloned().collect::>(); + index.push(NativeBranchEntry { + id: b.id.clone(), + name: b.name.clone(), + time: b.time, + client: b.client, + state: match b.state { + BranchState::Active => NativeBranchState::Active, + BranchState::Merged => NativeBranchState::Merged, + BranchState::Archived => NativeBranchState::Archived, + }, + base_images: images(&b.base), + head_images: images(&b.head), + }); + } + put( + &mut z, + BRANCH_INDEX, + craft_figcraft_format::Compression::Level(3), + &craft_figcraft_format::write_branch_index(&NativeBranchIndex { branches: index }).map_err(io_err)?, + )?; + } + if let Some(lib) = &doc.published { + library::write(&mut z, lib, &written)?; + } + z.finish().map_err(io_err) } /// Write version history `versions` (oldest first) under `dir`: `/index.json` and one /// `/.json` snapshot per version. Nothing when there are none. -fn put_versions(z: &mut zip::ZipWriter, dir: &str, versions: &[Version]) -> Result<(), FormatError> { +fn put_versions(z: &mut craft_figcraft_format::ArchiveWriter, dir: &str, versions: &[Version]) -> Result<(), FormatError> { if versions.is_empty() { return Ok(()); } @@ -644,16 +529,23 @@ fn put_versions(z: &mut zip::ZipWriter, dir: &str, versions: let name = format!("{dir}/{}.json", v.id); match &v.snapshot { Snapshot::Doc(d) => put_json(z, &name, d)?, - Snapshot::Stored { json, .. } => put(z, &name, json_options(), json)?, + Snapshot::Stored { json, .. } => put(z, &name, craft_figcraft_format::Compression::Level(3), json)?, } - let images: Vec<&String> = v.images().keys().collect(); - let mut entry = json!({"id": v.id, "name": v.name, "description": v.description, "time": v.time, "images": images}); - if v.auto { - entry["auto"] = json!(true); - } - index.push(entry); + index.push(NativeVersionEntry { + id: v.id.clone(), + name: v.name.clone(), + description: v.description.clone(), + time: v.time, + auto: v.auto, + images: v.images().keys().cloned().collect(), + }); } - put(z, &format!("{dir}/index.json"), json_options(), &serde_json::to_vec(&json!({"versions": index})).map_err(io_err)?)?; + put( + z, + &format!("{dir}/index.json"), + craft_figcraft_format::Compression::Level(3), + &craft_figcraft_format::write_version_index(&NativeVersionIndex { versions: index }).map_err(io_err)?, + )?; Ok(()) } @@ -662,75 +554,22 @@ pub fn load_bytes(bytes: &[u8]) -> Result<(Document, Vec), FormatError> load_bytes_with_versions(bytes).map(|l| (l.doc, l.issues)) } -/// Read archive member `name`, refusing members larger than `limit` bytes. -pub(crate) fn read_member(z: &mut zip::ZipArchive, name: &str, limit: u64) -> Result, FormatError> { +/// Read a member from a foreign ZIP archive, refusing entries larger than `limit`. +pub(crate) fn read_member(z: &mut zip::ZipArchive, name: &str, limit: u64) -> Result, FormatError> { let f = z.by_name(name).map_err(|e| FormatError::Corrupt(format!("{name}: {e}")))?; - let too_large = || FormatError::Corrupt(format!("{name} is too large")); if f.size() > limit { - return Err(too_large()); + return Err(FormatError::Corrupt(format!("{name} is too large"))); } let mut data = Vec::new(); f.take(limit.saturating_add(1)).read_to_end(&mut data).map_err(|e| FormatError::Corrupt(format!("{name}: {e}")))?; if data.len() as u64 > limit { - return Err(too_large()); + return Err(FormatError::Corrupt(format!("{name} is too large"))); } Ok(data) } -/// What one file open may still unpack, every area together ([`MAX_UNPACKED`]). -pub(crate) struct Unpacked { - left: u64, - total: u64, -} - -impl Unpacked { - pub(crate) fn new(total: u64) -> Self { - Self { left: total, total } - } - - /// Why a member is left out once the total is spent. - fn passed(&self) -> String { - match self.total / (1024 * 1024) { - 0 => format!("too large: the file's contents together pass {} bytes", self.total), - mb => format!("too large: the file's contents together pass {mb} MB"), - } - } - - /// Whether member `name` (by its recorded size) needs more than is left. - fn exceeded(&self, z: &mut zip::ZipArchive, name: &str) -> bool { - z.by_name(name).is_ok_and(|f| f.size() > self.left) - } - - /// [`read_member`] within `limit` (the area's own cap) and what is left of the total, which the - /// member then uses up. - pub(crate) fn read(&mut self, z: &mut zip::ZipArchive, name: &str, limit: u64) -> Result, FormatError> { - if self.exceeded(z, name) && z.by_name(name).is_ok_and(|f| f.size() <= limit) { - return Err(FormatError::Corrupt(format!("{name}: {}", self.passed()))); - } - let cap = limit.min(self.left); - let size = z.by_name(name).map_or(0, |f| f.size()); - let data = read_member(z, name, cap); - // A read that failed part way (a bad checksum at the end, say) did its unpacking all the - // same: it is charged in full, so an index naming that member again can't repeat it. One - // refused for its recorded size before any unpacking costs nothing. - if size <= cap { - self.left = self.left.saturating_sub(data.as_ref().map_or(size, |d| d.len() as u64)); - } - data - } -} - -/// Largest `document.json` read from an archive of `len` bytes in which it takes `packed`. -pub(crate) fn document_limit(packed: u64, len: u64) -> u64 { - packed.min(len).saturating_mul(DOCUMENT_RATIO).clamp(MAX_MEMBER, MAX_DOCUMENT) -} - -/// How many images, and how many bytes of them together, one file may give. -#[derive(Clone, Copy, Debug)] -pub(crate) struct ImageBudget { - pub images: usize, - pub bytes: u64, -} +/// The remaining archive-wide expansion budget while the app maps native records. +pub(crate) type Unpacked = ReadBudget; /// Read a `.figcraft` archive (or bare JSON) with its version history. pub fn load_bytes_with_versions(bytes: &[u8]) -> Result { @@ -750,22 +589,28 @@ pub(crate) fn load_limited(bytes: &[u8], budget: ImageBudget, total: u64) -> Res let (doc, issues) = from_json(text)?; return Ok(Loaded { issues, ..Loaded::from(doc) }); } - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| FormatError::Corrupt(e.to_string()))?; - let packed = z.by_name("document.json").map(|f| f.compressed_size()).unwrap_or(0); - let limit = document_limit(packed, bytes.len() as u64); + let mut z = + craft_figcraft_format::Archive::open(bytes, craft_figcraft_format::ArchiveLimits { max_entries: u64::MAX, max_total_bytes: u64::MAX }) + .map_err(|e| FormatError::Corrupt(e.to_string()))?; + load_archive(&mut z, budget, total, bytes.len() as u64) +} + +fn load_archive(z: &mut impl craft_figcraft_format::NativeArchive, budget: ImageBudget, total: u64, archive_len: u64) -> Result { + let packed = z.compressed_size("document.json").unwrap_or(0); + let limit = document_limit(packed, archive_len); let mut unpacked = Unpacked::new(total); - let text = String::from_utf8(unpacked.read(&mut z, "document.json", limit)?).map_err(|e| FormatError::Corrupt(e.to_string()))?; + let text = String::from_utf8(unpacked.read(z, "document.json", limit)?).map_err(|e| FormatError::Corrupt(e.to_string()))?; let (mut doc, mut issues, own_images) = parse_json(&text)?; - let ImagesRead { images, unread, past_budget } = read_images(&mut z, own_images.as_ref(), budget, &mut unpacked); + let ImagesRead { images, unread, past_budget } = read_images(z, own_images.as_ref(), budget, &mut unpacked); report_lost_images(&mut issues, &unread, &past_budget, own_images.as_ref(), &images); let images_past_budget = past_budget.len(); - match library::read(&mut z, &images, &mut unpacked) { + match library::read(z, &images, &mut unpacked) { Ok(lib) => doc.published = lib.map(Arc::new), Err(e) => issues.push(format!("the published library was skipped: {e}")), } let mut budget = MAX_VERSION_BYTES; - let versions = read_versions(&mut z, "versions", &images, &mut issues, &mut budget, &mut unpacked); - let branches = read_branches(&mut z, &images, &mut issues, &mut unpacked); + let versions = read_versions(z, "versions", &images, &mut issues, &mut budget, &mut unpacked); + let branches = read_branches(z, &images, &mut issues, &mut unpacked); // Images only the version history or branches use stay with them. let branch_images = branches.iter().flat_map(|b| b.base.images.keys().chain(b.head.images.keys()).chain(b.versions.iter().flat_map(|v| v.images().keys()))); @@ -782,13 +627,14 @@ pub(crate) fn load_limited(bytes: &[u8], budget: ImageBudget, total: u64) -> Res /// The archive's `images/` members by hash, within `budget`, and the ones that couldn't be read /// with why. The document's own images (`own`) are read first, so a file past the budget loses /// the images only its history uses before its own. -fn read_images( - z: &mut zip::ZipArchive, +fn read_images( + z: &mut impl craft_figcraft_format::NativeArchive, own: Option<&BTreeSet>, budget: ImageBudget, unpacked: &mut Unpacked, ) -> ImagesRead { - let mut hashes: Vec = z.file_names().filter_map(|n| n.strip_prefix("images/")).filter(|h| !h.is_empty()).map(str::to_string).collect(); + let mut hashes: Vec = + z.names().into_iter().filter_map(|n| n.strip_prefix("images/").map(str::to_owned)).filter(|h| !h.is_empty()).collect(); hashes.sort_by_key(|h| !own.is_some_and(|o| o.contains(h))); let mut images = BTreeMap::new(); let mut unread = Vec::new(); @@ -809,7 +655,7 @@ fn read_images( unread.push((hash, FormatError::Corrupt(format!("the file has more than {} images", budget.images)))); continue; } - if z.by_name(&name).is_ok_and(|f| f.size() > left) { + if z.declared_size(&name).is_some_and(|size| size > left) { let mb = budget.bytes / (1024 * 1024); past_budget.insert(hash.clone()); unread.push((hash, FormatError::Corrupt(format!("the file's images together pass {mb} MB")))); @@ -817,9 +663,9 @@ fn read_images( } // Past the file's total, an image is left out as one past the images' own budget: it stays // in the file, which can't then be saved over without losing it (#1313). - if unpacked.exceeded(z, &name) { + if unpacked.exceeds_remaining(z, &name) { past_budget.insert(hash.clone()); - unread.push((hash, FormatError::Corrupt(unpacked.passed()))); + unread.push((hash, FormatError::Corrupt(unpacked.exhausted_message()))); continue; } match unpacked.read(z, &name, left.min(MAX_MEMBER)) { @@ -880,8 +726,8 @@ fn report_lost_images( /// The version history kept under `dir` in an archive (none when it has no index), reading at /// most `budget` bytes of snapshots. Damaged entries are skipped and reported in `issues`; nothing /// here fails the load. -fn read_versions( - z: &mut zip::ZipArchive, +fn read_versions( + z: &mut impl craft_figcraft_format::NativeArchive, dir: &str, images: &BTreeMap, issues: &mut Vec, @@ -889,12 +735,12 @@ fn read_versions( unpacked: &mut Unpacked, ) -> Vec { let index_name = format!("{dir}/index.json"); - if z.index_for_name(&index_name).is_none() { + if !z.contains(&index_name) { return Vec::new(); } let index = match unpacked .read(z, &index_name, MAX_VERSION_INDEX) - .and_then(|b| serde_json::from_slice::(&b).map_err(|e| FormatError::Corrupt(e.to_string()))) + .and_then(|b| craft_figcraft_format::read_version_index(&b).map_err(|e| FormatError::Corrupt(e.to_string()))) { Ok(v) => v, Err(e) => { @@ -902,14 +748,13 @@ fn read_versions( return Vec::new(); } }; - let entries = index.get("versions").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); let mut out: Vec = Vec::new(); - for e in entries { + for e in index.versions { if out.len() >= MAX_VERSIONS { issues.push(format!("only the first {MAX_VERSIONS} versions were kept")); break; } - let id = e.get("id").and_then(Value::as_str).unwrap_or_default(); + let id = e.id.as_str(); if !is_valid_version_id(id) || out.iter().any(|v| v.id == id) { issues.push("a version with an invalid id was skipped".into()); continue; @@ -922,21 +767,13 @@ fn read_versions( } }; *budget = budget.saturating_sub(json.len() as u64); - let text = |k: &str, max: usize| e.get(k).and_then(Value::as_str).map(|s| clip(s, max)).unwrap_or_default(); - let images = e - .get("images") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) - .filter_map(|h| images.get(h).map(|i| (h.to_string(), i.clone()))) - .collect(); + let images = e.images.iter().filter_map(|h| images.get(h).map(|i| (h.clone(), i.clone()))).collect(); out.push(Version { id: id.to_string(), - name: text("name", MAX_VERSION_NAME), - description: text("description", MAX_VERSION_DESCRIPTION), - time: e.get("time").and_then(Value::as_u64).unwrap_or(0), - auto: e.get("auto").and_then(Value::as_bool).unwrap_or(false), + name: clip(&e.name, MAX_VERSION_NAME), + description: clip(&e.description, MAX_VERSION_DESCRIPTION), + time: e.time, + auto: e.auto, snapshot: Snapshot::Stored { json: Arc::new(json), images }, }); } @@ -945,18 +782,18 @@ fn read_versions( /// The branches of an archive (none when it has no index), parsed. Damaged entries are skipped and /// reported in `issues`; nothing here fails the load. -fn read_branches( - z: &mut zip::ZipArchive, +fn read_branches( + z: &mut impl craft_figcraft_format::NativeArchive, images: &BTreeMap, issues: &mut Vec, unpacked: &mut Unpacked, ) -> Vec { - if z.index_for_name(BRANCH_INDEX).is_none() { + if !z.contains(BRANCH_INDEX) { return Vec::new(); } let index = match unpacked .read(z, BRANCH_INDEX, MAX_VERSION_INDEX) - .and_then(|b| serde_json::from_slice::(&b).map_err(|e| FormatError::Corrupt(e.to_string()))) + .and_then(|b| craft_figcraft_format::read_branch_index(&b).map_err(|e| FormatError::Corrupt(e.to_string()))) { Ok(v) => v, Err(e) => { @@ -964,28 +801,26 @@ fn read_branches( return Vec::new(); } }; - let entries = index.get("branches").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); let mut out: Vec = Vec::new(); let mut budget = MAX_VERSION_BYTES; - for e in entries { + for e in index.branches { if out.len() >= MAX_BRANCHES { issues.push(format!("only the first {MAX_BRANCHES} branches were kept")); break; } - let id = e.get("id").and_then(Value::as_str).unwrap_or_default(); + let id = e.id.as_str(); if !is_valid_version_id(id) || out.iter().any(|b| b.id == id) { issues.push("a branch with an invalid id was skipped".into()); continue; } - let mut snapshot = |part: &str, list: &str| -> Result, FormatError> { + let mut snapshot = |part: &str, hashes: &[String]| -> Result, FormatError> { let json = unpacked.read(z, &format!("branches/{id}/{part}.json"), budget.min(MAX_MEMBER))?; budget = budget.saturating_sub(json.len() as u64); let (mut doc, _) = from_json(std::str::from_utf8(&json).map_err(|e| FormatError::Corrupt(e.to_string()))?)?; - let hashes = e.get(list).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); - doc.images = hashes.filter_map(|h| images.get(h).map(|i| (h.to_string(), i.clone()))).collect(); + doc.images = hashes.iter().filter_map(|h| images.get(h).map(|i| (h.clone(), i.clone()))).collect(); Ok(Arc::new(doc)) }; - let (base, head) = match (snapshot("base", "baseImages"), snapshot("head", "headImages")) { + let (base, head) = match (snapshot("base", &e.base_images), snapshot("head", &e.head_images)) { (Ok(b), Ok(h)) => (b, h), (Err(err), _) | (_, Err(err)) => { issues.push(format!("branch `{id}` was skipped: {err}")); @@ -994,10 +829,14 @@ fn read_branches( }; out.push(Branch { id: id.to_string(), - name: e.get("name").and_then(Value::as_str).map(|s| clip(s, MAX_VERSION_NAME)).unwrap_or_default(), - time: e.get("time").and_then(Value::as_u64).unwrap_or(0), - client: e.get("client").and_then(Value::as_u64).and_then(|c| u32::try_from(c).ok()).unwrap_or(0), - state: e.get("state").and_then(|s| BranchState::deserialize(s).ok()).unwrap_or(BranchState::Active), + name: clip(&e.name, MAX_VERSION_NAME), + time: e.time, + client: e.client, + state: match e.state { + NativeBranchState::Active => BranchState::Active, + NativeBranchState::Merged => BranchState::Merged, + NativeBranchState::Archived => BranchState::Archived, + }, versions: read_versions(z, &format!("branches/{id}/versions"), images, issues, &mut budget, unpacked), base, head, @@ -1062,8 +901,29 @@ pub fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Resul #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path) -> Result<(Document, Vec), FormatError> { - let bytes = std::fs::read(path).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?; - load_bytes(&bytes) + let mut file = std::fs::File::open(path).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?; + let archive_len = file.metadata().map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?.len(); + let mut first = None; + let mut chunk = [0u8; 8192]; + loop { + let count = file.read(&mut chunk).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?; + if count == 0 { + break; + } + if let Some(byte) = chunk[..count].iter().copied().find(|byte| !byte.is_ascii_whitespace()) { + first = Some(byte); + break; + } + } + file.seek(SeekFrom::Start(0)).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?; + if first == Some(b'{') { + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(|e| FormatError::Io(format!("{}: {e}", path.display())))?; + return load_bytes(&bytes); + } + let mut archive = craft_figcraft_format::SeekArchive::open(file, u64::MAX).map_err(|e| FormatError::Corrupt(e.to_string()))?; + let loaded = load_archive(&mut archive, IMAGE_BUDGET, MAX_UNPACKED, archive_len)?; + Ok((loaded.doc, loaded.issues)) } #[cfg(test)] @@ -1081,6 +941,8 @@ mod large_tests; #[cfg(test)] mod staging_tests; #[cfg(test)] +mod streaming_tests; +#[cfg(test)] mod thumbnail_tests; #[cfg(test)] mod unpacked_total_tests; diff --git a/crates/format/src/library.rs b/crates/format/src/library.rs index 99047f2be..8ed11fedb 100644 --- a/crates/format/src/library.rs +++ b/crates/format/src/library.rs @@ -10,24 +10,22 @@ //! so a missing, damaged or oversized library file is an error, never a crash. use std::collections::{BTreeMap, BTreeSet}; -use std::io::{Read, Seek, Write}; +use std::io::{Read, Seek}; use std::sync::Arc; -use figcraft_doc::{ImageData, LibraryManifest, NodeKind, PublishedLibrary, used_images}; +use figcraft_doc::{ + ImageData, LibraryAsset, LibraryCollection, LibraryManifest, LibraryStyle, LibraryVariable, NodeId, NodeKind, PublishedLibrary, used_images, +}; -use crate::{FormatError, MAX_MEMBER, Unpacked, from_json, image_data, io_err, json_options, put, put_json}; +use crate::{FormatError, MAX_MEMBER, Unpacked, from_json, image_data, io_err}; -const MANIFEST: &str = "library/manifest.json"; -const SNAPSHOT: &str = "library/document.json"; -const IMAGES: &str = "library/images/"; -/// Largest manifest read. -const MAX_MANIFEST: u64 = 16 * 1024 * 1024; -/// Most bytes of images read for one library. -const MAX_IMAGE_BYTES: u64 = 1024 * 1024 * 1024; -/// Longest library id and name kept. -const MAX_ID: usize = 64; -const MAX_NAME: usize = 200; -const MAX_DESCRIPTION: usize = 2000; +use craft_figcraft_format::library as native; + +// Test helpers use these names when constructing deliberately bounded archive entries. +#[cfg(test)] +const MANIFEST: &str = native::MANIFEST; +#[cfg(test)] +const MAX_MANIFEST: u64 = native::MAX_MANIFEST_BYTES; fn corrupt(e: impl std::fmt::Display) -> FormatError { FormatError::Corrupt(e.to_string()) @@ -35,52 +33,112 @@ fn corrupt(e: impl std::fmt::Display) -> FormatError { /// Whether `id` can be a library id: 1–64 ASCII letters, digits, `-` and `_`. pub fn is_valid_library_id(id: &str) -> bool { - (1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + native::is_valid_id(id) +} + +fn to_native_manifest(m: &LibraryManifest) -> native::Manifest { + native::Manifest { + id: m.id.clone(), + name: m.name.clone(), + version: m.version, + description: m.description.clone(), + time: m.time, + components: m + .components + .iter() + .map(|a| native::Component { id: a.id.0, name: a.name.clone(), set: a.set, version: a.version, published: a.published }) + .collect(), + styles: m + .styles + .iter() + .map(|s| native::Style { id: s.id.clone(), name: s.name.clone(), kind: s.kind.clone(), version: s.version, published: s.published }) + .collect(), + collections: m + .collections + .iter() + .map(|c| native::Collection { id: c.id.clone(), name: c.name.clone(), version: c.version, published: c.published }) + .collect(), + variables: m + .variables + .iter() + .map(|v| native::Variable { + id: v.id.clone(), + name: v.name.clone(), + collection: v.collection.clone(), + kind: v.kind.clone(), + version: v.version, + published: v.published, + }) + .collect(), + } +} + +fn from_native_manifest(m: native::Manifest) -> LibraryManifest { + LibraryManifest { + id: m.id, + name: m.name, + version: m.version, + description: m.description, + time: m.time, + components: m + .components + .into_iter() + .map(|a| LibraryAsset { id: NodeId(a.id), name: a.name, set: a.set, version: a.version, published: a.published }) + .collect(), + styles: m + .styles + .into_iter() + .map(|s| LibraryStyle { id: s.id, name: s.name, kind: s.kind, version: s.version, published: s.published }) + .collect(), + collections: m + .collections + .into_iter() + .map(|c| LibraryCollection { id: c.id, name: c.name, version: c.version, published: c.published }) + .collect(), + variables: m + .variables + .into_iter() + .map(|v| LibraryVariable { id: v.id, name: v.name, collection: v.collection, kind: v.kind, version: v.version, published: v.published }) + .collect(), + } } /// Write the published library's entries. `written` are the images already in `images/`. -pub(crate) fn write(z: &mut zip::ZipWriter, lib: &PublishedLibrary, written: &BTreeSet<&String>) -> Result<(), FormatError> { - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - put(z, MANIFEST, json_options(), &serde_json::to_vec(&lib.manifest).map_err(io_err)?)?; - put_json(z, SNAPSHOT, &lib.doc)?; - for (hash, img) in &lib.doc.images { - if !written.contains(hash) && ImageData::is_valid_key(hash) { - put(z, &format!("{IMAGES}{hash}"), stored, &img.bytes)?; - } - } - Ok(()) +pub(crate) fn write(z: &mut craft_figcraft_format::ArchiveWriter, lib: &PublishedLibrary, written: &BTreeSet<&String>) -> Result<(), FormatError> { + let already_written = written.iter().map(|hash| (*hash).clone()).collect(); + let images = lib.doc.images.iter().map(|(hash, image)| (hash.as_str(), image.bytes.as_slice())); + native::write_members( + z, + &to_native_manifest(&lib.manifest), + &crate::FiniteValue(&lib.doc), + &crate::native_image_index(&lib.doc), + &already_written, + images, + ) + .map_err(io_err) } /// The published library in an archive (`None` when the file was never published). `own` are /// the images already read from `images/`; what it unpacks comes out of `unpacked` (beyond the /// per-part caps). -pub(crate) fn read( - z: &mut zip::ZipArchive, +pub(crate) fn read( + z: &mut impl craft_figcraft_format::NativeArchive, own: &BTreeMap, unpacked: &mut Unpacked, ) -> Result, FormatError> { - if z.index_for_name(MANIFEST).is_none() { + if !z.contains(native::MANIFEST) { return Ok(None); } - let mut manifest: LibraryManifest = serde_json::from_slice(&unpacked.read(z, MANIFEST, MAX_MANIFEST)?).map_err(corrupt)?; + let wire_manifest = native::read_manifest(&unpacked.read(z, native::MANIFEST, native::MAX_MANIFEST_BYTES)?).map_err(corrupt)?; + let mut manifest = from_native_manifest(wire_manifest); if !is_valid_library_id(&manifest.id) { return Err(corrupt("the library has an invalid id")); } - let text = String::from_utf8(unpacked.read(z, SNAPSHOT, MAX_MEMBER)?).map_err(corrupt)?; - let mut budget = MAX_IMAGE_BYTES; + let text = String::from_utf8(unpacked.read(z, native::DOCUMENT, MAX_MEMBER)?).map_err(corrupt)?; let (mut doc, _) = from_json(&text)?; - for hash in used_images(&doc) { - if !ImageData::is_valid_key(&hash) { - continue; - } - if let Some(img) = own.get(&hash) { - doc.images.insert(hash, img.clone()); - continue; - } - let name = [format!("{IMAGES}{hash}"), format!("images/{hash}")].into_iter().find(|n| z.index_for_name(n).is_some()); - // A missing or oversized image shows as a placeholder, like in any other file. - let Some(data) = name.and_then(|n| unpacked.read(z, &n, budget.min(MAX_MEMBER)).ok()) else { continue }; - budget = budget.saturating_sub(data.len() as u64); + let available: BTreeSet = own.keys().cloned().collect(); + let images = native::read_image_resources(z, used_images(&doc), &available, unpacked); + for (hash, data) in images { doc.images.insert(hash, image_data(data)); } // Keep what the snapshot really holds; clip what people see. @@ -92,8 +150,8 @@ pub(crate) fn read( manifest.styles.retain(|s| styles.contains(s.id.as_str())); manifest.collections.retain(|c| collections.contains(c.id.as_str())); manifest.variables.retain(|v| variables.contains(&(v.id.as_str(), v.collection.as_str()))); - manifest.name = manifest.name.chars().take(MAX_NAME).collect(); - manifest.description = manifest.description.chars().take(MAX_DESCRIPTION).collect(); + manifest.name = native::clip_display(&manifest.name, native::MAX_NAME_CHARS); + manifest.description = native::clip_display(&manifest.description, native::MAX_DESCRIPTION_CHARS); Ok(Some(PublishedLibrary { manifest, doc: Arc::new(doc) })) } @@ -107,7 +165,7 @@ pub fn read_library(r: R) -> Result, Fo /// archive that would unpack to more is refused, or loses the images past it), for libraries from /// people the reader doesn't trust (a server). pub fn read_library_within(r: R, max_bytes: u64) -> Result, FormatError> { - let mut z = zip::ZipArchive::new(r).map_err(corrupt)?; + let mut z = craft_figcraft_format::SeekArchive::open(r, u64::MAX).map_err(corrupt)?; read(&mut z, &BTreeMap::new(), &mut Unpacked::new(max_bytes)) } diff --git a/crates/format/src/penpot/export.rs b/crates/format/src/penpot/export.rs index d0b9d3046..071809cab 100644 --- a/crates/format/src/penpot/export.rs +++ b/crates/format/src/penpot/export.rs @@ -1,5 +1,5 @@ use std::collections::{BTreeMap, BTreeSet}; -use std::io::{Cursor, Write}; +use std::io::Cursor; use figcraft_doc::color::{BlendMode, Color, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind}; use figcraft_doc::geom::kurbo::PathEl; @@ -13,7 +13,7 @@ use figcraft_doc::{ use serde_json::{Map, Value, json}; use super::{ROOT_ID, fingerprint, layout_fingerprint, strokes_fingerprint, text_fingerprint, tokens_fingerprint, uuid}; -use crate::{FormatError, io_err, json_options}; +use crate::{FormatError, io_err}; const DEFAULT_FEATURES: &[&str] = &["fdata/path-data", "design-tokens/v1", "variants/v1", "layout/grid", "components/v2", "fdata/shape-data-type"]; @@ -565,27 +565,19 @@ impl<'a> Exporter<'a> { "files": [{"id": self.file_id, "name": name, "features": file.get("features").cloned().unwrap_or(Value::Null)}], "relations": [], }); - let mut buf = Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let mut put = |path: &str, bytes: &[u8]| -> Result<(), FormatError> { - z.start_file(path, json_options()).map_err(io_err)?; - z.write_all(bytes).map_err(io_err) - }; - put("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?)?; - put(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?)?; - if let Some(tokens) = tokens { - put(&format!("{base}/tokens.json"), tokens.as_bytes())?; - } - for (path, value) in &entries { - put(path, &serde_json::to_vec_pretty(value).map_err(io_err)?)?; - } - for (path, bytes) in &blobs { - put(path, bytes)?; - } - z.finish().map_err(io_err)?; + let mut writer = craft_penpot::Writer::new(); + writer.add("manifest.json", &serde_json::to_vec_pretty(&manifest).map_err(io_err)?).map_err(io_err)?; + writer.add(&format!("{base}.json"), &serde_json::to_vec_pretty(&file).map_err(io_err)?).map_err(io_err)?; + if let Some(tokens) = tokens { + writer.add(&format!("{base}/tokens.json"), tokens.as_bytes()).map_err(io_err)?; } - Ok((buf.into_inner(), self.warnings)) + for (path, value) in &entries { + writer.add(path, &serde_json::to_vec_pretty(value).map_err(io_err)?).map_err(io_err)?; + } + for (path, bytes) in &blobs { + writer.add(path, bytes).map_err(io_err)?; + } + Ok((writer.finish().map_err(io_err)?, self.warnings)) } fn page_json(&self, page: NodeId, page_id: &str, index: usize, background: Color) -> Value { diff --git a/crates/format/src/penpot/export_tests.rs b/crates/format/src/penpot/export_tests.rs index 1e9e95638..e3ad744ef 100644 --- a/crates/format/src/penpot/export_tests.rs +++ b/crates/format/src/penpot/export_tests.rs @@ -1027,3 +1027,19 @@ fn stored_variable_ids_keep_penpot_token_identity() { assert_eq!(width, &expected); } } + +#[test] +fn shared_writer_keeps_manifest_first_and_deflated_members() { + let doc = Document::new("Shared container"); + let (bytes, _) = export(&doc).unwrap(); + let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json"); + for index in 0..zip.len() { + assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated); + } + let archive = craft_penpot::Archive::open(&bytes).unwrap(); + assert_eq!(archive.files.len(), 1); + assert_eq!(archive.files[0].name.as_deref(), Some("Shared container")); + assert_eq!(archive.manifest["generatedBy"], format!("figcraft/{}", env!("CARGO_PKG_VERSION"))); + assert!(import(&bytes).is_ok()); +} diff --git a/crates/format/src/rest.rs b/crates/format/src/rest.rs index 8797d9efa..0b9426ef6 100644 --- a/crates/format/src/rest.rs +++ b/crates/format/src/rest.rs @@ -61,18 +61,18 @@ pub use variables::export as export_variables; pub const MAX_NODES: usize = 200_000; /// Deepest layer nesting followed. const MAX_DEPTH: usize = 256; -/// Private .fig provenance, consumed only by the `.fig` import ([`import_with_networks`]). -pub(crate) const FIG_SOURCE_FIELD: &str = "_figSource"; -/// Hidden .fig library context; accepted only by the `.fig` import ([`import_with_networks`]). -pub(crate) const FIG_LIBRARY_CONTEXTS_FIELD: &str = "_figLibraryContexts"; -/// Ids of mains in a `.fig` file that its layer cap kept out; read only by the `.fig` import. -pub(crate) const FIG_CAPPED_MAINS_FIELD: &str = "_figCappedMains"; +/// The `.fig` mapping's private handoffs, read only by the `.fig` import ([`import_with_networks`]). +pub(crate) use craft_fig::rest::{FIG_CAPPED_MAINS_FIELD, FIG_LIBRARY_CONTEXTS_FIELD, FIG_SOURCE_FIELD}; /// Longest SVG path string read from one geometry entry. const MAX_PATH_BYTES: usize = 4 << 20; /// Most path elements in one vector. const MAX_PATH_ELEMENTS: usize = 200_000; -/// Most distinct warnings reported. -pub(crate) const MAX_WARNINGS: usize = 200; +#[cfg(test)] +pub(crate) use craft_figma_rest::MAX_WARNINGS; +/// Distinct warnings in first-seen order, with repeat counts (at most 200). The +/// import report reads the `(×n)` suffix off before it looks the note up in the catalogue, so a +/// counted note is still translated (`ui-egui`'s `note_text`). +pub(crate) use craft_figma_rest::Warnings; /// Most shared style definitions read. const MAX_STYLES: usize = 10_000; /// Image key used for image fills without an `imageRef`. @@ -348,41 +348,6 @@ fn children(v: &Value) -> &[Value] { v.get("children").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default() } -/// Distinct warnings in first-seen order, with repeat counts. Shared with the `.fig` mapper -/// (`crate::fig::map`), whose notes repeat per layer in the same way. -#[derive(Default)] -pub(crate) struct Warnings { - list: Vec<(String, usize)>, - index: BTreeMap, -} - -impl Warnings { - pub(crate) fn add(&mut self, msg: String) { - if let Some(i) = self.index.get(&msg) { - if let Some(e) = self.list.get_mut(*i) { - e.1 += 1; - } - } else if self.list.len() < MAX_WARNINGS { - self.index.insert(msg.clone(), self.list.len()); - self.list.push((msg, 1)); - } - } - - /// The notes met so far, without their counts, for the tests that ask whether one was met - /// (the product reads them through [`Self::finish`], with the counts). - #[cfg(test)] - pub(crate) fn seen(&self) -> impl Iterator { - self.list.iter().map(|(msg, _)| msg.as_str()) - } - - /// The notes, each with `(×n)` after it where it was met more than once. The import report - /// reads that suffix off before it looks the note up in the catalogue, so a counted note is - /// still translated (`ui-egui`'s `note_text`). - pub(crate) fn finish(self) -> Vec { - self.list.into_iter().map(|(m, n)| if n > 1 { format!("{m} (×{n})") } else { m }).collect() - } -} - /// The coordinate spaces a child is placed in: its parent's (`world`) and that of the nearest /// ancestor that is not a group or boolean (`frame`), both relative to the page. #[derive(Clone, Copy)] diff --git a/crates/format/src/sketch.rs b/crates/format/src/sketch.rs index 182447015..2389813bb 100644 --- a/crates/format/src/sketch.rs +++ b/crates/format/src/sketch.rs @@ -43,48 +43,15 @@ mod tree_tests; use std::collections::BTreeSet; use figcraft_doc::Document; -use serde_json::{Value, json}; +use serde_json::Value; + +// Container parsing is shared; FigCraft document projection remains in this module. +pub(crate) use craft_sketch::Archive; use crate::FormatError; -/// The oldest Sketch whose files open: from 48 on, text is plain JSON too. -pub const MIN_SKETCH: u32 = 48; -/// The newest `meta.json` format version checked against real files (Sketch 83); newer files -/// open with a warning. -pub const NEWEST_TESTED_VERSION: u64 = 139; -/// What opening a file saved by an older Sketch says. -pub const TOO_OLD: &str = "saved by a Sketch older than 48; open it in a newer Sketch and save it again"; -/// Largest JSON member read (a real page of a few thousand layers takes 33 MB). -const MAX_JSON_MEMBER: u64 = 512 * 1024 * 1024; -/// Most bytes a member may unpack to, per compressed byte (real JSON packs 5–20 times and images -/// barely; a zero-filled member a thousand times), with a floor for small members. -const MAX_RATIO: u64 = 100; -const MIN_ALLOWANCE: u64 = 16 * 1024 * 1024; -/// Most JSON read from one file in all. -#[cfg(not(target_pointer_width = "32"))] -const MAX_JSON_TOTAL: u64 = 2 * 1024 * 1024 * 1024; -#[cfg(target_pointer_width = "32")] -const MAX_JSON_TOTAL: u64 = 512 * 1024 * 1024; -/// Largest image member read. -const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES; -/// Most image bytes read from one file in all. -#[cfg(not(target_pointer_width = "32"))] -const MAX_IMAGE_TOTAL: u64 = 1024 * 1024 * 1024; -#[cfg(target_pointer_width = "32")] -const MAX_IMAGE_TOTAL: u64 = 256 * 1024 * 1024; -/// Most pages read from one file. -const MAX_PAGES: usize = 1000; - -/// Whether `bytes` look like a `.sketch` file: a zip holding `document.json` and `meta.json`, or -/// the SQLite database Sketch wrote before version 43 (so that it gets the "too old" message). -pub fn is_sketch(bytes: &[u8]) -> bool { - bytes.starts_with(b"SQLite format 3\0") - || (bytes.starts_with(b"PK") - && zip::ZipArchive::new(std::io::Cursor::new(bytes)).is_ok_and(|z| { - let names: BTreeSet<&str> = z.file_names().collect(); - names.contains("document.json") && names.contains("meta.json") - })) -} +pub use craft_sketch::{MIN_SKETCH, NEWEST_TESTED_VERSION, TOO_OLD, is_sketch}; +const MAX_JSON_MEMBER: u64 = craft_sketch::MAX_JSON_MEMBER; /// Finds the installed face a PostScript name belongs to: its family and style. pub type FontLookup = Box Option<(String, String)>>; @@ -133,7 +100,12 @@ fn import_parts( if bytes.starts_with(b"SQLite format 3\0") { return Err(FormatError::Io(TOO_OLD.into())); } - let archive = Archive::open(bytes, max_member)?; + let archive = + Archive::open_with(bytes, craft_sketch::Limits { max_page: max_member, max_image: figcraft_doc::ImageData::MAX_BYTES, ..Default::default() }) + .map_err(|error| match error { + craft_sketch::Error::TooOld => FormatError::Io(TOO_OLD.into()), + craft_sketch::Error::Corrupt(message) => FormatError::Corrupt(format!("Sketch file: {message}")), + })?; let map = tree::to_rest(&archive, name, max_nodes, fonts); if map.too_old { return Err(FormatError::Io(TOO_OLD.into())); @@ -172,135 +144,3 @@ fn embedded_fonts(document: &Value) -> Option { let list: Vec<&str> = families.iter().map(String::as_str).collect(); Some(format!("the file has embedded fonts FigCraft doesn't use ({}); install them to see the text as designed", list.join(", "))) } - -fn corrupt(msg: impl Into) -> FormatError { - FormatError::Corrupt(format!("Sketch file: {}", msg.into())) -} - -/// The parts of a `.sketch` archive: the document, the pages in document order and the images. -pub(crate) struct Archive<'b> { - pub document: Value, - /// `meta.json`'s format version (0 when missing). - pub version: u64, - /// `(id, page JSON)` in the document's order. - pub pages: Vec<(String, Value)>, - /// Problems met while reading (pages skipped). - pub warnings: Vec, - zip: zip::ZipArchive>, - /// Image bytes read so far. - image_total: std::cell::Cell, -} - -impl<'b> Archive<'b> { - fn open(bytes: &'b [u8], max_member: u64) -> Result { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| corrupt(e.to_string()))?; - let mut total = 0u64; - let meta = json_member(&mut z, "meta.json", MAX_JSON_MEMBER, &mut total)?; - if !meta.is_object() { - return Err(corrupt("meta.json is not an object")); - } - if app_major(&meta).is_some_and(|v| v < MIN_SKETCH) { - return Err(FormatError::Io(TOO_OLD.into())); - } - let mut warnings = Vec::new(); - if meta.get("version").and_then(Value::as_u64).is_some_and(|v| v > NEWEST_TESTED_VERSION) { - warnings.push("the file was saved by a newer Sketch than the import was checked with; some layers may differ".to_string()); - } - // A document.json that can't be read (nested too deep, damaged) loses its shared styles and - // library copies, not the pages: they are then taken in archive order. - let document = match json_member(&mut z, "document.json", MAX_JSON_MEMBER, &mut total) { - Ok(d) if d.is_object() => d, - other => { - let why = other.err().map_or_else(|| "not an object".to_string(), |e| e.to_string()); - warnings.push(format!( - "the document's shared styles and library symbols were skipped: {}", - why.trim_start_matches("not a valid FigCraft file: ") - )); - let pages: Vec = z - .file_names() - .filter_map(|n| n.strip_prefix("pages/")?.strip_suffix(".json")) - .map(|id| json!({"_ref": format!("pages/{id}")})) - .collect(); - json!({"pages": pages}) - } - }; - let refs = document.get("pages").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); - let mut pages = Vec::new(); - let mut seen = std::collections::HashSet::new(); - for r in refs.iter().take(MAX_PAGES) { - let Some(id) = r.get("_ref").and_then(Value::as_str).and_then(|s| s.strip_prefix("pages/")).filter(|id| valid_id(id)) else { - warnings.push("pages the document lists without a valid reference were skipped".into()); - continue; - }; - // A page listed twice is read once: a repeated reference must not repeat the unpacking. - if !seen.insert(id) { - continue; - } - match json_member(&mut z, &format!("pages/{id}.json"), max_member, &mut total) { - Ok(page) if page.is_object() => pages.push((id.to_string(), page)), - Ok(_) => warnings.push("pages that aren't JSON objects were skipped".into()), - Err(e) => warnings.push(format!("a page was skipped: {}", e.to_string().trim_start_matches("not a valid FigCraft file: "))), - } - } - if refs.len() > MAX_PAGES { - warnings.push(format!("the file has more than {MAX_PAGES} pages; the rest were skipped")); - } - let version = meta.get("version").and_then(Value::as_u64).unwrap_or(0); - Ok(Archive { document, version, pages, warnings, zip: z, image_total: std::cell::Cell::new(0) }) - } - - /// The bytes of the image a layer references (`images/`). - pub(crate) fn image(&self, r: &str) -> Option> { - let name = r.strip_prefix("images/").unwrap_or(r); - if !valid_id(name.split('.').next().unwrap_or("")) || name.split('.').count() > 2 { - return None; - } - // A clone shares the parsed directory and the bytes; the resolver only has shared access. - let mut z = self.zip.clone(); - let mut total = self.image_total.get(); - let data = capped_member(&mut z, &format!("images/{name}"), MAX_IMAGE, &mut total, MAX_IMAGE_TOTAL).ok(); - self.image_total.set(total); - data - } -} - -/// Member `name`, refused before unpacking when it would be larger than `limit`, than -/// [`MAX_RATIO`] times what it takes in the archive (past a floor), or than what is left of -/// `max_total` (`total`: read so far, counted up). -fn capped_member( - z: &mut zip::ZipArchive>, - name: &str, - limit: u64, - total: &mut u64, - max_total: u64, -) -> Result, FormatError> { - let (size, packed) = { - let f = z.by_name(name).map_err(|e| corrupt(format!("{name}: {e}")))?; - (f.size(), f.compressed_size()) - }; - let allowed = limit.min(packed.saturating_mul(MAX_RATIO).max(MIN_ALLOWANCE)).min(max_total.saturating_sub(*total)); - if size > allowed { - return Err(corrupt(format!("{name} is too large"))); - } - let data = crate::read_member(z, name, allowed); - // A failed read (a bad checksum at the end, say) unpacked all the same: charged in full, so - // a page list naming the member again can't repeat it within the budget. - *total += data.as_ref().map_or(size, |d| d.len() as u64); - data -} - -/// JSON member `name`, read by [`capped_member`] within the file's [`MAX_JSON_TOTAL`]. -fn json_member(z: &mut zip::ZipArchive>, name: &str, limit: u64, total: &mut u64) -> Result { - let data = capped_member(z, name, limit, total, MAX_JSON_TOTAL)?; - serde_json::from_slice(&data).map_err(|e| corrupt(format!("{name}: {e}"))) -} - -/// The major version of the Sketch that saved the file (`meta.json` `appVersion`, "50.2" → 50). -fn app_major(meta: &Value) -> Option { - meta.get("appVersion").and_then(Value::as_str)?.split('.').next()?.trim().parse().ok() -} - -/// Ids name archive members: letters, digits, `-` and `_` only, never a path. -fn valid_id(id: &str) -> bool { - !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') -} diff --git a/crates/format/src/sketch/tests.rs b/crates/format/src/sketch/tests.rs index d8ace8be9..784c542bd 100644 --- a/crates/format/src/sketch/tests.rs +++ b/crates/format/src/sketch/tests.rs @@ -206,3 +206,21 @@ fn members_over_budget_are_skipped() { assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); assert!(!page_names(&doc).contains(&"Big".to_string())); } + +/// The shared container refuses ambiguous member names instead of selecting one silently. +#[test] +fn duplicate_archive_members_are_refused() { + let mut z = sketch_zip("50.2", 103, document(&["A", "B"]), &[page("A", "Alpha", vec![]), page("B", "Beta", vec![])], &[]); + let from = b"pages/B.json"; + let to = b"pages/A.json"; + let mut replaced = 0; + for i in 0..z.len().saturating_sub(from.len()).saturating_add(1) { + if z.get(i..i + from.len()) == Some(from.as_slice()) { + z[i..i + from.len()].copy_from_slice(to); + replaced += 1; + } + } + assert_eq!(replaced, 2, "local and central directory names changed"); + let error = import(&z, "ambiguous").unwrap_err().to_string(); + assert!(error.contains("two entries of the archive share a name"), "{error}"); +} diff --git a/crates/format/src/streaming_tests.rs b/crates/format/src/streaming_tests.rs new file mode 100644 index 000000000..daf7ecc18 --- /dev/null +++ b/crates/format/src/streaming_tests.rs @@ -0,0 +1,64 @@ +//! The seekable on-disk reader uses the same format and recovery behavior as the byte reader. + +#![cfg(not(target_arch = "wasm32"))] + +use std::sync::Arc; + +use figcraft_doc::{Document, NodeKind}; + +use super::*; + +fn png(red: u8) -> Vec { + let image = image::RgbaImage::from_pixel(2, 2, image::Rgba([red, 0, 0, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +#[test] +fn seekable_reader_matches_byte_reader_for_history_and_branch_archives() { + let mut document = Document::new("Current"); + let current_image = add_image(&mut document, png(10)).unwrap().0; + + let mut older = Document::new("Older"); + let old_image = add_image(&mut older, png(20)).unwrap().0; + let version = Version::new("v1", "Before", "", 1, Arc::new(older.clone())); + + let mut head = document.clone(); + let page = head.first_page().unwrap(); + head.create(page, NodeKind::Rectangle, "Branch shape", 1.0, 2.0, 3.0, 4.0).unwrap(); + add_image(&mut head, png(30)).unwrap(); + let branch = Branch { + id: "b1".into(), + name: "Explore".into(), + time: 2, + client: 4, + state: BranchState::Active, + base: Arc::new(document.clone()), + versions: vec![Version::new("v2", "Branch base", "", 3, Arc::new(document.clone()))], + head: Arc::new(head), + }; + + let bytes = save_bytes_with_history(&document, None, &[version], &[branch]).unwrap(); + let from_bytes = load_bytes_with_versions(&bytes).unwrap(); + assert_eq!(from_bytes.versions.len(), 1); + assert_eq!(from_bytes.branches.len(), 1); + assert!(from_bytes.doc.images.contains_key(¤t_image)); + assert!(from_bytes.versions[0].images().contains_key(&old_image)); + + let path = std::env::temp_dir().join(format!("figcraft-stream-reader-{}.figcraft", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + let from_file = load_file(&path).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(from_file, (from_bytes.doc, from_bytes.issues)); +} + +#[test] +fn seekable_reader_keeps_newer_document_error_precedence() { + let bytes = crate::zip_files([("document.json", br#"{"version":999,"document":["malformed"]}"#.as_slice())]).unwrap(); + let path = std::env::temp_dir().join(format!("figcraft-stream-newer-{}.figcraft", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + let result = load_file(&path); + let _ = std::fs::remove_file(&path); + assert!(matches!(result, Err(FormatError::Newer(999)))); +} diff --git a/crates/format/src/thumbnail.rs b/crates/format/src/thumbnail.rs index 530038095..d60cd8883 100644 --- a/crates/format/src/thumbnail.rs +++ b/crates/format/src/thumbnail.rs @@ -7,13 +7,12 @@ use std::io::{Read, Seek}; use std::path::Path; /// Largest `thumbnail.png` read from an archive. -pub const MAX_THUMBNAIL_BYTES: u64 = 8 * 1024 * 1024; +pub const MAX_THUMBNAIL_BYTES: u64 = craft_figcraft_format::MAX_PREVIEW_THUMBNAIL_BYTES; /// Largest image file read as its own picture. pub const MAX_IMAGE_FILE_BYTES: u64 = 32 * 1024 * 1024; /// Widest or tallest picture decoded (pixels); a larger one gives none. pub const MAX_THUMBNAIL_SIDE: u32 = 8192; -/// Largest `document.json` read for its page colour, and `.fig` `meta.json`. -const MAX_DOCUMENT_BYTES: u64 = 64 * 1024 * 1024; +/// Largest `.fig` `meta.json` read for its page colour. const MAX_META_BYTES: u64 = 1024 * 1024; /// Most memory one decode may take. const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024; @@ -29,8 +28,7 @@ pub struct Thumbnail { /// The bytes of `thumbnail.png` in a zip archive (`.figcraft`, `.fig`); `None` when it isn't a zip, /// has no thumbnail, or the thumbnail is larger than [`MAX_THUMBNAIL_BYTES`]. pub fn thumbnail_png(archive: R) -> Option> { - let mut z = zip::ZipArchive::new(archive).ok()?; - crate::read_member(&mut z, "thumbnail.png", MAX_THUMBNAIL_BYTES).ok() + craft_figcraft_format::read_preview_thumbnail(archive).ok().flatten() } /// The bytes of `previews/preview.png` in a `.sketch` zip; `None` as [`thumbnail_png`] gives it. @@ -148,35 +146,26 @@ pub fn file_preview(path: &Path, fit: u32) -> Preview { /// The [`Preview`] of a `.figcraft` or `.fig` archive: `thumbnail.png`, and the first page's colour /// from `document.json` (`.figcraft`) or `meta.json` (`.fig`). pub fn archive_preview(archive: R, fit: u32) -> Preview { - let Ok(mut z) = zip::ZipArchive::new(archive) else { return Preview::default() }; - let picture = crate::read_member(&mut z, "thumbnail.png", MAX_THUMBNAIL_BYTES).ok().and_then(|png| decode_thumbnail(&png, fit)); - let (page, kind) = if z.file_names().any(|n| n == "document.json") { - crate::read_member(&mut z, "document.json", MAX_DOCUMENT_BYTES).ok().map(|json| figcraft_page(&json)).unwrap_or_default() + let Ok(mut z) = craft_figcraft_format::SeekArchive::open(archive, u64::MAX) else { return Preview::default() }; + let native = craft_figcraft_format::read_preview_archive_from(&mut z); + let picture = native.thumbnail_png.and_then(|png| decode_thumbnail(&png, fit)); + let (page, kind) = if native.has_document { + native.document.as_ref().map(figcraft_page).unwrap_or_default() } else { - (crate::read_member(&mut z, "meta.json", MAX_META_BYTES).ok().and_then(|json| fig_page(&json)), figcraft_doc::FileKind::Design) + let meta = z.read("meta.json", MAX_META_BYTES).ok().flatten(); + (meta.as_deref().and_then(fig_page), figcraft_doc::FileKind::Design) }; Preview { page, picture, kind } } /// The first page's background in a `.figcraft` `document.json`, and the file's kind. -fn figcraft_page(json: &[u8]) -> (Option<[f32; 4]>, figcraft_doc::FileKind) { - #[derive(serde::Deserialize)] - struct Head { - #[serde(default)] - pages: Vec, - #[serde(default)] - nodes: std::collections::BTreeMap, - #[serde(default)] - kind: figcraft_doc::FileKind, - } - #[derive(serde::Deserialize)] - struct Node { - #[serde(default)] - background: Option, - } - let Ok(head) = serde_json::from_slice::(json) else { return (None, figcraft_doc::FileKind::Design) }; +fn figcraft_page(head: &craft_figcraft_format::PreviewDocument) -> (Option<[f32; 4]>, figcraft_doc::FileKind) { let page = head.pages.first().and_then(|first| head.nodes.get(&first.to_string())).and_then(|n| n.background.as_ref()).and_then(rgba); - (page, head.kind) + let kind = match head.kind { + craft_figcraft_format::PreviewKind::Design => figcraft_doc::FileKind::Design, + craft_figcraft_format::PreviewKind::Board => figcraft_doc::FileKind::Board, + }; + (page, kind) } /// The canvas colour a `.fig` file's `meta.json` gives (`client_meta.background_color`). diff --git a/crates/format/src/unpacked_total_tests.rs b/crates/format/src/unpacked_total_tests.rs index 92db654e5..1aa47c5b3 100644 --- a/crates/format/src/unpacked_total_tests.rs +++ b/crates/format/src/unpacked_total_tests.rs @@ -108,8 +108,8 @@ fn a_read_that_fails_part_way_still_spends_the_total() { let mut bytes = buf.into_inner(); let at = 30 + "snapshots/v1.json".len() + body.len() / 2; bytes[at] ^= 0xff; - let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); - let size = z.by_name("snapshots/v1.json").unwrap().size(); + let mut z = craft_figcraft_format::SeekArchive::open(std::io::Cursor::new(bytes), u64::MAX).unwrap(); + let size = z.declared_size("snapshots/v1.json").unwrap(); assert_eq!(size, body.len() as u64); let mut total = crate::Unpacked::new(size + size / 2); assert!(total.read(&mut z, "snapshots/v1.json", 1 << 20).is_err(), "the damaged member fails"); diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 59b4ee818..3e82b1865 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -187,4 +187,30 @@ mod tests { assert!(out.contains(&bomb)); assert!(out.len() < 3 * bomb.len(), "{}", out.len()); } + + /// Every command the server's instructions and the prompts name exists: an agent told to run a + /// renamed or misspelt one gets an error instead of the workflow. + #[test] + fn the_commands_the_instructions_and_prompts_name_exist() { + let ids: Vec<&str> = figcraft_engine::all_commands().iter().map(|c| c.id).collect(); + let namespaces: Vec<&str> = ids.iter().filter_map(|id| id.split('.').next()).collect(); + let texts = std::iter::once(crate::INSTRUCTIONS).chain(PROMPTS.iter().map(|p| p.template)); + let mut named = 0; + for text in texts { + for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '.')).map(|w| w.trim_end_matches('.')) { + let Some((ns, rest)) = word.split_once('.') else { continue }; + // wait_for_changes events, which the prompts name too. + let event = matches!(word, "comment.added" | "comment.replied"); + if event || rest.is_empty() || !rest.starts_with(|c: char| c.is_ascii_lowercase()) || !namespaces.contains(&ns) { + continue; + } + named += 1; + assert!(ids.contains(&word), "`{word}` is not a command"); + } + } + assert!(named > 10, "the check found the command ids ({named})"); + for id in ["component.create", "instance.create", "component.addProperty", "instance.setProperties", "component.combineVariants"] { + assert!(crate::INSTRUCTIONS.contains(id), "the instructions name {id}"); + } + } } diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 70ac05999..58eb6b2e2 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -36,7 +36,16 @@ reports both x/y relative to the parent frame (groups don't count) and absoluteB positioned by the layout (set layout, gap, padding, mainAlign, crossAlign, sizingH/sizingV instead). \ Every menu item, panel action and shortcut is a command: find ids and params with list_commands (use a filter) \ and run them with run_command, or several as one undo step with batch. Commands act on `ids` when given, else \ -on the selection; new layers become the selection. Colours are \"#RRGGBB\" or \"#RRGGBBAA\". Verify your work: \ +on the selection; new layers become the selection. Colours are \"#RRGGBB\" or \"#RRGGBBAA\". \ +Repeated UI (buttons, inputs, cards, list rows, tab bars, icons) is a component: build it once, make it one with \ +component.create (or create_node type component), then place every other copy with \ +instance.create {component, parent?, x?, y?} instead of duplicating layers, so every copy follows its main component. \ +States and sizes are variants of one set: name the mains Property=value (State=Default, State=Hover) and run \ +component.combineVariants on them; component.addVariant {id} adds one more. What changes from copy to copy is a \ +component property: component.addProperty {id, name, type: text|boolean|instanceSwap, layer} on the component (on the \ +set once its variants are combined, then component.bindProperty {layer, property} for each other variant's layer), and \ +instance.setProperties {ids, properties} sets it on each copy. get_node shows whether a layer is an instance and of \ +which main. Verify your work: \ inspect_document / get_node return the layer tree as JSON (check sizes, fills, layout, overrides), and \ screenshot returns a PNG of the page or of given layers to look at. undo/redo step through history. \ Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \ diff --git a/crates/render/src/band_tests.rs b/crates/render/src/band_tests.rs index 6cdf2cd88..630f48bce 100644 --- a/crates/render/src/band_tests.rs +++ b/crates/render/src/band_tests.rs @@ -163,3 +163,75 @@ fn huge_backdrop_blur_renders_in_one_piece() { assert!(render_bands(&d, p, &view(1.0), &Options::default(), 4).is_none()); assert!(render_view(&d, p, &view(1.0), &Options::default()).is_some()); } + +/// [`row_diffs`] down the columns: an artifact of column bands runs down a whole column. +fn col_diffs(a: &Pixmap, b: &Pixmap) -> Vec<(f64, usize)> { + let (w, h) = (a.width() as usize, a.height() as usize); + let column = |p: &Pixmap, x: usize| -> Vec { (0..h).flat_map(|y| p.data()[(y * w + x) * 4..(y * w + x) * 4 + 4].to_vec()).collect() }; + (0..w).map(|x| row_stats(&column(a, x), &column(b, x))).collect() +} + +#[test] +fn columns_match_one_piece_rendering() { + let (d, p) = scene(true, true); + for scale in [1.0, 2.0] { + let v = view(scale); + let one = render_view_single(&d, p, &v, &Options::default()).unwrap(); + for bands in [2, 3, 7] { + let banded = render_columns(&d, p, &v, &Options::default(), bands).unwrap(); + assert_eq!((banded.width(), banded.height()), (one.width(), one.height())); + for (x, (mean, off)) in col_diffs(&one, &banded).into_iter().enumerate() { + assert!( + row_ok(mean, off, v.height as usize), + "scale {scale}, {bands} columns: column {x} differs ({off} pixels, {mean:.2} on average)" + ); + } + } + } + let (mut d, p) = scene(true, true); + let g = d.find_by_name("Glass", None)[0]; + d.get_mut(g).unwrap().effects = vec![Effect { kind: EffectKind::BackgroundBlur(figcraft_doc::Blur::uniform(1e6)), visible: true }]; + assert!(render_columns(&d, p, &view(1.0), &Options::default(), 4).is_none(), "a blur past a whole column: in one piece"); +} + +/// The strips a pan uncovers render in bands along their longer side, and match one piece: no row +/// or column where a band's edge shows (a seam differs along all of it). A strip is too narrow for +/// [`row_ok`]'s mean: the edge antialiasing every band render has (a few pixels along a curve) +/// outweighs it there, so this counts the pixels that differ at all. +#[test] +fn a_tall_or_wide_part_of_a_view_matches_one_piece_rendering() { + let (d, p) = scene(true, true); + for (w, h) in [(60, 480), (880, 60), (200, 200)] { + let v = View { origin: (35.0, -10.0), scale: 2.0, width: w, height: h }; + let one = render_view_single(&d, p, &v, &Options::default()).unwrap(); + let part = render_part(&d, p, &v, &Options::default()).unwrap(); + assert_eq!((part.width(), part.height()), (w, h)); + for (y, (_, off)) in row_diffs(&one, &part).into_iter().enumerate() { + assert!(off * 20 <= w as usize, "{w} x {h}: row {y} differs in {off} pixels"); + } + for (x, (_, off)) in col_diffs(&one, &part).into_iter().enumerate() { + assert!(off * 20 <= h as usize, "{w} x {h}: column {x} differs in {off} pixels"); + } + } +} +/// A textured layer scatters its pixels up to the texture's radius, past where a band cuts the +/// view; it is drawn off screen whole before it is cut, so column and row bands show it exactly as +/// one piece does, clipped to its shape or not. +#[test] +fn a_textured_layer_renders_the_same_in_bands() { + for clip_to_shape in [false, true] { + let mut d = Document::new("texture"); + let p = d.first_page().unwrap(); + let r = d.create(p, NodeKind::Rectangle, "T", 20.0, 20.0, 400.0, 200.0).unwrap(); + let n = d.get_mut(r).unwrap(); + n.fills = vec![Paint::solid(Color::from_hex("E03030").unwrap())]; + let texture = figcraft_doc::Texture { size: 0.5, radius: 12.0, clip_to_shape, ..Default::default() }; + n.effects = vec![Effect { kind: EffectKind::Texture(texture), visible: true }]; + let v = View { origin: (0.0, 0.0), scale: 1.7, width: 760, height: 400 }; + let one = render_view_single(&d, p, &v, &Options::default()).unwrap(); + for bands in [2, 3, 7] { + assert!(render_columns(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} columns"); + assert!(render_bands(&d, p, &v, &Options::default(), bands).unwrap().data() == one.data(), "{bands} rows"); + } + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6700fbc72..8d0710cda 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -138,6 +138,58 @@ pub fn render_view(doc: &Document, page: NodeId, view: &View, opts: &Options) -> render_one(doc, page, view, opts) } +/// [`render_view`] for a part of a view a retained render redraws (the strips a pan uncovers, the +/// area of an edit): in parallel bands however few pixels it has, along its longer side (rows of a +/// tall strip, columns of a wide one), since what it costs is the layers it crosses (a shadow is +/// drawn whole for a sliver of it), not its pixels. +pub(crate) fn render_part(doc: &Document, page: NodeId, view: &View, opts: &Options) -> Option { + start_render(); + #[cfg(not(target_arch = "wasm32"))] + if let Some(pool) = band_pool() { + let threads = pool.current_num_threads().clamp(1, 16) as u32; + let rendered = if view.height >= view.width { + let bands = threads.min(view.height / 96); + (bands > 1).then(|| pool.install(|| render_bands(doc, page, view, opts, bands))).flatten() + } else { + let bands = threads.min(view.width / 96); + (bands > 1).then(|| pool.install(|| render_columns(doc, page, view, opts, bands))).flatten() + }; + if rendered.is_some() { + return rendered; + } + } + render_one(doc, page, view, opts) +} + +/// [`render_bands`] across: `bands` columns, overlapping by what background blurs read. +#[cfg(not(target_arch = "wasm32"))] +fn render_columns(doc: &Document, page: NodeId, view: &View, opts: &Options, bands: u32) -> Option { + use rayon::prelude::*; + let band_w = view.width.div_ceil(bands.max(1)); + let overlap = band_overlap(doc, view, band_w)?; + let s = view.scale.max(1e-9); + let parts: Vec<(u32, Option)> = (0..bands) + .into_par_iter() + .map(|i| { + let x0 = i * band_w; + let w = band_w.min(view.width.saturating_sub(x0)).max(1); + let left = x0.saturating_sub(overlap); + let right = (x0 + w + overlap).min(view.width).max(x0 + w); + let v = + View { origin: (view.origin.0 + f64::from(left) / s, view.origin.1), scale: view.scale, width: right - left, height: view.height }; + let own = tiny_skia::IntRect::from_xywh((x0 - left) as i32, 0, w, view.height.clamp(1, 16_384)); + (x0, render_one(doc, page, &v, opts).zip(own).and_then(|(p, r)| p.clone_rect(r))) + }) + .collect(); + let mut out = new_pixmap(view.width, view.height)?; + let copy = tiny_skia::PixmapPaint { blend_mode: tiny_skia::BlendMode::Source, ..Default::default() }; + for (x0, part) in parts { + let part = part?; + out.draw_pixmap(x0 as i32, 0, part.as_ref(), ©, tiny_skia::Transform::identity(), None); + } + Some(out) +} + /// The stack a thread that renders needs (#1082). A level of the layer tree takes about 6.5 KB of /// stack in a render (6.8 KB in a debug build), so the deepest render [`MAX_EXPORT_DEPTH`] allows, /// pattern sources included, needs about 1.7 MB: more than the 2 MiB threads get by default once @@ -590,6 +642,8 @@ mod mask_bounds_tests; #[cfg(test)] mod paint_behaviour_tests; #[cfg(test)] +mod pan_bench_tests; +#[cfg(test)] mod progressive_tests; #[cfg(test)] mod render_depth_tests; diff --git a/crates/render/src/pan_bench_tests.rs b/crates/render/src/pan_bench_tests.rs new file mode 100644 index 000000000..aca3d60ad --- /dev/null +++ b/crates/render/src/pan_bench_tests.rs @@ -0,0 +1,62 @@ +//! Pan render timings: a page of 60 × 60 cards, each with a drop shadow and an inner shadow, seen +//! at 100% through a 1600 × 1100 device-pixel view. Run in release: +//! `cargo test --release -p figcraft-render --lib pan_render_timings -- --ignored --nocapture`. +//! +//! "full" renders the whole view; "pan" rows go through `Retained` as the canvas does, each step +//! moving the view by `step` device pixels and redrawing only the strips it uncovers. + +use std::sync::Arc; +use std::time::Instant; + +use figcraft_color::{Color, Paint}; +use figcraft_doc::{Document, Effect, EffectKind, NodeId, NodeKind, Shadow}; + +use crate::{Options, Retained, View, render_view}; + +const STEPS: u32 = 12; + +/// The cards: (document, page). +fn cards() -> (Arc, NodeId) { + let mut d = Document::new("pan bench"); + let p = d.first_page().unwrap(); + for y in 0..60u32 { + for x in 0..60u32 { + let c = d.create(p, NodeKind::Rectangle, "Card", f64::from(x) * 140.0, f64::from(y) * 110.0, 120.0, 90.0).unwrap(); + let n = d.get_mut(c).unwrap(); + n.fills = vec![Paint::solid(Color::new(x as f32 / 60.0, y as f32 / 60.0, 0.7, 1.0))]; + n.corners.radii = [12.0; 4]; + n.effects = vec![ + Effect { kind: EffectKind::DropShadow(Shadow { radius: 18.0, offset: (0.0, 6.0), ..Shadow::default() }), visible: true }, + Effect { kind: EffectKind::InnerShadow(Shadow { radius: 8.0, ..Shadow::default() }), visible: true }, + ]; + } + } + (Arc::new(d), p) +} + +fn view(origin: (f64, f64)) -> View { + View { origin, scale: 1.0, width: 1600, height: 1100 } +} + +#[test] +#[ignore = "timing; run in release with --ignored --nocapture"] +fn pan_render_timings() { + let (d, p) = cards(); + let opts = Options { lod: true, ..Options::default() }; + let t0 = Instant::now(); + for _ in 0..4 { + render_view(&d, p, &view((1000.0, 1000.0)), &opts).unwrap(); + } + println!("full: {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0 / 4.0); + for (name, step) in [("pan right", (60.0, 0.0)), ("pan down", (0.0, 60.0)), ("pan diagonally", (60.0, 24.0)), ("pan right fast", (240.0, 0.0))] { + let mut r = Retained::default(); + let mut at = (1000.0, 1000.0); + r.render(&d, p, &view(at), &opts).unwrap(); + let t0 = Instant::now(); + for _ in 0..STEPS { + at = (at.0 + step.0, at.1 + step.1); + r.render(&d, p, &view(at), &opts).unwrap(); + } + println!("{name} ({:?} px a step): {:.1} ms a step", step, t0.elapsed().as_secs_f64() * 1000.0 / f64::from(STEPS)); + } +} diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index f345e21d6..e8a711fc6 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -553,7 +553,7 @@ fn render_into(frame: FrameRender<'_>, d: &Px, margin: i64, pix: &mut Pixmap) -> let (rw, rh) = (u32::try_from(ex - ox).ok()?, u32::try_from(ey - oy).ok()?); // The same pixel grid as the frame: origin (px + offset) / scale. let sub = View { origin: ((px.0 + ox) as f64 / s, (px.1 + oy) as f64 / s), scale: s, width: rw, height: rh }; - let part = render_view(doc, page, &sub, opts)?; + let part = crate::render_part(doc, page, &sub, opts)?; let inner = IntRect::from_xywh( i32::try_from(d.x0 - ox).ok()?, i32::try_from(d.y0 - oy).ok()?, diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index d248bdf07..57f578249 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -9,6 +9,7 @@ description = "FigCraft SVG export (shapes, gradients, images, strokes, effects workspace = true [dependencies] +craft-xml = { workspace = true } figcraft-geom = { workspace = true } figcraft-color = { workspace = true } figcraft-doc = { workspace = true } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 680f0eb4a..97c8ba0f7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -195,16 +195,9 @@ fn blend_style(b: figcraft_color::BlendMode) -> String { } } -/// `s` escaped for XML text and attribute values; characters XML 1.0 forbids (control characters -/// other than tab, newline and carriage return, U+FFFE and U+FFFF) are left out. -fn esc(s: &str) -> String { - s.chars().filter(|&c| xml_char(c)).collect::().replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) -} - -/// Whether XML 1.0 allows `c` (see [`esc`]). -fn xml_char(c: char) -> bool { - !matches!(c, '\u{0}'..='\u{8}' | '\u{b}' | '\u{c}' | '\u{e}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}') -} +// Shared XML wire escaping and character validity; layer-name policy stays below. +// Attribute escaping also preserves tabs/LF/CR through XML readers' whitespace normalization. +use craft_xml::{esc_attr as esc, is_xml_char as xml_char}; fn hex(c: Color) -> String { format!("#{}", c.to_hex()) diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 8bce898da..e2a262890 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -451,3 +451,15 @@ fn a_whole_ellipse_drawn_backwards_keeps_its_simple_stroke() { assert_eq!(backwards, forwards, "{align:?}"); } } + +#[test] +fn shared_xml_escaping_keeps_markup_controls_and_attribute_whitespace() { + let input = "A<&\"'\t\n\r\u{1}\u{fffe}🦊"; + assert_eq!(super::esc(input), "A<&"' 🦊"); + let markup = format!("", super::esc(input)); + let root = craft_xml::parse(markup.as_bytes()).unwrap(); + assert_eq!(root.attr("label"), Some("A<&\"'\t\n\r🦊")); + for c in ['\0', '\u{b}', '\u{fffe}', '\u{ffff}'] { + assert!(!super::xml_char(c)); + } +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 65df051e7..f5774307e 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -555,7 +555,7 @@ fn names(f: &skrifa::FontRef) -> (Option, Option) { /// document: the browser has no other fonts. The symbol fonts come last: Apple Symbols (macOS), /// Segoe UI Symbol (Windows) and the Noto symbol and math fonts (Linux), for signs such as ⌖ and ⤒ /// that no text face has. -const FALLBACK_FAMILIES: [&str; 32] = [ +const FALLBACK_FAMILIES: [&str; 33] = [ "Inter", "Helvetica Neue", "Arial", @@ -563,6 +563,7 @@ const FALLBACK_FAMILIES: [&str; 32] = [ "DejaVu Sans", "Noto Sans", "BIZ UDPGothic", + "Noto Sans JP", "Hiragino Sans", "PingFang SC", "Hiragino Sans GB", diff --git a/crates/text/src/fontdb_tests.rs b/crates/text/src/fontdb_tests.rs index bf459fe06..2585ced73 100644 --- a/crates/text/src/fontdb_tests.rs +++ b/crates/text/src/fontdb_tests.rs @@ -604,6 +604,7 @@ fn every_embeddable_script_face_is_a_document_fallback() { "Noto Sans Hebrew", "Noto Sans Devanagari", "Noto Sans Georgian", + "Noto Sans JP", "Noto Sans Symbols", "Noto Sans Symbols 2", ] { diff --git a/crates/ui-egui/locales/bs.toml b/crates/ui-egui/locales/bs.toml index e8d2c38c0..f533632fc 100644 --- a/crates/ui-egui/locales/bs.toml +++ b/crates/ui-egui/locales/bs.toml @@ -1739,7 +1739,7 @@ status = "draft — needs native review" "duplicate grid track sizing entries use equal tracks" = "duplirani unosi veličina traka mreže koriste jednake trake" "e.g. count + 1" = "npr. count + 1" "e.g. count >= 3 and not done" = "npr. count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "kutni i zakrivljeni konektori bez sačuvane putanje slijede FigCraftovo vlastito usmjeravanje" +"elbowed and curved connectors without a saved path are routed afresh" = "kutni i zakrivljeni konektori bez sačuvane putanje slijede FigCraftovo vlastito usmjeravanje" "entries without a node type were skipped" = "unosi bez vrste čvora su preskočeni" "figcraft:// links from a browser, chat or email open this app and join the session." = "figcraft:// linkovi iz preglednika, chata ili e-pošte otvaraju ovu aplikaciju i pridružuju se sesiji." "from {server}" = "sa servera {server}" diff --git a/crates/ui-egui/locales/de.toml b/crates/ui-egui/locales/de.toml index 91d24ced1..0c0ad0f24 100644 --- a/crates/ui-egui/locales/de.toml +++ b/crates/ui-egui/locales/de.toml @@ -1948,7 +1948,7 @@ status = "draft — needs native review" "Your unsaved files were too large for the browser to keep." = "Ihre ungespeicherten Dateien waren zu groß, als dass der Browser sie behalten konnte." "Z to A" = "Z bis A" "connector labels without a saved snapshot are centred on the line, without their background" = "Verbinder-Beschriftungen ohne gespeicherten Schnappschuss werden mittig auf der Linie und ohne Hintergrund dargestellt" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "Abgewinkelte und gebogene Verbinder ohne gespeicherten Pfad folgen dem eigenen Routing von FigCraft" +"elbowed and curved connectors without a saved path are routed afresh" = "Abgewinkelte und gebogene Verbinder ohne gespeicherten Pfad folgen dem eigenen Routing von FigCraft" "instance swap properties whose default component was past the layer limit were skipped" = "Instanztausch-Eigenschaften, deren Standardkomponente über dem Ebenenlimit lag, wurden übersprungen" "instances whose component was past the layer limit were imported as frames" = "Instanzen, deren Komponente über dem Ebenenlimit lag, wurden als Rahmen importiert" "invalid vector region fill paint list; layer fill used" = "Ungültige Füllungsliste der Vektorregion; Füllung der Ebene verwendet" diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 769ac7a1d..47db9eab4 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -961,6 +961,7 @@ name = "English" "Nested instance" = "Nested instance" "New board" = "New board" "New design file" = "New design file" +"New from selection" = "New from selection" "Newest first" = "Newest first" "Next or previous control in the focused region" = "Next or previous control in the focused region" "Next frame" = "Next frame" @@ -1405,6 +1406,7 @@ name = "English" "Server for online sharing" = "Server for online sharing" "Server key" = "Server key" "Set as default" = "Set as default" +"Set as opening page" = "Set as opening page" "Set corner smoothing to 60%" = "Set corner smoothing to 60%" "Set variable" = "Set variable" "Set variable mode" = "Set variable mode" @@ -1822,7 +1824,7 @@ name = "English" "duplicate grid track sizing entries use equal tracks" = "duplicate grid track sizing entries use equal tracks" "e.g. count + 1" = "e.g. count + 1" "e.g. count >= 3 and not done" = "e.g. count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "elbowed and curved connectors without a saved path follow FigCraft's own routing" +"elbowed and curved connectors without a saved path are routed afresh" = "elbowed and curved connectors without a saved path are routed afresh" "entries without a node type were skipped" = "entries without a node type were skipped" "figcraft:// links from a browser, chat or email open this app and join the session." = "figcraft:// links from a browser, chat or email open this app and join the session." "from {server}" = "from {server}" @@ -1891,7 +1893,6 @@ name = "English" "set-variable actions without a value were skipped" = "set-variable actions without a value were skipped" "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" "shape generated outline is missing or damaged; using its rectangle" = "shape generated outline is missing or damaged; using its rectangle" -"shape with text layers import as frames with their text" = "shape with text layers import as frames with their text" "slot content assignment target is missing or is not slot content" = "slot content assignment target is missing or is not slot content" "slot content assignment uses the empty GUID sentinel and was skipped" = "slot content assignment uses the empty GUID sentinel and was skipped" "slot layers without a matching slot property were imported as frames" = "slot layers without a matching slot property were imported as frames" @@ -1901,6 +1902,7 @@ name = "English" "stars and polygons without point counts or geometry use the default point count" = "stars and polygons without point counts or geometry use the default point count" "sticky layers import as frames with their text" = "sticky layers import as frames with their text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "style settings of some vector segments aren't supported; those segments use the layer's stroke" +"swapped instances whose previous component isn't in the file took the new component's look" = "swapped instances whose previous component isn't in the file took the new component's look" "text path underline or strikethrough decoration is not rendered" = "text path underline or strikethrough decoration is not rendered" "text style overrides refer to missing table entries" = "text style overrides refer to missing table entries" "the file has no pages" = "the file has no pages" diff --git a/crates/ui-egui/locales/fi.toml b/crates/ui-egui/locales/fi.toml index 80a405261..a780166e3 100644 --- a/crates/ui-egui/locales/fi.toml +++ b/crates/ui-egui/locales/fi.toml @@ -1789,7 +1789,7 @@ status = "draft — needs native review" "duplicate grid track sizing entries use equal tracks" = "päällekkäiset ruudukon kokomääritykset käyttävät tasakokoisia osia" "e.g. count + 1" = "esim. count + 1" "e.g. count >= 3 and not done" = "esim. count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "kulmikkaat ja kaarevat yhdistimet, joilla ei ole tallennettua polkua, seuraavat FigCraftin omaa reititystä" +"elbowed and curved connectors without a saved path are routed afresh" = "kulmikkaat ja kaarevat yhdistimet, joilla ei ole tallennettua polkua, seuraavat FigCraftin omaa reititystä" "entries without a node type were skipped" = "kohteet, joilta puuttuu solmutyyppi, ohitettiin" "figcraft:// links from a browser, chat or email open this app and join the session." = "selaimen, keskustelun tai sähköpostin figcraft://-linkit avaavat tämän sovelluksen ja liittyvät istuntoon." "from {server}" = "palvelimelta {server}" diff --git a/crates/ui-egui/locales/ka.toml b/crates/ui-egui/locales/ka.toml index fdd8a6f1b..19b86ef4e 100644 --- a/crates/ui-egui/locales/ka.toml +++ b/crates/ui-egui/locales/ka.toml @@ -1783,7 +1783,7 @@ status = "draft — reviewed by a native speaker, awaiting a maintainer's approv "duplicate grid track sizing entries use equal tracks" = "ბადის ტრეკის ზომის დუბლირებული ჩანაწერებისას ტრეკები თანაბარია" "e.g. count + 1" = "მაგ. count + 1" "e.g. count >= 3 and not done" = "მაგ. count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "შენახული ტრაექტორიის გარეშე კუთხოვანი და მრუდი შემაერთებლები FigCraft-ის საკუთარ მარშრუტს მიჰყვება" +"elbowed and curved connectors without a saved path are routed afresh" = "შენახული ტრაექტორიის გარეშე კუთხოვანი და მრუდი შემაერთებლები FigCraft-ის საკუთარ მარშრუტს მიჰყვება" "entries without a node type were skipped" = "კვანძის ტიპის გარეშე ჩანაწერები გამოტოვებულია" "figcraft:// links from a browser, chat or email open this app and join the session." = "ბრაუზერიდან, ჩატიდან ან ელფოსტიდან figcraft:// ბმულები ხსნის ამ აპს და უერთდება სესიას." "from {server}" = "წყარო: {server}" diff --git a/crates/ui-egui/locales/sv.toml b/crates/ui-egui/locales/sv.toml index a64458182..43fa665dc 100644 --- a/crates/ui-egui/locales/sv.toml +++ b/crates/ui-egui/locales/sv.toml @@ -22,6 +22,7 @@ name = "Svenska" "A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "En samling i den här filen med dessa lägen och variabler: ange overrides för deras värden per läge och lägg till egna variabler" "A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "Det finns redan en .figcraft-fil med det här namnet. Välj dess fullständiga namn för att bekräfta att den ersätts." "A later vote" = "En senare omröstning" +"A layer in an auto layout frame is placed by its frame" = "Ett lager i en auto layout-frame placeras av framen" "A layer on its own aligns to its frame: select more layers, or one in a frame" = "Ett ensamt lager justeras mot sin frame: markera fler lager, eller ett lager i en frame" "A responsive product page: hero, features, figures, a quote and a footer" = "En responsiv produktsida: toppsektion, funktioner, figurer, ett citat och en sidfot" "A spring plays until it settles: its mass, stiffness and damping set how long" = "En fjäder spelas tills den stannar: dess massa, styvhet och dämpning avgör hur länge" @@ -123,6 +124,7 @@ name = "Svenska" "Android Vector Drawable" = "Android Vector Drawable" "Angular" = "Vinkelmått" "Animation" = "Animering" +"Annotation" = "Anteckning" "Annotations" = "Annoteringar" "Annotations shown on the canvas" = "Annoteringar som visas på arbetsytan" "Another server, or one that needs its key. The usual server is set in Preferences." = "En annan server, eller en som kräver sin nyckel. Standardservern anges i Inställningar." @@ -522,6 +524,7 @@ name = "Svenska" "Duo" = "Duo" "Duplicate" = "Duplicera" "Duplicate by dragging" = "Duplicera genom att dra" +"Duplicate group" = "Duplicera grupp" "Duplicate mode" = "Duplicera läge" "Duplicate page" = "Duplicera sida" "Edit" = "Redigera" @@ -534,6 +537,9 @@ name = "Svenska" "Edit padding on all sides" = "Redigera padding på alla sidor" "Edit style" = "Redigera stil" "Edit variable" = "Redigera variabel" +"Edit variables" = "Redigera variabler" +"Scope" = "Omfång" +"No scope is shared by all the selected variables" = "Inget omfång delas av alla markerade variabler" "Edit with the builder" = "Redigera med byggaren" "Edited {when}" = "Ändrat {when}" "Effect settings" = "Effektinställningar" @@ -883,6 +889,7 @@ name = "Svenska" "Pasted design layers; the clipboard didn't carry the images of: {layers}" = "Designlager inklistrade; urklippet innehöll inte bilderna för: {layers}" "Remove these results from the file" = "Ta bort de här resultaten från filen" "Scroll wheel zoom" = "Zooma med scrollhjulet" +"Invert zoom direction" = "Invertera zoomriktning" "Shared by your team on {server}" = "Delat av ditt team på {server}" "Slot name" = "Platsens namn" "Mar" = "Mar" @@ -1399,6 +1406,7 @@ name = "Svenska" "Server for online sharing" = "Server för delning online" "Server key" = "Servernyckel" "Set as default" = "Ange som standard" +"Set as opening page" = "Ange som startsida" "Set corner smoothing to 60%" = "Ställ in hörnutjämning på 60 %" "Set variable" = "Ange variabel" "Set variable mode" = "Ange variabelläge" @@ -1574,6 +1582,11 @@ name = "Svenska" "Text content" = "Textinnehåll" "Text on a path" = "Text längs en bana" "Text size" = "Textstorlek" +"Small" = "Liten" +"Medium" = "Medel" +"Large" = "Stor" +"Extra large" = "Extra stor" +"Huge" = "Enorm" "Text style" = "Textstil" "Text styles" = "Textstilar" "Texts" = "Texter" @@ -1618,6 +1631,7 @@ name = "Svenska" "This version can't be read." = "Den här versionen kan inte läsas." "This version doesn't have it: all of it is new." = "Den här versionen saknar det: allt är nytt." "Tidy up" = "Snygga till" +"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Markera en rad, en kolumn eller ett helt rutnät med tre eller fler lager, utanför ett auto layout-flöde" "Tile" = "Sida vid sida" "Tile type" = "Upprepningstyp" "Timer" = "Timer" @@ -1810,7 +1824,7 @@ name = "Svenska" "duplicate grid track sizing entries use equal tracks" = "dubbla storleksposter för rutnätsspår använder lika stora spår" "e.g. count + 1" = "t.ex. count + 1" "e.g. count >= 3 and not done" = "t.ex. count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "vinklade och böjda kopplingar utan sparad bana följer FigCrafts egen dragning" +"elbowed and curved connectors without a saved path are routed afresh" = "vinklade och böjda kopplingar utan sparad bana följer FigCrafts egen dragning" "entries without a node type were skipped" = "poster utan nodtyp hoppades över" "figcraft:// links from a browser, chat or email open this app and join the session." = "figcraft://-länkar från en webbläsare, chatt eller e-post öppnar den här appen och ansluter till sessionen." "from {server}" = "från {server}" @@ -1886,7 +1900,9 @@ name = "Svenska" "some vector segments refer to style settings missing from the file; they use the layer's stroke" = "vissa vektorsegment hänvisar till stilinställningar som saknas i filen; de använder lagrets kontur" "stale or invalid grid track sizing entries were ignored" = "inaktuella eller ogiltiga storleksposter för rutnätsspår ignorerades" "stars and polygons without point counts or geometry use the default point count" = "stjärnor och polygoner utan antal punkter eller geometri använder standardantalet punkter" +"sticky layers import as frames with their text" = "fästlappslager importeras som frames med sin text" "style settings of some vector segments aren't supported; those segments use the layer's stroke" = "stilinställningar för vissa vektorsegment stöds inte; de segmenten använder lagrets kontur" +"swapped instances whose previous component isn't in the file took the new component's look" = "utbytta instanser vars tidigare komponent inte finns i filen fick den nya komponentens utseende" "text path underline or strikethrough decoration is not rendered" = "understrykning eller genomstrykning av text på bana ritas inte" "text style overrides refer to missing table entries" = "overrides av textstilar hänvisar till tabellposter som saknas" "the file has no pages" = "filen har inga sidor" @@ -2351,6 +2367,7 @@ name = "Svenska" "plugins.runLast" = "Kör senaste plugin" "pref.autoSave" = "Spara filer automatiskt" "pref.highlightHover" = "Framhäv lager vid hovring" +"pref.invertZoom" = "Invertera zoomriktning" "pref.keepTool" = "Behåll verktyget markerat efter användning" "pref.language" = "Gränssnittsspråk" "pref.nudge" = "Steglängd" @@ -2508,6 +2525,7 @@ name = "Svenska" "text.weightDown" = "Minska teckenvikten" "text.weightUp" = "Öka teckenvikten" "text.wrapStyle" = "Radbrytningsstil" +"tool.annotation" = "Anteckning" "tool.arrow" = "Pil" "tool.comment" = "Kommentar" "tool.connector" = "Koppling" @@ -2696,6 +2714,9 @@ name = "Svenska" "text.alignJustify" = "Marginaljustera text" "text.alignLeft" = "Vänsterjustera text" "text.alignRight" = "Högerjustera text" +"text.directionAuto" = "Auto" +"text.directionLtr" = "Vänster till höger" +"text.directionRtl" = "Höger till vänster" "view.assets" = "Resurser" "view.design" = "Design" "view.layers" = "Lager" diff --git a/crates/ui-egui/locales/ta.toml b/crates/ui-egui/locales/ta.toml index 1fe649d13..cae1132c6 100644 --- a/crates/ui-egui/locales/ta.toml +++ b/crates/ui-egui/locales/ta.toml @@ -1811,7 +1811,7 @@ status = "draft — needs native review" "duplicate grid track sizing entries use equal tracks" = "நகல் கட்ட டிராக் அளவு உள்ளீடுகள் சம டிராக்குகளைப் பயன்படுத்தும்" "e.g. count + 1" = "எ.கா. count + 1" "e.g. count >= 3 and not done" = "எ.கா. count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "சேமித்த பாதை இல்லாத வளைந்த மற்றும் மடிந்த கனெக்டர்கள் FigCraft-இன் சொந்த வழித்தடத்தைப் பின்பற்றும்" +"elbowed and curved connectors without a saved path are routed afresh" = "சேமித்த பாதை இல்லாத வளைந்த மற்றும் மடிந்த கனெக்டர்கள் FigCraft-இன் சொந்த வழித்தடத்தைப் பின்பற்றும்" "entries without a node type were skipped" = "நோட் வகை இல்லாத உள்ளீடுகள் தவிர்க்கப்பட்டன" "figcraft:// links from a browser, chat or email open this app and join the session." = "உலாவி, அரட்டை அல்லது மின்னஞ்சலில் உள்ள figcraft:// இணைப்புகள் இந்த ஆப்ஸைத் திறந்து அமர்வில் சேர்க்கும்." "from {server}" = "{server} இலிருந்து" diff --git a/crates/ui-egui/locales/zh-Hant.toml b/crates/ui-egui/locales/zh-Hant.toml index a14f334ae..b50586add 100644 --- a/crates/ui-egui/locales/zh-Hant.toml +++ b/crates/ui-egui/locales/zh-Hant.toml @@ -1779,7 +1779,7 @@ status = "draft — needs native review" "duplicate grid track sizing entries use equal tracks" = "重複的格線軌道大小項目會使用相等軌道" "e.g. count + 1" = "例如 count + 1" "e.g. count >= 3 and not done" = "例如 count >= 3 and not done" -"elbowed and curved connectors without a saved path follow FigCraft's own routing" = "沒有儲存路徑的肘形與曲線連接線會採用 FigCraft 自己的路徑規劃" +"elbowed and curved connectors without a saved path are routed afresh" = "沒有儲存路徑的肘形與曲線連接線會採用 FigCraft 自己的路徑規劃" "entries without a node type were skipped" = "已略過沒有節點類型的項目" "figcraft:// links from a browser, chat or email open this app and join the session." = "來自瀏覽器、聊天或電子郵件的 figcraft:// 連結會開啟此應用程式並加入工作階段。" "from {server}" = "來自 {server}" diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index f63ab334a..b76ac91aa 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -90,6 +90,8 @@ impl FigApp { "quality": if self.canvas.tex_coarse { "preview" } else { "refined" }, "previewLatencyMs": self.canvas.preview_latency_ms, "refineLatencyMs": self.canvas.refine_latency_ms, + // The share of the canvas only the page colour covered last frame (no render reached it). + "uncovered": self.canvas.uncovered, }, "live": live::inspect(self), "window": self.windows.current, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 51507b0a5..5de28c832 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -62,6 +62,9 @@ pub struct CanvasState { /// shows its image at once while it renders again, instead of a blank canvas (and, where /// renders are slow, a coarse preview). kept: Vec, + /// The coarse image of the area around the view ([`render_worker::Surround`]), shown where + /// the texture doesn't reach, and the file and page it is of. + surround: Option<(egui::TextureHandle, figcraft_render::View, (u64, NodeId))>, submitted: Option, /// The view of the last render asked for. want_view: Option, @@ -71,6 +74,8 @@ pub struct CanvasState { /// canvas texture (ms; the texture is uploaded when that frame is painted). pub preview_latency_ms: Option, pub refine_latency_ms: Option, + /// The share of the canvas no render covered last frame: the page background showed there. + pub uncovered: f32, dragging: bool, space_pan: bool, middle_pan: Option<(Pos2, f64, f64)>, @@ -104,11 +109,13 @@ impl Default for CanvasState { tex_coarse: false, tex_seq: 0, kept: Vec::new(), + surround: None, submitted: None, want_view: None, render_work: None, preview_latency_ms: None, refine_latency_ms: None, + uncovered: 0.0, dragging: false, space_pan: false, middle_pan: None, @@ -339,6 +346,21 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_coarse = done.coarse; app.canvas.tex_seq = done.seq; } + if let Some(around) = worker.surround() + && shown == Some((around.uid, around.page)) + { + let of = (around.uid, around.page); + match &mut app.canvas.surround { + Some((t, view, at)) => { + t.set(around.image, egui::TextureOptions::LINEAR); + (*view, *at) = (around.view, of); + } + None => { + let t = ctx.load_texture("figcraft-canvas-surround", around.image, egui::TextureOptions::LINEAR); + app.canvas.surround = Some((t, around.view, of)); + } + } + } let painter = ui.painter_at(rect); crate::theme::set_canvas_page(&ctx, bg); let image = if let (Some(tex), Some(v), true) = (&app.canvas.texture, &app.canvas.tex_view, shown.is_some() && app.canvas.tex_of == shown) { @@ -351,7 +373,16 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { } else { None }; - background::paint(&painter, rect, bg, image.map(|(_, r)| r)); + // Not in pixel preview: its pixels are the point, and it keeps no image around the view. + let pixel_preview = app.session.ds().ok().and_then(|ds| ds.view.pixel_preview_scale()).is_some(); + let surround = match (&app.canvas.surround, pixel_preview) { + (Some((tex, v, of)), false) if shown == Some(*of) => { + let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0); + Some((tex.id(), presented_image_rect(app.to_screen(v.origin.0, v.origin.1), v, zoom, ppp, false))) + } + _ => None, + }; + app.canvas.uncovered = background::paint(&painter, rect, bg, image.map(|(_, r)| r), surround); if let Some((texture, image_rect)) = image { painter.image(texture, image_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } @@ -461,5 +492,8 @@ mod wheel_zoom_tests; #[cfg(test)] mod zoom_preview_tests; +#[cfg(test)] +mod surround_tests; + #[cfg(test)] mod tab_switch_tests; diff --git a/crates/ui-egui/src/canvas/background.rs b/crates/ui-egui/src/canvas/background.rs index f7eadd640..cac9e2179 100644 --- a/crates/ui-egui/src/canvas/background.rs +++ b/crates/ui-egui/src/canvas/background.rs @@ -1,6 +1,6 @@ //! The transparency grid behind the page; rendered pixels already contain the page colour. -use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, pos2}; +use egui::{Color32, CornerRadius, Id, Painter, Rect, TextureHandle, TextureId, pos2}; /// Reuse the checkerboard texture, updating its pixels when the active theme changes. fn grid_texture(ctx: &egui::Context) -> TextureHandle { @@ -25,18 +25,40 @@ fn grid_texture(ctx: &egui::Context) -> TextureHandle { texture } -/// Draw the transparency grid and apply page colour only outside the rendered image. -pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option) { +/// Draw the transparency grid, and where the rendered image doesn't reach the coarse image around +/// the view (`surround`: its texture and screen rect), and the page colour past that. Returns the +/// share of `rect` that only the page colour covers. +pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered: Option, surround: Option<(TextureId, Rect)>) -> f32 { if background.a() < 255 { // Repeat four pixels instead of allocating one shape per square on a large canvas. let texture = grid_texture(painter.ctx()); let uv = Rect::from_min_size(egui::Pos2::ZERO, rect.size() / 16.0); painter.image(texture.id(), rect, uv, Color32::WHITE); } - // The render contains the page colour and its alpha. Painting that colour beneath it - // applies alpha twice (50% becomes 75%). Only uncovered areas need the fallback colour. - let covered = rendered.map(|r| r.intersect(rect)).filter(|r| r.is_positive()); - let areas = match covered { + // Renders contain the page colour and its alpha. Painting that colour (or the coarse image) + // beneath one applies alpha twice (50% becomes 75%): each area gets exactly one of them. + let mut bare = 0.0; + for area in outside(rect, rendered) { + let rest = match surround { + Some((texture, at)) => { + if area.intersect(at).is_positive() { + painter.with_clip_rect(area).image(texture, at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + outside(area, Some(at)) + } + None => outside(area, None), + }; + for r in rest { + painter.rect_filled(r, CornerRadius::ZERO, background); + bare += r.area(); + } + } + if rect.area() > 0.0 { (bare / rect.area()).clamp(0.0, 1.0) } else { 0.0 } +} + +/// The parts of `rect` outside `covered`: at most four strips that don't overlap. +fn outside(rect: Rect, covered: Option) -> impl Iterator { + let areas = match covered.map(|r| r.intersect(rect)).filter(|r| r.is_positive()) { Some(r) => [ Rect::from_min_max(rect.min, pos2(rect.right(), r.top())), Rect::from_min_max(pos2(rect.left(), r.bottom()), rect.max), @@ -45,9 +67,7 @@ pub(super) fn paint(painter: &Painter, rect: Rect, background: Color32, rendered ], None => [rect, Rect::NOTHING, Rect::NOTHING, Rect::NOTHING], }; - for area in areas.into_iter().filter(|r| r.is_positive()) { - painter.rect_filled(area, CornerRadius::ZERO, background); - } + areas.into_iter().filter(|r| r.is_positive()) } #[cfg(test)] @@ -59,7 +79,7 @@ mod tests { fn shapes(alpha: u8, rendered: Option) -> egui::FullOutput { let ctx = egui::Context::default(); let mut out = ctx.run_ui(Default::default(), |ui| { - paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered); + paint(ui.painter(), canvas(), Color32::from_rgba_unmultiplied(255, 0, 0, alpha), rendered, None); }); out.textures_delta.clear(); out @@ -169,7 +189,9 @@ mod tests { let mut previous_id = None; for tokens in [crate::theme::Tokens::light(), crate::theme::Tokens::dark(), crate::theme::Tokens::light()] { crate::theme::apply(&ctx, tokens); - let mut out = ctx.run_ui(Default::default(), |ui| paint(ui.painter(), canvas(), Color32::TRANSPARENT, None)); + let mut out = ctx.run_ui(Default::default(), |ui| { + paint(ui.painter(), canvas(), Color32::TRANSPARENT, None, None); + }); let (tile, _) = ctx.data(|d| d.get_temp::<(TextureHandle, [Color32; 2])>(Id::unique("canvas_transparency_grid"))).expect("drawn checkerboard"); let grid_index = assert_grid(&out, tile.id(), canvas()); @@ -227,4 +249,47 @@ mod tests { } } } + + /// Past the rendered image the coarse image around the view shows, clipped to outside the + /// image, and the page colour only past both: nothing is painted twice, and what is left bare + /// is what the call returns. + #[test] + fn the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest() { + let ctx = egui::Context::default(); + let around = TextureId::User(7); + // The render covers the left half; the coarse image reaches 80 to the right. + let rendered = Rect::from_min_max(pos2(0.0, 0.0), pos2(50.0, 100.0)); + let at = Rect::from_min_max(pos2(-100.0, -100.0), pos2(80.0, 200.0)); + let mut bare = -1.0; + let mut out = ctx.run_ui(Default::default(), |ui| { + bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), Some((around, at))); + }); + out.textures_delta.clear(); + let coarse: Vec<_> = out.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Mesh(m) if m.texture_id == around)).collect(); + assert_eq!(coarse.len(), 1, "one strip of the canvas lies past the render"); + assert_eq!(coarse[0].clip_rect, Rect::from_min_max(pos2(50.0, 0.0), pos2(100.0, 100.0)), "clipped to past the render"); + let fills: Vec = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Rect(r) => Some(r.rect), + _ => None, + }) + .collect(); + assert_eq!(fills, [Rect::from_min_max(pos2(80.0, 0.0), pos2(100.0, 100.0))], "the page colour only past both"); + assert!((bare - 0.2).abs() < 1e-6, "a fifth of the canvas is bare: {bare}"); + // Without one the page colour fills all of it; with one reaching everywhere nothing. + let mut out = ctx.run_ui(Default::default(), |ui| { + bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), None); + }); + out.textures_delta.clear(); + assert!((bare - 0.5).abs() < 1e-6, "{bare}"); + let everywhere = Rect::from_min_max(pos2(-100.0, -100.0), pos2(200.0, 200.0)); + let mut out = ctx.run_ui(Default::default(), |ui| { + bare = paint(ui.painter(), canvas(), Color32::RED, Some(rendered), Some((around, everywhere))); + }); + out.textures_delta.clear(); + assert_eq!(bare, 0.0); + assert!(!out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(_))), "no page colour under the coarse image"); + } } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index 44a478807..c0fc8f312 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -19,6 +19,9 @@ //! ([`figcraft_render::Steps`]), at least a band a frame and more while they fit in [`STEP_MS`], //! so input is handled while it draws (on a page whose render takes seconds, a band is a //! fraction of that: eight at most). +//! On the desktop a third thread keeps a coarse image of the area around the view +//! ([`Surround`]): where the canvas image doesn't reach (a pan past its edge before the strips are +//! drawn, a zoom out) the canvas shows that, blurred, instead of the bare page colour. use std::sync::Arc; @@ -32,9 +35,9 @@ use web_time::Instant; pub const PREVIEW_FACTOR: f64 = 4.0; /// Full renders quicker than this (about a frame) show without a preview. pub const PREVIEW_AFTER_MS: f64 = 12.0; -/// The browser refines a zoom's preview only once no newer request came for this long (or for as -/// long as the last full render took, when shorter): a full render there blocks the page, and one -/// between every two wheel steps of a zoom held it up for seconds. +/// A zoom's preview is refined only once no newer request came for this long (or for as long as +/// the last full render took, when shorter): in the browser a full render blocks the page, and on +/// the desktop it can't be stopped, so one between every two wheel steps of a zoom held it up. pub const SETTLE_MS: u64 = 120; /// The browser draws a full render a band at a time ([`figcraft_render::Steps`]): at least one /// band a frame, and more while they fit in this long, so input is handled while it draws. A @@ -145,6 +148,78 @@ fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 } } +/// The coarse image around the view is this many views wide and tall, centred on it. +const SURROUND_SPAN: f64 = 3.0; + +/// The area [`SURROUND_SPAN`] times as wide and tall as `view`, centred on it, with +/// [`PREVIEW_FACTOR`] times fewer pixels per page unit (`view` is at most as large as a texture, +/// so this is too). +pub fn surround_view(view: &View) -> View { + let c = coarse_view(view); + let s = c.scale.max(1e-9); + let (w, h) = (f64::from(c.width), f64::from(c.height)); + let pad = (SURROUND_SPAN - 1.0) / 2.0; + let side = |n: f64| (n * SURROUND_SPAN).ceil().max(1.0) as u32; + View { origin: (view.origin.0 - pad * w / s, view.origin.1 - pad * h / s), scale: c.scale, width: side(w), height: side(h) } +} + +/// Whether `around` reaches a third of `view`'s size past each of its sides: a pan that far shows +/// no edge. +fn reaches(around: &View, view: &View) -> bool { + let (a, v) = (around.page_rect(), view.page_rect()); + let (mx, my) = (v.width() / 3.0, v.height() / 3.0); + a.x0 <= v.x0 - mx && a.y0 <= v.y0 - my && a.x1 >= v.x1 + mx && a.y1 >= v.y1 + my +} + +/// Whether `a` and `b` are the same view, bit for bit. +fn same_view(a: &View, b: &View) -> bool { + (a.origin.0.to_bits(), a.origin.1.to_bits(), a.scale.to_bits(), a.width, a.height) + == (b.origin.0.to_bits(), b.origin.1.to_bits(), b.scale.to_bits(), b.width, b.height) +} + +/// The coarse image of the area around the view ([`surround_view`]), kept between requests. +#[derive(Default)] +pub struct Surround { + retained: Retained, + /// The file, page and view of the image handed over last, and whether it was soft-proofed + /// (marked after the render, so the kept image can't tell). + of: Option<(u64, NodeId, View, bool)>, +} + +impl Surround { + /// The image around `job`'s view when the one handed over last no longer stands for it (of + /// another file, page or zoom, short of a third of a view past an edge, or the document + /// changed), drawn on the kept one: a pan shifts it and redraws the strips, an edit the areas + /// that changed. `None` in pixel preview, whose pixels are the point. + pub fn render(&mut self, job: &Job) -> Option { + if !job.zoom_preview { + return None; + } + let want = surround_view(&job.view); + let view = match &self.of { + Some((uid, page, have, _)) + if *uid == job.uid && *page == job.page && have.scale.to_bits() == want.scale.to_bits() && reaches(have, &job.view) => + { + have.clone() + } + _ => want, + }; + let same = self + .of + .as_ref() + .is_some_and(|(uid, page, have, proof)| *uid == job.uid && *page == job.page && *proof == job.proof && same_view(have, &view)); + 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)) + }); + if d.is_some() { + self.of = Some((job.uid, job.page, view, job.proof)); + } + d + } +} + /// `view` with [`PREVIEW_FACTOR`] times fewer pixels each way, showing at least the same area. pub fn coarse_view(view: &View) -> View { let shrink = |n: u32| (f64::from(n) / PREVIEW_FACTOR).ceil().max(1.0) as u32; @@ -413,6 +488,12 @@ pub struct Worker { finished: Arc, /// The watchdog is drawing a late preview, or has one to hand over and wake the UI for. previewing: Arc, + /// The images around the view ([`Surround`]) from their thread. + surround_rx: std::sync::mpsc::Receiver, + /// The newest request handed to the surround thread, and the newest it is done with (its image + /// handed over and the UI woken, or none needed). + surround_asked: Arc, + surround_done: Arc, } #[cfg(not(target_arch = "wasm32"))] @@ -467,6 +548,33 @@ impl Worker { if let Err(e) = watchdog { log::error!("render preview thread: {e}"); } + // The image around the view, on a thread of its own so it never holds up the canvas image: + // the render thread hands it each request it has refined, the newest queued one wins. + let (around_tx, around) = std::sync::mpsc::channel::<(u64, Job)>(); + let (surround_tx, surround_rx) = std::sync::mpsc::channel::(); + let surround_ctx = ctx.clone(); + let surround_asked = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let surround_done = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let (asked, surrounded) = (surround_asked.clone(), surround_done.clone()); + let surrounding = + std::thread::Builder::new().name("figcraft-render-surround".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || { + let mut surround = Surround::default(); + while let Ok((mut seq, mut job)) = around.recv() { + while let Ok(newer) = around.try_recv() { + (seq, job) = newer; + } + if let Some(d) = surround.render(&job) { + if surround_tx.send(d).is_err() { + break; + } + surround_ctx.request_repaint_of(viewport); + } + surrounded.store(seq, std::sync::atomic::Ordering::SeqCst); + } + }); + if let Err(e) = surrounding { + log::error!("render surround thread: {e}"); + } let spawned = std::thread::Builder::new().name("figcraft-render".into()).stack_size(figcraft_render::RENDER_STACK).spawn(move || { let mut renders = Renders::default(); let mut next = None; @@ -481,10 +589,19 @@ impl Worker { break; } ctx.request_repaint_of(viewport); - // A newer request makes refining this one moot: it gets its own preview. - if let Ok(newer) = jobs.try_recv() { - next = Some(newer); - continue; + // A newer request makes refining this one moot: it gets its own preview. Wait + // for one as the browser does ([`SETTLE_MS`], or the last full render's time + // when shorter): a full render can't be stopped, so one started between two + // steps of a zoom held every later step up for as long as it took. + let wait = std::time::Duration::try_from_secs_f64(renders.full_ms_so_far() / 1000.0) + .map_or(std::time::Duration::ZERO, |full| full.min(std::time::Duration::from_millis(SETTLE_MS))); + match jobs.recv_timeout(wait) { + Ok(newer) => { + next = Some(newer); + continue; + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, } } if renders.wants_late_preview(&job) { @@ -493,11 +610,21 @@ impl Worker { } let done = renders.refine(&job); refined.store(seq, std::sync::atomic::Ordering::SeqCst); + let refined_job = done.is_some(); if let Some(d) = done && done_tx.send(answering(d, seq)).is_err() { break; } + if refined_job { + // Asked before the send (and before this request counts as done), so `in_flight` + // holds until the surround thread is done with it. Without that thread (it failed + // to start) the page colour shows past the edge. + asked.store(seq, std::sync::atomic::Ordering::SeqCst); + if around_tx.send((seq, job)).is_err() { + asked.store(0, std::sync::atomic::Ordering::SeqCst); + } + } ctx.request_repaint_of(viewport); done_with.store(seq, std::sync::atomic::Ordering::SeqCst); } @@ -505,7 +632,7 @@ impl Worker { if let Err(e) = spawned { log::error!("render thread: {e}"); } - Self { tx, rx, submitted: 0, finished, previewing } + Self { tx, rx, submitted: 0, finished, previewing, surround_rx, surround_asked, surround_done } } pub fn submit(&mut self, job: Job) { @@ -515,9 +642,13 @@ impl Worker { } /// Whether a submitted job is still rendering or hasn't woken the UI yet, the watchdog's late - /// preview included (a finished image may still wait for [`Self::poll`]). + /// preview and the image around the view included (a finished image may still wait for + /// [`Self::poll`] or [`Self::surround`]). pub fn in_flight(&self) -> bool { - self.finished.load(std::sync::atomic::Ordering::SeqCst) < self.submitted || self.previewing.load(std::sync::atomic::Ordering::SeqCst) + use std::sync::atomic::Ordering::SeqCst; + self.finished.load(SeqCst) < self.submitted + || self.previewing.load(SeqCst) + || self.surround_done.load(SeqCst) < self.surround_asked.load(SeqCst) } /// The best of the renders finished since the last poll ([`better`]). @@ -528,6 +659,11 @@ impl Worker { } best } + + /// The newest image around the view ([`Surround`]) finished since the last call. + pub fn surround(&mut self) -> Option { + self.surround_rx.try_iter().last() + } } /// The browser's worker: renders inline, one image a frame: a preview first when one is due, the @@ -590,6 +726,11 @@ impl Inline { pub fn in_flight(&self) -> bool { self.pending.is_some() } + /// shortcut: the browser renders on the page's own thread, so it keeps no image around the view + /// (one would hold the page up); draw one there once the canvas renders on a wasm thread (#1500). + pub fn surround(&mut self) -> Option { + None + } pub fn poll(&mut self) -> Option { self.poll_at(Instant::now()) } diff --git a/crates/ui-egui/src/canvas/surround_tests.rs b/crates/ui-egui/src/canvas/surround_tests.rs new file mode 100644 index 000000000..f869c860c --- /dev/null +++ b/crates/ui-egui/src/canvas/surround_tests.rs @@ -0,0 +1,83 @@ +//! The coarse image around the view ([`Surround`]): three views wide and tall at a quarter of the +//! pixels each way, kept while the view stays a third of a view inside it, moved (a shift and the +//! strips) when a pan goes further, patched after an edit, none in pixel preview; and the desktop +//! worker hands one over after each refined render, so a pan past the canvas image shows that +//! instead of the bare page colour. + +use std::time::Duration; + +use figcraft_render::{View, Work}; +use serde_json::json; + +use super::zoom_preview_tests::{document, job, view_at}; +use crate::render_worker::{Job, PREVIEW_FACTOR, Surround, Worker, surround_view}; + +/// Whether `outer` shows all of the page `inner` does, give or take the snapping to whole pixels. +fn contains(outer: &View, inner: &View) -> bool { + let (o, i) = (outer.page_rect(), inner.page_rect()); + let eps = 2.0 / outer.scale; + o.x0 <= i.x0 + eps && o.y0 <= i.y0 + eps && o.x1 >= i.x1 - eps && o.y1 >= i.y1 - eps +} + +#[test] +fn the_area_around_a_view_is_three_views_wide_at_a_quarter_of_the_pixels() { + let v = view_at((400.0, 300.0), 2.0, 800, 600); + let a = surround_view(&v); + assert_eq!(a.scale, v.scale / PREVIEW_FACTOR); + assert_eq!((a.width, a.height), (600, 450), "3 × 800 / 4 by 3 × 600 / 4"); + let (pa, pv) = (a.page_rect(), v.page_rect()); + assert!((pa.center().x - pv.center().x).abs() < 1e-9 && (pa.center().y - pv.center().y).abs() < 1e-9, "centred on the view"); + assert!((pa.width() - 3.0 * pv.width()).abs() < 1e-9 && (pa.height() - 3.0 * pv.height()).abs() < 1e-9); +} + +#[test] +fn the_image_around_the_view_is_kept_for_small_pans_and_moved_for_far_ones() { + let (s, rect) = document(); + let ds = s.ds().unwrap(); + let at = |c: (f64, f64)| job(&ds.doc, ds.page, ds.uid, view_at(c, 1.0, 400, 300)); + let mut around = Surround::default(); + let first = around.render(&at((250.0, 150.0))).expect("the first one"); + assert_eq!(first.work, Work::Full); + assert!(first.coarse && contains(&first.view, &surround_view(&at((250.0, 150.0)).view))); + assert!(around.render(&at((250.0, 150.0))).is_none(), "the same request: nothing new"); + // A quarter of a view: it still reaches more than a third of a view past every side. + assert!(around.render(&at((350.0, 225.0))).is_none(), "kept for a small pan"); + // Most of a view: moved to centre on the view again, built on the kept image. + let moved = around.render(&at((570.0, 150.0))).expect("moved for a far pan"); + assert!(matches!(moved.work, Work::Partial { .. }), "a shift and the strips: {:?}", moved.work); + assert!(contains(&moved.view, &surround_view(&at((570.0, 150.0)).view))); + // An edit redraws its area. + let mut s = s; + s.execute("node.set", &json!({"id": rect, "props": {"x": 140}})).unwrap(); + let ds = s.ds().unwrap(); + let edited = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 1.0, 400, 300)); + assert!(matches!(around.render(&edited).expect("after an edit").work, Work::Partial { .. })); + // Soft proof marks the image after it renders: turning it on or off hands over a new one. + assert!(around.render(&Job { proof: true, ..edited.clone() }).is_some(), "proof on"); + assert!(around.render(&Job { proof: true, ..edited.clone() }).is_none()); + assert!(around.render(&edited).is_some(), "proof off"); + // Another zoom starts over; pixel preview has none. + let zoomed = job(&ds.doc, ds.page, ds.uid, view_at((570.0, 150.0), 2.0, 400, 300)); + assert_eq!(around.render(&zoomed).expect("another zoom").work, Work::Full); + assert!(around.render(&Job { zoom_preview: false, ..job(&ds.doc, ds.page, ds.uid, view_at((0.0, 0.0), 8.0, 400, 300)) }).is_none()); +} + +#[test] +fn the_worker_hands_over_the_image_around_each_refined_view() { + let (s, _) = document(); + let ds = s.ds().unwrap(); + let j = job(&ds.doc, ds.page, ds.uid, view_at((250.0, 150.0), 1.0, 400, 300)); + let mut w = Worker::new(egui::Context::default()); + w.submit(j.clone()); + let start = std::time::Instant::now(); + let around = loop { + assert!(start.elapsed() < Duration::from_secs(60), "no image around the view came"); + if let Some(d) = w.surround() { + break d; + } + std::thread::sleep(Duration::from_millis(2)); + }; + assert_eq!((around.uid, around.page), (ds.uid, ds.page)); + assert!(contains(&around.view, &surround_view(&j.view)), "it reaches a view past every side"); + assert!(w.poll().is_some_and(|d| !d.coarse), "the refined image came through as before"); +} diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index bb36c0aae..af9914b74 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -27,7 +27,7 @@ use crate::render_worker::{ /// 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 /// or an edit meanwhile would redraw in full instead of patching. -fn document() -> (Session, NodeId) { +pub(super) fn document() -> (Session, NodeId) { figcraft_text::scan_system_fonts(); let mut s = Session::new(); for k in 0..12 { @@ -69,11 +69,11 @@ fn slow_scene(views: &[View], ms: f64) -> Session { } /// A `w` × `h` device-pixel view at `scale` centred on page point `c`. -fn view_at(c: (f64, f64), scale: f64, w: u32, h: u32) -> View { +pub(super) fn view_at(c: (f64, f64), scale: f64, w: u32, h: u32) -> View { View { origin: (c.0 - f64::from(w) / scale / 2.0, c.1 - f64::from(h) / scale / 2.0), scale, width: w, height: h } } -fn job(doc: &Arc, page: NodeId, uid: u64, view: View) -> Job { +pub(super) fn job(doc: &Arc, page: NodeId, uid: u64, view: View) -> Job { Job { doc: doc.clone(), page, @@ -405,6 +405,34 @@ fn a_slow_first_render_gets_a_preview_beside_it_and_a_quick_one_none() { assert_eq!(drain(&mut w), [(1, false)], "done before the threshold: no preview"); } +#[test] +fn the_render_thread_refines_a_zoom_only_once_it_pauses() { + // A full render can't be stopped: a zoom step's started as soon as its preview was out held the + // next step up for as long as it took. The next step coming while the preview shows skips it. + let views: Vec = [1.0, 0.5, 0.25].into_iter().map(|s| view_at((300.0, 200.0), s, 1200, 1200)).collect(); + let s = slow_scene(&views, 4.0 * PREVIEW_AFTER_MS); + let ds = s.ds().unwrap(); + let at = |i: usize| job(&ds.doc, ds.page, ds.uid, views[i].clone()); + let mut w = Worker::new(egui::Context::default()); + w.submit(at(0)); + drain(&mut w); + // A zoom out: its preview, then the next step while that preview is on screen. + w.submit(at(1)); + let start = std::time::Instant::now(); + let preview = loop { + assert!(start.elapsed() < Duration::from_secs(60), "no preview came"); + if let Some(d) = w.poll() { + break d; + } + std::thread::sleep(Duration::from_millis(1)); + }; + assert_eq!((preview.seq, preview.coarse), (2, true)); + w.submit(at(2)); + let got = drain(&mut w); + assert!(!got.contains(&(2, false)), "the step zoomed past is never refined: {got:?}"); + assert_eq!(got.last(), Some(&(3, false)), "the last step is: {got:?}"); +} + #[test] fn a_preview_replaces_a_refined_image_of_the_same_zoom_elsewhere_on_the_page() { // 800 × 600: A at 100% from the page origin, B at 800% about its top-left, A' back at 100% diff --git a/crates/ui-egui/src/frame_new_from_selection_tests.rs b/crates/ui-egui/src/frame_new_from_selection_tests.rs new file mode 100644 index 000000000..557e8b761 --- /dev/null +++ b/crates/ui-egui/src/frame_new_from_selection_tests.rs @@ -0,0 +1,133 @@ +//! The Frame tool's panel starts with New from selection (#1683): with layers selected it wraps +//! them in a frame, as Object ▸ Frame selection does, in one undo step, and returns to the Move +//! tool; with nothing selected it does nothing. + +use egui::accesskit::Role; +use egui::{Pos2, pos2}; +use figcraft_doc::{NodeId, NodeKind}; +use figcraft_engine::{Session, ToolId}; +use serde_json::json; + +use crate::layers_drag_tests::Ui; + +/// Two rectangles, both selected when `select`, with the Frame tool active. +fn scene(select: bool) -> (Ui, [NodeId; 2]) { + let mut s = Session::new(); + let mut rect = + |x: i32| NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let ids = [rect(0), rect(80)]; + let selected: &[NodeId] = if select { &ids } else { &[] }; + s.execute("select.set", &json!({"ids": selected})).unwrap(); + s.execute("tool.set", &json!({"tool": "frame"})).unwrap(); + (Ui::new(s), ids) +} + +/// The middle of the button named `label`, found in the AccessKit tree, and whether it says it is +/// disabled. +fn named_button(u: &mut Ui, label: &str) -> (Pos2, bool) { + u.ctx.enable_accesskit(); + u.frame(vec![]); + let out = u.frame_output(vec![]); + let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes; + let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::Button && n.label() == Some(label)).expect(label); + let b = n.bounds().expect("bounds"); + (pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32), n.is_disabled()) +} + +fn click(u: &mut Ui, p: Pos2) { + u.button(p, true); + u.button(p, false); + u.frame(vec![]); +} + +#[test] +fn new_from_selection_frames_the_selected_layers_and_returns_to_move() { + let (mut u, [a, b]) = scene(true); + let history = u.app.session.undo_depth().0; + let (at, disabled) = named_button(&mut u, "New from selection"); + assert!(!disabled); + click(&mut u, at); + let doc = u.app.session.doc().unwrap(); + let parent = doc.node(a).unwrap().parent.expect("a parent"); + assert_eq!(doc.node(b).unwrap().parent, Some(parent), "both layers in the same frame"); + assert!(matches!(doc.node(parent).unwrap().kind, NodeKind::Frame), "the parent is a new frame"); + assert_eq!(u.app.session.undo_depth().0, history + 1, "one undo step"); + assert_eq!(u.app.session.tool.tool, ToolId::Move); +} + +#[test] +fn new_from_selection_does_nothing_without_a_selection() { + let (mut u, [a, _]) = scene(false); + let page = u.app.session.doc().unwrap().node(a).unwrap().parent; + let history = u.app.session.undo_depth().0; + let (at, disabled) = named_button(&mut u, "New from selection"); + assert!(disabled, "screen readers hear it is disabled"); + click(&mut u, at); + assert_eq!(u.app.session.doc().unwrap().node(a).unwrap().parent, page, "nothing was framed"); + assert_eq!(u.app.session.undo_depth().0, history); + assert_eq!(u.app.session.tool.tool, ToolId::Frame, "the Frame tool stays"); +} + +/// Sections never go in frames (`object.frameSelection` refuses them): with a section selected, +/// alone or with other layers, the button is disabled, and clicking it shows no error and keeps +/// the Frame tool. +#[test] +fn new_from_selection_is_disabled_for_a_section() { + let (mut u, [a, b]) = scene(false); + let section = NodeId(u.app.session.execute("object.wrapInSection", &json!({"ids": [a]})).unwrap()["id"].as_u64().unwrap()); + for selected in [vec![section], vec![section, b]] { + u.app.session.execute("select.set", &json!({"ids": selected})).unwrap(); + u.app.session.execute("tool.set", &json!({"tool": "frame"})).unwrap(); + let history = u.app.session.undo_depth().0; + let (at, disabled) = named_button(&mut u, "New from selection"); + assert!(disabled, "{selected:?}"); + click(&mut u, at); + assert_eq!(u.app.session.undo_depth().0, history, "nothing was framed"); + assert!(u.app.ui.toast.is_none(), "no error: {:?}", u.app.ui.toast); + assert_eq!(u.app.session.tool.tool, ToolId::Frame, "the Frame tool stays"); + } + // A layer inside the section can be framed (in the section). + u.app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + u.app.session.execute("tool.set", &json!({"tool": "frame"})).unwrap(); + let (at, disabled) = named_button(&mut u, "New from selection"); + assert!(!disabled); + click(&mut u, at); + let frame = u.app.session.doc().unwrap().node(a).unwrap().parent.unwrap(); + assert_eq!(u.app.session.doc().unwrap().node(frame).unwrap().parent, Some(section)); + assert_eq!(u.app.session.tool.tool, ToolId::Move); +} + +#[test] +fn new_from_selection_respects_instance_structure_and_slots() { + for slot in [false, true] { + let mut s = Session::new(); + let frame = NodeId(s.execute("frame.create", &json!({"width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap()); + let content = NodeId(s.execute("frame.create", &json!({"parent": frame, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + let rect = NodeId(s.execute("shape.rectangle", &json!({"parent": content, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let component = NodeId(s.execute("component.create", &json!({"ids": [frame]})).unwrap()["id"].as_u64().unwrap()); + if slot { + s.execute("component.makeSlot", &json!({"id": content})).unwrap(); + } + let instance = NodeId(s.execute("instance.create", &json!({"component": component, "x": 300, "y": 0})).unwrap()["id"].as_u64().unwrap()); + let doc = s.doc().unwrap(); + let child = doc.subtree(instance).into_iter().find(|id| doc.node(*id).and_then(|n| n.source) == Some(rect)).unwrap(); + s.execute("select.set", &json!({"ids": [child]})).unwrap(); + s.execute("tool.set", &json!({"tool": "frame"})).unwrap(); + let mut u = Ui::new(s); + let history = u.app.session.undo_depth().0; + let parent = u.app.session.doc().unwrap().node(child).unwrap().parent; + let (at, disabled) = named_button(&mut u, "New from selection"); + assert_eq!(disabled, !slot, "only content within a slot can be reframed"); + click(&mut u, at); + assert!(u.app.ui.toast.is_none(), "disabled action must not raise an error"); + if slot { + assert_eq!(u.app.session.undo_depth().0, history + 1); + assert_ne!(u.app.session.doc().unwrap().node(child).unwrap().parent, parent); + assert_eq!(u.app.session.tool.tool, ToolId::Move); + } else { + assert_eq!(u.app.session.undo_depth().0, history); + assert_eq!(u.app.session.doc().unwrap().node(child).unwrap().parent, parent); + assert_eq!(u.app.session.tool.tool, ToolId::Frame); + } + } +} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 00b36e37c..572cd5de7 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -204,9 +204,35 @@ fn importer_notes() -> BTreeSet { keys.extend(literals(&std::fs::read_to_string(&path).unwrap(), &["warn("])); } } + // The `.fig` mapping itself is craft-fig's (`craft_fig::rest`); its notes are ours to translate. + let rest = craft_fig_src().join("rest"); + for path in sources(&rest).into_iter().chain([rest.with_extension("rs")]) { + if !path.file_name().unwrap().to_string_lossy().contains("tests") { + keys.extend(literals(&std::fs::read_to_string(&path).unwrap(), &["warn("])); + } + } keys } +/// The `src` directory of the craft-fig sources this build uses, as Cargo resolved them. +fn craft_fig_src() -> std::path::PathBuf { + let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()); + // Unfiltered, `cargo metadata` needs every target's packages (accesskit_ios, ...) in Cargo's + // cache, and `--offline` cannot fetch them; a build fetches only the host's. Filter to the host. + let version = std::process::Command::new(&cargo).arg("-vV").output().unwrap(); + let version = String::from_utf8(version.stdout).unwrap(); + let host = version.lines().find_map(|l| l.strip_prefix("host: ")).expect("cargo -vV names its host"); + let out = std::process::Command::new(&cargo) + .args(["metadata", "--format-version", "1", "--offline", "--filter-platform", host]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + .unwrap(); + assert!(out.status.success(), "cargo metadata: {}", String::from_utf8_lossy(&out.stderr)); + let meta: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + let package = meta["packages"].as_array().unwrap().iter().find(|p| p["name"] == "craft-fig").expect("craft-fig is a dependency"); + std::path::Path::new(package["manifest_path"].as_str().unwrap()).parent().unwrap().join("src") +} + /// The lookup functions whose first argument is a catalog key. const LOOKUPS: &[&str] = &["tr(", "trf(", "trn(", "tr_noop("]; diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index 93a80d9bd..467bb9fd3 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -643,6 +643,50 @@ fn the_page_menus_rename_starts_with_the_keyboard_in_the_name() { assert_clicking_page_opens_it(&mut u, p2, p1, r2); } +/// Right-clicks `at` in the pages list and returns the menu's "Set as opening page" item, if shown. +fn opening_item(u: &mut Ui, at: Pos2) -> Option { + u.frame(vec![ + Event::PointerMoved(at), + Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, + ]); + u.frame(vec![Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]); + let shapes: Vec = u.frame_output(vec![]).shapes.into_iter().map(|c| c.shape).collect(); + crate::live_tests::has_text(&shapes, "Set as opening page").then(|| crate::live_tests::text_center(&shapes, "Set as opening page")) +} + +/// The pages list's menu offers "Set as opening page" on a page and not on a divider, and using it +/// writes the document's opening page without moving the viewer's own page (#1817). +#[test] +fn the_page_menu_sets_the_opening_page_and_not_on_dividers() { + let mut s = Session::new(); + let p1 = s.page().unwrap(); + let p2 = id(s.execute("page.add", &json!({})).unwrap()); + let div = id(s.execute("page.add", &json!({"name": "-"})).unwrap()); + s.execute("page.move", &json!({"id": div, "index": 1})).unwrap(); + s.execute("page.select", &json!({"id": p1})).unwrap(); + let mut u = Ui::new(s); + let (r1, r2) = (page_row(&mut u, p1, p2), page_row(&mut u, p2, p1)); + let mid = Pos2::new(r1.x, (r1.y + r2.y) / 2.0); + u.app.session.execute("page.select", &json!({"id": p1})).unwrap(); + u.frame(vec![]); + assert_eq!(opening_item(&mut u, mid), None, "a divider has no such item"); + u.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + for _ in 0..5 { + u.frame(vec![]); + } + let item = opening_item(&mut u, r2).expect("a page has the item (and its menu is open)"); + assert_ne!(u.app.session.doc().unwrap().current_page, Some(p2), "not the opening page yet"); + u.frame(vec![Event::PointerMoved(item)]); + u.button(item, true); + u.button(item, false); + for _ in 0..3 { + u.frame(vec![]); + } + assert_eq!(u.app.session.doc().unwrap().current_page, Some(p2), "the document's opening page is the clicked page"); + assert_eq!(u.app.session.page().unwrap(), p1, "the viewer's own page stays"); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); +} + /// The y of the line between the pages and the layers, above the layers' row at `layer` (found by /// the resize cursor it shows when hovered). fn pages_edge_at(u: &mut Ui, layer: f32) -> f32 { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bfb2ab216..692b55ff0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -116,6 +116,8 @@ mod font_menu_regrow_tests; #[cfg(test)] mod frame_label_tests; #[cfg(test)] +mod frame_new_from_selection_tests; +#[cfg(test)] mod gap_handle_tests; #[cfg(test)] mod gradient_shorthand_tests; @@ -302,6 +304,8 @@ mod vector_keys_tests; #[cfg(test)] mod vector_panel_tests; #[cfg(test)] +mod vector_point_radius_tests; +#[cfg(test)] mod vector_point_xy_tests; #[cfg(test)] mod vector_tail_ui_tests; diff --git a/crates/ui-egui/src/panels/frame_presets.rs b/crates/ui-egui/src/panels/frame_presets.rs index 9eb281622..014a7a01e 100644 --- a/crates/ui-egui/src/panels/frame_presets.rs +++ b/crates/ui-egui/src/panels/frame_presets.rs @@ -1,20 +1,49 @@ -//! The Frame tool's panel: frame presets by category. Clicking one adds a frame of that size next -//! to the page's frames and returns to the Move tool. +//! The Frame tool's panel: New from selection, then frame presets by category. Clicking a preset +//! adds a frame of that size next to the page's frames; either returns to the Move tool. use egui::{Align2, CornerRadius, Id, Sense, Ui, pos2, vec2}; +use figcraft_doc::{Document, NodeId, NodeKind}; use serde_json::json; use crate::FigApp; +use crate::a11y; use crate::i18n::tr; use crate::icons::{self, Icon}; use crate::theme::{Tokens, regular, semibold}; use crate::widgets::{self, PAD}; -/// Draw the expandable frame-preset categories; choosing a preset runs `frame.create`, -/// switches to the Move tool and zooms to the new selection. +/// Whether `object.frameSelection` would frame `selection`: layers on a page, none of them a +/// section (sections never go in frames, #1683). +fn can_frame(doc: &Document, selection: &[NodeId]) -> bool { + !selection.is_empty() + && selection.iter().all(|i| doc.node(*i).is_some_and(|n| n.parent.is_some() && !matches!(n.kind, NodeKind::Section { .. }))) + && figcraft_engine::cmd::edit::roots(doc, selection) + .iter() + .all(|id| doc.node(*id).and_then(|n| n.parent).is_some_and(|parent| !figcraft_engine::components::structure_locked(doc, parent))) +} + +/// Draw New from selection and the expandable frame-preset categories. New from selection wraps +/// the selected layers in a frame (`object.frameSelection`, #1683); choosing a preset runs +/// `frame.create` and zooms to the new selection. Both switch to the Move tool. pub fn panel(app: &mut FigApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); widgets::section_header(ui, tr("Frame"), &[], false); + let framable = app.session.ds().is_ok_and(|ds| can_frame(&ds.doc, &ds.selection)); + let mut from_selection = false; + ui.horizontal(|ui| { + ui.add_space(PAD); + let resp = widgets::button(ui, tr("New from selection"), false, framable); + if !framable { + a11y::disabled(&resp); + } + from_selection = resp.clicked(); + }); + ui.add_space(4.0); + // The Frame tool stays when framing failed (its error is shown). + if from_selection && app.run("object.frameSelection", json!({})).is_some() { + app.run("tool.set", json!({"tool": "move"})); + return; + } let w = ui.available_width(); let mut cats: Vec<&str> = Vec::new(); for (c, ..) in figcraft_engine::cmd::create::FRAME_PRESETS { diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 138e3ec6f..d20fafe32 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -333,6 +333,13 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { } ui.close(); } + // The page the file opens on, for everyone (#1817); a divider can't be one. + if !divider && ui.button(tr("Set as opening page")).clicked() { + if !crate::menus::dev_mode_refuses(app, "page.setOpening") { + app.run("page.setOpening", json!({"id": id})); + } + ui.close(); + } if ui.button(tr("Delete page")).clicked() { if !crate::menus::dev_mode_refuses(app, "page.delete") { delete_page(app, id); diff --git a/crates/ui-egui/src/present.rs b/crates/ui-egui/src/present.rs index 8f23069f2..f7af47c5f 100644 --- a/crates/ui-egui/src/present.rs +++ b/crates/ui-egui/src/present.rs @@ -248,6 +248,12 @@ struct Snapshot { overlays: Vec, history: Vec, scroll: HashMap, + /// When each instance last changed variant: a temporary change that reverts restores it, so + /// the variant shown again keeps its After delay deadline. + swapped: HashMap, + /// The After delays that had fired: a temporary variant change clears the swapped instance's, + /// and the revert puts them back so a delay that already ran doesn't run again. + delays_fired: HashSet<(NodeId, usize)>, } /// A "while hovering / while pressing" state that reverts when the pointer leaves / lifts. @@ -290,6 +296,8 @@ pub struct Presenter { bar_thumb: Option<(NodeId, usize, egui::TextureHandle)>, arrived: f64, delays_fired: HashSet<(NodeId, usize)>, + /// When each instance last changed variant (Change to): its After delay timers count from then. + swapped: HashMap, /// Mouse triggers waiting out their delay. waiting: Vec, hovered: Vec, @@ -370,6 +378,7 @@ impl Presenter { bar_thumb: None, arrived: -1.0, delays_fired: HashSet::new(), + swapped: HashMap::new(), waiting: Vec::new(), hovered: Vec::new(), press: None, @@ -460,6 +469,9 @@ mod tail_tests; #[cfg(test)] mod delay_tests; +#[cfg(test)] +mod afterdelay_chain_tests; + #[cfg(test)] mod overlay_anchor_tests; diff --git a/crates/ui-egui/src/present/actions.rs b/crates/ui-egui/src/present/actions.rs index cfc3f26a8..017003025 100644 --- a/crates/ui-egui/src/present/actions.rs +++ b/crates/ui-egui/src/present/actions.rs @@ -218,6 +218,9 @@ impl Presenter { } figcraft_engine::components::sync_instance(d, inst); self.settle(&before); + // The new variant's After delay interactions are fresh: they count from now. + self.delays_fired.retain(|(id, _)| !doc.is_ancestor(inst, *id)); + self.swapped.insert(inst, now); true } Action::SetVariable { variable, value, expr } => { diff --git a/crates/ui-egui/src/present/afterdelay_chain_tests.rs b/crates/ui-egui/src/present/afterdelay_chain_tests.rs new file mode 100644 index 000000000..af67d1f1a --- /dev/null +++ b/crates/ui-egui/src/present/afterdelay_chain_tests.rs @@ -0,0 +1,350 @@ +//! A chain of variant After delay steps (Change to) plays to the end, each step's delay counted +//! from when its variant appeared (#2352). Driven through egui headless on the harness's clock. + +use figcraft_doc::{NodeId, NodeKind}; +use figcraft_engine::Session; +use serde_json::{Value, json}; + +use crate::present_tests::{Ui as Harness, id}; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")) +} + +/// Variants A to D of one set, an instance on A in a screen, each step an After delay of `ms` +/// changing to the next variant. (harness presenting the screen, the instance, the variants) +fn chain(ms: u32) -> (Harness, NodeId, Vec) { + let mut s = Session::new(); + let variants: Vec = ["A", "B", "C", "D"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + for pair in variants.windows(2) { + let it = json!({"id": pair[0], "trigger": {"type": "afterDelay", "ms": ms}, "action": {"type": "changeTo", "dest": pair[1]}, "transition": {"type": "instant"}, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", it); + } + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + (u, inst, variants) +} + +/// The variant (index) the instance shows in the presenter. +fn shown(u: &Harness, inst: NodeId, variants: &[NodeId]) -> Option { + let p = crate::tabs::shown_or_paused(&u.app)?; + let d = p.doc.as_ref()?; + match d.node(inst)?.kind { + NodeKind::Instance { component, .. } => variants.iter().position(|v| *v == component), + _ => None, + } +} + +#[test] +fn a_chain_of_variant_after_delays_plays_to_the_end() { + let (mut u, inst, variants) = chain(0); + u.frames(30, Vec::new); + assert_eq!(shown(&u, inst, &variants), Some(3), "A -> B -> C -> D"); +} + +#[test] +fn each_step_waits_its_own_delay_from_when_its_variant_appeared() { + let (mut u, inst, variants) = chain(500); + // Step until the instance shows B, then note the time. + let mut guard = 0; + while shown(&u, inst, &variants) != Some(1) { + u.frame(Vec::new()); + guard += 1; + assert!(guard < 120, "A never changed to B"); + } + let appeared = u.time; + while u.time < appeared + 0.4 { + u.frame(Vec::new()); + } + assert_eq!(shown(&u, inst, &variants), Some(1), "400 ms after B appeared: still B"); + while u.time < appeared + 0.6 { + u.frame(Vec::new()); + } + assert_eq!(shown(&u, inst, &variants), Some(2), "600 ms after B appeared: C"); +} + +/// A hover that changes the variant and reverts leaves the variant shown again on its own After +/// delay deadline (counted from the screen's arrival), not from the hover. +#[test] +fn a_hover_variant_that_reverts_keeps_the_after_delay_deadline() { + let mut s = Session::new(); + let variants: Vec = ["A", "Hover", "Next"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let instant = json!({"type": "instant"}); + let delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 1000}, "action": {"type": "changeTo", "dest": variants[2]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", delay); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let start = u.time; + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + while u.time < start + 0.8 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + u.frame(vec![egui::Event::PointerMoved(on)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + while u.time < start + 0.9 { + u.frame(vec![egui::Event::PointerMoved(on)]); + } + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + while u.time < start + 1.3 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + assert_eq!(shown(&u, inst, &variants), Some(2), "A's 1,000 ms delay from the arrival fired, not 1,000 ms after the hover"); +} + +/// A delay that already ran on a variant stays run after a hover changes the variant and reverts: +/// the keys the temporary change cleared come back with the revert. +#[test] +fn a_hover_variant_that_reverts_does_not_rerun_a_fired_delay() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "count", "type": "number", "value": 0})); + let count = s.doc().unwrap().variables.get("count").map(|v| v.id.clone()).unwrap(); + let variants: Vec = ["A", "Hover"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let instant = json!({"type": "instant"}); + // A's delay leaves A on screen: it counts its runs (count = count + 1). + let inc = json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": count}}, {"value": {"type": "number", "value": 1}}]}}); + let delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 100}, "action": {"type": "setVariable", "variable": count, "value": null, "expr": inc}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", delay); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let start = u.time; + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + while u.time < start + 0.3 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + let fired: Vec<(NodeId, usize)> = crate::tabs::shown_or_paused(&u.app).map(|p| p.delays_fired.iter().copied().collect()).unwrap_or_default(); + assert!(!fired.is_empty(), "A's delay ran before the hover"); + u.frame(vec![egui::Event::PointerMoved(on)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + u.frames(5, Vec::new); + let p = crate::tabs::shown_or_paused(&u.app).expect("presenting"); + assert!(fired.iter().all(|k| p.delays_fired.contains(k)), "the delay that ran before the hover is still marked as run: {:?}", p.delays_fired); + let runs = p.design.as_ref().and_then(|d| d.variables.resolve(&count, &Default::default())); + assert_eq!(runs, Some(figcraft_doc::VariableValue::Number(1.0)), "A's delay ran once, not again after the hover"); +} + +/// A delay that fires on the hover variant names that variant's interaction: after the revert it +/// doesn't count as A's delay at the same index, which still runs on its own deadline. +#[test] +fn a_delay_fired_on_a_hover_variant_does_not_block_the_restored_variants_delay() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "a_runs", "type": "number", "value": 0})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "hover_runs", "type": "number", "value": 0})); + let var = |s: &Session, name: &str| s.doc().unwrap().variables.get(name).map(|v| v.id.clone()).unwrap(); + let (a_runs, hover_runs) = (var(&s, "a_runs"), var(&s, "hover_runs")); + let inc = |v: &str| json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": v}}, {"value": {"type": "number", "value": 1}}]}}); + let variants: Vec = ["A", "Hover"] + .iter() + .enumerate() + .map(|(k, state)| { + let f = id(&ex( + &mut s, + "frame.create", + json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}), + )); + id(&ex(&mut s, "component.create", json!({"ids": [f]}))) + }) + .collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let instant = json!({"type": "instant"}); + // A: index 0 a 1,000 ms delay counting its runs, index 1 the hover. Hover: index 0 a delay due at once. + let a_delay = json!({"id": variants[0], "trigger": {"type": "afterDelay", "ms": 1000}, "action": {"type": "setVariable", "variable": a_runs, "value": null, "expr": inc(&a_runs)}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", a_delay); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let h_delay = json!({"id": variants[1], "trigger": {"type": "afterDelay", "ms": 0}, "action": {"type": "setVariable", "variable": hover_runs, "value": null, "expr": inc(&hover_runs)}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", h_delay); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let start = u.time; + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + let value = |u: &Harness, v: &str| { + crate::tabs::shown_or_paused(&u.app).and_then(|p| p.design.as_ref().and_then(|d| d.variables.resolve(v, &Default::default()))) + }; + while u.time < start + 0.2 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + while u.time < start + 0.4 { + u.frame(vec![egui::Event::PointerMoved(on)]); + } + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + assert_eq!(value(&u, &hover_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "the hover variant's delay ran"); + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + while u.time < start + 1.3 { + u.frame(vec![egui::Event::PointerMoved(away)]); + } + assert_eq!(value(&u, &a_runs), Some(figcraft_doc::VariableValue::Number(1.0)), "A's own delay at index 0 ran on its deadline"); +} + +/// A layer that only the hover variant has, with its own After delay that ran during the hover, +/// leaves no fired key behind after the revert (its id may be issued again by the next hover). +#[test] +fn a_hover_variants_own_layer_leaves_no_fired_key_after_the_revert() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Run", "modes": ["Default"]})); + ex(&mut s, "variable.create", json!({"collection": "Run", "name": "runs", "type": "number", "value": 0})); + let runs = s.doc().unwrap().variables.get("runs").map(|v| v.id.clone()).unwrap(); + let inc = json!({"op": {"op": "add", "args": [{"value": {"type": "alias", "value": runs}}, {"value": {"type": "number", "value": 1}}]}}); + let frames: Vec = ["A", "Hover"] + .iter() + .enumerate() + .map(|(k, state)| { + id(&ex(&mut s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 60, "name": format!("State={state}")}))) + }) + .collect(); + // Only the hover state has this layer, with a delay due at once. + let dot = id(&ex(&mut s, "shape.rectangle", json!({"x": 160, "y": 610, "width": 10, "height": 10, "parent": frames[1]}))); + let instant = json!({"type": "instant"}); + let dot_delay = json!({"id": dot, "trigger": {"type": "afterDelay", "ms": 0}, "action": {"type": "setVariable", "variable": runs, "value": null, "expr": inc}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", dot_delay); + let variants: Vec = frames.iter().map(|f| id(&ex(&mut s, "component.create", json!({"ids": [f]})))).collect(); + ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()})); + let hover = json!({"id": variants[0], "trigger": {"type": "onHover"}, "action": {"type": "changeTo", "dest": variants[1]}, "transition": instant, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", hover); + let set = s.doc().unwrap().node(variants[0]).unwrap().parent.unwrap(); + let screen = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 300, "name": "Screen"}))); + let inst = id(&ex(&mut s, "instance.create", json!({"component": set, "x": 20, "y": 20, "parent": screen}))); + ex(&mut s, "instance.swap", json!({"ids": [inst], "component": variants[0]})); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": screen})); + u.frame(Vec::new()); + let hot = u.app.inspect()["presenter"]["hotspots"].as_array().cloned().unwrap_or_default(); + let h = hot.iter().find(|h| h["id"] == json!(inst)).unwrap_or_else(|| panic!("no hotspot on the instance: {hot:?}")); + let r: Vec = h["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() as f32).collect(); + let (on, away) = (egui::pos2((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0), egui::pos2(r[0] - 40.0, r[1] - 40.0)); + for _ in 0..6 { + u.frame(vec![egui::Event::PointerMoved(on)]); + } + assert_eq!(shown(&u, inst, &variants), Some(1), "while hovering: the hover variant"); + let p = crate::tabs::shown_or_paused(&u.app).expect("presenting"); + let ran = p.design.as_ref().and_then(|d| d.variables.resolve(&runs, &Default::default())); + assert_eq!(ran, Some(figcraft_doc::VariableValue::Number(1.0)), "the hover variant's own layer ran its delay"); + u.frame(vec![egui::Event::PointerMoved(away)]); + u.frame(Vec::new()); + assert_eq!(shown(&u, inst, &variants), Some(0), "the hover left: A again"); + let p = crate::tabs::shown_or_paused(&u.app).expect("presenting"); + let d = p.design.as_ref().expect("a document"); + let stale: Vec<_> = p.delays_fired.iter().filter(|(id, _)| !d.contains(*id)).collect(); + assert!(stale.is_empty(), "no fired key names a layer the restored document lacks: {stale:?}"); +} + +/// An edit in the editor while presenting brings back the editor's variants, so the swap times of +/// the variants changed at run time no longer delay them. +#[test] +fn an_edit_while_presenting_drops_the_swap_times() { + let (mut u, inst, variants) = chain(500); + let start = u.time; + let mut guard = 0; + while shown(&u, inst, &variants) != Some(1) { + u.frame(Vec::new()); + guard += 1; + assert!(guard < 120, "A never changed to B"); + } + // An edit: the presenter shows the editor's document again, the instance on A. + u.run("page.rename", json!({"name": "Renamed"})); + u.frame(Vec::new()); + let edited = u.time; + // A's 500 ms delay counts from the screen's arrival, long past: it fires at once, not 500 ms + // after the run-time change to B. + while u.time < edited + 0.2 { + u.frame(Vec::new()); + } + assert!(edited < start + 0.9, "the edit came before B's own delay was due"); + assert_eq!(shown(&u, inst, &variants), Some(1), "A changed to B again right after the edit"); +} + +#[test] +fn a_single_after_delay_still_fires_once() { + let mut s = Session::new(); + let a = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 400, "name": "A"}))); + let b = id(&ex(&mut s, "frame.create", json!({"x": 400, "y": 0, "width": 300, "height": 400, "name": "B"}))); + let it = json!({"id": a, "trigger": {"type": "afterDelay", "ms": 100}, "action": {"type": "navigate", "dest": b}, "transition": {"type": "instant"}, "durationMs": 0}); + ex(&mut s, "proto.interaction.add", it); + let mut u = Harness::new(s); + u.run("proto.present", json!({"start": a})); + u.frames(3, Vec::new); + let name = |u: &Harness| u.app.inspect()["presenter"]["name"].as_str().unwrap_or_default().to_string(); + assert_eq!(name(&u), "A", "not before the delay"); + u.frames(30, Vec::new); + assert_eq!(name(&u), "B", "once the delay is over"); + u.frames(60, Vec::new); + assert_eq!(name(&u), "B", "and not again"); +} diff --git a/crates/ui-egui/src/present/navigate.rs b/crates/ui-egui/src/present/navigate.rs index b5ae19cec..a83e3940f 100644 --- a/crates/ui-egui/src/present/navigate.rs +++ b/crates/ui-egui/src/present/navigate.rs @@ -42,6 +42,8 @@ impl Presenter { self.closing.retain(|(_, o)| doc.contains(o.id)); // These hold states of the document before the edit. self.temp = None; + // The edit's variants replace the runtime ones: their swap times no longer apply. + self.swapped.clear(); self.anim = None; self.scroll_anim = None; self.stop_scrolling(); @@ -150,6 +152,8 @@ impl Presenter { overlays: self.overlays.clone(), history: self.history.clone(), scroll: self.scroll.clone(), + swapped: self.swapped.clone(), + delays_fired: self.delays_fired.clone(), }) } @@ -170,6 +174,7 @@ impl Presenter { } self.arrived = now; self.delays_fired.clear(); + self.swapped.clear(); self.waiting.clear(); self.hovered.clear(); self.rev += 1; @@ -220,6 +225,16 @@ impl Presenter { pub(super) fn revert(&mut self, now: f64) { let Some(t) = self.temp.take() else { return }; + // The delays fired during the temporary change: inside an instance it changed the variant + // of, a key names the temporary variant's interaction, not the restored one's, so drop it; + // keep the others, and put back the ones the change cleared. + let changed: Vec = self.swapped.iter().filter(|(i, at)| t.snap.swapped.get(*i) != Some(*at)).map(|(i, _)| *i).collect(); + let restored = &t.snap.doc; + let during: Vec<(NodeId, usize)> = self.delays_fired.difference(&t.snap.delays_fired).copied().collect(); + let mut fired = t.snap.delays_fired.clone(); + fired.extend(during.into_iter().filter(|(id, _)| !changed.iter().any(|i| i == id || restored.is_ancestor(*i, *id)))); + // A layer the temporary change added is gone again (and its id may be issued anew). + fired.retain(|(id, _)| restored.contains(*id)); self.begin(t.transition.reversed(), t.dur, t.easing, now); self.current = t.snap.current; self.design = Some(t.snap.doc); @@ -227,6 +242,8 @@ impl Presenter { self.overlays = t.snap.overlays; self.history = t.snap.history; self.scroll = t.snap.scroll; + self.swapped = t.snap.swapped; + self.delays_fired = fired; self.stop_scrolling(); self.hovered.clear(); self.rev += 1; @@ -245,7 +262,9 @@ pub(crate) fn next_delay(p: &Presenter, doc: &Document, root: NodeId, now: f64) if let Trigger::AfterDelay { ms } = it.trigger && !p.delays_fired.contains(&(id, k)) { - let due = since + f64::from(ms) / 1000.0 - now; + // Inside an instance that changed variant, the timer starts when it did. + let from = p.swapped.iter().filter(|(inst, _)| doc.is_ancestor(**inst, id)).fold(since, |a, (_, t)| a.max(*t)); + let due = from + f64::from(ms) / 1000.0 - now; if next.is_none_or(|(_, d)| due < d) { next = Some(((id, k), due)); } diff --git a/crates/ui-egui/src/vector_point_radius_tests.rs b/crates/ui-egui/src/vector_point_radius_tests.rs new file mode 100644 index 000000000..5a10a2421 --- /dev/null +++ b/crates/ui-egui/src/vector_point_radius_tests.rs @@ -0,0 +1,40 @@ +//! The vector edit panel's Corner radius for a point (#2334): a typed radius larger than half the +//! point's segments is kept and shown as typed, and the point is drawn rounded across the whole of +//! the segments whose other ends stay sharp, as Figma draws it. + +use egui::Key; +use figcraft_geom::Point; +use figcraft_geom::kurbo::{ParamCurve, PathSeg}; +use serde_json::json; + +use crate::field_tests::{field, type_into}; +use crate::vector_point_xy_tests::setup; + +#[test] +fn a_typed_radius_is_kept_shown_and_drawn_across_the_sharp_neighbours_segments() { + // The 100 × 60 rectangle in vector edit mode; point 2 is its bottom right corner. + let (mut u, id) = setup(); + u.app.session.execute("vector.edit.select", &json!({"vertices": [2]})).unwrap(); + type_into(&mut u, "Corner radius", "100", Key::Enter); + assert_eq!(field(&mut u, "Corner radius").1, "100", "the field shows the radius as typed"); + let doc = u.app.session.doc().unwrap(); + let net = figcraft_engine::vectoredit::network(doc, id).unwrap(); + assert_eq!(net.vertices.iter().map(|v| v.radius).collect::>(), vec![0.0, 0.0, 100.0, 0.0], "only point 2 stores it, unclamped"); + assert_eq!(net.vertices[2].point(), Point::new(100.0, 60.0)); + // Both neighbours are sharp, so the arc reaches the whole 60 of the shorter side: from the top + // right corner to 60 along the bottom, on a circle of radius 60 centred at (40, 0). + let arcs: Vec<_> = net + .fill_path() + .segments() + .filter_map(|s| match s { + PathSeg::Cubic(c) => Some(c), + _ => None, + }) + .collect(); + assert_eq!(arcs.len(), 1, "{arcs:?}"); + let ends = [arcs[0].p0, arcs[0].p3]; + let close = |a: Point, b: Point| (a - b).hypot() < 1e-9; + assert!(ends.iter().any(|e| close(*e, Point::new(100.0, 0.0))) && ends.iter().any(|e| close(*e, Point::new(40.0, 60.0))), "{ends:?}"); + let h = 60.0 / 2f64.sqrt(); + assert!(close(arcs[0].eval(0.5), Point::new(40.0 + h, h)), "{:?}", arcs[0].eval(0.5)); +} diff --git a/crates/ui-egui/src/vector_point_xy_tests.rs b/crates/ui-egui/src/vector_point_xy_tests.rs index e93f62873..7f6c911e3 100644 --- a/crates/ui-egui/src/vector_point_xy_tests.rs +++ b/crates/ui-egui/src/vector_point_xy_tests.rs @@ -9,7 +9,9 @@ use serde_json::json; use crate::field_tests::{field, scrub, type_into, undo_steps}; use crate::layers_drag_tests::Ui; -fn setup() -> (Ui, NodeId) { +/// A 100 × 60 rectangle at the origin, selected and in vector edit mode (points clockwise from +/// the top left), and its id. +pub(crate) fn setup() -> (Ui, NodeId) { let mut s = Session::new(); let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap(); let id = NodeId(r["id"].as_u64().unwrap()); diff --git a/crates/vectordrawable/Cargo.toml b/crates/vectordrawable/Cargo.toml index 461e9c079..6185049e3 100644 --- a/crates/vectordrawable/Cargo.toml +++ b/crates/vectordrawable/Cargo.toml @@ -9,6 +9,7 @@ description = "FigCraft Android Vector Drawable export (shapes, strokes, gradien workspace = true [dependencies] +craft-vectordrawable.workspace = true figcraft-geom = { workspace = true } figcraft-color = { workspace = true } figcraft-doc = { workspace = true } diff --git a/crates/vectordrawable/src/xml.rs b/crates/vectordrawable/src/xml.rs index 62b6d5b65..4bb76f21d 100644 --- a/crates/vectordrawable/src/xml.rs +++ b/crates/vectordrawable/src/xml.rs @@ -5,48 +5,14 @@ use std::fmt::Write as _; use figcraft_color::Color; -use figcraft_geom::BezPath; -use figcraft_geom::kurbo::PathEl; use crate::model::{Fill, GradKind, GroupItem, Item, ItemKind, NativeStroke, PathItem}; const ANDROID: &str = "http://schemas.android.com/apk/res/android"; const AAPT: &str = "http://schemas.android.com/aapt"; -/// A number as Android reads it: rounded to 3 decimals, no trailing zeros, `0` for anything -/// non-finite (the walk leaves out shapes whose numbers aren't finite). -pub(crate) fn num(v: f64) -> String { - if !v.is_finite() { - return "0".into(); - } - // Android reads these as 32-bit floats, so clamp to that range; this also keeps the scaling - // below from overflowing to infinity. - let v = v.clamp(-f64::from(f32::MAX), f64::from(f32::MAX)); - let r = (v * 1000.0).round() / 1000.0; - let s = format!("{r}"); - if s == "-0" { "0".into() } else { s } -} - -/// `s` for an attribute value: markup escaped, whitespace that parsers would fold kept as -/// character references, and characters XML 1.0 forbids dropped. -pub(crate) fn esc(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - '\t' => out.push_str(" "), - '\n' => out.push_str(" "), - '\r' => out.push_str(" "), - c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {} - c => out.push(c), - } - } - out -} +// Shared wire primitives; app-specific drawable projection and colour policy stay here. +pub(crate) use craft_vectordrawable::write::{esc, num, path_data}; /// `#RRGGBB`, or `#AARRGGBB` when not opaque. pub(crate) fn color(c: Color) -> String { @@ -54,33 +20,6 @@ pub(crate) fn color(c: Color) -> String { if a == 255 { format!("#{r:02X}{g:02X}{b:02X}") } else { format!("#{a:02X}{r:02X}{g:02X}{b:02X}") } } -/// SVG path syntax, absolute commands. -pub(crate) fn path_data(p: &BezPath) -> String { - let mut s = String::new(); - let pt = |x: f64, y: f64| format!("{},{}", num(x), num(y)); - for el in p.elements() { - if !s.is_empty() { - s.push(' '); - } - match *el { - PathEl::MoveTo(a) => { - let _ = write!(s, "M{}", pt(a.x, a.y)); - } - PathEl::LineTo(a) => { - let _ = write!(s, "L{}", pt(a.x, a.y)); - } - PathEl::QuadTo(a, b) => { - let _ = write!(s, "Q{} {}", pt(a.x, a.y), pt(b.x, b.y)); - } - PathEl::CurveTo(a, b, c) => { - let _ = write!(s, "C{} {} {}", pt(a.x, a.y), pt(b.x, b.y), pt(c.x, c.y)); - } - PathEl::ClosePath => s.push('Z'), - } - } - s -} - struct Out { s: String, } @@ -244,3 +183,29 @@ fn path(o: &mut Out, depth: usize, p: &PathItem) { o.close(depth + 1, "aapt:attr"); o.close(depth, "path"); } + +#[cfg(test)] +mod shared_wire_tests { + use super::*; + use figcraft_geom::BezPath; + + #[test] + fn shared_attributes_preserve_exact_xml() { + assert_eq!(esc("<&>\"'\t\n\r\0\u{ffff}é𝄞 "), "<&>"' é𝄞&#9;"); + } + + #[test] + fn shared_numbers_and_paths_preserve_android_syntax() { + assert_eq!(num(-0.0001), "0"); + assert_eq!(num(f64::NAN), "0"); + assert_eq!(num(f64::INFINITY), "0"); + assert_eq!(num(1.23456), "1.235"); + let mut p = BezPath::new(); + p.move_to((0.0, -0.0)); + p.line_to((1.23456, 2.0)); + p.quad_to((3.0, 4.0), (5.0, 6.0)); + p.curve_to((7.0, 8.0), (9.0, 10.0), (11.0, 12.0)); + p.close_path(); + assert_eq!(path_data(&p), "M0,0 L1.235,2 Q3,4 5,6 C7,8 9,10 11,12 Z"); + } +} diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 19b7ac13d..567b9b61e 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -32,15 +32,11 @@ all end with the same geometry. | Prototyping and Developer Mode refuse on boards | done | `proto.*`, `dev.*`, `view.prototype`, `view.devMode` say why | | Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text 16 by default (FigJam's "Small", read twice from its size field, 2026-11-12) and fixed as it fills: the note grows taller and never shrinks its text (2026-11-09, #2157); a size menu in the contextual bar (Small 16, Medium 24, Large 40, Extra large 64, Huge 96; a number when the size matches none) sets every selected sticky, the note grows taller when Huge no longer fits and shrinks back to square at Large, and the sticky tool remembers the last size for new stickies, all measured in FigJam's web app, 2026-11-12; stickies saved with another size keep it, the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it | | Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; size presets done (the bar's menu, `board.setStyle {fontSize}`, `board.sticky {fontSize}`); no stacks | -| Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar | +| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | | | Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | -| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was | | Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before. Dragging a "+" carries the preview ("drag the preview to any location on your board"): let go on empty board and the next one is made there, centred on the pointer, joined by a connector leaving by the handle's side (`at: [x, y]`, a point of the page); let go on another sticky or shape, inside a section too, and a connector joins the two instead, the object outlined while over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile (`board_connect_tests`, #1919) | -| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | -| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before | | Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) | | A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side | | Connector paths reshaped by hand | done | a selected elbow or curved connector shows path handles: one on each run long enough to take one, one in the middle of a curve. Dragging a run moves it, and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins and is saved with the file; changing the style or moving an end to something else goes back to routing itself. No way back by itself otherwise: the public help describes none | @@ -72,6 +68,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Shapes with text, Connectors, Create the next shape already connected. | | 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` | | 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). | | 2026-11-09 | patch | M12, #2157: a sticky's text is 18 and stays 18 (measured in FigJam's web app: ten lines, then a long paragraph, never changed it; the note kept its width and grew taller). The normalize pass no longer resets a sticky's text to a size by its length (24 down to 11 before), so stickies in saved files keep their size. Size presets (Small to Huge) are still missing. Tests: `a_new_sticky_starts_at_18`, `a_sticky_keeps_its_text_size_as_text_is_added`, `a_sticky_saved_with_another_text_size_keeps_it` | diff --git a/docs/cli.md b/docs/cli.md index a83fbe5c3..07b19e58b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -118,7 +118,8 @@ page 1 "Screens": 380 nodes, 4 top-level after the frame (`Home.png`, `Settings.png`…); with no frames, one file per top-level layer. The name is kept as it is, except for the characters file systems refuse (`/ \ : * ? " < > |` and control characters), which become `_`, and leading or trailing spaces and dots, which are - dropped. A name is cut at 100 characters. The app's export replaces the same characters (there a + dropped. Reserved Windows device names such as `CON` get a leading `_`. + A name is cut at 100 characters. The app's export replaces the same characters (there a `/` makes a folder). Two layers with the same name get `Name 2`, `Name 3`… - `` has an image extension: one file with the given `--node`, or the whole page composited. - `--node` takes a layer id (`12` or `0:12`) or a layer name. diff --git a/docs/collaboration-parity.md b/docs/collaboration-parity.md index 4fb173ccc..77026dbb2 100644 --- a/docs/collaboration-parity.md +++ b/docs/collaboration-parity.md @@ -1,6 +1,6 @@ # Collaboration parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing) Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model, @@ -15,6 +15,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla | Real-time co-editing | yes | **core built, no networking** (#103): client-scoped ids, per-property change sets with fractional positions, server ordering and validation, optimistic clients, binary messages; randomized multi-client convergence tests over real commands. Live sessions over the network landed (`crates/collab-net`): the WebSocket transport (keep-alive, size and rate limits, a live connection reconnecting until you leave, and rejoining with offline edits merged), hosting from the app (this machine or the local network) with invite links, live cursors with name tags, selections, avatars and follow, `collab.*` commands. Document sync between apps works over them (the host's server orders every batch; guests open the host's file as a new tab). Sessions are per document: each open file has its own or none, several run at once (host one, join another, publish a third) and keep syncing behind the tab in front, and closing a file ends its session only. Revert to saved is refused until the document leaves its live session; its access checks and sync association stay intact. Undo is per person (only your own steps, others' later writes left alone), refused edits roll back with a toast, and a reconnect resumes as the same client with what it missed (or a snapshot) and sends what was made offline. The browser build joins (same messages through the browser's WebSocket API); `figcraft://` invite links open the desktop app and join. Styles, variables, collections, modes and comments made in a session take ids from their creator's space (the server checks it), so concurrent creations all survive; modes, per-mode values and replies inside one entry still resolve last-writer-wins. A standalone `figcraft-server` keeps many files, persists them (a snapshot plus a log, compacted), loses nothing confirmed across a restart (apps resume as the same participants) and takes files published from the app (File ▸ Publish to server…). The desktop app and the CLI open `wss://` links too (TLS through a reverse proxy), and releases ship the server for Linux with a deployment guide (systemd, Caddy, nginx, Docker) and `install.sh`. A server can be open to the public: anyone publishes without the key, within limits per address, and files nobody opens expire. Message limits follow the server's `max_file_mb`, so files above 64 MiB publish and open (the client takes at most 1 GiB from a server, and the server warns when large limits meet open publishing, #705); a damaged generation field in a file's log no longer drops the edits flushed to it (#687). Image entries are checked as they apply: a key must be a plain name (letters, digits, `-`, `_`; it becomes `images/` in a saved file), bytes under a content-hash key must hash to it (lowercase sha256), a side is at most 65 535 px and the decoded bytes at most 256 MiB (what the importers read), a key's bytes can't be replaced and an image a layer shows can't be removed, so no collaborator can poison the shared image store or balloon memory; snapshots and server logs from before these checks open without the images they refuse (#1086). The batches kept for apps that reconnect are bounded in bytes by default (64 MiB; `max_log_mb` on `figcraft-server`), and an app further behind catches up with a snapshot (#1069). Placing a layer among its siblings is a binary search, so large pastes and reorders in one batch no longer take quadratic time (#1065). A refused batch's fixes take time linear in the batch: each deleted layer is restored once and each entry fix looked up once (#1063). Left: server archives beyond Linux | 25–55 | | Live cursors, selections, viewports; follow / observation mode; spotlight | yes | **done, in live sessions**: named cursors (one name for live sessions and comments: Preferences ▸ Your name, also in the Share popover and the Join dialog, kept in the browser too; a rename shows at once in the sessions you're in, #1380), selection outlines, avatars (an AI agent attached over MCP also shows its avatar and an outline around the layers it last edited or selected while it works, in or out of a session, #1416), follow (click an avatar), others' text carets and selected characters with their names, a note when two people type in one layer; spotlight (your avatar's menu, `collab.spotlight`): everyone follows your view and page, people who join later too, anyone who moves their view stops following and a banner offers to follow again, a newer spotlight takes over. Left: polish (no accounts, so anyone in the session can spotlight) | 2–4 | | Cursor chat, audio, high-fives | yes | **partial, in live sessions**: cursor chat (`/` opens a bubble at your pointer; everyone sees it as you type, it fades a few seconds after the last change, Enter sends and Escape takes it back, 100 characters; `collab.cursorChat` for agents); sent as ephemeral presence the host checks and rate-limits, never stored. No audio, high-fives or emote reactions | 2–5 | +| Opening page of a shared file | the page a link names, else the first | **partial**: a file joined from a server opens on its opening page, which is the open document's current page: the page the file was opened on (the page stored in the file when it was opened, else the first page) until someone sets one, not always the first page; a later page switch, a save on another page or publishing does not move it (a local save stamps the page being viewed into the saved file's bytes for the next time that file is opened, but does not change the open document's opening page, which is the synced property, and a link cannot name a page; `page.setOpening {id?}` (the pages list's Set as opening page, the MCP server too) writes it as a document change, one undo step, so everyone who joins afterwards lands on it, unless a spotlight is on, in which case they follow the spotlighter's page instead; each viewer's own page stays their own (#1817) | — | | Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. No accounts, teams or projects | 8–17 | | Comments: pins on frames and layers, threads, reactions, @mentions, resolve, unread, search and filters, links, in the presenter | yes (shared) | **done, local**: stored in the file, your name from Preferences (an AI agent attached over MCP comments as its own name, marked Agent); a behaviour suite from the documentation (pinning and following layers, threads, own edits and deletes, mentions, reactions, C and Shift+C, stepping, filters, saving, copy and paste); restoring a version keeps them. `comment.list` (CLI, MCP) gives each message its `mentions` (`{name, known, you}`, by the highlighting rule). In a live session threads sync and anyone in it can reply, react and resolve (no accounts: a name is who you are) | (shared once multiplayer lands) | | Version history: named versions, autosave checkpoints, view before restore, restore, duplicate | yes (cloud) | **done**, saved in the `.figcraft` file: restoring keeps the replaced design as an autosave first, a titled autosave becomes a named version, merging a branch records the file before and after. Versions are per person in a live session (a shared history needs accounts); no comparing two versions (Developer Mode compares a ready-for-dev layer with its state when marked) | — | @@ -26,6 +27,8 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla | Date | Change | Summary | |---|---|---| +| 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. | +| 2026-11-04 | minor | M9, #1817: a file on a server opened on the page that was current at publish time, with no way to change it: `DocProp::CurrentPage` was synced but nothing wrote it. `page.setOpening {id?}` (the pages list's "Set as opening page", the MCP server too) writes the opening page as a document change, one undo step, so everyone who joins afterwards lands on it; a divider is refused; nobody's own page moves. Tests: `page_opening_tests`, `collab_live_tests::the_opening_page_syncs_and_moves_no_ones_view`. Numbers unchanged. | | 2026-11-04 | minor | M9: a session you joined no longer turns into a local file by itself. A dropped connection reconnects until you leave (a minute's pause after each 12 attempts, a pause Retry now skips); only the host ending the session and refusals that are for good stop it; queued messages go out paced. While disconnected the tab shows a red mark and a strip across the canvas says so; a session that ended stays on its tab with Try again, Save a copy and Dismiss | | 2026-11-04 | minor | M9: joining a session again merges what you did while disconnected as one undoable edit, through the three-way merge branches use, as the same client when the server still knows it. What conflicts keeps the other person's, and your whole version opens beside it as an unsaved copy. A server that no longer knows you merges the same way instead of discarding unconfirmed work | | 2026-11-06 | patch | M9, #2026: one conflicting auto layout edit added a conflict for every size and place it moved (a padding changed on both sides of a file with one instance gave 10, with 15 instances 138), and a `layout` conflict took all auto layout fields together, so a gap changed only on the branch was lost if main won the padding. `merge::plan` now leaves out values both sides work out for themselves: a hugging frame's or a filling child's size, text sizing to its characters, an auto layout child's place (when both sides turn it the same way) and a value a layer in an instance takes from its main; merging keeps the file merged into's own value and normalising lays it out from the merged inputs. `layout` and `childLayout` merge field by field: a field changed on one side merges, each field changed both ways is its own conflict (`/layout.padding`, shown as auto layout padding with both sides' values). Tests: `branch_tests::one_conflicting_auto_layout_edit_is_one_conflict`, `branch_tests::auto_layout_fields_changed_one_way_survive_a_conflict`, `branch_tests::sizes_auto_layout_works_out_never_conflict`; the merge fuzz test leaves worked-out values out of what each side must show | diff --git a/docs/components-parity.md b/docs/components-parity.md index ee68e73b8..61598ab9a 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -13,7 +13,6 @@ accounts). | Feature | Status | Notes | |---|---|---| | 2026-11-11 | minor | M3, #2022: an instance lists only the properties its variant's layers use (its variant properties, slots, and the boolean, text and instance swap properties a layer of its current variant reads), as measured in Figma's web app: an instance of variant A lists `State` and `A label`, never `B label` or a property no layer reads. The set and its variants still list every definition, so unused ones can be deleted there. A long property name in the panel is cut to one line with an ellipsis, the full name on hover, instead of wrapping over the rows around it. Tests: `prop_order_tests::an_instance_lists_only_the_properties_its_variant_uses`, `component_props_reorder_tests::a_long_property_name_stays_on_one_line`, `prop_value_tests::a_set_keeps_each_named_text_definition_and_layers_read_their_own`. Grade unchanged. | -| Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main | | Create component, instances, detach, reset, go to main, restore main, push changes | done | push from a nested layer goes to the outer main; with two or more layers selected the Design panel header's component button opens a menu with Create component, Create multiple components (each layer its own component in place, one undo step) and Create component set (each layer a component, wrapped in place in a set 20 px around: variants `Property 1=` left to right, `prop=value` names kept, layers that all share a name give a set of that name with `Property 1=Default` variants; measured in Figma), one layer keeps the plain click (#2088) | | Per-layer overrides with reset; kept across main edits, nested swaps, copy/paste | done | main edits match a full rebuild exactly at 2,000 instances | | What an instance overrides: fills, strokes, effects, visibility, layer names, text content and every text property (resizing included), auto layout padding, gap and alignment, layout grids, export settings, prototype interactions, nested swaps and property values; the size and resizing (hug, fill, fixed, min and max) of layers inside it | done | each kept when the main changes that property, reset per group; opacity and corner radius too (documentation silent); size and resizing are kept through relayout, undo, save, `.fig` and REST import and detach, and stay with the instance on push | @@ -82,6 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| | 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-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 | | 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b06d79932..381992c55 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -236,7 +236,9 @@ zoom preview or the refined image (`canvas.quality`: `preview` or `refined`) and asking for a render to its preview and its refined image being handed to egui as the canvas texture (`canvas.previewLatencyMs`, `canvas.refineLatencyMs`, on a monotonic clock, rendering included in the browser too; the GPU upload and presenting the frame come after; `null` until -there was one). `importReport` holds the Import report window's content (`{name, pages, layers, images, appended, placed, warnings, warningCount}`, +there was one), and the share of the canvas only the page colour covered last frame, no render +reaching it (`canvas.uncovered`, 0 to 1: past the canvas image the desktop shows a coarse image of the +area around the view). `importReport` holds the Import report window's content (`{name, pages, layers, images, appended, placed, warnings, warningCount}`, `null` while none is open). The window opens only for a file the user opened or imported in the app (File ▸ Open or Import, Open recent, a recent file on the home screen, a drop, a paste, the system's open event). Emulated user input counts as the user's action: `ui.input` and `ui.key` (for example a Cmd+V paste or a click diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index d77dce75f..0443708c0 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -14,8 +14,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) | -| 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, 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); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | +| 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); the native targets don't write image or pattern fills yet, and 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 | | Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) | @@ -31,6 +30,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 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-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 feeac9e05..bdef310aa 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -39,8 +39,7 @@ and prototype interactions are still unchecked there. | BMP | — | yes | | — | | 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). 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. 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`), never with a real clipboard from other software | with `.fig` | -| 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). 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). 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` | +| 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). 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` | ## Export @@ -53,9 +52,8 @@ export limit, not a native document nesting limit. | Format | Figma | FigCraft | Notes | Hours | |---|---|---|---|---| -| PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels | — | -| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); a color profile per setting as for PNG (`colorProfile`), the file tagged with an ICC profile (APP2) for sRGB and for Display P3 | — | | PNG | yes, scales/suffixes | yes | export settings per layer, presets (`2x`, `512w`, `512h`), preview, "Export N layers"; ignore overlapping layers (on by default; off: every layer showing in the area) and include bounding box (the layer's own box; the Export section offers it for text layers, and `file.export` and `export.update` take it for any layer); slashes in layer names export into folders. The exported area is what the layer paints: shadows towards their offset, outside and centre strokes, unclipped children, a mask group's mask, nothing for hidden layers; slices export everything under them, except that with ignore overlapping layers on a slice inside a frame or group exports only that frame or group; sides round up to whole pixels; a color profile per setting (Same as file, the default, sRGB or Display P3: `colorProfile`), the pixels converted and the file tagged (`sRGB` chunk, or ICC and `cICP`) | — | +| JPG | yes | yes | white where transparent; quality 1 to 100 (`quality` on `file.export`, export settings and MCP `export`; default 90; the Export panel has no control for it yet); a color profile per setting as for PNG (`colorProfile`), the file tagged with an ICC profile (APP2) for sRGB and for Display P3 | — | | SVG | yes (outline text option, ids) | yes | alpha/luminance masks kept; noise, texture, progressive and background blur, glass embedded as images; outline text (off: `` with one `` per line, one style per layer), unique id attributes from layer names, explicit depth-limit refusal, nested frames clipped by their parent's clip (#327), simplified strokes (stroke attributes for centred strokes and for inside and outside strokes on boxes and ellipses) | — | | PDF | yes | yes | one page per frame, real selectable text in subset fonts, links, vectors and gradients as vectors, effects as images; bleed, crop/bleed marks, page boxes, naive CMYK; checked by rendering the PDF back against PNG exports; explicit depth-limit refusal; RGB is always sRGB (no color profile setting and no output intent) | CMYK output intent 2–4 | | WebP | — | yes (ours) | a color profile per setting as for PNG; sRGB files untagged, Display P3 files with the generated ICC profile | — | @@ -198,6 +196,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Pasted content from other apps, PNG. | | 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software | | 2026-11-12 | minor | M6, #2323: the `.fig` export writes text on a path as the format's own layer kind (`TEXT_PATH`): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (`textPathStart.tValue`, found by inverse arc length) and the side as `forward`. Vertical alignment is written as top, which is how text on a path draws. The importer already read all of it; a closed path comes back starting at the marked segment, the same curve and start point. Text with more than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Checked through the importer only, not in other software | | 2026-11-12 | minor | M6, #2297: the `.fig` exporter writes an image paint's adjustments as `paintFilter` (seven fields: exposure, contrast, vibrance from saturation, temperature, tint, highlights, shadows; the tint's sign is flipped, as the importer reads it), and no longer warns about them; the importer already read them. Not checked in other software | diff --git a/docs/gaps.md b/docs/gaps.md index 66ac5bb9f..2971d9bf0 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-12 · **Change:** minor (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-17 · **Change:** minor (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 @@ -306,6 +306,28 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe write lock, went from about 45 µs to 0.2 µs (the lookup logic timed alone). The faces drawn are those drawn before, except where two are equally near the run's style (the one read already is kept) and for Hiragino's W3-style names (read as their weight). +- **Landed (2026-11-17):** the desktop's render thread waits the same way after a zoom's preview + (`SETTLE_MS`, or the last full render's time when shorter) before refining it. A full render + there can't be stopped, so one started between two steps of a held zoom made every later step + wait for it: on a 29,000 × 12,600 page of 9,000 layers with images and shadows (M1 Pro, 2x + display) full renders took 110–520 ms, and the preview stood in for that long. Pans and edits are + refined at once, as before. +- **Landed (2026-11-17):** the desktop keeps a coarse image of the area around the view, three + views wide and tall at a quarter of the pixels each way (`render_worker::Surround`, on a thread of + its own after each refined render, built on the last one: a pan shifts it, an edit patches it). + Where the canvas image doesn't reach, a pan past its edge before the strips are drawn or a zoom + out, the canvas shows that, blurred, then sharp, instead of the bare page colour. On a page of + 3,600 cards with shadows panned at 60 pt a step (debug build), the canvas was 36% bare on + average and at 77 of 80 steps; now none of it is. `ui.inspect` reports the bare share + (`canvas.uncovered`). The browser keeps none (it renders on the page's thread). +- **Landed (2026-11-17):** the strips a pan uncovers, and the areas an edit redraws, render in + parallel bands as full renders do (`render_part`): rows of a tall strip, columns of a wide one, + however few pixels they have. A strip costs the layers it crosses, not its pixels (a card's + shadow is drawn whole for a sliver of it), and was drawn on one thread: on a page of 3,600 cards + with a drop and an inner shadow each, a 60 px pan took 33 ms right and 47 ms down where the + whole view took 80 ms; now 9 and 11 ms (`pan_bench_tests`, release, a 32-thread desktop; bands stop at 16). In the app + (release) a pan step on that page went from 150–170 ms to 17–27 ms. The browser renders on one + thread and is unchanged. - **Landed (2026-10-28):** the browser refines a zoom's preview only once no newer request has come for 120 ms (`SETTLE_MS`), or for as long as its last full render took when that is shorter: its full renders run on the UI thread, and one between every two wheel steps held the page up @@ -595,6 +617,9 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Gap 7: a pan past the canvas image shows a coarse image of the area around the view (desktop), not the bare page colour; `canvas.uncovered` in `ui.inspect`. Numbers unchanged. Tests: `surround_tests`, `background::tests::the_image_around_the_view_fills_what_the_render_leaves_and_the_page_colour_the_rest` | +| 2026-11-17 | minor | Gap 7: the strips a pan uncovers render in parallel bands (rows of a tall strip, columns of a wide one), 3–5× quicker pans on effect-heavy pages. Numbers unchanged. Tests: `band_tests::columns_match_one_piece_rendering`, `band_tests::a_tall_or_wide_part_of_a_view_matches_one_piece_rendering`; timings: `pan_bench_tests` | +| 2026-11-17 | minor | Gap 7: the desktop refines a zoom's preview only once the zoom has paused, as the browser does, so a full render that can't be stopped no longer holds up the next steps of a held zoom. Numbers unchanged. Test: `zoom_preview_tests::the_render_thread_refines_a_zoom_only_once_it_pauses` | | 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them | | 2026-11-10 | minor | Gap 13: a boolean group's corner radius rounds every sharp corner of its result (#2222); the boolean clause leaves the 2026-10-12 "Left" list | | 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 3b48ac54c..e74c0df7f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -110,11 +110,8 @@ supported by both apps (CJK, Arabic and Devanagari shaping, IME); Figma has no v | Simplified Chinese (Mandarin) | zh-Hans | 2,216 / 2,352 (94.2%, draft) | yes | CJK text and IME in documents; UI text in an installed Chinese face, ahead of Japanese ones (web: the `FIGCRAFT_EMBED_CJK` build) | no | draft | 1–2 (after native review) | | Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 (100%: 1,975 UI strings, 641 command labels, 31 menu wordings; draft, counted 2026-11-03) | yes | CJK text and IME in documents; UI text in an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC or Heiti TC (web: only with a built-in TC face); zh-TW, zh-HK, zh-MO and zh-Hant read it, an explicit Hans stays Simplified | no | draft | 1–2 (after native review) | | Spanish | es, es-419 | 2,352 / 2,352 (100%, draft); es-419 overlays 104 Latin American wordings (draft) | yes | Latin | no | draft | 0–1 (after native review) | -| Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; UI font fallback to check | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab` embeds Noto Sans Arabic (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | | Hindi | hi | 0 (0%) | no | Devanagari shaping works in documents; the desktop UI takes an installed Devanagari face (Nirmala UI, Kohinoor Devanagari, Noto Sans Devanagari, Lohit) for names and values (#2014); no UI catalog | no | none | 4–7 | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); panels do not mirror | no | draft | review + panel mirroring (not re-estimated) | -| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web not offered (font budget excludes Arabic); the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | +| Arabic | ar | 1,857 / 1,857 UI strings, 620 command labels, 31 menu wordings (draft, counted 2026-10-28) | catalog complete; native review pending | Existing bidi/shaping and Arabic system fallback; web: only a build with `FIGCRAFT_EMBED_SCRIPTS=Arab`, or with `FIGCRAFT_WEB_FONTS` naming Noto Sans Arabic, embeds it (the font budget leaves it out otherwise, #1902); documents draw in it and the picker offers the Arabic UI then; the window mirrors (panels swap sides), rows inside the panels do not | no | draft | review + mirrored panel rows (not re-estimated) | | French | fr | 2,328 / 2,352 (99.0%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Portuguese | pt-BR | 2,331 / 2,352 (99.1%, draft) | yes | Latin | no | draft | 1–2 (after native review) | | Indonesian | id | 2,292 / 2,352 (97.4%, draft) | yes | Latin | no | draft | 1–2 (after native review) | @@ -149,6 +146,7 @@ Hindi and Arabic. | Date | Change | Summary | |---|---|---| +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): Hindi, Arabic. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source and marked as a draft awaiting native review. `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it; an explicit Hans still reads Simplified Chinese. The desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled. No plural forms. Localization grade and estimates unchanged | | 2026-11-03 | patch | M10, #1902: the web build drew Persian and Arabic text as missing-glyph boxes. The browser has no system fonts, and `crates/text/build.rs` keeps the web catalog to Inter, Noto Sans Georgian, the wordmark and (with `FIGCRAFT_EMBED_CJK`) Noto Sans CJK, so craft-fonts' Noto Sans Arabic never reached it. `FIGCRAFT_EMBED_SCRIPTS=Arab,Hebr,…` (script tags as the manifest's scripts column lists them) now embeds those scripts' faces in a web build; the default build and its size are unchanged, and with `Arab` embedded the picker offers the Arabic UI as well (`cjk::can_show`, as on the desktop). Noto Sans Hebrew, Devanagari and Georgian join Arabic and Thai among the document fallbacks, so an embedded face draws its script in an Inter document. Tests: `web_embeds_other_scripts_faces_only_when_asked` in the build script, `every_embeddable_script_face_is_a_document_fallback`. | | 2026-11-05 | patch | #2014: the panels drew a String variable's Amharic value as boxes: the UI took a system face for Hebrew and Arabic only. `bidi::script_fallbacks` now samples one letter of each of 16 scripts (Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as well as Hebrew and Arabic; Bengali and Thai keep `crate::cjk`'s faces) against the system's families for each (Windows, macOS, the common Linux fonts), the first installed one that draws the letter taken once. Desktop only: the web build has no system fonts. Test: `bidi::tests::other_scripts_take_an_installed_system_face` (skips scripts the machine has no face for). | diff --git a/docs/mcp.md b/docs/mcp.md index 9b44a0c55..b94c5a56e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -94,8 +94,14 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: (writing through it would create its target, wherever that is). A path outside the roots gets the same refusal whatever exists there, so a refusal doesn't tell what is outside. Folders are compared by whole names: `/work2/x` is not inside `/work`. On Windows the case comes from the disk (`C:\WORK\x` is - inside `C:\work`), `\\?\` and UNC (`\\server\share\…`) paths are resolved like drive-letter ones, - and new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused. + inside `C:\work`), `\\?\C:\…` paths are resolved like drive-letter ones, and + new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused. + A path on another computer (`\\server\share\…`, `\\?\UNC\…`, WebDAV's `\\host@SSL\share\…`) or a device + path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`) is refused by its spelling before anything looks it up, since looking + it up would contact that host, unless a root is on the same share; a link whose target is one of those is + 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` @@ -182,6 +188,18 @@ Or in a project's `.mcp.json`: leaves its contents where they are, and so does resizing a frame with `cmd` held (constraints ignored); a layer a mask hides can't be clicked there, and a mask group's box and exports are the mask's (plus any layers under the mask). +- Repeated UI (buttons, inputs, cards, list rows, tab bars, icons) is a component and its copies + are instances: make it once with `component.create` (or `create_node` type `component`) and place + each other copy with `instance.create {component, parent?, x?, y?}` rather than duplicating the + layers, so every copy follows the main. States and sizes are variants of one set: name the mains + `Property=value` (`State=Default`, `State=Hover`) and run `component.combineVariants` on them; + `component.addVariant {id}` adds one more. What changes per copy is a component property: + `component.addProperty {id, name, type: text|boolean|instanceSwap, layer}` on the component, or + on the set once its variants are combined, then `component.bindProperty {layer, property}` for + each other variant's layer (a property added to one variant before combining stays that + variant's, so an instance switched to another variant loses it); `instance.setProperties {ids, + properties}` sets it on each copy. The server's `initialize` instructions say this too, since + agents otherwise tend to copy layers. - Children of an auto-layout frame are positioned by the layout: set `layout`, `gap`, `padding`, `mainAlign`, `crossAlign`, `sizingH`/`sizingV` instead of x/y. In one call, `layout` applies before the keys that tune it, so `{"layout": {"mode": "vertical"}, "gap": 8}` keeps the gap; @@ -691,7 +709,10 @@ on; `key` resolves keys the way the canvas does. Commands behind keys: in the pages list, never opened and holding no layers), `page.list` (each page's `divider`), `page.rename`, `page.move {id, index}`, `page.duplicate` ("Copy of …", after its source, with its colour, flows (starting at the copied frames), prototype settings and guides), - `page.delete` (the last page that isn't a divider stays). + `page.delete` (the last page that isn't a divider stays), `page.setOpening {id?}` (the page the + file opens on for everyone who opens or joins it, the current page when none is named, a divider + refused: a document change, so it syncs in a live session and undoes, #1817; the choice is saved + with the file and opens it for everyone, whichever page the saver was on). - `component.list`: each component's `folder` (the Assets panel's folders: its page, the frames holding it, then its name's slash parts) and `label` (the name on its tile). - `view.contextMenu` (`Shift+F10`): the selection's context menu, at its layer row when the layers diff --git a/docs/prototyping-parity.md b/docs/prototyping-parity.md index 6ca217eec..d9f5d51b0 100644 --- a/docs/prototyping-parity.md +++ b/docs/prototyping-parity.md @@ -39,7 +39,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Key/gamepad on a controller: the trigger takes a controller button in place of a key, pressed anywhere on the screen | **added** | `Gamepad A` … `Gamepad Home` (the standard layout's 17 buttons, face buttons by position) as the trigger's key, picked from the Controller menu beside the key field; the player polls controllers only while the prototype has such a trigger and the window has the focus, and plays each press once (held buttons don't repeat); Windows reads Xbox-compatible controllers, the browser its Gamepad API's standard-mapped ones; `controller_buttons_fire_key_gamepad_triggers`, `controller_buttons_play_key_gamepad_triggers` | | A controller button is not the keyboard key of the same name; the d-pad is not the arrow keys; a keyboard modifier held makes a button press another input | silent | pinned as stated | | REST files: controller triggers (`device` other than `KEYBOARD`) | **added** | they were skipped; their code reads as the standard layout's button index (silent: the schema doesn't say what the codes count); two buttons at once or an unknown code is skipped with a warning; `controller_triggers_import_as_their_button` | -| After delay: timed from when the screen shows | pass | `triggers_fire_on_their_gesture` | +| After delay: timed from when the screen shows; a chain of variant changes on After delay plays to the end, each step's delay counted from when its variant appears (#2352) | pass | `triggers_fire_on_their_gesture`, `a_chain_of_variant_after_delays_plays_to_the_end` | | After delay on an overlay: timed from when the overlay opens, again each time it opens | **fixed** | timed from when the screen under it arrived (a toast opened late closed at once) and fired only the first time; `an_overlays_after_delay_counts_from_when_it_opens` | | Nested layers with the same trigger: the top-most layer's interaction wins; a layer without that trigger lets it through to the one under it | pass | `nested_hotspots_and_click_through`, `hotspots_priority_and_click_through` | | A layer without interactions over a hotspot | silent | it doesn't block it: clicks reach the hotspot under it | @@ -108,6 +108,7 @@ tool; opt-in), **silent** (the documentation doesn't say; the case pins the curr | Date | Change | Summary | |---|---|---| +| 2026-11-14 | patch | M5, #2352: a chain of variant changes on After delay plays to the end (A to B to C to D); before, the step a variant had fired stayed marked as fired when the instance changed variant, so the chain stopped after one step, and now each step's delay counts from when its variant appears (`crates/ui-egui/src/present/afterdelay_chain_tests.rs`). Numbers unchanged | | 2026-11-09 | patch | M7, #2158: a connection dragged from a variant (or a layer in it) onto a sibling variant of its set did nothing, because the drop looked only for top-level frames and a variant's top-level frame is its set. It now creates Change to the sibling (On click, Instant, as measured in Figma's web app) and outlines the sibling while dragging; the set's background and the variant itself still add nothing, and a frame outside the set still gets Navigate to | | 2026-11-06 | patch | M5, #2027: `proto.settings` took any string as the device (`"Pixel Nonexistent"`, `"iphone 16"`) and saved it in the file; the presenter then drew no device while its picker showed the name as if it were one, and the settings couldn't be read back over MCP (`proto.settings {}` answered `{ok: true}`). An unknown name (or a non-string) is now refused with every name the picker offers (`None`, `Custom size` and the devices), as an unknown colour is refused with the device's colours, and nothing changes; a known name is taken in any case and stored as the picker spells it. Every call answers the page's settings after it: device, background, rotation, the colour shown, the screen as presented, the custom size and responsive. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back` | | 2026-10-31 | minor | Gap 15: the Controller menu names buttons as PlayStation and Switch controllers do; that item leaves the missing list. Estimate unchanged. Test: `present::tail_tests`. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6c69fe034..c88776361 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # FigCraft parity with Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; 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; an exported layer with a background blur or glass keeps the blurred content behind it within its bounds (#2213); a typed number and a full stop at the start of a paragraph starts a numbered list at that number, as measured in Figma 2026-11-11; justified Chinese, Japanese and Korean text, written without spaces, spreads each line's room between its characters so its right edge aligns (#1970); joining the two ends of a path broken open by a deleted point closes it again, so its fill and selection outline follow the new segment and its corner radius instead of a straight line across the gap (#1951); glass's docs say which centre splay bends away from and where a shape gets no core; glass bends towards its core, rounded rectangles 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, measured against the reference tool; bulleted lists use the same bullet at every level of indentation, as the help center says, instead of a white bullet and a square at the deeper levels; typing `1)` and a space at the start of a paragraph starts a numbered list, as `1.` does, both being the help center's creation characters; a link on text is underlined by default, as the help center says, and Underline takes the underline off while the link stays; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the browser build uses the fonts installed on the computer once asked, each read when text uses it (#1051); plugin widgets have hover styles: a layer's `hover` fill, stroke, opacity or text colour shows while the pointer is over it (gap 6); Thai, Lao, Khmer and Burmese lines break between words (#1219); MCP and control calls name their document (#998); shadows of images with transparent pixels follow their alpha (#1289); Arabic draft catalog; truncated text fills its last line before the ellipsis and keeps truncating when resized; auto-height text with max lines (#1375, #1376, #1377), numbers unchanged; 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; `.sketch` import, best effort: import/export breadth 86% → 87%, file formats 60% → 61%, headline numbers unchanged; Canvas & navigation's remaining work no longer lists outline mode's Include hidden layers and Include object bounds; boards: area 22 (weight 0, outside the weighted sum); 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, iteration marks 〱–〵 and the halfwidth parentheses; Turkish reviewed, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; vector edit mode regions: hover hatch, selection and drag; plugin log byte/count limits (#191); core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; starter templates, a Templates tab and Getting started tips on the home screen: essentials ~57% → ~59%; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages, numbers unchanged but menu breadth 211/211; text box sizes measured against documents re-saved by other software: whole-pixel line heights, advances on a 1024-per-em grid, letter spacing between glyphs only, numbers unchanged; .fig export checked by opening written files in other software, numbers unchanged; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; 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; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; auto layout behaviour suite and fixes; 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; feature breadth ~80%; ready ~49%; last major: full re-measure against Figma desktop 126.10.7; rows for the community batches: Selection colors, smart-selection spacing and a Present tab (#753), `.fig` import fidelity, paste from another design app, a `.fig` copy from Save as; control requests while the window is minimised (#720); catalog counts re-measured; automation roots (#715); number variables in the text content picker (#629); frames and sections convert into each other (#719)) · **Target:** Figma Design (desktop app 126.10.7, macOS) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (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 @@ -11,6 +11,8 @@ summarizes it; [`gaps.md`](gaps.md) is the ranked work list; the measured menu c [`prototyping-parity.md`](prototyping-parity.md), [`dev-mode-parity.md`](dev-mode-parity.md), [`collaboration-parity.md`](collaboration-parity.md), [`boards-parity.md`](boards-parity.md). +> SVG XML wire follow-up (2026-11-16): export escaping and XML 1.0 character checks delegate to pinned `craft-xml`. Attribute tab/LF/CR are emitted as references to survive XML normalization. Local SVG document/path serialization and import mapping remain; this scoped change does not raise the parity grade. Hosted validation is pending. + ## Headline | Number | Value | Kind | @@ -649,6 +651,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th | Date | Change | Summary | |---|---|---| +| 2026-11-15 | minor | 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 | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius rounds every sharp corner of its result (row 4). Numbers unchanged | | 2026-11-08 | minor | M8: measured in Figma on 2026-11-08, vector edit mode's Point section: X and Y show the value the selected points share, or Mixed when they differ, and a typed value sets every selected point's own coordinate in the layer being edited, points of other edited layers left as they are (it moved the group's top-left before); a relative edit (`+10`, `*2`, `/2`) typed into a Mixed field applies to each point's own value (`vector.edit.position` takes a number or `{add}`, `{mul}`, `{div}` per axis); the W and H row and other edited layers' points are unchanged. | | 2026-11-11 | patch | M4: typing a number, a full stop and a space at the start of a plain paragraph starts a numbered list at that number (`5. ` then "x", Enter, "y" reads 5. then 6.), as measured in Figma web on 2026-11-11 (it has no start-number field: the start comes only from the typed number); before, only `1. ` and `1)` started a list. `0. `, `12a. ` and a bracket after a number other than 1 stay text (not measured), and the number is capped at 9999. Also measured: a plain paragraph or a bullet item between numbered items restarts the count at 1, and an indented sub-item does not break the outer count; those rows were pinned as silent. Tests: `text_tail_tests::typed_list_starts`, `typed_number_starts_the_list_there`, `tail_tests` restart rows. Numbers unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4c6581510..0137c49c1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); 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 marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; 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 keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; 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); 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); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (going back to a page shows it where it was left, not fitted again; Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); 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 marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; 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 keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; 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); 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); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -16,9 +16,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| | Light and dark themes | done | colours from `theme::Tokens`; component, variant and instance rows in the Layers panel take the theme's component tint, at AA on the panel and on their selected row (hidden ones in the faded text colour, at least 3:1 on the panel, a hovered row and their selected row), and the rows inside a selected component a tone of its row (`layers_component_rows_tests`, #1903); a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) | -| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | -| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | rail and tab strip icons 20 pt (#553); frameless window on Windows/Linux with drawn buttons; on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | -| Light and dark themes | done | colours from `theme::Tokens`; a file or a page made while the dark theme shows gets a `#1E1E1E` page (`#F5F5F5` in the light theme), its own from then on: changing the theme repaints no page and opened files keep theirs; the file the app opens with takes the theme once it is known; the CLI, MCP and exports have no theme and keep `#F5F5F5`; text drawn with the Text tool is white on a dark page and black on a light one (so is text a command makes in the app without naming a fill; headless sessions keep black) (`theme_pages_tests`, `dark_page_text_tests`) | +| UI3 layout: tab strip as title bar, icon rail, file header, pages + layers, floating bottom toolbar with flyouts, Design / Prototype / Inspect panels | done | rail and tab strip icons 20 pt (#553); frameless window on Windows/Linux with drawn buttons; tabs reorder by dragging along the strip, and closing one whose file has unsaved changes asks Don't Save / Cancel / Save (Alt+close drops the changes at once, #2032); on a Wayland compositor that offers no server-side decorations (GNOME) the window gets winit's Adwaita controls instead (#592; checked by its author on GNOME, KDE not run) | | Minimize UI (Shift+Cmd/Ctrl+\\, the Minimize button by the file name) and Show/Hide UI (Cmd/Ctrl+\\) | done | Minimize collapses the navigation bar and both sidebars and keeps the toolbar and the panel widths; "If you select an object while the panels are minimized, the left sidebar remains minimized while the right sidebar expands [...] Once all objects are deselected, the right panel minimizes again" (Explore the navigation bar and left sidebar); a small Expand button at the top left of the canvas puts them back (FigCraft's own, the article names no control for it). Hide UI takes the toolbar too (`panel_width_tests`, `shortcuts_tests`; #1835) | | Resizable panels | done | each panel's edge drags its width (left 240–450, right 240–500, 240 by default, as measured in Figma's web app on 2026-11-08; a double-click on the edge or View ▸ Panels ▸ Reset panel widths puts the default back); the widths are each window's own, the main window's are kept in the preferences when a drag ends and come back at the next start (a width saved under other limits is clamped to the current ones on load, and one that isn't a number, NaN or infinite, falls back to 240), a new window opens with those of the window it comes from; Minimize UI hides the panels and brings them back as they were; the view keeps its centre and zoom while a panel is resized; in a window too small for them the panels give way so the canvas keeps 160 px (the left one first), down to the smallest window (800×500) (`panel_width_tests`). The double-click reset to 240 matches Figma's; no snap points | | Design panel's sections on one grid | done | every section lays its rows out on the same grid: the panel is 240 pt, its content 16 pt in from the left and 8 pt from the right, two 88 pt columns at that width with 8 pt gutters and a 24 pt column for the buttons at a row's end (the columns are flex, so they share the panel when it is dragged wider); rows 24 pt in a 32 pt track, 10 pt captions over them; section titles 11 pt semibold and a row's values 11 pt, their buttons 24 pt and 4 pt apart. The panel's edge is drawn inside it: a frame stroke counts as margin and took 1 pt off each side, putting every right margin 1–2 pt out (checked in the app on Windows over the control channel) | @@ -51,7 +49,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) (a child's padlock can't be toggled while its parent is locked) | | Rename: double click, F2 / Cmd+R, Tab to the next row; several layers open Rename layers (match, regular expressions, current name and number codes, start value, preview) | done | numbered in stacking order, pinned; Tab on the last row wraps to the first row's rename, measured in Figma's web app on 2026-11-12 (`tab_on_the_last_row_commits_and_wraps_to_the_first`); Shift+Tab on the first row ends the rename (not measured); Tab and Shift+Tab move only the rename, the selection stays on the layer first renamed, measured in Figma's web app on 2026-11-12 (`tab_while_renaming_leaves_the_selection_on_the_first_layer`); a double-click on a row's icon zooms to the layer (selecting it first) and renames nothing, while a double-click on the name or elsewhere on the row still renames, measured in Figma's web app on 2026-11-12 (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`) | | Find layers (filter by name) | done | not covered by the documentation | -| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`) | +| Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`); going back to a page shows it where it was left in the session, only a page not shown yet is fitted to its content (`page.select`, Previous/Next page; `page_view_tests`) | | Assets panel: folders from page, frames and slash names (fold away), search, thumbnails, drag onto the canvas or into frames and auto layout, Alt-drop swap, enabled libraries | done | Shift+I (Quick insert), Alt+2 and View ▸ Panels ▸ Assets open it; the toolbar's Resources button was removed (the left rail's Assets tab and those shortcuts are the ways in) | | Hide when publishing from the Assets panel's context menu | done | a right-click on one of this file's components (also Libraries ▸ Hide when publishing for the selection, `component.hideWhenPublishing {ids?, on?}`): the model's sign of it is the name, so hiding puts a `.` before the name and showing takes the leading `.` and `_` away (one undo step, saved and synced like a rename; a variant or a layer inside hides its whole component or set); a hidden component shows a crossed eye on its tile and a dimmer name, the menu item its check mark; the next publish leaves it out and brings it back when shown again (`hide_publishing_tests`). Library components (read-only here) have no such menu | @@ -65,13 +63,12 @@ interaction feel only partly compared: the interactions measured so far, case by | Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) | | Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming | | Resize handles: Shift keeps proportions, Alt from centre, constraints-aware | done | Alt shrinks too; past an edge flips (several layers mirror); groups and mixed rotations scale each layer along its own axes, keeping rotation and flip (no skew: children turned off a right angle are approximate); Cmd/Ctrl ignores a frame's constraints (`transform_behaviour_tests`); Shift keeps the ratio (a corner by the axis dragged most, an edge scaling the other axis about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, each read afresh on every move (`handle_drags_resize_by_the_documented_rules`; measured in Figma's web app, 2026-11-08; Ctrl/Cmd while dragging not measurable) | -| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; the Rotation field shows and sets the rotation on the page (its own angle plus its parents'), in frames and groups alike, measured in Figma's web app 2026-11-10 (#2196): a rectangle drawn inside a turned frame reads 0, typing 7 makes it 7 on the page; the panel sends `node.set absoluteRotation`, while `rotation` stays the angle to the parent for scripts, inspect, codegen and the formats. Pinned, not measured: several layers read one value when their page angles agree (typing sets them all, one undo step); a flipped layer reads in the same form as before (a horizontal flip reads 180 plus the angle) and typing keeps the flip; a flipped parent is handled by the world math. Tests: `absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre`, `the_absolute_rotation_key_turns_about_a_moved_origin_too`, `the_rotation_field_shows_and_sets_the_rotation_on_the_page` | -| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0 | +| Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0; the Rotation field shows and sets the rotation on the page (its own angle plus its parents'), in frames and groups alike, measured in Figma's web app 2026-11-10 (#2196): a rectangle drawn inside a turned frame reads 0, typing 7 makes it 7 on the page; the panel sends `node.set absoluteRotation`, while `rotation` stays the angle to the parent for scripts, inspect, codegen and the formats. Pinned, not measured: several layers read one value when their page angles agree (typing sets them all, one undo step); a flipped layer reads in the same form as before (a horizontal flip reads 180 plus the angle) and typing keeps the flip; a flipped parent is handled by the world math. Tests: `absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre`, `the_absolute_rotation_key_turns_about_a_moved_origin_too`, `the_rotation_field_shows_and_sets_the_rotation_on_the_page` | | Flip, rotate 90° | done | | | Rotation origin (Alt+R) | done | a handle at the selection's centre to drag (snaps to the box's corners, edge middles and centre), double-click puts it back, Escape or Alt+R hides it; the corner handles, the rotation field, Rotate 90°/180° and `transform.rotate` turn about it; it follows the layers and lasts as long as the selection, not saved (the documentation doesn't say; pinned) | | Align and Distribute (Design panel and shortcuts) | done | single and multi-layer Align and Distribute were measured in Figma's web app on 2026-11-12 and match: one layer aligns to its frame, several to their combined bounds, Distribute spaces three or more. Align is disabled for a child in an auto layout frame's flow (Alt+A and Alt+S do nothing, the frame is untouched), as measured; the panel's tip says the frame places the layer, and an absolutely positioned child still aligns to its frame (not measured, so today's behaviour is kept). Tidy up was measured to differ (Figma keeps the order and sizes and evens one gap per axis): not yet. Tests: `align_is_unavailable_for_a_child_in_an_auto_layout_flow`, `an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it`, `the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow` | | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | -| Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | +| Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's move and rotation (the move of its centre in the page frame, then the turn about the copy's own centre, or the selection's centre for several layers; not its size), also after a Duplicate whose copy was moved, as long as the copies stay selected and the selection hasn't changed (measured in Figma's web app, 2026-11-12); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | @@ -85,10 +82,8 @@ interaction feel only partly compared: the interactions measured so far, case by | Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | | Smart selection spacing | partial | with layers in a row, a column or an aligned grid selected, the Layout section shows horizontal and vertical spacing ("Mixed" until set; typed, scrubbed, fractional and negative) and pink handles in the gaps on the canvas drag them, one undo step, Escape cancels (`arrange.spacing`; sizes, parents and offsets within each track kept; at most 2,000 layers; flow children, locked layers and layers inside instances left out). A ring at each layer's centre drags it to another place in a regular row, column or complete top-left-aligned grid: the others close up and make room around it with the gaps kept, and with Cmd/Ctrl held the two layers swap places instead, previewed live while dragging (`selection_reorder_tests`; no ring on a layer under 16 px on screen). Not covered: reordering irregular grids, and several marked layers moved together. Checked by its author on macOS and in the app on Windows (#402) | | Tidy up | partial | measured in Figma's web app on 2026-11-12 (a row, a column, a 2 x 3 grid of unequal sizes and its transpose, and many runs on the gap, the unavailable cases among them): the order and the sizes are kept; in a row or a column the first layer also stays and the other axis is untouched (a grid can move a layer on both axes, as below). A row (one group of layers whose Y ranges overlap, side by side) evens its horizontal gaps and a column its vertical gaps to one gap: the most common existing gap (the smaller of two equally common ones), else the mean rounded to a whole number, half up (30, 40, 30 gives 30; 80, 20, 45 gives 48; 10, 10, 50, 90 gives 10; 10, 25 gives 18; 10, 25, 30 gives 22). Layers of a row may overlap along X, and overlapping layers in a chain count as a row (the first and third needn't touch): the negative gap counts in the mean (50 px squares at X 0, 60, 105, 170, gaps 10, -5, 15, give X 0, 57, 114, 171; squares at X 0, 40, 80, 150 give 0, 40, 80, 120). Measured in Figma's web app on 2026-11-13: a negative gap is raised so no layer reaches the one two places before it, floor(-w / 2) + 1 for the narrowest interior layer's width w, so 10, 20 and 30 wide interior layers among 100s give -4, -9 and -14 (X 0, 96, 102, 198, 294, 390 for widths 100, 10, 100 x4), while six layers 100 wide keep the most common gap, -40; only those widths were measured, and an explicit `spacing` is not raised. A grid (two or more rows and columns, one layer in every cell) is packed along the axis with more groups: a column is as wide as its widest layer around the middle of where its layers were, the first column stays, each layer is centred in its column to a whole pixel with Snap to pixel grid on, and every column is stacked from the selection's top; a grid with more rows than columns is the mirror image (centred rows, laid out left to right). The vertical gap reads 51 or 52 in Figma's own runs (mean 51.67), so FigCraft's positions along a stack can differ by a pixel there. Unavailable, as measured, for fewer than three layers, for layers that all overlap each other (one row and one column), for a diagonal and for an irregular layout: a greyed-out row with a tip in the Design panel's menu, the command moving nothing and adding no undo step. Not measured, FigCraft's choices: a 2 x 2 grid packed as columns; layers in an auto layout flow being unavailable (the frame places them; the measurement could not tell this from an irregular layout); the 2,000 layer cap; rotated layers counting by their box; gaps a pixel apart being different gaps; an explicit `spacing` setting the gap and taking two layers; no rounding with Snap to pixel grid off. Tests: tidy_tests | -| Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also offers enabled libraries' published color styles and Create style (`selection.createColorStyle`); no library variables and no new variable from a row (#403) | -| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) | | Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance; a layer without children shows it only with two paint groups, such as a red fill and a blue stroke; one paint group, however many layers share it, hides it), counting the selected layers' own fills and strokes and their descendants' (measured in Figma's web app, 2026-11-09, #2188, on frames, groups and rectangles only; the rule for components and instances is not measured), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also lists each enabled library's published color styles under the library's name (a library that can't be read offers none), and a linked row's menu switches it to another style; a library style is copied in, linked and read-only, in the same undo step (`selection.applyColorStyle` with `library`). Create style on an ordinary row asks for a name (the next free "Color n" first) and makes a style of the row's whole paint, gradients, opacity, blend mode and variables bound to gradient stops included, linked to every fill and stroke the row stands for in one undo step; a name in use keeps the window open (`selection.createColorStyle`). Text ranges with fills of their own take the style's value, without a link. No library variables from there, and no new variable from a row (#403) | -| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes | +| Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) | ## Tools @@ -99,13 +94,10 @@ interaction feel only partly compared: the interactions measured so far, case by | Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) | | Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; a Count handle sits on a polygon's first vertex or a star's first outer point clockwise from the top, and the count follows the pointer's angle about the centre, `round(360 / angle)` clockwise from the top point, clamped to 3 to 60, in one undo step (measured in Figma's web app, 2026-11-12; a polygon's maximum wasn't read and is clamped at 60 like the star's, the help center's range); corner smoothing rounds rectangles and frames only | | Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) | -| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | +| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn, an arc reaching along the whole of a segment whose other end is sharp and half of one whose other end is rounded too, so one rounded corner of a 100 × 100 square with radius 100 runs from one neighbour to the other, while the radius field keeps what was typed (#2334, `vector_radius_tests`, `vector_point_radius_tests`); Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | -| Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003) | -| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | -| Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. Not yet included: per-paragraph settings, text-style support and the `.fig` import/export mapping (#1827). Test: `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003); a boolean group takes a corner radius from the Design panel and from `node.set cornerRadius`: every sharp corner of its result rounds, convex and concave, layers inside keep their own radius and do not stack with it, a radius larger than the edges allow shrinks to fit while the field keeps the value typed, Flatten bakes the arcs and a mixed selection reads Mixed; measured in Figma's web app on 2026-11-10 (#2222; `crates/pathops/src/round_tests.rs`, `crates/render/src/boolean_radius_tests.rs`, `crates/engine/src/boolean_radius_tests.rs`, the boolean group test in `crates/ui-egui/src/field_tests.rs`). Pinned and not yet compared with Figma: corner smoothing on a boolean group draws the polygon profile between straight edges, a corner beside a curve stays within the curve piece next to it, and there is no radius handle on the canvas | -| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; no spell check | +| Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | | Text: wrap style (Auto, Balance, Pretty) | done | per text layer (`wrapStyle` on `node.set`, `text.wrapStyle`, the Type settings control under Vertical trim, inspect, CSS `text-wrap: balance` or `pretty`): Auto breaks greedily; Balance narrows each paragraph as far as it goes without another line, so its lines come out close to the same length (what browsers do for `text-wrap: balance`); Pretty keeps lines full and, when the last line is one word, narrows one of the last four lines just enough to give a word to the lines after it (Explore text properties: "Auto: Figma fits as many words as possible on each line before wrapping to the next", "Balance: Figma distributes text as evenly as possible across every line, so each line is close to the same length", "Pretty: Figma keeps each line full, but adjusts the last four lines to avoid an orphan"). Saved line breaks from a file still win. At three levels (the text layer, a paragraph and a text style, per Explore text properties): the paragraph level is the caret's or the selection's paragraphs while editing (`text.wrapStyle`; the control follows them), or `start`/`end` on `node.set wrapStyle` (a paragraph's own style beats the layer's; setting the layer sets every paragraph again; Enter carries it to the new paragraph; inspect reports `lineWrapStyles` when paragraphs differ and CSS `text-wrap` only when they agree); the text-style level is a style's `wrapStyle` (shown read-only in the style editor, applied with the style, moved by `style.update`, unlinking when edited). The `.fig` import/export mapping stays open (#1827): a `.fig` export leaves the wrap styles out and a `.fig` import reads every text as Auto, so the wrap styles are lost through a `.fig` round trip. Test: `text_behaviour_tests::wrap_style_per_paragraph_overrides_the_layers`, `styles_behaviour_tests::text_styles_carry_the_wrap_style`, `text_behaviour_tests::balance_and_pretty_wrap_styles_break_lines_as_documented` | | Text: direction override (Text ▸ Text direction) | done | per paragraph (`ParaList::direction`: auto, ltr, rtl): Text ▸ Text direction ▸ Auto / Left to right / Right to left and `text.direction {direction, ids?}` set the edited paragraphs while editing, else every paragraph of the selected texts; `node.set textDirection` the layer's (or the chars `start`/`end` name); the Type settings control appears once a right-to-left script is in the text or a direction is forced; inspect reports `textDirection` when the paragraphs agree and `lineDirections` otherwise; Developer Mode's CSS writes `direction: ltr` or `rtl` when every paragraph is forced the same way (with `text-align: left` beside `rtl`, as Left is absolute on the canvas); `.fig` import and export carry each line's `sourceDirectionality`, read up to the paragraph count. Layout gives the paragraph its base level, so a forced right-to-left paragraph of Latin letters starts at the right, mirrors its list gutter and indent and orders its runs right to left, and a forced left-to-right paragraph of Hebrew the other way ("By default, Figma automatically handles text direction based on language detection. However, controls are available to override text direction per paragraph", "Go to Text > Text direction. Select Left to right or Right to left", Add right-to-left text). Not included: a direction in text styles (the article names none). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests` | | Text: superscript and subscript | done | `sups` / `subs` use the font's own glyphs where it has the feature and every letter or digit of the run gets one; otherwise the standard glyphs are drawn shrunk and raised or lowered by the font's OS/2 superscript and subscript metrics (0.65 em at 0.35 em up or 0.14 em down without them), and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says ("Figma draws a synthesized version by using the font's standard version of the character, shrinking it, and positioning it accordingly"; mixed glyphs "all update to the synthesized form for consistency"), #1828; tests `text::tests::superscript_native_or_synthesised_and_never_mixed`, `text_behaviour_tests::superscript_and_subscript_are_synthesised_without_glyphs_for_them` | @@ -120,7 +112,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Item | Status | Notes | |---|---|---| -| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_testsPreferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_testszoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) | +| Pan/zoom: wheel, pinch, Space-drag, Shift+0/1/2, Cmd+0, `+`/`-` | done | Shift-wheel pans sideways, pinch and the zoom tool keep the point under the pointer; Preferences ▸ Scroll wheel zoom makes a mouse wheel zoom about the pointer and Cmd/Ctrl+wheel scroll (a wheel told from a trackpad by the device macOS reports, elsewhere by line versus pixel steps; #1390); the arrows pan the view with nothing selected by 64 px, 320 px (five steps) with Shift (`view.pan`; measured in Figma's web app at 100% zoom: one Right press 62–64 px in two trials, Shift+Right about 320 px, reading offsets from screenshots, about ±3 px); Preferences ▸ Invert zoom direction (Figma's Preferences menu has it, checked 2026-11-09; #2145) reverses wheel zoom: Cmd/Ctrl+wheel, and a plain mouse wheel with Scroll wheel zoom on, zoom out where they would zoom in, by the same factor, while a trackpad pinch and panning are unchanged (only the setting's existence was measured, so the pinch is left alone); zoom steps, limits (2%–25,600%) and frame order pinned where the documentation is silent (`view_behaviour_tests`); Zoom to selection (Shift+2) fits the selection into the canvas above the floating bottom toolbar with a 40 pt margin on all four sides, centred in that area, at a continuous zoom (measured in Figma's web app, 2026-11-09; `zoom_to_selection_leaves_forty_points_and_clears_the_toolbar`, `zoom_to_selection_on_a_wide_layer_is_limited_by_the_width`, `zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height`); Zoom to fit (Shift+1) keeps its 64 pt margin, margin not measured yet (`zoom_to_fit_is_unchanged`) | | Rulers and guides (drag out, move, remove; rotated frames; frame guides) | done | guides belong to the page or a top-level frame (a frame moved into another keeps its guides but they stop applying); a click selects one for Delete, the arrows or the context menu's Remove guide; Alt-drag drops a copy; Alt while dragging measures to the layers in the frame it crosses; ruler numbering checked by eye only | | Frame labels (rotated, right-to-left), size badge | done | | | Outline mode | done | Outlines, outlines for the selection, mask outlines, frame outlines; shapes are clicked on their outlines, reaching layers behind; View ▸ Outlines ▸ Include hidden layers (`view.outlinesHiddenLayers`) outlines hidden layers too and Include object bounds (`view.outlinesObjectBounds`) draws the box of every layer whose outline isn't its box (groups, text, ellipses, vectors); what either draws can be clicked there (a hidden layer on its outline, a group on its box) and nothing else can; both are view settings like the other outline flags (per file, off in a new one, checked in the menu); the lines are light on a dark page (`outline_options_tests`). The main menu now shows a check mark beside every View toggle that is on | @@ -149,7 +141,6 @@ in the table. `crates/ui-egui/src/shortcut_keys_tests.rs` drives the keys a look | | Count | Notes | |---|---|---| | Documented shortcuts (rows) | 137 | each with macOS and Windows/Linux keys | -| Bound as documented | 136 (110 before this suite) | 113 keymap bindings, 15 held keys, gestures and presentation keys, 6 vector edit tool keys | | Bound as documented | 136 (110 before this suite) | 113 keymap bindings, 16 held keys, gestures and presentation keys, 6 vector edit tool keys | | Bound on other keys (documented conflict) | 1 | Run last plugin: the documentation also gives Ctrl+Alt+P to pixel preview on Windows; the plugin takes Ctrl+Alt+Shift+P there | | Missing | 0 | moving the rotation origin (Alt+R, `transform.rotationOrigin`) and placing an object with Enter after choosing its tool (`tool.place`) were the last two | @@ -216,11 +207,14 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| +| 2026-11-17 | patch | M8: each page keeps its view in a session: going back to a page (the Pages list, `page.select`, Previous/Next page) shows it where it was left instead of fitting it again; a new page is still fitted, and going to the page shown moves nothing (`page_view_tests`) | +| 2026-11-13 | patch | Rows that recent merges had duplicated or garbled are merged back into one row each (no behaviour change): UI3 layout, Light and dark themes, Rotate just outside a corner, Selection colors, Keyboard box selection, Boolean groups, Text: point, auto height, fixed, Text: wrap style, Bound as documented, Pan/zoom. | | 2026-11-12 | patch | M8: a double-click on a layer's icon in the Layers panel selects the layer and zooms the canvas to it (`view.zoomSelection`) and starts no rename, as measured in Figma's web app on 2026-11-12; a double-click on the name or elsewhere on the row still renames; the icon's hit area is the rect the row paints the icon in (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`), Rename row | | 2026-11-12 | minor | M8: Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12. A row or column evens one gap (the most common one, the smaller of a tie, else the mean rounded half up) and keeps the other axis, layers of a row may overlap along X (also in a chain, and a negative gap is raised so no layer reaches the one two before it, measured in Figma's web app on 2026-11-13), and a grid is packed along the axis with more groups; fewer than three layers, layers that all overlap, a diagonal and an irregular layout grey the row out and move nothing. Measured: those rules and the unavailable cases; FigCraft's choices: a 2 x 2 grid as columns, auto layout flow children, the 2,000 layer cap, rotated layers by their box, `spacing` with two layers, and no rounding with pixel snapping off. Tests: tidy_tests (a_row_keeps_its_order_sizes_and_y_and_evens_the_gaps, gaps_that_all_differ_take_their_mean_taken_down, a_mean_is_rounded_half_up, two_equally_common_gaps_give_the_smaller, an_overlapping_pair_in_a_row_is_tidied_and_its_negative_gap_counts, a_grid_is_tidied_by_columns, a_transposed_grid_is_tidied_by_rows, layers_on_a_diagonal_are_unavailable, an_irregular_selection_is_unavailable and the rest). | | 2026-11-13 | patch | M8, #2307: with Crop chosen in an image fill's colour picker, a press and drag on the image moved the whole layer: the press closed the picker, which committed the crop as a plain move. The picker now treats a crop drag as its own control (as it does the open gradient's handles, #1852), so the drag moves the picture inside the layer. A drag whose gesture something else committed under the held button no longer shows the engine's internal "no gesture in progress" as a message (`EngineError::NoGesture`, dropped by the canvas). Tests: `crop_image_tests::crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_layer`, `a_drag_whose_gesture_was_committed_under_the_button_shows_no_message`. | | 2026-11-12 | minor | M8: Align is unavailable for the one selected layer of an auto layout frame that takes part in its flow, as in Figma (measured in Figma's web app on 2026-11-12: the Design panel's Align buttons are greyed out, Alt+A and Alt+S do nothing and the frame's alignment doesn't change). `align_target` returns none for it, so `can_align` is false and the `align.*` commands leave the layout alone; the disabled tip reads "A layer in an auto layout frame is placed by its frame" (`align_blocked_by_auto_layout`). An absolutely positioned child still aligns to its frame and multi-layer selections are unchanged (neither measured). Single and multi-layer Align and Distribute otherwise matched Figma; Tidy up differs (Figma keeps the order and sizes and evens one gap per axis) and is not yet changed. Tests: `align_is_unavailable_for_a_child_in_an_auto_layout_flow`, `an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it`, `the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow` | | 2026-11-12 | patch | M5, #1560: the context menu's Select layer lists locked layers with a padlock in the leading column (the Layers panel's padlock icon; a row both selected and locked shows the check) and picking one selects it, as Lock and unlock layers' note says and as measured in Figma's web app, 2026-11-10; the submenu shows only with more than one layer under the pointer (measured on a single locked layer only: the least certain rule). Left clicks, hover and marquee still never reach a locked layer. `select.layersAt` lists locked layers too and its rows gain `locked`. Tests: `layers_at_a_point_list_locked_layers_with_a_flag_and_select_set_takes_them`, `select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`. Counts unchanged | +| 2026-11-13 | patch | M4, #2334: a vector point's corner radius was cut to half of its shorter segment, so radius 100 on one corner of a 100 × 100 square drew a radius-50 arc. Figma (the issue's screenshot) draws it from one neighbour to the other. Now each arc may reach along the whole of a segment whose other end stays sharp, and along half of one whose other end is rounded too (as before; Figma's plugin docs clamp each end of such an edge to half its length); the shorter room of the two segments wins, and a smoothed corner uses the same room before losing smoothing. The stored radius and the Point section's field were already as typed. Not measured: how Figma splits a segment between two rounded ends with different radii. Tests: `vector_radius_tests` (doc), `vector_point_radius_tests` (UI) | | 2026-11-09 | patch | Zoom to selection: the selection is fitted with a 40 pt margin into the canvas above the floating bottom toolbar (`ViewState::bottom_inset`, set by the UI each frame, never saved; `view.set` takes `bottomInset`) and centred in that area, as measured in Figma's web app on 2026-11-09. Zoom to fit is unchanged (margin not measured yet). Numbers unchanged. | | 2026-11-13 | patch | M1: Shift+Cmd/Ctrl+V (Paste over selection) puts the pasted layers just above the selected layer, in its parent and in the copied order, at its position; they went to the top of the parent's layers, so in an auto layout frame they ended the flow instead of following the selected layer. | | 2026-11-12 | patch | Drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis with no 45° snap, Alt copies, Shift keeps a resize's ratio (an edge scales about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, and a modifier changed mid-drag is read fresh on each move; FigCraft matches in all six, Ctrl/Cmd while dragging could not be measured; no code change | this page | @@ -341,3 +335,4 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-12 | patch | M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre, so K, 2, Enter scales about the centre (measured in Figma's web app, 2026-11-09; `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`) | | 2026-11-12 | minor | M8: a selected polygon or star has a Count handle on the canvas (hover label Count N), measured in Figma's web app on 2026-11-12: it sits on the first vertex clockwise from the top (a star's first outer point, not inset), and a drag sets the count to round(360 / the pointer's clockwise angle from the top point about the centre), so 90 degrees gives 4, 72 gives 5 and 45 gives 8, with the step shrinking as the count grows; one drag is one undo step. The count is clamped to 3 to 60 (the help center's range for a star; a polygon's maximum was not read). Tests: `a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top`, `dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre`, `a_count_drag_is_one_undo_step` | | 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code | +| 2026-11-12 | minor | M8, #2293: Duplicate repeats the last copy's move and rotation, not only the shift of its bounds' corner. The step is the move of the copies' centre in the page frame (not turned by the accumulated rotation) plus the turn each copy has over its source, applied about the new copy's centre, or the selection's centre for several layers; size is not stepped; a deselect forgets the step. Measured in Figma's web app on 2026-11-12 (typed and dragged moves and turns, one layer and two). | diff --git a/sonar-project.properties b/sonar-project.properties index 7bd9e8ce6..8c36accaf 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -6,6 +6,14 @@ sonar.exclusions=craft-fonts/** # S4790 (weak hash): a .fig file names each image by the SHA-1 of its bytes (20 bytes, the only # length readers accept). It is an identifier the format fixes, not a security choice. -sonar.issue.ignore.multicriteria=fig_image_sha1 +sonar.issue.ignore.multicriteria=fig_image_sha1,gha-lockfile sonar.issue.ignore.multicriteria.fig_image_sha1.ruleKey=rust:S4790 sonar.issue.ignore.multicriteria.fig_image_sha1.resourceKey=crates/format/src/fig/export.rs + +# githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by +# .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned +# and the lockfile covers the actions those actions use too. Sonar does not read lockfiles yet, so +# the rule flags the tag refs anyway: +# https://community.sonarsource.com/t/githubactions-s7637-false-positives-for-actions-pinned-through-native-actions-lock/190814 +sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637 +sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/** diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7ff4bba4f..42ec5f610 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -266,6 +266,27 @@ fn parity() -> bool { true } +/// Cargo versions require a numeric core and nonempty, ASCII prerelease/build identifiers. +fn valid_version(v: &str) -> bool { + let (without_build, build) = v.split_once('+').map_or((v, None), |(version, build)| (version, Some(build))); + let (core, pre) = without_build.split_once('-').map_or((without_build, None), |(core, pre)| (core, Some(pre))); + let mut numbers = core.split('.'); + if !(0..3).all(|_| { + numbers.next().is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit()) && (n.len() == 1 || !n.starts_with('0')) && n.parse::().is_ok()) + }) || numbers.next().is_some() + { + return false; + } + let identifiers = |s: &str, allow_numeric_leading_zeroes: bool| { + s.split('.').all(|id| { + !id.is_empty() + && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + && (allow_numeric_leading_zeroes || id.len() == 1 || !id.starts_with('0') || !id.bytes().all(|b| b.is_ascii_digit())) + }) + }; + pre.is_none_or(|p| identifiers(p, false)) && build.is_none_or(|b| identifiers(b, true)) +} + fn version(sub: Option<&str>, value: Option<&str>) -> bool { let path = root().join("Cargo.toml"); let Ok(text) = std::fs::read_to_string(&path) else { return false }; @@ -277,9 +298,7 @@ fn version(sub: Option<&str>, value: Option<&str>) -> bool { .to_string(); match (sub, value) { (Some("set"), Some(v)) => { - let valid = - v.split(['-', '+']).next().is_some_and(|core| core.split('.').count() == 3 && core.split('.').all(|p| p.parse::().is_ok())); - if !valid { + if !valid_version(v) { eprintln!("version must look like 1.2.3 or 1.2.3-rc.1"); return false; } @@ -296,3 +315,49 @@ fn version(sub: Option<&str>, value: Option<&str>) -> bool { } } } + +#[cfg(test)] +mod version_tests { + use super::valid_version; + + #[test] + fn accepts_cargo_versions_including_prerelease_and_build_metadata() { + for v in [ + "0.0.0", + "1.2.3", + "18446744073709551615.0.0", + "1.2.3-0", + "1.2.3-01a", + "1.2.3-alpha-beta.1", + "1.2.3-18446744073709551616", + "1.2.3+001", + "1.2.3-rc.1+build.7", + ] { + assert!(valid_version(v), "{v}"); + } + } + + #[test] + fn rejects_versions_that_would_leave_the_manifest_invalid() { + for v in [ + "", + "1.2", + "1.2.3.4", + "01.2.3", + "1.02.3", + "1.2.03", + "18446744073709551616.0.0", + "1.2.3-", + "1.2.3-01", + "1.2.3-rc.01", + "1.2.3-a..b", + "1.2.3-a_b", + "1.2.3+", + "1.2.3+meta+again", + "1.2.3-alpha\"", + "1.2.3-alpha\n", + ] { + assert!(!valid_version(v), "{v:?}"); + } + } +}