mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-19 09:01:20 +01:00
Merge upstream/main into feat/variables-window-resize-2354
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Model-Effort: Opus 5.5 driver, no subagent
This commit is contained in:
commit
d3d48eebd5
123 files changed
+3759
-6930
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
Generated
+148
-9
@@ -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]]
|
||||
|
||||
+13
@@ -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"
|
||||
|
||||
+2
-1
@@ -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 cLine truncated
|
||||
> **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 |
|
||||
|
||||
@@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result<usize, ValueError> {
|
||||
|
||||
/// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1.
|
||||
fn attach(s: &str) -> Result<String, ValueError> {
|
||||
if s.contains(':') {
|
||||
if let Some((host, port)) = s.rsplit_once(':') {
|
||||
if host.is_empty() || port.parse::<u16>().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"],
|
||||
] {
|
||||
|
||||
@@ -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<ExitCode> {
|
||||
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::<String>();
|
||||
// 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");
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -118,3 +118,6 @@ real_name = "Ashok Ram"
|
||||
|
||||
[people.GiovanniBot]
|
||||
sync_github_name = true
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -91,6 +91,10 @@ pub enum NodeKind {
|
||||
flows: Vec<crate::proto::Flow>,
|
||||
#[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,
|
||||
|
||||
+49
-11
@@ -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<VectorNetwork> {
|
||||
self.rounded_smoothed(0.0)
|
||||
}
|
||||
@@ -424,7 +444,9 @@ impl VectorNetwork {
|
||||
*x = true;
|
||||
}
|
||||
}
|
||||
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect();
|
||||
let turns: Vec<Option<Turn>> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect();
|
||||
let rounds: Vec<bool> = turns.iter().map(Option::is_some).collect();
|
||||
let corners: Vec<Corner> = 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<Corner> {
|
||||
/// 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<Turn> {
|
||||
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<Corner> {
|
||||
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).
|
||||
|
||||
@@ -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<CubicBez> {
|
||||
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<Point> = 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::<Vec<_>>(), 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<Point> = 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:?}");
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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<Unresolved> {
|
||||
// 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<Refused> {
|
||||
// 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<Path>, b: impl AsRef<Path>) -> 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::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
@@ -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: `<tmp>/figcraft-roots-<name>-<pid>`, 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");
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
+112
-10
@@ -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<Value> {
|
||||
|
||||
/// 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<NodeId>,
|
||||
@@ -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<Step> {
|
||||
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<f64> = 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::<f64>() / n, res.iter().map(|m| m.1).sum::<f64>() / 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<Point> {
|
||||
let q = crate::tools::selection_box(doc, ids)?;
|
||||
Some(Point::new(q.iter().map(|c| c.x).sum::<f64>() / 4.0, q.iter().map(|c| c.y).sum::<f64>() / 4.0))
|
||||
}
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
_ => (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<Value> {
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator<Item = (NodeId, Vec<ExportSetting>)>, 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<Value> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,8 @@ impl FileSnapshot {
|
||||
/// files are from its folder.
|
||||
fn encode_at(&self, path: Option<&str>) -> Result<Vec<u8>> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
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<CommandSpec> {
|
||||
// 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<CommandSpec> {
|
||||
}
|
||||
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()?;
|
||||
|
||||
@@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let ds = s.ds_mut()?;
|
||||
ds.page = pg;
|
||||
ds.open_page(pg);
|
||||
ds.selection.clear();
|
||||
ds.zoom_to_fit();
|
||||
Ok(json!({"page": pg}))
|
||||
}
|
||||
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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<library::Stamp>,
|
||||
/// Where each page's view was left in this session (its centre and zoom; see
|
||||
/// [`Self::open_page`]; not saved).
|
||||
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
|
||||
}
|
||||
|
||||
/// 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),
|
||||
|
||||
@@ -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<NodeId> = 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<NodeId> = 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<NodeId> = 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<NodeId> = 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<NodeId> {
|
||||
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<NodeId> = 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<NodeId> = 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::<f64>() / 4.0, q.iter().map(|c| c.y).sum::<f64>() / 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<NodeId> = 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<NodeId> = 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<NodeId> = 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));
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<NodeId> = 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, .. }))
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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 }
|
||||
+19
-276
@@ -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<Result<(Document, Vec<String>), FormatError>> {
|
||||
@@ -135,24 +98,23 @@ pub fn import(bytes: &[u8], name: &str) -> Result<(Document, Vec<String>), Forma
|
||||
}
|
||||
|
||||
fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result<(Document, Vec<String>), 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::<String>();
|
||||
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<String>) -> 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<String, usize> {
|
||||
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<String, Arc<[u8]>> {
|
||||
let blobs = msg.get("blobs").map(Kv::list).unwrap_or_default();
|
||||
let mut copies: BTreeMap<usize, Arc<[u8]>> = 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<String, Arc<[u8]>>, in_zip: impl Fn(&str) -> bool) -> BTreeMap<String, String> {
|
||||
let mut first: BTreeMap<usize, &String> = 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<String,
|
||||
}
|
||||
}
|
||||
|
||||
/// The hash and blob index of an `Image` value whose `dataBlob` points at a usable blob.
|
||||
fn embedded_image(image: &Kv, blobs: &[Kv]) -> 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<u64>,
|
||||
skipped: Cell<usize>,
|
||||
}
|
||||
|
||||
/// The parts of a `.fig` archive the import reads.
|
||||
struct Archive<'b> {
|
||||
canvas: Vec<u8>,
|
||||
file_name: Option<String>,
|
||||
/// `images/<hash>` members (or nothing for a bare canvas).
|
||||
zip: Option<zip::ZipArchive<std::io::Cursor<&'b [u8]>>>,
|
||||
image_budget: ZipImageBudget,
|
||||
}
|
||||
|
||||
impl<'b> Archive<'b> {
|
||||
fn open(bytes: &'b [u8]) -> Result<Self, FormatError> {
|
||||
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::<serde_json::Value>(&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<Vec<u8>> {
|
||||
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<u8>), 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<Vec<&[u8]>, 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<Vec<u8>, 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<Vec<u8>, FormatError> {
|
||||
let capped = |r: &mut dyn Read| -> Option<Vec<u8>> {
|
||||
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 {
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<u8>, Vec<String>), 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<u8>, 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<Vec<u8>, 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<Vec<u8>>)],
|
||||
thumbnail: Option<&[u8]>,
|
||||
) -> Result<Vec<u8>, 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<u8> {
|
||||
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<path::Command> = 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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<T>(msg: impl Into<String>) -> Result<T, KiwiError> {
|
||||
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<Type>,
|
||||
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<Field>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Schema {
|
||||
pub defs: Vec<Def>,
|
||||
}
|
||||
|
||||
/// 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<u8>),
|
||||
Enum(&'s str),
|
||||
Array(Vec<Kv<'s>>),
|
||||
/// 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<f64> {
|
||||
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<bool> {
|
||||
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<u8, KiwiError> {
|
||||
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<u32, KiwiError> {
|
||||
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<i32, KiwiError> {
|
||||
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<u64, KiwiError> {
|
||||
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<i64, KiwiError> {
|
||||
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<f32, KiwiError> {
|
||||
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<String, KiwiError> {
|
||||
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<Schema, KiwiError> {
|
||||
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<usize> {
|
||||
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<Kv<'s>, 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<Kv<'s>, 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<Option<HashMap<u32, usize>>>,
|
||||
}
|
||||
|
||||
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<Kv<'s>, 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<Kv<'s>, 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<Kv<'s>, 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<u8>);
|
||||
|
||||
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<u8> {
|
||||
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<Vec<u8>, 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<i128> {
|
||||
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<Schema, KiwiError> {
|
||||
let lines: Vec<Vec<&str>> = text.lines().map(|l| l.split_whitespace().collect::<Vec<_>>()).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");
|
||||
}
|
||||
}
|
||||
+234
-619
@@ -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<String, Value>;
|
||||
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<Vec<Point>> {
|
||||
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<Side>), (Point, Option<Side>)) {
|
||||
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<Str
|
||||
to_rest_for(msg, name, max_nodes, false)
|
||||
}
|
||||
|
||||
/// The REST JSON (as `to_rest`) for a FigJam whiteboard (`board`) or a design file: a
|
||||
/// whiteboard's stickies come out as native board items.
|
||||
/// Map a FigJam whiteboard's stickies as native board items when `board` is true.
|
||||
pub(super) fn to_rest_for(msg: &Kv, name: &str, max_nodes: usize, board: bool) -> (Value, Vec<String>, Vec<Option<VectorNetwork>>) {
|
||||
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<Option<VectorNetwork>> =
|
||||
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<Value> = 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<String>) {
|
||||
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<String, (BoardShape, bool)>) {
|
||||
fn visit(json: &mut Value, shapes: &std::collections::HashMap<String, (BoardShape, bool)>, visited: &mut std::collections::HashSet<String>) {
|
||||
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<BoardShape> {
|
||||
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<String> {
|
||||
@@ -110,538 +260,3 @@ pub(super) fn adapt_warning(w: String) -> Option<String> {
|
||||
}
|
||||
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<f64> {
|
||||
n.get(k).and_then(Kv::f64)
|
||||
}
|
||||
|
||||
fn guid(v: &Kv) -> Option<String> {
|
||||
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<String> {
|
||||
v.get("guid").and_then(guid).filter(|g| g != NO_STYLE)
|
||||
}
|
||||
|
||||
fn vec2(v: &Kv) -> Option<Value> {
|
||||
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<Affine> {
|
||||
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<f64> {
|
||||
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<f64>,
|
||||
/// 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<Affine> {
|
||||
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<Item = (&'a Kv<'a>, 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<f64> {
|
||||
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<f64> {
|
||||
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<bool> {
|
||||
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<String, &'a Kv<'a>>,
|
||||
kids: BTreeMap<String, Vec<(&'a str, String)>>,
|
||||
blobs: Vec<&'a [u8]>,
|
||||
/// Component property definitions: id → (REST name "Name#id", type).
|
||||
prop_defs: BTreeMap<String, (String, &'a str)>,
|
||||
/// 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<String, String>,
|
||||
/// 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<String, BTreeMap<String, String>>,
|
||||
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<String, Rc<OverrideScope>>,
|
||||
/// 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<Value>,
|
||||
/// 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<String>,
|
||||
mapped_mains: BTreeSet<String>,
|
||||
/// 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<Option<VectorNetwork>>,
|
||||
/// 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<String, Vec<(&'a str, String)>> = 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<String, BTreeMap<String, String>> = 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<String> {
|
||||
// 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<String> {
|
||||
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<String> {
|
||||
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<String>) {
|
||||
self.warnings.add(w.into());
|
||||
}
|
||||
|
||||
fn children(&self, id: &str) -> Vec<String> {
|
||||
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::<u64>().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<String, String>,
|
||||
by_id: HashMap<String, String>,
|
||||
/// Every live variable node of the file, with a key or not.
|
||||
local: BTreeSet<String>,
|
||||
/// 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<String, String>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static VAR_CANON: std::cell::RefCell<Option<VarCanon>> = 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<String, ((u64, u64), String)> = HashMap::new();
|
||||
let mut copies: Vec<(String, String)> = Vec::new();
|
||||
let mut local = BTreeSet::new();
|
||||
let mut sets: HashMap<String, ((u64, u64), String)> = 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<String> {
|
||||
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<String> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<Value>> {
|
||||
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<Value> = 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::<String>() } 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<Vec<Value>> {
|
||||
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<Vec<Value>> {
|
||||
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<BoardShape> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -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<String>, Vec<OverrideRow<'a>>>;
|
||||
|
||||
/// 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<String>,
|
||||
aliases: BTreeMap<String, Option<String>>,
|
||||
}
|
||||
|
||||
/// 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<V> {
|
||||
own: BTreeMap<String, V>,
|
||||
outer: Option<Rc<Chain<V>>>,
|
||||
}
|
||||
|
||||
impl<V> Chain<V> {
|
||||
/// `outer`'s values, then `own`'s for keys `outer` lacks (shared as it is when `own` adds nothing).
|
||||
fn over(outer: Option<&Rc<Chain<V>>>, own: BTreeMap<String, V>) -> Rc<Self> {
|
||||
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<String>,
|
||||
pub(super) overrides: Rc<Overrides<'a>>,
|
||||
/// 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<Chain<(&'a Kv<'a>, f64)>>,
|
||||
/// Slot property GUID → private slot-content node GUID.
|
||||
pub(super) slot_contents: Rc<Chain<String>>,
|
||||
/// 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<String>,
|
||||
/// 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<OverrideScope> {
|
||||
if let Some(scope) = self.override_scopes.get(main) {
|
||||
return Rc::clone(scope);
|
||||
}
|
||||
let mut current = BTreeSet::new();
|
||||
let mut aliases: BTreeMap<String, Option<String>> = 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<String> = 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<String> =
|
||||
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<String, (&'a Kv<'a>, f64)> = BTreeMap::new();
|
||||
let mut slot_contents: BTreeMap<String, String> = 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<String> {
|
||||
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<String> {
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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<Point> {
|
||||
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<RouteEnd> {
|
||||
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<Value> = 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<Value> = 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<Value> = 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<Point>) -> Vec<Value> {
|
||||
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<Obj> {
|
||||
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<Value> {
|
||||
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<Value>,
|
||||
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<ConnectorPath> {
|
||||
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<Side>, 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<Point> {
|
||||
let mut pts: Vec<Point> = 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()
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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:?}"
|
||||
);
|
||||
}
|
||||
@@ -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<String> = 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<String> = 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<Value> = 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<String> {
|
||||
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<String> {
|
||||
let mut targets: Vec<String> = 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<String>) -> Option<Value> {
|
||||
let mut included = BTreeSet::new();
|
||||
let mut parents: BTreeMap<String, String> = 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<Value> {
|
||||
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<Value> {
|
||||
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<String, Vec<(String, Value)>> = 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<Value> = 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
|
||||
}
|
||||
@@ -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())));
|
||||
}
|
||||
@@ -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<Self> {
|
||||
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<Self> {
|
||||
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<String>>,
|
||||
slot_content: Option<String>,
|
||||
}
|
||||
|
||||
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<Fit>,
|
||||
depth: usize,
|
||||
) -> Option<Value> {
|
||||
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<Fit>,
|
||||
depth: usize,
|
||||
included: Option<&BTreeSet<String>>,
|
||||
) -> Option<Value> {
|
||||
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<Value> {
|
||||
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<Vec<Value>> {
|
||||
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::<String>())));
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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::<String>()));
|
||||
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<Value> = 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<u64, &Kv> =
|
||||
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<Value> = 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<Value> =
|
||||
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<Value> = 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<Value> = 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<usize> = (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<String> {
|
||||
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)
|
||||
}
|
||||
@@ -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::<Obj>();
|
||||
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<Value> {
|
||||
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<String, Option<&Kv<'a>>> = 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<String> {
|
||||
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<Value> {
|
||||
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
|
||||
}
|
||||
@@ -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<f64> {
|
||||
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<String> {
|
||||
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::<Value>(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<Value> = 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<f64> = 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<Value> {
|
||||
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<Value> = 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<Value> = 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<Value> {
|
||||
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<Value> {
|
||||
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)},
|
||||
})
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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<f64> = 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<Value> = 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<Value> {
|
||||
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<Value> =
|
||||
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<Value> {
|
||||
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<f64> = 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)
|
||||
}
|
||||
@@ -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<f64> {
|
||||
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<bool> {
|
||||
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<Vec<usize>> {
|
||||
// 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<usize> = 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<char> = 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<u32> =
|
||||
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<f64> {
|
||||
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<f64> = net.vertices.iter().map(|p| p.x).chain(net.segments.iter().flat_map(|s| [s.ta.0, s.tb.0])).collect();
|
||||
let ys: Vec<f64> = 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<f64>, warn: &mut dyn FnMut(String)) {
|
||||
let ids: Vec<u64> = 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<f64>) -> 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
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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::<Option<Vec<Value>>>()?;
|
||||
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<String> {
|
||||
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<Value> {
|
||||
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))
|
||||
}
|
||||
@@ -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<Vec<usize>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Network {
|
||||
pub vertices: Vec<Vertex>,
|
||||
pub segments: Vec<Segment>,
|
||||
pub regions: Vec<Region>,
|
||||
}
|
||||
|
||||
struct Reader<'b> {
|
||||
b: &'b [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
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<f64> {
|
||||
Some(f64::from(f32::from_bits(self.u32()?))).filter(|x| x.is_finite())
|
||||
}
|
||||
|
||||
/// An index below `len`.
|
||||
fn index(&mut self, len: usize) -> Option<usize> {
|
||||
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<usize> {
|
||||
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<Network> {
|
||||
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::<Option<Vec<usize>>>()?);
|
||||
}
|
||||
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<u8> {
|
||||
let mut out = Vec::new();
|
||||
let u = |v: u32, out: &mut Vec<u8>| out.extend_from_slice(&v.to_le_bytes());
|
||||
let fl = |v: f64, out: &mut Vec<u8>| 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
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
@@ -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"]);
|
||||
}
|
||||
|
||||
@@ -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<TextPath, &'static str> {
|
||||
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<usize> = 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<Use>, bool), &'static str> {
|
||||
let marker = net.segments.get(marked).ok_or("invalid start segment index")?;
|
||||
let mut adjacency = vec![Vec::<usize>::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"));
|
||||
}
|
||||
}
|
||||
@@ -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<Item = u
|
||||
let mut msg = head.0;
|
||||
msg.extend(elements);
|
||||
msg.push(0);
|
||||
export::canvas(&encode::schema(sc), &msg).unwrap()
|
||||
craft_fig::encode_canvas(&encode::schema(sc), &msg).unwrap()
|
||||
}
|
||||
|
||||
/// `pages` pages of `rects` rectangles and `texts` texts of `chars` characters, framed the way the
|
||||
@@ -125,7 +125,7 @@ fn opens_whole(label: &str, pages: usize, rects: usize, texts: usize, chars: usi
|
||||
let file = canvas(pages, rects, texts, chars);
|
||||
let (sc, msg) = decode_canvas(&file).unwrap();
|
||||
let root = sc.find("Message").unwrap();
|
||||
let one_per_byte = file.len().clamp(kiwi::value_budget(0), kiwi::value_budget(usize::MAX));
|
||||
let one_per_byte = file.len().clamp(craft_fig::value_budget(0), craft_fig::value_budget(usize::MAX));
|
||||
let refused = sc.decode_message_within(root, &msg, one_per_byte).is_err_and(|e| e.0 == "message: too many values");
|
||||
assert!(refused, "{label}: one value per compressed byte no longer refuses it");
|
||||
let (doc, warnings) = import(&file, label).unwrap_or_else(|e| panic!("{label}: refused: {e}"));
|
||||
@@ -133,7 +133,7 @@ fn opens_whole(label: &str, pages: usize, rects: usize, texts: usize, chars: usi
|
||||
assert!(warnings.is_empty(), "{label}: {warnings:?}");
|
||||
println!("{label}: {} canvas bytes, {} layers", file.len(), doc.node_count());
|
||||
drop(doc);
|
||||
assert!(sc.decode_message_within(root, &msg, kiwi::value_budget(file.len()) / 10 * 9).is_ok(), "{label}: not within 90% of its budget");
|
||||
assert!(sc.decode_message_within(root, &msg, craft_fig::value_budget(file.len()) / 10 * 9).is_ok(), "{label}: not within 90% of its budget");
|
||||
file.len()
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ fn dense_canvases_open_whole() {
|
||||
#[ignore = "heavy: --release --ignored, about 9 GB"]
|
||||
fn a_canvas_budgeted_at_the_ceiling_opens_whole() {
|
||||
let packed = opens_whole("50 MB text-heavy canvas", 106, 0, 5000, 100);
|
||||
assert_eq!(kiwi::value_budget(packed), kiwi::value_budget(usize::MAX), "budgeted at the ceiling");
|
||||
assert_eq!(craft_fig::value_budget(packed), craft_fig::value_budget(usize::MAX), "budgeted at the ceiling");
|
||||
}
|
||||
|
||||
/// However far a small canvas inflates, the floor bounds what it may decode.
|
||||
|
||||
+195
-333
@@ -31,76 +31,27 @@ pub use library::{is_valid_library_id, read_library, read_library_within};
|
||||
mod density;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::{Read, Seek, Write};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_doc::{Document, ImageData};
|
||||
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
|
||||
use serde::{Deserialize, Serialize, Serializer};
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
#[cfg(test)]
|
||||
use serde_json::json;
|
||||
use sha2::Digest;
|
||||
|
||||
pub const EXTENSION: &str = "figcraft";
|
||||
pub const FORMAT: &str = "figcraft";
|
||||
pub const VERSION: u32 = 1;
|
||||
/// Largest archive member we read (guards against zip bombs).
|
||||
const MAX_MEMBER: u64 = 512 * 1024 * 1024;
|
||||
/// `document.json` may unpack to [`DOCUMENT_RATIO`] times what it takes in the archive, within
|
||||
/// [`MAX_MEMBER`] and [`MAX_DOCUMENT`]: a large document saved by us (a 900 000-layer file packs
|
||||
/// 1.48 GB into 244 MB) opens again, while a small archive still can't unpack into gigabytes.
|
||||
/// 32-bit targets (wasm32) have a 4 GB address space in all, so their ceiling is lower.
|
||||
const DOCUMENT_RATIO: u64 = 16;
|
||||
#[cfg(not(target_pointer_width = "32"))]
|
||||
const MAX_DOCUMENT: u64 = 4 * 1024 * 1024 * 1024;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const MAX_DOCUMENT: u64 = 1024 * 1024 * 1024;
|
||||
/// Most versions a file keeps: saving more is refused, extra entries in a file are skipped.
|
||||
pub const MAX_VERSIONS: usize = 100;
|
||||
pub use craft_figcraft_format::{
|
||||
BRANCH_INDEX, BranchEntry as NativeBranchEntry, BranchIndex as NativeBranchIndex, BranchState as NativeBranchState, DOCUMENT_RATIO, EXTENSION,
|
||||
FORMAT, FormatError, IMAGE_BUDGET, ImageBudget, MAX_BRANCHES, MAX_DOCUMENT, MAX_MEMBER, MAX_UNPACKED, MAX_VERSION_BYTES, MAX_VERSION_DESCRIPTION,
|
||||
MAX_VERSION_INDEX, MAX_VERSION_NAME, MAX_VERSIONS, ReadBudget, VERSION, VersionEntry as NativeVersionEntry, VersionIndex as NativeVersionIndex,
|
||||
clip, document_limit, is_valid_version_id,
|
||||
};
|
||||
#[cfg(test)]
|
||||
const JSON_LEVEL: i64 = 3;
|
||||
/// The export warning for colour calculations that resolve to nothing (an operand missing, or more
|
||||
/// than 32 variables to read), shared by the Penpot and `.fig` exports.
|
||||
pub(crate) const CALCULATIONS_LEFT_OUT: &str = "colour calculations that don't resolve were left out";
|
||||
/// Longest version name and description kept (chars).
|
||||
pub const MAX_VERSION_NAME: usize = 200;
|
||||
pub const MAX_VERSION_DESCRIPTION: usize = 2000;
|
||||
/// Largest version index and total size of the version snapshots read from one file.
|
||||
const MAX_VERSION_INDEX: u64 = 16 * 1024 * 1024;
|
||||
const MAX_VERSION_BYTES: u64 = 1024 * 1024 * 1024;
|
||||
/// Most images, and image bytes together, read from one file (members past it are left out).
|
||||
const IMAGE_BUDGET: ImageBudget = ImageBudget { images: 20_000, bytes: 4 * 1024 * 1024 * 1024 };
|
||||
/// Most bytes one open of a `.figcraft` file unpacks, every area together: its document, images,
|
||||
/// published library, version history and branches ([`Unpacked`], #1079). Each area keeps its own
|
||||
/// cap; their sum was about 10 GB. Read in that order, the document (a 900 000-layer one unpacks
|
||||
/// to 1.5 GB) and the images up to their own 4 GiB cap fit, so a file whose images pass that cap
|
||||
/// (#1313: an 84 MiB document with 7.3 GiB of images) keeps as many as before; the history and
|
||||
/// branches share what is left. 32-bit targets (wasm32) have 4 GB of address space in all.
|
||||
#[cfg(not(target_pointer_width = "32"))]
|
||||
const MAX_UNPACKED: u64 = 6 * 1024 * 1024 * 1024;
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
const MAX_UNPACKED: u64 = 2 * 1024 * 1024 * 1024;
|
||||
const BRANCH_INDEX: &str = "branches/index.json";
|
||||
/// Most branches a file keeps: making more is refused, extra entries in a file are skipped.
|
||||
pub const MAX_BRANCHES: usize = 100;
|
||||
/// Deflate level of JSON members (see [`json_options`]).
|
||||
const JSON_LEVEL: i64 = 3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FormatError {
|
||||
Io(String),
|
||||
Corrupt(String),
|
||||
Newer(u32),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FormatError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> 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<Version>,
|
||||
}
|
||||
|
||||
/// 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<u8>) -> 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<String, ImageData>,
|
||||
#[serde(flatten)]
|
||||
doc: &'a Document,
|
||||
}
|
||||
/// The image hashes a `document.json` lists in its `imageIndex` (`None` without one).
|
||||
type ImageIndex = Option<BTreeSet<String>>;
|
||||
|
||||
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<S: Serializer>(images: &&BTreeMap<String, ImageData>, s: S) -> Result<S::Ok, S::Error> {
|
||||
#[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<craft_figcraft_format::ImageIndexEntry> {
|
||||
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<S: serde::ser::SerializeStructVariant> 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<Value, FormatError> {
|
||||
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<String>), 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<BTreeSet<String>>;
|
||||
|
||||
/// 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<u64>,
|
||||
images: ImageIndex,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Header {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
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<A: MapAccess<'de>>(self, mut map: A) -> Result<Header, A::Error> {
|
||||
let mut h = Header::default();
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
match key.as_str() {
|
||||
"version" => h.version = map.next_value::<Value>()?.as_u64(),
|
||||
"imageIndex" => {
|
||||
h.images = map
|
||||
.next_value::<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::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
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<String>, 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::<Document>(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<W: Write + Seek>(
|
||||
z: &mut zip::ZipWriter<W>,
|
||||
/// 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<Item = (&'a str, &'a [u8])>) -> Result<Vec<u8>, 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<W: Write + Seek>(z: &mut zip::ZipWriter<W>, 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<Vec<u8>, 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::<Vec<String>>();
|
||||
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::<Vec<String>>();
|
||||
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`: `<dir>/index.json` and one
|
||||
/// `<dir>/<id>.json` snapshot per version. Nothing when there are none.
|
||||
fn put_versions<W: Write + Seek>(z: &mut zip::ZipWriter<W>, 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<W: Write + Seek>(z: &mut zip::ZipWriter<W>, 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<String>), 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<R: Read + Seek>(z: &mut zip::ZipArchive<R>, name: &str, limit: u64) -> Result<Vec<u8>, FormatError> {
|
||||
/// Read a member from a foreign ZIP archive, refusing entries larger than `limit`.
|
||||
pub(crate) fn read_member<R: Read + std::io::Seek>(z: &mut zip::ZipArchive<R>, name: &str, limit: u64) -> Result<Vec<u8>, 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<R: Read + Seek>(&self, z: &mut zip::ZipArchive<R>, 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<R: Read + Seek>(&mut self, z: &mut zip::ZipArchive<R>, name: &str, limit: u64) -> Result<Vec<u8>, 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<Loaded, FormatError> {
|
||||
@@ -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<Loaded, FormatError> {
|
||||
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<R: Read + Seek>(
|
||||
z: &mut zip::ZipArchive<R>,
|
||||
fn read_images(
|
||||
z: &mut impl craft_figcraft_format::NativeArchive,
|
||||
own: Option<&BTreeSet<String>>,
|
||||
budget: ImageBudget,
|
||||
unpacked: &mut Unpacked,
|
||||
) -> ImagesRead {
|
||||
let mut hashes: Vec<String> = z.file_names().filter_map(|n| n.strip_prefix("images/")).filter(|h| !h.is_empty()).map(str::to_string).collect();
|
||||
let mut hashes: Vec<String> =
|
||||
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<R: Read + Seek>(
|
||||
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<R: Read + Seek>(
|
||||
}
|
||||
// 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<R: Read + Seek>(
|
||||
z: &mut zip::ZipArchive<R>,
|
||||
fn read_versions(
|
||||
z: &mut impl craft_figcraft_format::NativeArchive,
|
||||
dir: &str,
|
||||
images: &BTreeMap<String, ImageData>,
|
||||
issues: &mut Vec<String>,
|
||||
@@ -889,12 +735,12 @@ fn read_versions<R: Read + Seek>(
|
||||
unpacked: &mut Unpacked,
|
||||
) -> Vec<Version> {
|
||||
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::<Value>(&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<R: Read + Seek>(
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
let entries = index.get("versions").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let mut out: Vec<Version> = 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<R: Read + Seek>(
|
||||
}
|
||||
};
|
||||
*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<R: Read + Seek>(
|
||||
|
||||
/// 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<R: Read + Seek>(
|
||||
z: &mut zip::ZipArchive<R>,
|
||||
fn read_branches(
|
||||
z: &mut impl craft_figcraft_format::NativeArchive,
|
||||
images: &BTreeMap<String, ImageData>,
|
||||
issues: &mut Vec<String>,
|
||||
unpacked: &mut Unpacked,
|
||||
) -> Vec<Branch> {
|
||||
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::<Value>(&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<R: Read + Seek>(
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
let entries = index.get("branches").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let mut out: Vec<Branch> = 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<Arc<Document>, FormatError> {
|
||||
let mut snapshot = |part: &str, hashes: &[String]| -> Result<Arc<Document>, 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<R: Read + Seek>(
|
||||
};
|
||||
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<String>), 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;
|
||||
|
||||
+104
-46
@@ -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<W: Write + Seek>(z: &mut zip::ZipWriter<W>, 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<R: Read + Seek>(
|
||||
z: &mut zip::ZipArchive<R>,
|
||||
pub(crate) fn read(
|
||||
z: &mut impl craft_figcraft_format::NativeArchive,
|
||||
own: &BTreeMap<String, ImageData>,
|
||||
unpacked: &mut Unpacked,
|
||||
) -> Result<Option<PublishedLibrary>, 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<String> = 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<R: Read + Seek>(
|
||||
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: Read + Seek>(r: R) -> Result<Option<PublishedLibrary>, 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: Read + Seek>(r: R, max_bytes: u64) -> Result<Option<PublishedLibrary>, 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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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<String, usize>,
|
||||
}
|
||||
|
||||
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<Item = &str> {
|
||||
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<String> {
|
||||
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)]
|
||||
|
||||
+12
-172
@@ -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<dyn Fn(&str) -> 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<String> {
|
||||
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<String>) -> 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<String>,
|
||||
zip: zip::ZipArchive<std::io::Cursor<&'b [u8]>>,
|
||||
/// Image bytes read so far.
|
||||
image_total: std::cell::Cell<u64>,
|
||||
}
|
||||
|
||||
impl<'b> Archive<'b> {
|
||||
fn open(bytes: &'b [u8], max_member: u64) -> Result<Self, FormatError> {
|
||||
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<Value> = 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/<name>`).
|
||||
pub(crate) fn image(&self, r: &str) -> Option<Vec<u8>> {
|
||||
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<std::io::Cursor<&[u8]>>,
|
||||
name: &str,
|
||||
limit: u64,
|
||||
total: &mut u64,
|
||||
max_total: u64,
|
||||
) -> Result<Vec<u8>, 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<std::io::Cursor<&[u8]>>, name: &str, limit: u64, total: &mut u64) -> Result<Value, FormatError> {
|
||||
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<u32> {
|
||||
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'_')
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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))));
|
||||
}
|
||||
@@ -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<R: Read + Seek>(archive: R) -> Option<Vec<u8>> {
|
||||
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<R: Read + Seek>(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<u64>,
|
||||
#[serde(default)]
|
||||
nodes: std::collections::BTreeMap<String, Node>,
|
||||
#[serde(default)]
|
||||
kind: figcraft_doc::FileKind,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Node {
|
||||
#[serde(default)]
|
||||
background: Option<serde_json::Value>,
|
||||
}
|
||||
let Ok(head) = serde_json::from_slice::<Head>(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`).
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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, \
|
||||
|
||||
@@ -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<u8> { (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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Pixmap> {
|
||||
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<Pixmap> {
|
||||
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<Pixmap>)> = (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;
|
||||
|
||||
@@ -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<Document>, 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));
|
||||
}
|
||||
}
|
||||
@@ -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()?,
|
||||
|
||||
@@ -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 }
|
||||
|
||||
+3
-10
@@ -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::<String>().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())
|
||||
|
||||
@@ -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!("<svg label=\"{}\"/>", 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));
|
||||
}
|
||||
}
|
||||
@@ -555,7 +555,7 @@ fn names(f: &skrifa::FontRef) -> (Option<String>, Option<String>) {
|
||||
/// 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",
|
||||
|
||||
@@ -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",
|
||||
] {
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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} இலிருந்து"
|
||||
|
||||
@@ -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}"
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Kept>,
|
||||
/// 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<JobKey>,
|
||||
/// The view of the last render asked for.
|
||||
want_view: Option<figcraft_render::View>,
|
||||
@@ -71,6 +74,8 @@ pub struct CanvasState {
|
||||
/// canvas texture (ms; the texture is uploaded when that frame is painted).
|
||||
pub preview_latency_ms: Option<f64>,
|
||||
pub refine_latency_ms: Option<f64>,
|
||||
/// 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;
|
||||
@@ -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<Rect>) {
|
||||
/// 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<Rect>, 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<Rect>) -> impl Iterator<Item = Rect> {
|
||||
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<Rect>) -> 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<Rect> = 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");
|
||||
}
|
||||
}
|
||||
@@ -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<Done> {
|
||||
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<std::sync::atomic::AtomicU64>,
|
||||
/// The watchdog is drawing a late preview, or has one to hand over and wake the UI for.
|
||||
previewing: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// The images around the view ([`Surround`]) from their thread.
|
||||
surround_rx: std::sync::mpsc::Receiver<Done>,
|
||||
/// 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<std::sync::atomic::AtomicU64>,
|
||||
surround_done: Arc<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
#[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::<Done>();
|
||||
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<Done> {
|
||||
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<Done> {
|
||||
None
|
||||
}
|
||||
pub fn poll(&mut self) -> Option<Done> {
|
||||
self.poll_at(Instant::now())
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<Document>, page: NodeId, uid: u64, view: View) -> Job {
|
||||
pub(super) fn job(doc: &Arc<Document>, 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<View> = [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%
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,9 +204,35 @@ fn importer_notes() -> BTreeSet<String> {
|
||||
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("];
|
||||
|
||||
|
||||
@@ -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<Pos2> {
|
||||
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<egui::Shape> = 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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user