diff --git a/.coderabbit.yaml b/.coderabbit.yaml
new file mode 100644
index 000000000..2408084cf
--- /dev/null
+++ b/.coderabbit.yaml
@@ -0,0 +1,6 @@
+# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
+reviews:
+ auto_review:
+ # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
+ ignore_usernames:
+ - "dependabot[bot]"
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..d39962e1c
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,32 @@
+version: 2
+updates:
+ # Maintain Rust / Cargo dependencies
+ - package-ecosystem: "cargo"
+ directories:
+ - "/"
+ - "/plugins"
+ schedule:
+ interval: "daily"
+ time: "06:00"
+ timezone: "America/New_York"
+ # Consolidate updates into a single PR rather than one PR per crate
+ groups:
+ cargo-dependencies:
+ patterns:
+ - "*"
+ commit-message:
+ prefix: "chore(deps)"
+
+ # Maintain GitHub Actions workflows
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ time: "06:00"
+ timezone: "America/New_York"
+ groups:
+ actions:
+ patterns:
+ - "*"
+ commit-message:
+ prefix: "ci(deps)"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e613617a1..9700a8e91 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -33,7 +33,7 @@ jobs:
name: test (ubuntu-latest)
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- name: Install Linux system dependencies (egui/winit/rfd)
run: |
@@ -74,7 +74,7 @@ jobs:
name: wasm32 check
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
+ - uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml
index ca0cd49f6..ff15bfbc4 100644
--- a/.github/workflows/freebsd.yml
+++ b/.github/workflows/freebsd.yml
@@ -31,6 +31,5 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
- freebsd-release: "14.3"
run-package-check: true
- craft-fonts-ref: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
+ craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
diff --git a/.github/workflows/nix.yml b/.github/workflows/nix.yml
index 18392587a..01cb9cd66 100644
--- a/.github/workflows/nix.yml
+++ b/.github/workflows/nix.yml
@@ -18,16 +18,6 @@ concurrency:
cancel-in-progress: true
jobs:
- eval:
- runs-on: ubuntu-latest
- timeout-minutes: 15
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- - uses: cachix/install-nix-action@13d8dd58da0234aa297dedd986986ccb8e7f3e24 # v31.11.1
- - name: nix flake check --no-build
- run: |
- if [ -f flake.nix ]; then
- nix flake check --no-build --all-systems
- else
- echo "No flake.nix present in this repository; skipping check."
- fi
+ nix:
+ # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
+ uses: storytold/craft-common-actions/.github/workflows/nix.yml@main
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 75f7a5fae..dd2aefddb 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -24,8 +24,14 @@ jobs:
with:
app-name: figcraft
app-title: FigCraft
+ # Needs fonts/latin-manifest.txt (Inter): crates/text/build.rs fails a release without it. Only
+ # craft-fonts' pr/latin-presentation-fonts has it; its main has Noto Sans Georgian but no Inter.
+ # Re-pin once one commit has both (storytold/craft-fonts#42).
craft-fonts-ref: 43913056ce82a3fdad0ef69f6b88d1dc922a8104
has-server: true
+ # The browser has no system fonts: without craft-fonts the web build can't draw text (#885).
+ # crates/text/build.rs keeps the web build to Inter.
+ web-craft-fonts: true
version: ${{ inputs.version }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 1f72aeb7c..96dff6a9e 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -25,6 +25,7 @@ Release builds embed fonts from the optional craft-fonts build input
| Family | Licence | Upstream |
|---|---|---|
| Inter | SIL Open Font License 1.1 | https://github.com/rsms/inter |
+| Archivo | SIL Open Font License 1.1 | [Google Fonts / Archivo](https://github.com/google/fonts/tree/6c70c829f09ea345d3590406693220ea35c6553f/ofl/archivo) |
| Roboto, Montserrat, Lato, Open Sans, Poppins, Nunito Sans, Merriweather, Playfair Display, Source Sans 3, Source Serif 4, Carlito, Caladea | SIL Open Font License 1.1 | Google Fonts / upstream repositories (see craft-fonts) |
| Liberation Sans, Serif, Mono | SIL Open Font License 1.1 | https://github.com/liberationfonts |
| BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans Arabic | SIL Open Font License 1.1 | Google Fonts (see craft-fonts) |
diff --git a/Cargo.lock b/Cargo.lock
index aead39d1f..1d047aa42 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -259,6 +259,7 @@ dependencies = [
"parking_lot",
"percent-encoding",
"windows-sys 0.60.2",
+ "wl-clipboard-rs",
"x11rb",
]
@@ -855,6 +856,11 @@ dependencies = [
"libc",
]
+[[package]]
+name = "craft-docpath"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09a67fb9a3fbd17ffe63#82a24b006eefa036b43c09a67fb9a3fbd17ffe63"
+
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -1407,7 +1413,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
[[package]]
name = "figcraft"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"arboard",
"eframe",
@@ -1421,17 +1427,20 @@ dependencies = [
"fmv-macos-events",
"image",
"log",
+ "raw-window-handle",
"rfd",
"serde_json",
"wat",
+ "wayland-client",
"webbrowser",
"windows",
+ "winit",
"winresource",
]
[[package]]
name = "figcraft-cli"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-doc",
"figcraft-engine",
@@ -1445,7 +1454,7 @@ dependencies = [
[[package]]
name = "figcraft-collab"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"base64 0.22.1",
"figcraft-color",
@@ -1460,7 +1469,7 @@ dependencies = [
[[package]]
name = "figcraft-collab-net"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"base64 0.22.1",
"figcraft-collab",
@@ -1483,7 +1492,7 @@ dependencies = [
[[package]]
name = "figcraft-color"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"kurbo",
"serde",
@@ -1492,7 +1501,7 @@ dependencies = [
[[package]]
name = "figcraft-doc"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-color",
"figcraft-geom",
@@ -1504,9 +1513,10 @@ dependencies = [
[[package]]
name = "figcraft-engine"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"base64 0.22.1",
+ "craft-docpath",
"figcraft-collab",
"figcraft-color",
"figcraft-doc",
@@ -1531,7 +1541,7 @@ dependencies = [
[[package]]
name = "figcraft-format"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-doc",
"figcraft-pathops",
@@ -1546,7 +1556,7 @@ dependencies = [
[[package]]
name = "figcraft-geom"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"kurbo",
"serde",
@@ -1554,7 +1564,7 @@ dependencies = [
[[package]]
name = "figcraft-layout"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-doc",
"figcraft-geom",
@@ -1562,7 +1572,7 @@ dependencies = [
[[package]]
name = "figcraft-mcp"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"base64 0.22.1",
"figcraft-collab-net",
@@ -1578,7 +1588,7 @@ dependencies = [
[[package]]
name = "figcraft-pathops"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-doc",
"figcraft-geom",
@@ -1587,7 +1597,7 @@ dependencies = [
[[package]]
name = "figcraft-pdf"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-color",
"figcraft-doc",
@@ -1599,12 +1609,12 @@ dependencies = [
"krilla",
"log",
"thiserror 2.0.21",
- "tiny-skia",
+ "tiny-skia 0.12.0",
]
[[package]]
name = "figcraft-plugin"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-color",
"serde",
@@ -1617,7 +1627,7 @@ dependencies = [
[[package]]
name = "figcraft-render"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"crc32fast",
"figcraft-color",
@@ -1630,12 +1640,12 @@ dependencies = [
"moxcms",
"png",
"rayon",
- "tiny-skia",
+ "tiny-skia 0.12.0",
]
[[package]]
name = "figcraft-server"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"crc32fast",
"ctrlc",
@@ -1659,7 +1669,7 @@ dependencies = [
[[package]]
name = "figcraft-svg"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"base64 0.22.1",
"figcraft-color",
@@ -1675,7 +1685,7 @@ dependencies = [
[[package]]
name = "figcraft-text"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-doc",
"figcraft-geom",
@@ -1689,7 +1699,7 @@ dependencies = [
[[package]]
name = "figcraft-ui-egui"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"base64 0.22.1",
"egui",
@@ -1714,7 +1724,7 @@ dependencies = [
[[package]]
name = "figcraft-web"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"eframe",
"egui",
@@ -1734,6 +1744,12 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
[[package]]
name = "flate2"
version = "1.1.10"
@@ -2563,7 +2579,7 @@ dependencies = [
"skrifa 0.42.1",
"smallvec",
"subsetter",
- "tiny-skia-path",
+ "tiny-skia-path 0.12.0",
"xmp-writer",
"yoke",
"zune-jpeg",
@@ -2820,6 +2836,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -3204,6 +3229,16 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "os_pipe"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -3264,6 +3299,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "petgraph"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
+dependencies = [
+ "fixedbitset",
+ "hashbrown 0.15.5",
+ "indexmap",
+]
+
[[package]]
name = "phf"
version = "0.13.1"
@@ -3981,6 +4027,17 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "sctk-adwaita"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
+dependencies = [
+ "log",
+ "smithay-client-toolkit 0.19.2",
+ "tiny-skia 0.11.4",
+]
+
[[package]]
name = "self_cell"
version = "1.3.0"
@@ -4440,6 +4497,20 @@ dependencies = [
"zune-jpeg",
]
+[[package]]
+name = "tiny-skia"
+version = "0.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "bytemuck",
+ "cfg-if",
+ "log",
+ "tiny-skia-path 0.11.4",
+]
+
[[package]]
name = "tiny-skia"
version = "0.12.0"
@@ -4452,7 +4523,18 @@ dependencies = [
"cfg-if",
"log",
"png",
- "tiny-skia-path",
+ "tiny-skia-path 0.12.0",
+]
+
+[[package]]
+name = "tiny-skia-path"
+version = "0.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
+dependencies = [
+ "arrayref",
+ "bytemuck",
+ "strict-num",
]
[[package]]
@@ -4574,6 +4656,17 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "tree_magic_mini"
+version = "3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
+dependencies = [
+ "memchr",
+ "nom",
+ "petgraph",
+]
+
[[package]]
name = "ttf-parser"
version = "0.25.1"
@@ -4730,7 +4823,7 @@ dependencies = [
"skrifa 0.44.0",
"strict-num",
"svgtypes",
- "tiny-skia-path",
+ "tiny-skia-path 0.12.0",
"unicode-bidi",
"unicode-script",
"unicode-vo",
@@ -5683,6 +5776,7 @@ dependencies = [
"raw-window-handle",
"redox_syscall 0.4.1",
"rustix 0.38.44",
+ "sctk-adwaita",
"smithay-client-toolkit 0.19.2",
"smol_str",
"tracing",
@@ -5726,6 +5820,24 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+[[package]]
+name = "wl-clipboard-rs"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"
+dependencies = [
+ "libc",
+ "log",
+ "os_pipe",
+ "rustix 1.1.5",
+ "thiserror 2.0.21",
+ "tree_magic_mini",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+]
+
[[package]]
name = "write-fonts"
version = "0.48.1"
@@ -5822,7 +5934,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "xtask"
-version = "0.6.0"
+version = "0.8.0"
dependencies = [
"figcraft-engine",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index 8f125ac3e..1eef32c76 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,7 @@ exclude = ["plugins"]
# default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"]
[workspace.package]
-version = "0.6.0"
+version = "0.8.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -32,6 +32,9 @@ figcraft-mcp = { path = "crates/mcp" }
figcraft-collab-net = { path = "crates/collab-net" }
figcraft-plugin = { path = "crates/plugin" }
+# Which paths stored in a document may be followed (craft-libs).
+craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
+
# foundation
kurbo = { version = "0.13", features = ["serde"] }
thiserror = "2"
diff --git a/NOTICE b/NOTICE
index 9aaba825b..a0baaa279 100644
--- a/NOTICE
+++ b/NOTICE
@@ -20,3 +20,34 @@ licence texts.
Rust crate dependencies keep their own licenses (MIT, Apache-2.0, BSD, ISC, Zlib, OFL for egui's
default fonts, CDLA-Permissive-2.0 for the root certificate list webpki-roots compiles in, and
similar permissive licenses); see each crate's metadata.
+
+Linux Wayland window decorations
+-------------------------------
+sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
+commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux
+for vector window controls. Its title-font features are disabled: no Cantarell
+font is embedded by this dependency and no font file is added to this repo.
+
+sctk-adwaita's MIT licence:
+
+MIT License
+
+Copyright (c) 2022 Bartłomiej Maryńczak
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 0910bf9e7..63bc739bf 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
🎛️ Familiar by design
- The toolbar, layers panel, Design panel, menus and shortcuts sit where your hands expect them. If you know Figma, you already know FigCraft.
+ The toolbar, layers panel, Design panel, menus and shortcuts sit right where your hands expect them.
⚡ Native and fast
@@ -227,8 +230,8 @@ The desktop app also offers a loopback-only control channel (`figcraft --control
- **Its own renderer:** tiny-skia on every core for the canvas and exports, with layer blending, effects and masks; booleans from linesweeper, geometry from kurbo, text from skrifa and HarfRust.
- **Runs in the browser:** the whole engine and UI compile to WebAssembly.
- **Accessible:** screen readers get names, roles, values and states for the tools, layer rows, fields, dropdowns, tabs and menus (AccessKit on desktop), F6 moves the keyboard between the toolbar, layers, canvas and properties (Tab within them, Escape back to the canvas), the system's reduce-motion setting is honoured, and panel text meets WCAG AA contrast in both themes.
-- **Languages:** English, Russian and Turkish (reviewed by native speakers), and Spanish, French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Czech and Indonesian drafts, picked in Preferences or taken from the system or browser and switched live; adding a language is one catalog file ([`docs/translating.md`](docs/translating.md)).
-- **Plugins:** sandboxed WebAssembly plugins (a metered, pure-Rust interpreter with a memory cap and no file or network access, in the browser too) that act through the same commands, each run one undo step, within the permissions their manifest asks for. A Rust SDK and two example plugins are in [`plugins/`](plugins); see [`docs/plugins.md`](docs/plugins.md).
+- **Languages:** English, Russian and Turkish (reviewed by native speakers), and Spanish, French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese, Czech, Indonesian and Georgian drafts, picked in Preferences or taken from the system or browser and switched live; adding a language is one catalog file ([`docs/translating.md`](docs/translating.md)).
+- **Plugins:** sandboxed WebAssembly plugins (a metered, pure-Rust interpreter with a memory cap and no file or network access, in the browser too) that act through the same commands, each run one undo step, within the permissions their manifest asks for. A Rust SDK and three example plugins are in [`plugins/`](plugins); see [`docs/plugins.md`](docs/plugins.md).
- **Live sessions (preview):** share the open file from the app (Share ▸ Start sharing: online through a server, or on your local network), give the others the short join code it shows (or the invite link), and edit it together: everyone's changes sync live, with cursors, selections, avatars and follow, and undo takes back only your own changes. Others join from the desktop app (invite links open it) or from the browser build. See [`docs/collab-protocol.md`](docs/collab-protocol.md).
- **A server of your own (preview):** `figcraft-server` keeps a team's files, publishes them from the app (File ▸ Publish to server…, or Share ▸ Online with your server in Preferences) and hands out share links and join codes that let people edit or only view; files survive restarts and apps reconnect where they were. No accounts yet: links are the access. Releases ship it for Linux, and the desktop app joins over `wss://`; [hosting it on a rented Linux server](docs/server.md#deploy-on-a-linux-server) takes a systemd unit and Caddy or nginx (or Docker). See [`docs/server.md`](docs/server.md).
- **Never crashes:** no `unwrap`, `expect` or `panic` in shipped code, enforced by clippy; commands run behind a guard so a bug fails one action, not your session.
@@ -262,7 +265,7 @@ New contributors and AI agents: start with [`AGENTS.md`](AGENTS.md), then [`docs
Installers for macOS (universal, signed and notarized), Windows (x64, x86 and arm64), Linux (AppImage, `.deb`, `.rpm`, Flatpak and tarball), FreeBSD and the web are attached to each [GitHub release](https://github.com/storytold/figcraft/releases). Maintainers: [`docs/releasing.md`](docs/releasing.md) explains how releases are built, signed and published.
> [!IMPORTANT]
-> **Status:** FigCraft is in **alpha**: about 49% of the way to replacing Figma for real work, by our own estimate. Nearly all of Figma's main menu is wired ([`docs/parity-checklist.md`](docs/parity-checklist.md)) and the core editor works end to end, but FigCraft opens `.fig` files only best effort, has only a first preview of multiplayer (live sessions hosted from the app or a self-hosted server, with per-person undo and share links to edit or to view; no accounts, teams or cloud yet), runs its own WebAssembly plugins rather than Figma's, and hasn't been checked against real Figma documents. The honest, area-by-area picture is in the [roadmap](ROADMAP.md) and [`docs/target-app-parity.md`](docs/target-app-parity.md). Expect rough edges and please file issues, or tell us what broke on [Discord](https://discord.gg/artcraft).
+> **Status:** FigCraft is in **alpha**: about 49% of the way to replacing proprietary tools for real work, by our own estimate. Nearly all tracked interface design actions in the menu checklist are wired ([`docs/parity-checklist.md`](docs/parity-checklist.md)) and the core editor works end to end, but FigCraft opens `.fig` files only best effort, has only a first preview of multiplayer (live sessions hosted from the app or a self-hosted server, with per-person undo and share links to edit or to view; no accounts, teams or cloud yet), runs its own WebAssembly plugins, and hasn't been checked against real design documents. The honest, area-by-area picture is in the [roadmap](ROADMAP.md) and [`docs/target-app-parity.md`](docs/target-app-parity.md). Expect rough edges and please file issues, or tell us what broke on [Discord](https://discord.gg/artcraft).
## Privacy and online sharing
@@ -348,8 +351,6 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif
part of this repository and FigCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
-Figma is a trademark of Figma, Inc. FigCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Figma, Inc.; the name is used only to describe the workflows FigCraft is compatible with.
-
Made by the ArtCraft team and community.
diff --git a/ROADMAP.md b/ROADMAP.md
index d6159904e..f19153613 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (Adobe Fonts found on macOS (#298); bounded canvas pan overscan; community fixes from #478 up and a control-channel fix (#589); bounded canvas pan overscan; Typography spacing icons support scrubbing (#373); font scans skip named pipes; system theme on first run; recent files as cards with thumbnails on the home screen; community fixes: lost images reported on loading (#207), SVG import budgets (#190), Leptos code (#223), full screen (#227), server snapshots readable again (#188), owner-only preferences (#200), ruzstd 0.9.1 (#182), layer cycle repair (#205), batch rollback, Direct3D 12 on Windows, plugin metering (#192); vector edit mode regions: hover hatch, selection and drag; SVG/PDF exports refuse over-depth documents (#208); bounded MCP/control framing, connections and queues (#201); plugin log limits (#191); live-session revert guard (#198); attached MCP no longer replays after a lost reply (#194); repeat command recursion fix; the Layout panel's constrain-proportions link scales the other side, #220; core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; starter templates, a Templates tab and Getting started tips on the home screen; your online files; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; Windows QA pass with eight fixes; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%) · **Target:** Figma Design (desktop app 126.10.7)
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (Adobe Fonts found on macOS (#298); community batch #753: Selection colors, smart-selection spacing, a Present tab; language table re-measured from the catalogs; community fixes from #524 up (55 PRs: `.fig` import fidelity, paste from other apps, the Actions palette, editor fixes, server limits) and a boolean-op crash guard; number variables in the text content picker (#629); frames and sections convert into each other (#719); bounded canvas pan overscan; community fixes from #478 up and a control-channel fix (#589); bounded canvas pan overscan; Typography spacing icons support scrubbing (#373); font scans skip named pipes; system theme on first run; recent files as cards with thumbnails on the home screen; community fixes: lost images reported on loading (#207), SVG import budgets (#190), Leptos code (#223), full screen (#227), server snapshots readable again (#188), owner-only preferences (#200), ruzstd 0.9.1 (#182), layer cycle repair (#205), batch rollback, Direct3D 12 on Windows, plugin metering (#192); vector edit mode regions: hover hatch, selection and drag; SVG/PDF exports refuse over-depth documents (#208); bounded MCP/control framing, connections and queues (#201); plugin log limits (#191); live-session revert guard (#198); attached MCP no longer replays after a lost reply (#194); repeat command recursion fix; the Layout panel's constrain-proportions link scales the other side, #220; core editor leftovers: component playground, auto gap handles, variables inside styles, inner shadows and background blur on groups, command-made text readable on dark pages, a one-step frame/group convert, delays on mouse triggers and manual overlay offsets, wrapped-line alignment; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; starter templates, a Templates tab and Getting started tips on the home screen; your online files; everyday editing partials: number fields, outline options, Hide when publishing, cursors, panel widths, dark pages; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; a public figcraft-server: open hosting, owner tokens, per-address limits, idle expiry, moderation, install.sh; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; headline percentages recomputed from the area table: feature breadth ~84%, core ~94%, mainstream ~50%; text lists, hanging punctuation and decoration styles; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; styles and variables behaviour suite and fixes; prototyping behaviour suite and fixes; components behaviour suite and fixes; embedded image colour profiles; layers panel keyboard: F2 rename, Shift+F10 context menu, keyboard box selection, 10k-layer QA; per-side stroke weight variables; text behaviour suite: CJK line breaking, metrics, vertical trim; selection and transform behaviour suite and fixes; `.fig` import, best effort; Windows QA pass with eight fixes; auto layout behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings; feature breadth ~80%; ready ~49%) · **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
@@ -13,7 +13,7 @@ start with [`docs/gaps.md`](docs/gaps.md).
| | Value | Kind |
|---|---|---|
-| Menu/command breadth | **100%** (211 / 211) | measured, [`docs/parity-checklist.md`](docs/parity-checklist.md) (`cargo xtask parity`) |
+| Menu/command breadth | **100%** (212 / 212) | measured, [`docs/parity-checklist.md`](docs/parity-checklist.md) (`cargo xtask parity`) |
| Feature breadth | **~85%** (core editor ~94%) | estimated, [`docs/target-app-parity.md`](docs/target-app-parity.md) |
| Ready for real work | **~53%** | estimated, same doc (written dimension weights and scores) |
| Essentials user | **~59%** | estimated: core features 77.8% × 0.92 launch/stability × 0.94 discoverability × 0.88 opening files people send ([method](docs/target-app-parity.md#essentials-user)) |
@@ -99,25 +99,25 @@ native speakers' reviews of the six language drafts need people.
| Language | Code | Strings | Status |
|---|---|---|---|
| English | en | 100% | full |
-| Simplified Chinese | zh-Hans | 100% | draft (needs native review) |
-| Spanish | es, es-419 | 100% (es-419: an overlay of 98 entries) | draft (needs native review) |
+| Simplified Chinese | zh-Hans | 95% | draft (needs native review) |
+| Spanish | es, es-419 | 100% (es-419: an overlay of 101 entries) | draft (needs native review) |
| Hindi | hi | 0% | none |
| Arabic | ar | 0% | none |
-| French | fr | 100% | draft (needs native review) |
-| Portuguese (Brazil) | pt-BR | 100% | draft (needs native review) |
-| Indonesian | id | 0% | none |
-| Japanese | ja | 100% | draft (needs native review) |
-| German | de | 100% | draft (needs native review) |
-| Korean | ko | 100% | draft (needs native review) |
+| French | fr | 95% | draft (needs native review) |
+| Portuguese (Brazil) | pt-BR | 95% | draft (needs native review) |
+| Indonesian | id | 99% | draft (needs native review) |
+| Japanese | ja | 99% | draft (needs native review) |
+| German | de | 96% | draft (needs native review) |
+| Korean | ko | 95% | draft (needs native review) |
| Vietnamese | vi | 0% | none |
-Also shipped: Swedish (`sv`: every UI string, 120 of 588 command labels and menu wordings; native review welcome). Figma ships English, Japanese, Korean, French, German, Spanish and Portuguese
+Percentages measured 2026-10-17 over 2,272 entries (strings added since a draft show English). Also shipped: Russian (`ru`, 99%, reviewed by VanTan), Swedish (`sv`, 99.6%, command labels since 2026-10-17; native review welcome), Turkish (`tr`, 99%) and Czech (`cs`, 99%, draft). Figma ships English, Japanese, Korean, French, German, Spanish and Portuguese
(Brazil); FigCraft has the localization layer, English and Spanish (Spain and Latin America),
-French, German, Brazilian Portuguese, Japanese, Korean and Simplified Chinese drafts (Preferences ▸
+French, German, Brazilian Portuguese, Japanese, Korean, Simplified Chinese and Indonesian drafts (Preferences ▸
Language; Traditional Chinese has no catalog; CJK UI
text uses an installed CJK font, loaded only when needed; adding a language:
[`docs/translating.md`](docs/translating.md)). Document text in any script (bidi, Arabic shaping,
-IME) already works. Detail: [`docs/localization-parity.md`](docs/localization-parity.md).
+IME) already works (macOS IME composition fixed for #747, not yet checked on a Mac). Detail: [`docs/localization-parity.md`](docs/localization-parity.md).
## Upcoming
@@ -131,6 +131,9 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
## Progress log
+- **2026-10-17** · Control channel while the window is minimised (M8, #720): a minimised or covered window answers every request that acts on the app's state (edits, `ui.inspect`, `ui.pointer`, `ui.key`, `ui.type`, `ui.set`, `app.quit`…) without drawing, and what needs a drawn frame (`ui.screenshot`, `ui.input`, `window.new`) is an error at once; before, those waited up to 60 s and held up every later request on the connection (an attached agent's `inspect_ui` or window screenshot stalled until the window came back). Measured on Windows 11, minimised: requests ~100 ms each (eframe wakes a minimised window at most ten times a second; ~2 ms on screen), a window screenshot fails in ~100 ms instead of 60 s, idle CPU 0. Numbers unchanged.
+- **2026-10-17** · Number variables on text content (M3, #629): the Typography section's variable picker also lists number variables for a text layer's content, as the engine already accepted (the text shows the number, e.g. 42.5, and follows the variable). Other text fields keep their own types. Numbers unchanged.
+- **2026-10-17** · Frames and sections convert into each other (M1, #719): `object.convertToSection` turns a frame on the page or in a section into a section in place (same box, name, fill and layers, which stay where they are; what only a frame has goes: auto layout, clipping, layout grids, guides, scrolling), and `object.convertToFrame` now also turns a section into a frame that keeps its fill and doesn't clip, so the look stays. Nested frames, instances, main components and sections holding sections are refused with the reason; one undo step each. Both are in the canvas context menu (Convert to section / Convert to frame) and in Spanish. Numbers unchanged.
- **2026-10-16** · Adobe Fonts found on macOS (M7, #298): fonts activated through Adobe Fonts rendered in the fallback font without a warning, because Creative Cloud keeps them in its own folder as hidden files named by number, which the font scan never read. The macOS scan now includes `~/Library/Application Support/Adobe/CoreSync/plugins/livetype`, and files without an extension are indexed when they start with a font signature. Fonts are read in place. Regression test in the font database tests; docs/cli.md lists the folder. Numbers unchanged.
- **2026-10-14** · Corner handles win over the corner-radius handles (M1, #292): a press on the inner half of a corner handle's square picked the radius handle 10 px in, so the drag neither resized nor (dragging outward) rounded anything. Inside the drawn square the corner now resizes both sides (in ratio with Shift or the link); further in the radius handle still answers. Regression test in the transform behaviour suite. Numbers unchanged.
- **2026-10-14** · Home screen recent files as cards (M7): each card shows the picture its file carries on its first page's colour, the file's icon, name and "Edited ... ago"; sort by name, creation or last change either way; a table view; a click selects, a double-click or Enter opens, arrow keys move; Open, Show in folder and Remove from recents on right-click. Numbers unchanged.
@@ -314,6 +317,16 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
+| 2026-10-20 | minor | Duplicating a main component makes an instance (#892): Duplicate and Alt-drag copied a main component as a second main; within its file the copy is now an instance of it, as Copy then Paste already was (a variant duplicated in its set stays a variant). Numbers unchanged. |
+| 2026-10-20 | minor | Readable disabled and selected text (#890): the dim text colour (disabled buttons, placeholders, hints) is at least 3:1 against panels, fields and selected rows in both themes (it was 2.1:1 in the light theme), a disabled button is grey with that text instead of fading to 40%, and selected text (renaming a page or layer, any text box) takes the theme's readable green on the highlight (1.4:1 in the dark theme before, now 4.2:1 or more); checked with the colour contrast helper (`theme::tests`). Numbers unchanged |
+| 2026-10-20 | minor | Layer data reads back (#879): `node.get` (the command, the control method and MCP `get_node`) and `document.inspect` report a layer's or page's `pluginData` as `{key: value}` when it has any, so a tool that keeps state in a file with `node.set {props: {pluginData}}` can read it on its next run (`plugin_data_tests`). Numbers unchanged |
+| 2026-10-20 | minor | Measuring while nudging (#894): with Alt held over another layer, the arrows nudge the selection (Shift: the big step) and the distances follow every nudge (Alt+arrows used to do nothing); while measuring, the selection's handles and size label hide and both layers keep their outlines (`measure_nudge_tests`). Numbers unchanged |
+| 2026-10-20 | minor | Release fonts (#885): the web release embeds craft-fonts again (Inter), so the browser version draws text and lists fonts; it had none since releases moved to the shared workflow. The craft-fonts pin goes back to the commit with the Latin manifest (the Georgian change had moved it to one without Inter, which would have failed the next release). Numbers unchanged. |
+| 2026-10-17 | minor | Community batch #753 (10 PRs): Selection colors for mixed selections (#403); smart-selection spacing fields and canvas handles (#402); a Present tab with device and scale controls (#537); adding auto layout to an empty frame keeps its size (#369); `node.set` applies auto layout keys to frames only and warns about font styles a family lacks (#603); canvas images on whole device pixels (#359); Adwaita window controls on Wayland without server decorations (#592, not run on GNOME or KDE by the maintainers); the keyboard shortcuts panel closes on the home screen (#548); macOS paste modifiers in tests (#750); credits column tests (#347). `cargo xtask parity` re-run: 212 / 212 menu items (100%; the catalog gained View ▸ Full screen with #227 on 2026-10-14), 561 commands. Language table re-measured from the catalogs (2,272 entries): the drafts read 95–99% (strings added since 2026-10-12 show English), Indonesian has a draft (99%; it read none), and Russian, Swedish (its command labels from #599), Turkish and Czech are listed with their counts. Per-area parity rows for the day's landings in `docs/gaps.md`, `target-app-parity.md` and the area docs. Numbers unchanged |
+| 2026-10-17 | minor | Control channel while the window is minimised (M8, #720): a minimised or covered window answers every request that acts on the app's state (edits, `ui.inspect`, `ui.pointer`, `ui.key`, `ui.type`, `ui.set`, `app.quit`…) without drawing, and what needs a drawn frame (`ui.screenshot`, `ui.input`, `window.new`) is an error at once; before, those waited up to 60 s and held up every later request on the connection (an attached agent's `inspect_ui` or window screenshot stalled until the window came back). Measured on Windows 11, minimised: requests ~100 ms each (eframe wakes a minimised window at most ten times a second; ~2 ms on screen), a window screenshot fails in ~100 ms instead of 60 s, idle CPU 0. Numbers unchanged. |
+| 2026-10-17 | minor | Community fixes from #524 up (batches #727, #728, #733, #735, #736 and #729; 55 PRs) and a crash guard. `.fig` import: explicit instance identity, overrides by key, text style precedence, grid track sizes, slot content, connector labels, skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, text on a path, image adjustments and embedded images; large files open within budgets from the file's own size; an import report after opening; imported bytes stay out of the command journal. Files and paste: save a copy as `.fig`; Cmd/Ctrl+V pastes images copied in other apps and layers copied from another design app (`edit.pasteDesignLayers`); paste over and paste properties; clipboard reads on Linux and the BSDs time out after 2 s. Editor: live font preview on hover; Shift+I and Resources open Assets; Shift-drag moves the selection; thin strokes take a nearby double-click; dropped points merge; Flatten keeps open paths; the Actions palette gets tabs, ranked search, a keyboard highlight and recents; the colour picker opens on a new fill or stroke; text strokes follow their alignment; selection highlights after line breaks; a draggable pages/layers divider; variant properties reorder by drag; submenus keep their hover with a safe triangle; menu actions that need a value ask for it; File ▸ Rename edits the name in place. Engine: bad paint indexes, non-finite geometry and pages in copy/cut are refused; a param naming a layer says so when it isn't one; a CLI script is one undo step and resolves `$step`. Server and collaboration: message limits follow `max_file_mb` (client capped at 1 GiB); a damaged generation field no longer drops flushed edits; the web build joins a session from a `#join=` link. Also Swedish command labels, Nix CI through the shared workflow, paint bounds once per render, and a guard that turns a panic inside the boolean-op library into bad input (the stroke draws unclipped). Numbers unchanged. |
+| 2026-10-17 | minor | Number variables on text content (M3, #629): the Typography section's variable picker also lists number variables for a text layer's content, as the engine already accepted (the text shows the number, e.g. 42.5, and follows the variable). Other text fields keep their own types. Numbers unchanged. |
+| 2026-10-17 | minor | Frames and sections convert into each other (M1, #719): `object.convertToSection` turns a frame on the page or in a section into a section in place (same box, name, fill and layers, which stay where they are; what only a frame has goes: auto layout, clipping, layout grids, guides, scrolling), and `object.convertToFrame` now also turns a section into a frame that keeps its fill and doesn't clip, so the look stays. Nested frames, instances, main components and sections holding sections are refused with the reason; one undo step each. Both are in the canvas context menu (Convert to section / Convert to frame) and in Spanish. Numbers unchanged. |
| 2026-10-16 | minor | Adobe Fonts found on macOS (M7, #298): fonts activated through Adobe Fonts rendered in the fallback font without a warning, because Creative Cloud keeps them in its own folder as hidden files named by number, which the font scan never read. The macOS scan now includes `~/Library/Application Support/Adobe/CoreSync/plugins/livetype`, and files without an extension are indexed when they start with a font signature. Fonts are read in place. Regression test in the font database tests; docs/cli.md lists the folder. Numbers unchanged |
| 2026-10-16 | minor | Community fixes from #478 up (batches #591, #598, #602; 69 PRs) and a control-channel fix: a line that isn't JSON now ends a `--control` connection, so a web page can't drive the app through a browser request (#589). Highlights: page copies keep navigation, flows, prototype settings and guides; Find and Replace keeps line endings and case-insensitive matches; text hyperlinks survive import and export; recent colours record only what was picked; MCP screenshots respect `maxSize`; Swedish catalog (UI strings), Czech plurals; bounded canvas overscan while panning; Korean fallback at the run's weight; many vector-edit, guide, page and .fig round-trip fixes. Numbers unchanged |
| 2026-10-15 | minor | Drop files anywhere to open them (M7): dragging files over the window shows a "Drop to open" (home) or "Drop to import" (canvas) overlay. On the home screen each supported file opens as a document of its own and other files are turned away with a toast; on the canvas the files import at the drop point. Both wait behind a small card that is on screen before a large file blocks the window. A canvas import stays with the document and page that received the drop even if the tab or page changes meanwhile, and is cancelled with a message if that document or page is gone. Numbers unchanged. |
diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs
index 372082c24..4c162dbb5 100644
--- a/apps/figcraft-cli/src/args.rs
+++ b/apps/figcraft-cli/src/args.rs
@@ -1,5 +1,6 @@
//! Minimal std-only argument parsing: positionals, `--key value` / `--key=value` / `-o value`
-//! options, and boolean `--flag`s. Unknown options are usage errors.
+//! options (given again: the last counts, or all with [`Args::values`]), and boolean `--flag`s.
+//! Unknown options are usage errors.
use std::collections::BTreeMap;
@@ -8,7 +9,7 @@ use crate::{CliError, CliResult};
#[derive(Debug, Default)]
pub struct Args {
pub positional: Vec,
- values: BTreeMap,
+ values: BTreeMap>,
flags: Vec,
}
@@ -34,7 +35,7 @@ impl Args {
Some(v) => v,
None => it.next().cloned().ok_or_else(|| CliError::Usage(format!("`{arg}` needs a value")))?,
};
- a.values.insert(name.to_string(), v);
+ a.values.entry(name.to_string()).or_default().push(v);
} else if flags.contains(&name) && inline.is_none() {
a.flags.push(name.to_string());
} else {
@@ -45,7 +46,12 @@ impl Args {
}
pub fn value(&self, k: &str) -> Option {
- self.values.get(k).cloned()
+ self.values.get(k).and_then(|v| v.last()).cloned()
+ }
+
+ /// Every value of an option that may be given more than once, in order.
+ pub fn values(&self, k: &str) -> &[String] {
+ self.values.get(k).map_or(&[], Vec::as_slice)
}
pub fn flag(&self, k: &str) -> bool {
@@ -62,9 +68,9 @@ impl Args {
/// PDF print options: `--bleed LENGTH` (points, or "3mm", "0.125in"), `--crop-marks`,
/// `--bleed-marks`, `--cmyk`.
pub fn print(&self) -> CliResult {
- let bleed = match self.values.get("bleed") {
+ let bleed = match self.value("bleed") {
None => 0.0,
- Some(s) => figcraft_doc::PrintSettings::parse_length(s)
+ Some(s) => figcraft_doc::PrintSettings::parse_length(&s)
.filter(|b| *b <= figcraft_doc::PrintSettings::MAX_BLEED)
.ok_or_else(|| CliError::Usage(format!("--bleed takes points or a length like 3mm or 0.125in (up to 2in), got `{s}`")))?,
};
@@ -72,7 +78,7 @@ impl Args {
}
pub fn scale(&self) -> CliResult {
- match self.values.get("scale") {
+ match self.value("scale") {
None => Ok(1.0),
Some(s) => s
.trim_end_matches('x')
@@ -85,7 +91,7 @@ impl Args {
/// A comma-separated list of whole numbers (`--layers 1000,10_000`).
pub fn usizes(&self, k: &str, default: &[usize]) -> CliResult> {
- match self.values.get(k) {
+ match self.value(k) {
None => Ok(default.to_vec()),
Some(s) => s
.split(',')
@@ -110,6 +116,10 @@ mod tests {
assert_eq!(a.value("o").as_deref(), Some("out"));
assert_eq!(a.scale().unwrap(), 2.0);
assert!(a.flag("json"));
+ let a = Args::parse(&v(&["--root", "a", "--root=b"]), &["root"], &[]).unwrap();
+ assert_eq!(a.values("root"), ["a", "b"]);
+ assert_eq!(a.value("root").as_deref(), Some("b"));
+ assert!(a.values("none").is_empty());
}
#[test]
diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs
index 4fb485e10..462155998 100644
--- a/apps/figcraft-cli/src/files.rs
+++ b/apps/figcraft-cli/src/files.rs
@@ -29,9 +29,20 @@ fn image_format(e: &str) -> Option {
}
}
+/// Writes through [`figcraft_engine::file_access`] when automation roots are in force, so a
+/// confined run can only write inside a write root (#833).
+///
+/// Unconfined it writes with `std::fs::write`, as it always did. `file_access::write` stages the
+/// bytes and renames them into place, which **replaces** a symbolic link at `path` instead of
+/// writing through it to its target -- a change of behaviour for anyone whose output path is a
+/// link, and nothing to do with confinement. Inside a root the staged write is the right one:
+/// `Roots::check` has already refused a link that leads out of the root.
fn write(path: &str, bytes: &[u8]) -> CliResult<()> {
if let Some(dir) = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) {
- std::fs::create_dir_all(dir).map_err(|e| CliError::Failed(format!("{}: {e}", dir.display())))?;
+ figcraft_engine::file_access::create_dir_all(dir).map_err(|e| CliError::Failed(e.to_string()))?;
+ }
+ if figcraft_engine::file_access::current().is_some() {
+ return figcraft_engine::file_access::write(path, bytes).map_err(|e| CliError::Failed(e.to_string()));
}
std::fs::write(path, bytes).map_err(|e| CliError::Failed(format!("{path}: {e}")))
}
@@ -155,6 +166,7 @@ pub fn info(path: &str, as_json: bool) -> CliResult {
Some(json!({"id": p, "name": pn.name, "nodes": nodes, "topLevel": pn.children.len(), "frames": frames}))
})
.collect();
+ let missing = figcraft_engine::fonts::missing(&doc);
let v = json!({
"file": path,
"name": doc.name,
@@ -164,6 +176,7 @@ pub fn info(path: &str, as_json: bool) -> CliResult {
"variables": doc.variables.variables.len(),
"images": doc.images.len(),
"notes": notes,
+ "missingFonts": missing.iter().map(|m| json!({"family": m.family, "layers": m.layers})).collect::>(),
});
if as_json {
println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
@@ -187,6 +200,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult {
println!(" {} {} \"{}\" {}×{}", f["id"], f["type"].as_str().unwrap_or(""), f["name"].as_str().unwrap_or(""), f["width"], f["height"]);
}
}
+ for m in &missing {
+ let layers = if m.layers == 1 { "text layer" } else { "text layers" };
+ println!("missing font \"{}\": {} {layers} (drawn in a fallback font)", m.family, m.layers);
+ }
Ok(ExitCode::SUCCESS)
}
@@ -238,7 +255,7 @@ pub fn export(file: &str, out: &str, t: &Target) -> CliResult {
println!("{out}");
return Ok(ExitCode::SUCCESS);
}
- std::fs::create_dir_all(out).map_err(|e| CliError::Failed(format!("{out}: {e}")))?;
+ figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
let ids = match target {
Some(t) => vec![t],
None => {
@@ -323,7 +340,8 @@ pub fn parse_script(text: &str) -> Result, String> {
}
pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliResult {
- let text = std::fs::read_to_string(script).map_err(|e| CliError::Failed(format!("{script}: {e}")))?;
+ let bytes = figcraft_engine::file_access::read(script).map_err(|e| CliError::Failed(e.to_string()))?;
+ let text = String::from_utf8(bytes).map_err(|_| CliError::Failed(format!("{script}: not UTF-8")))?;
let steps = parse_script(&text).map_err(|e| CliError::Failed(format!("{script}: {e}")))?;
let mut s = match input {
Some(path) => {
@@ -333,17 +351,32 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>) -> CliRe
}
None => Session::new(),
};
- for (i, (cmd, params)) in steps.iter().enumerate() {
- let r = s.execute(cmd, params);
- s.ui_requests.clear();
- match r {
- Ok(v) => println!("{}", json!({"step": i, "command": cmd, "ok": true, "result": v})),
- Err(e) => {
- println!("{}", json!({"step": i, "command": cmd, "ok": false, "error": e.to_string()}));
- eprintln!("error: step {i} ({cmd}) failed: {e}");
- return Ok(ExitCode::from(1));
- }
+ // One undo step and all-or-nothing, the way the same commands behave through `command.batch`
+ // (MCP, the control channel, plugins): `{"$step": n}` resolves against the steps before it, and
+ // a step that fails takes the whole script back instead of leaving the earlier steps applied.
+ // The result lines are held back until the script is through, so none of them reports work that
+ // was rolled back.
+ let mut results: Vec = Vec::with_capacity(steps.len());
+ let mut failed_at = 0;
+ let outcome = s.grouped(&format!("run {script}"), |s| {
+ for (i, (cmd, params)) in steps.iter().enumerate() {
+ failed_at = i;
+ let v = s.batch_step(&results, i, cmd, params)?;
+ s.ui_requests.clear();
+ results.push(v);
}
+ Ok(())
+ });
+ if let Err(e) = outcome {
+ let cmd = steps.get(failed_at).map_or("", |(cmd, _)| cmd.as_str());
+ let i = failed_at;
+ println!("{}", json!({"step": i, "command": cmd, "ok": false, "error": e.to_string(), "rolledBack": true}));
+ eprintln!("error: step {i} ({cmd}) failed: {e}");
+ eprintln!("the script's document changes were rolled back");
+ return Ok(ExitCode::from(1));
+ }
+ for (i, ((cmd, _), v)) in steps.iter().zip(&results).enumerate() {
+ println!("{}", json!({"step": i, "command": cmd, "ok": true, "result": v}));
}
if let Some(out) = out {
let ds = s.ds().map_err(|e| CliError::Failed(e.to_string()))?;
@@ -422,4 +455,62 @@ mod tests {
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2);
std::fs::remove_dir_all(dir).unwrap();
}
+
+ fn temp_dir(tag: &str) -> std::path::PathBuf {
+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let dir = std::env::temp_dir().join(format!("figcraft-cli-{tag}-{}-{stamp}", std::process::id()));
+ std::fs::create_dir(&dir).unwrap();
+ dir
+ }
+
+ /// A script resolves `{"$step": n}` like the same commands through `command.batch`. Each step
+ /// used to run on its own, so the reference reached `parent` unresolved, `node.create` read it
+ /// as "no parent" and the layer landed on the page — with every step reporting success.
+ #[test]
+ fn a_script_puts_a_layer_in_a_layer_an_earlier_step_made() {
+ let dir = temp_dir("run-step");
+ let script = dir.join("script.json");
+ std::fs::write(
+ &script,
+ r#"[
+ {"command": "node.create", "params": {"type": "frame", "name": "Card", "x": 0, "y": 0, "width": 200, "height": 100}},
+ {"command": "node.create", "params": {"type": "rectangle", "name": "child", "parent": {"$step": 0}, "x": 10, "y": 10, "width": 20, "height": 20}}
+ ]"#,
+ )
+ .unwrap();
+ let out = dir.join("out.figcraft");
+ run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap();
+
+ let mut s = Session::empty();
+ s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
+ let doc = s.doc().unwrap();
+ let page = s.page().unwrap();
+ let top = doc.node(page).unwrap().children.clone();
+ assert_eq!(top.len(), 1, "only the frame is top level, not the rectangle too");
+ assert_eq!(doc.node(top[0]).unwrap().name, "Card");
+ let inner = doc.node(top[0]).unwrap().children.clone();
+ assert_eq!(inner.len(), 1, "the rectangle went inside the frame");
+ assert_eq!(doc.node(inner[0]).unwrap().name, "child");
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ /// A step that fails takes the whole script back: nothing is written, and the failure says so.
+ #[test]
+ fn a_failed_step_leaves_no_output() {
+ let dir = temp_dir("run-rollback");
+ let script = dir.join("script.json");
+ std::fs::write(
+ &script,
+ r#"[
+ {"command": "node.create", "params": {"type": "frame", "name": "Card", "x": 0, "y": 0, "width": 200, "height": 100}},
+ {"command": "node.set", "params": {"ids": [99999], "props": {"name": "nope"}}}
+ ]"#,
+ )
+ .unwrap();
+ let out = dir.join("out.figcraft");
+ // The failure is the script's, not the call's: the CLI reports it and exits non-zero.
+ run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap())).unwrap();
+ assert!(!out.exists(), "a script that failed writes nothing");
+ std::fs::remove_dir_all(dir).unwrap();
+ }
}
diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs
index 590b50f14..badc5bc30 100644
--- a/apps/figcraft-cli/src/main.rs
+++ b/apps/figcraft-cli/src/main.rs
@@ -22,8 +22,9 @@ USAGE:
figcraft-cli convert
figcraft-cli render -o [--scale N] [--page NAME]
figcraft-cli run [--in ] [--out ]
+ (info, export, convert, render and run also take --automation-read-root DIR / --automation-write-root DIR)
figcraft-cli commands [--json] [--filter TEXT]
- figcraft-cli mcp [--attach PORT]
+ figcraft-cli mcp [--attach PORT] [--automation-read-root DIR]... [--automation-write-root DIR]...
figcraft-cli plugin publish --server ws://host:port/[?key=KEY]
figcraft-cli perf [--layers N[,N...]] [--instances N[,N...]]
figcraft-cli help | --help | --version
@@ -42,8 +43,33 @@ crop and bleed marks, CMYK colour). `run` executes a JSON array (or JSON lines)
`plugin publish` sends a plugin folder (figcraft-plugin.json, its module, an optional assets/ folder)
to a figcraft-server's plugin directory as a new version; the server's key comes from the address or
the FIGCRAFT_SERVER_KEY environment variable (which keeps it out of the shell history).
+`--automation-read-root DIR` / `--automation-write-root DIR` (each may be repeated; the folders
+must exist) confine the files a subcommand touches: reads only inside a read or write root, writes
+only inside a write root, everything else refused -- so giving no write root denies writing
+altogether. They are taken by `mcp`, to confine the agent's commands, and by `info`, `export`,
+`convert`, `render` and `run`, to confine that one run; without them a subcommand reads and writes
+as the user who started it, as before. A running app confines itself: start it with
+`figcraft --control PORT` and the same flags (`--attach` refuses them).
See docs/cli.md and docs/mcp.md.";
+/// The automation roots a file subcommand was given, if any. Omitting both leaves the run
+/// unconfined, as before; giving either confines every file the subcommand touches (#833).
+const ROOT_FLAGS: [&str; 2] = ["automation-read-root", "automation-write-root"];
+
+fn roots_of(a: &Args) -> CliResult> {
+ let (read, write) = (a.values("automation-read-root"), a.values("automation-write-root"));
+ if read.is_empty() && write.is_empty() {
+ return Ok(None);
+ }
+ Ok(Some(figcraft_engine::file_access::Roots::new(read, write).map_err(CliError::Failed)?))
+}
+
+/// Runs `f` confined to the roots `a` carries.
+fn confined(a: &Args, f: impl FnOnce() -> CliResult) -> CliResult {
+ let roots = roots_of(a)?.map(std::sync::Arc::new);
+ figcraft_engine::file_access::confined(roots.as_ref(), f)
+}
+
fn main() -> ExitCode {
let argv: Vec = std::env::args().skip(1).collect();
match run(&argv) {
@@ -94,35 +120,38 @@ fn run(argv: &[String]) -> CliResult {
Ok(ExitCode::SUCCESS)
}
"info" => {
- let a = Args::parse(rest, &[], &["json"])?;
+ let a = Args::parse(rest, &ROOT_FLAGS, &["json"])?;
let file = a.one_positional("info ")?;
- files::info(&file, a.flag("json"))
+ confined(&a, || files::info(&file, a.flag("json")))
}
"export" => {
- let a = Args::parse(rest, &["format", "scale", "page", "node", "o", "out", "bleed"], &["crop-marks", "bleed-marks", "cmyk"])?;
+ let valued = [&["format", "scale", "page", "node", "o", "out", "bleed"][..], &ROOT_FLAGS[..]].concat();
+ let a = Args::parse(rest, &valued, &["crop-marks", "bleed-marks", "cmyk"])?;
let file = a.one_positional("export -o ")?;
let out = a.value("o").or_else(|| a.value("out")).ok_or_else(|| CliError::Usage("export needs -o ".into()))?;
let target =
files::Target { format: a.value("format"), scale: a.scale()?, page: a.value("page"), node: a.value("node"), print: a.print()? };
- files::export(&file, &out, &target)
+ confined(&a, || files::export(&file, &out, &target))
}
"convert" => {
- let a = Args::parse(rest, &[], &[])?;
+ let a = Args::parse(rest, &ROOT_FLAGS, &[])?;
match a.positional.as_slice() {
- [i, o] => files::convert(i, o),
+ [i, o] => confined(&a, || files::convert(i, o)),
_ => Err(CliError::Usage("convert ".into())),
}
}
"render" => {
- let a = Args::parse(rest, &["o", "out", "scale", "page"], &[])?;
+ let valued = [&["o", "out", "scale", "page"][..], &ROOT_FLAGS[..]].concat();
+ let a = Args::parse(rest, &valued, &[])?;
let file = a.one_positional("render -o ")?;
let out = a.value("o").or_else(|| a.value("out")).ok_or_else(|| CliError::Usage("render needs -o ".into()))?;
- files::render(&file, &out, a.scale()?, a.value("page").as_deref())
+ confined(&a, || files::render(&file, &out, a.scale()?, a.value("page").as_deref()))
}
"run" => {
- let a = Args::parse(rest, &["in", "out"], &[])?;
+ let valued = [&["in", "out"][..], &ROOT_FLAGS[..]].concat();
+ let a = Args::parse(rest, &valued, &[])?;
let script = a.one_positional("run ")?;
- files::run_script(&script, a.value("in").as_deref(), a.value("out").as_deref())
+ confined(&a, || files::run_script(&script, a.value("in").as_deref(), a.value("out").as_deref()))
}
"commands" => {
let a = Args::parse(rest, &["filter"], &["json"])?;
@@ -133,11 +162,20 @@ fn run(argv: &[String]) -> CliResult {
Ok(ExitCode::SUCCESS)
}
"mcp" => {
- let a = Args::parse(rest, &["attach"], &[])?;
+ let valued = [&["attach"][..], &ROOT_FLAGS[..]].concat();
+ let a = Args::parse(rest, &valued, &[])?;
if !a.positional.is_empty() {
return Err(CliError::Usage("mcp takes no positional arguments".into()));
}
- mcp(a.value("attach").as_deref())
+ let attach = a.value("attach");
+ // The app runs the commands: only its own roots can confine them.
+ if attach.is_some() && ROOT_FLAGS.iter().any(|f| !a.values(f).is_empty()) {
+ return Err(CliError::Usage(
+ "--attach can't take automation roots: start the app with them instead (`figcraft --control PORT --automation-read-root DIR ...`)"
+ .into(),
+ ));
+ }
+ mcp(attach.as_deref(), roots_of(&a)?)
}
"plugin" => {
let a = Args::parse(rest, &["server"], &[])?;
@@ -205,7 +243,7 @@ fn publish_plugin(folder: &str, server: &str) -> CliResult {
Ok(ExitCode::SUCCESS)
}
-fn mcp(attach: Option<&str>) -> CliResult {
+fn mcp(attach: Option<&str>, roots: Option) -> CliResult {
let backend: Box = match attach {
Some(p) => {
let addr = if p.contains(':') {
@@ -220,7 +258,10 @@ fn mcp(attach: Option<&str>) -> CliResult {
None => Box::new(figcraft_mcp::Headless::new()),
};
eprintln!("figcraft MCP server ({}) on stdio", backend.describe());
- let mut server = figcraft_mcp::Server::new(backend);
+ if let Some(r) = &roots {
+ eprintln!("file access confined to {}", r.to_json());
+ }
+ let mut server = figcraft_mcp::Server::new(backend).with_roots(roots);
let stdin = std::io::stdin();
let stdout = std::io::stdout();
server.serve(stdin.lock(), stdout.lock()).map_err(|e| format!("stdio: {e}"))?;
diff --git a/apps/figcraft-cli/tests/cli.rs b/apps/figcraft-cli/tests/cli.rs
index 9dd522031..eb42b8d88 100644
--- a/apps/figcraft-cli/tests/cli.rs
+++ b/apps/figcraft-cli/tests/cli.rs
@@ -25,6 +25,9 @@ fn bad_arguments_exit_2_without_panicking() {
&["render", "a", "-o"],
&["perf", "--shapes", "lots"],
&["mcp", "--attach", "notaport"],
+ // An attached app confines itself: roots go to `figcraft --control`.
+ &["mcp", "--attach", "7979", "--automation-read-root", "."],
+ &["mcp", "--automation-write-root"],
&["convert", "a"],
] {
let out = bin().args(args).output().unwrap();
@@ -120,9 +123,147 @@ fn mcp_over_stdio() {
assert_eq!(lines[2]["result"]["isError"], false);
}
+#[test]
+fn mcp_over_stdio_confined_to_automation_roots() {
+ let d = tmp("roots");
+ for sub in ["in", "out", "outside"] {
+ std::fs::create_dir_all(d.join(sub)).unwrap();
+ }
+ let p = |rel: &str| d.join(rel).to_string_lossy().into_owned();
+ // A root that isn't a folder stops the server before it serves.
+ let out = bin().args(["mcp", "--automation-read-root", &p("missing")]).output().unwrap();
+ assert_eq!(out.status.code(), Some(1));
+ assert!(String::from_utf8_lossy(&out.stderr).contains("--automation-read-root"));
+ let mut child = bin()
+ .args(["mcp", "--automation-read-root", &p("in"), "--automation-write-root", &p("out")])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ {
+ let stdin = child.stdin.as_mut().unwrap();
+ let call = |id: u32, tool: &str, args: serde_json::Value| {
+ serde_json::json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": tool, "arguments": args}}).to_string()
+ };
+ writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
+ writeln!(stdin, "{}", call(2, "create_node", serde_json::json!({"type": "ellipse"}))).unwrap();
+ writeln!(stdin, "{}", call(3, "save_file", serde_json::json!({"path": p("outside/a.figcraft")}))).unwrap();
+ writeln!(stdin, "{}", call(4, "save_file", serde_json::json!({"path": p("out/a.figcraft")}))).unwrap();
+ writeln!(stdin, "{}", call(5, "open_file", serde_json::json!({"path": p("outside/a.figcraft")}))).unwrap();
+ writeln!(stdin, "{}", call(6, "open_file", serde_json::json!({"path": p("out/a.figcraft")}))).unwrap();
+ }
+ drop(child.stdin.take());
+ let out = child.wait_with_output().unwrap();
+ assert!(out.status.success());
+ let lines: Vec = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
+ assert_eq!(lines.len(), 6);
+ assert!(lines[0]["result"]["instructions"].as_str().unwrap().contains("only these folders may be read"));
+ let error = |i: usize| lines[i]["result"]["isError"] == true;
+ assert!(!error(1) && error(2) && !error(3) && error(4) && !error(5), "{lines:?}");
+ assert!(lines[2]["result"]["content"][0]["text"].as_str().unwrap().contains("automation path rejected"));
+ assert!(d.join("out/a.figcraft").is_file() && !d.join("outside/a.figcraft").exists());
+ let _ = std::fs::remove_dir_all(&d);
+}
+
#[test]
fn commands_json_lists_everything() {
let out = bin().args(["commands", "--json"]).output().unwrap();
let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert!(v.as_array().unwrap().len() > 200);
}
+
+/// The automation roots confine the file subcommands too, not just `mcp` (#833): a read outside a
+/// root, and a write outside a write root, are refused and leave no file behind. Without the flags
+/// the same commands behave as they always did.
+#[test]
+fn file_subcommands_are_confined_to_automation_roots() {
+ let d = tmp("file-roots");
+ let _ = std::fs::remove_dir_all(&d);
+ for sub in ["in", "out"] {
+ std::fs::create_dir_all(d.join(sub)).unwrap();
+ }
+ let p = |rel: &str| d.join(rel).to_string_lossy().into_owned();
+ let out_of = |o: &std::process::Output| String::from_utf8_lossy(&o.stderr).into_owned();
+
+ // A document to work on, made unconfined.
+ std::fs::write(d.join("in/make.json"), br#"[{"command":"shape.rectangle","params":{"x":0,"y":0,"width":40,"height":20}}]"#).unwrap();
+ let made = bin().args(["run", &p("in/make.json"), "--out", &p("in/doc.figcraft")]).output().unwrap();
+ assert!(made.status.success(), "{}", out_of(&made));
+
+ // Inside the roots: renders as usual.
+ let ok = bin()
+ .args(["render", &p("in/doc.figcraft"), "-o", &p("out/ok.png"), "--automation-read-root", &p("in"), "--automation-write-root", &p("out")])
+ .output()
+ .unwrap();
+ assert!(ok.status.success(), "{}", out_of(&ok));
+ assert!(d.join("out/ok.png").is_file());
+
+ // A write outside the write root is refused, and nothing is written.
+ let escaped = d.join("escaped.png");
+ let refused = bin()
+ .args([
+ "render",
+ &p("in/doc.figcraft"),
+ "-o",
+ &escaped.to_string_lossy(),
+ "--automation-read-root",
+ &p("in"),
+ "--automation-write-root",
+ &p("out"),
+ ])
+ .output()
+ .unwrap();
+ assert!(!refused.status.success());
+ assert!(out_of(&refused).contains("may be written"), "{}", out_of(&refused));
+ assert!(!escaped.exists(), "the refused render wrote a file anyway");
+
+ // No write root at all: writing is refused outright, reading still works.
+ let no_write = bin().args(["render", &p("in/doc.figcraft"), "-o", &p("out/no.png"), "--automation-read-root", &p("in")]).output().unwrap();
+ assert!(!no_write.status.success());
+ assert!(out_of(&no_write).contains("no folder may be written"), "{}", out_of(&no_write));
+
+ // A read outside every root is refused: `info` on the document with only `out` readable.
+ let read_refused = bin().args(["info", &p("in/doc.figcraft"), "--automation-read-root", &p("out")]).output().unwrap();
+ assert!(!read_refused.status.success());
+ assert!(out_of(&read_refused).contains("may be read"), "{}", out_of(&read_refused));
+
+ // `convert` and `run` take them as well, and a root that is not a folder is refused.
+ let missing = bin().args(["convert", &p("in/doc.figcraft"), &p("out/c.svg"), "--automation-read-root", &p("missing")]).output().unwrap();
+ assert!(!missing.status.success());
+ assert!(out_of(&missing).contains("automation-read-root"), "{}", out_of(&missing));
+
+ // Unconfined, the same render still writes wherever it is told.
+ let plain = bin().args(["render", &p("in/doc.figcraft"), "-o", &escaped.to_string_lossy()]).output().unwrap();
+ assert!(plain.status.success(), "{}", out_of(&plain));
+ assert!(escaped.is_file());
+ let _ = std::fs::remove_dir_all(&d);
+}
+
+/// An output path that is a symbolic link is written through, to its target, as `std::fs::write`
+/// always did. Routing the CLI's writes through `file_access` for #833 would otherwise have
+/// replaced the link with a regular file, because that write stages the bytes and renames them
+/// into place.
+#[cfg(unix)]
+#[test]
+fn an_unconfined_write_follows_a_symbolic_link() {
+ let d = tmp("symlink-out");
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(d.join("real")).unwrap();
+ let p = |rel: &str| d.join(rel).to_string_lossy().into_owned();
+ std::fs::write(d.join("in.json"), br#"[{"command":"shape.rectangle","params":{"x":0,"y":0,"width":40,"height":20}}]"#).unwrap();
+ let made = bin().args(["run", &p("in.json"), "--out", &p("doc.figcraft")]).output().unwrap();
+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
+
+ let target = d.join("real/target.png");
+ std::fs::write(&target, b"placeholder").unwrap();
+ let link = d.join("link.png");
+ std::os::unix::fs::symlink(&target, &link).unwrap();
+
+ let out = bin().args(["render", &p("doc.figcraft"), "-o", &link.to_string_lossy()]).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link is still a link");
+ let written = std::fs::read(&target).unwrap();
+ assert!(written.starts_with(b"\x89PNG"), "the target holds the render, not the placeholder");
+ let _ = std::fs::remove_dir_all(&d);
+}
diff --git a/apps/figcraft-cli/tests/fonts.rs b/apps/figcraft-cli/tests/fonts.rs
index c5901ac50..ef5c638fa 100644
--- a/apps/figcraft-cli/tests/fonts.rs
+++ b/apps/figcraft-cli/tests/fonts.rs
@@ -45,3 +45,25 @@ fn headless_runs_resolve_installed_families_unless_opted_out() {
assert_eq!(run_one("face", face.clone(), &[], false)["family"], json!(installed), "text uses the installed family");
assert_ne!(run_one("face", face, &["--no-system-fonts"], false)["family"], json!(installed), "opted out, it falls back");
}
+
+#[test]
+fn info_lists_the_fonts_a_file_uses_that_are_missing() {
+ let d = std::env::temp_dir().join(format!("figcraft-cli-missing-{}", std::process::id()));
+ std::fs::create_dir_all(&d).unwrap();
+ let (script, file) = (d.join("make.json"), d.join("doc.figcraft"));
+ let text =
+ |family: &str| json!({"command": "text.create", "params": {"text": "Hamburgefonstiv", "x": 0, "y": 0, "props": {"fontFamily": family}}});
+ std::fs::write(&script, json!([text("FigCraft Missing CLI"), text("FigCraft Missing CLI")]).to_string()).unwrap();
+ let cli = || Command::new(env!("CARGO_BIN_EXE_figcraft-cli"));
+ let made = cli().arg("run").arg(&script).arg("--out").arg(&file).output().unwrap();
+ assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr));
+
+ let out = cli().arg("info").arg(&file).arg("--json").output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let v: Value = serde_json::from_slice(&out.stdout).unwrap();
+ assert_eq!(v["missingFonts"], json!([{"family": "FigCraft Missing CLI", "layers": 2}]));
+
+ let out = cli().arg("info").arg(&file).output().unwrap();
+ let shown = String::from_utf8_lossy(&out.stdout);
+ assert!(shown.contains("missing font \"FigCraft Missing CLI\": 2 text layers"), "{shown}");
+}
diff --git a/apps/figcraft-server/src/config.rs b/apps/figcraft-server/src/config.rs
index bd587b767..d5f4f761e 100644
--- a/apps/figcraft-server/src/config.rs
+++ b/apps/figcraft-server/src/config.rs
@@ -135,9 +135,23 @@ impl Config {
/// abuse contact, or one whose clients would all count as its proxy).
pub fn warnings(&self) -> Vec {
let mut out = Vec::new();
+ let client_max = NetLimits::default().max_server_message >> 20;
+ if usize::try_from(self.file_mb()).is_ok_and(|mb| mb >= client_max) {
+ out.push(format!(
+ "max_file_mb is {}: the app opens files of up to {} MiB, so a file that large can't be opened",
+ self.file_mb(),
+ client_max - 1
+ ));
+ }
if !self.open_publish {
return out;
}
+ if self.file_mb() > 64 {
+ out.push(format!(
+ "open_publish is on with max_file_mb = {}: anyone may send messages that large, and the memory set aside for reading and queueing them grows to eight times it; keep it at 64 or less on a public server",
+ self.file_mb()
+ ));
+ }
if self.operator_contact.trim().is_empty() {
out.push("open_publish is on but operator_contact is empty: people can't reach you about abuse; set it (and terms_url)".into());
}
@@ -168,7 +182,7 @@ impl Config {
return Err("`idle_days` must be from 0 to 3650".into());
}
let terms = self.terms_url.trim();
- if !terms.is_empty() && !(terms.starts_with("https://") || terms.starts_with("http://")) || terms.contains(char::is_whitespace) {
+ if !(terms.is_empty() || terms.starts_with("https://") || terms.starts_with("http://")) || terms.contains(char::is_whitespace) {
return Err("`terms_url` must be a web address (https://…)".into());
}
if self.operator_contact.chars().count() > 120 || self.operator_contact.chars().any(char::is_control) || terms.len() > 500 {
@@ -253,8 +267,9 @@ impl Config {
}
}
- /// Largest message a client may send when open to the public: a whole file (or plugin bundle)
- /// and a margin, not the core's 64 MiB.
+ /// Largest message a client may send: a whole file (or plugin bundle) and a margin. Open to the
+ /// public this is also the cap (strangers' files stay small); a private server never goes below
+ /// the core's 64 MiB, and a `max_file_mb` above it raises the cap with it.
fn open_message(&self) -> usize {
usize::try_from(self.file_mb().max(self.max_plugin_mb).saturating_add(1).saturating_mul(1 << 20)).unwrap_or(usize::MAX)
}
@@ -265,9 +280,9 @@ impl Config {
fn core(&self) -> figcraft_collab::Limits {
let base = figcraft_collab::Limits { max_peers: self.max_people, ..figcraft_collab::Limits::default() };
if !self.open_publish {
- return base;
+ return figcraft_collab::Limits { max_message_bytes: base.max_message_bytes.max(self.open_message()), ..base };
}
- let max = self.open_message().min(base.max_message_bytes);
+ let max = self.open_message();
let file = usize::try_from(self.file_mb().saturating_mul(1 << 20)).unwrap_or(usize::MAX);
figcraft_collab::Limits { max_message_bytes: max, max_log_bytes: (file / 4).max(256 << 10), ..base }
}
@@ -279,21 +294,24 @@ impl Config {
pub fn net(&self) -> NetLimits {
let base = NetLimits { max_connections: self.max_connections, trusted_proxy: self.proxy().ok().flatten(), ..NetLimits::default() };
if !self.open_publish {
- return base;
+ let max = base.max_client_message.max(self.open_message());
+ return NetLimits { max_client_message: max, max_queued_bytes: base.max_queued_bytes.max(max.saturating_add(1 << 20)), ..base };
}
- let max = self.open_message().min(base.max_client_message);
+ let max = self.open_message();
// Shared budgets: one block of addresses (an IPv4 address, an IPv6 /48) gets at most an
- // eighth of each, and its biggest consumers are dropped first.
- let (queued, reading) = (256usize << 20, 192usize << 20);
+ // eighth of each, and its biggest consumers are dropped first. Each still fits one whole
+ // message, or a file as large as `max_file_mb` could never arrive.
+ let one = max.saturating_add(1 << 20);
+ let (queued, reading) = ((256usize << 20).max(one.saturating_mul(8)), (192usize << 20).max(one.saturating_mul(8)));
NetLimits {
max_per_address: self.max_connections_per_ip,
max_client_message: max,
- max_queued_bytes: max.saturating_add(1 << 20),
+ max_queued_bytes: one,
max_queued_block: queued / 8,
max_queued_total: queued,
- max_reading_block: max.saturating_add(1 << 20).min(reading / 8),
+ max_reading_block: one.min(reading / 8),
max_reading_total: reading,
- max_in_flight: 128 << 20,
+ max_in_flight: (128usize << 20).max(one),
reserve_for_sessions: self.max_connections / 8,
request_idle: std::time::Duration::from_secs(20),
..base
diff --git a/apps/figcraft-server/src/disk.rs b/apps/figcraft-server/src/disk.rs
index f58f25b21..af6e0f990 100644
--- a/apps/figcraft-server/src/disk.rs
+++ b/apps/figcraft-server/src/disk.rs
@@ -8,8 +8,10 @@
//! length (u32 LE), CRC-32 (u32 LE), one [`Journal`] entry in the wire encoding.
//!
//! Compaction writes the next generation's snapshot, then an empty log of that generation. A log
-//! whose generation isn't the snapshot's is from before a compaction that was cut short: what it
-//! holds is in the snapshot already. A log ends at its first damaged record (a write cut short).
+//! whose generation isn't the snapshot's is usually from before a compaction that was cut short
+//! (what it holds is in the snapshot already), but no checksum covers either generation, so the
+//! store replays such a log anyway and reports any change the snapshot lacked. A log ends at its
+//! first damaged record (a write cut short).
use std::fs::{self, File};
use std::io::{self, Read, Write};
diff --git a/apps/figcraft-server/src/public_tests.rs b/apps/figcraft-server/src/public_tests.rs
index fea2667e9..978d9e8ee 100644
--- a/apps/figcraft-server/src/public_tests.rs
+++ b/apps/figcraft-server/src/public_tests.rs
@@ -413,7 +413,7 @@ fn open_mode_has_safe_defaults_and_warns_the_operator() {
assert_eq!(open.net().request_idle, Duration::from_secs(20), "idle one-shot requests go quickly");
assert_eq!(open.net().reserve_for_sessions, 512 / 8);
assert_eq!(open.net().max_client_message, 17 << 20);
- assert_eq!(private.net().max_client_message, NetLimits::default().max_client_message, "unchanged when private");
+ assert_eq!(private.net().max_client_message, 65 << 20, "private: a 64 MiB file and a margin");
let w = open.warnings().join("\n");
assert!(w.contains("operator_contact is empty") && w.contains("trusted_proxy"), "{w}");
let set = Config { operator_contact: "abuse@example.com".into(), trusted_proxy: Some("127.0.0.1".into()), max_file_mb: Some(8), ..open };
@@ -493,3 +493,34 @@ fn open_connections_never_reach_what_needs_the_key() {
assert!(!format!("{info:?}").contains(&k));
server.stop();
}
+
+#[test]
+fn files_above_64_mib_fit_every_limit() {
+ // `max_file_mb` may go up to 4096: every cap a whole file's message meets on its way in must
+ // follow it, or the upload is dropped by the transport before the server can say why.
+ for open_publish in [false, true] {
+ let cfg = Config { open_publish, max_file_mb: Some(256), public_url: Some("wss://figcraft.example.com/".into()), ..Config::default() };
+ let (net, core, file) = (cfg.net(), cfg.store().core, 256usize << 20);
+ assert!(net.max_client_message > file, "open={open_publish}: {}", net.max_client_message);
+ assert!(net.max_queued_bytes > file && net.max_reading_block > file && net.max_in_flight > file, "open={open_publish}: {net:?}");
+ assert!(net.max_reading_total >= net.max_reading_block && net.max_queued_total >= net.max_queued_block);
+ assert!(core.max_message_bytes > file, "open={open_publish}: {}", core.max_message_bytes);
+ }
+ // A client takes such a file too, but caps what any server may make it buffer at 1 GiB.
+ assert_eq!(NetLimits::default().max_server_message, 1 << 30);
+}
+
+#[test]
+fn large_files_warn_the_operator() {
+ let public_url = Some("wss://figcraft.example.com/".into());
+ let warns = |open_publish, mb| {
+ Config { open_publish, max_file_mb: Some(mb), public_url: public_url.clone(), ..Config::default() }.warnings().join(
+ "
+",
+ )
+ };
+ assert!(!warns(true, 64).contains("max_file_mb"), "{}", warns(true, 64));
+ assert!(warns(true, 65).contains("open_publish is on with max_file_mb = 65"), "{}", warns(true, 65));
+ assert!(!warns(false, 1023).contains("max_file_mb"), "{}", warns(false, 1023));
+ assert!(warns(false, 1024).contains("can't be opened"), "{}", warns(false, 1024));
+}
diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs
index 538adefff..ea9bc626c 100644
--- a/apps/figcraft-server/src/store.rs
+++ b/apps/figcraft-server/src/store.rs
@@ -440,7 +440,7 @@ impl Store {
&& let Ok(log) = disk::read_log(&bytes)
&& log.generation != generation
{
- log::info!("file at {}: its log predates the last compaction; it is ignored", path.display());
+ log::info!("file at {}: its log isn't of its snapshot's generation; it is replayed over it when the file opens", path.display());
}
let bytes = [SNAPSHOT, LOG].iter().filter_map(|n| fs::metadata(path.join(n)).ok()).map(|m| m.len()).sum();
Ok(Entry { meta, links, log: None, bytes, forced: 0 })
@@ -1126,8 +1126,32 @@ impl Store {
fresh_log = true;
}
}
- // From before a compaction that was cut short: the snapshot has it all.
- Ok(_) => {}
+ // From before a compaction that was cut short, the snapshot has it all; or a generation
+ // field damaged, which no checksum covers. Replaying tells them apart without trusting
+ // it: entries the snapshot holds are skipped, so only edits it lacks change anything.
+ Ok(log) => {
+ let before = server.seq();
+ let mut stopped = None;
+ for entry in log.entries {
+ if let Err(e) = server.replay(entry) {
+ stopped = Some(e);
+ break;
+ }
+ }
+ let (snap, found, recovered) = (generation, log.generation, server.seq().saturating_sub(before));
+ if recovered > 0 {
+ issues.push(format!(
+ "file {file}: its log's generation ({found}) doesn't match its snapshot's ({snap}), but it held \
+ {recovered} changes the snapshot didn't; they were recovered"
+ ));
+ }
+ if let Some(e) = stopped {
+ issues.push(format!(
+ "file {file}: its log's generation ({found}) doesn't match its snapshot's ({snap}) and it stops \
+ making sense after {recovered} newer changes ({e}); the rest was dropped"
+ ));
+ }
+ }
Err(why) => issues.push(format!("file {file}: {why}; starting a new log")),
}
for i in issues {
diff --git a/apps/figcraft-server/tests/header_recovery.rs b/apps/figcraft-server/tests/header_recovery.rs
new file mode 100644
index 000000000..d728908d1
--- /dev/null
+++ b/apps/figcraft-server/tests/header_recovery.rs
@@ -0,0 +1,139 @@
+//! A generation field damaged after an abrupt stop must not make the server drop a log that still
+//! holds confirmed edits (#408): the log is replayed over the snapshot, which only the changes the
+//! snapshot lacks survive, and the damage is reported. A genuine leftover of a compaction cut short
+//! still restores silently.
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+use figcraft_collab::message::{Access, ClientMsg};
+use figcraft_collab::{Client, Outgoing, Replica, Server};
+use figcraft_collab_net::hub::Backend;
+use figcraft_doc::Document;
+use figcraft_server::config::Config;
+use figcraft_server::disk::{self, LOG, SNAPSHOT};
+use figcraft_server::store::{FILES, Store};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+struct Fixture(PathBuf);
+
+impl Fixture {
+ fn new() -> Self {
+ let path = std::env::temp_dir().join(format!("figcraft-header-recovery-{}", figcraft_collab_net::token::file_id().unwrap()));
+ fs::create_dir(&path).unwrap();
+ Self(path)
+ }
+}
+
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ let _ = fs::remove_dir_all(&self.0);
+ }
+}
+
+fn page_name(server: &Server) -> String {
+ let doc = server.document();
+ doc.node(doc.first_page().unwrap()).unwrap().name.clone()
+}
+
+/// A published file whose first page was renamed "Kept", flushed to its log (not compacted), then
+/// the store dropped without stopping (an abrupt stop). Returns the file id and the final state.
+fn renamed_and_stopped(data: &Path) -> (String, Server) {
+ let mut store = Store::open(data, Config::default().store()).unwrap();
+ let snapshot = Replica::new(Document::new("Fixture")).snapshot().unwrap();
+ let (info, _, _) = store.publish("Fixture", &snapshot).unwrap();
+ let id = info.id;
+ let mut server = store.open(&id).unwrap();
+ let ClientMsg::Hello(hello) = Client::hello("f", "", "Editor", "#FF8800") else { panic!("not a hello") };
+ let (_, messages) = server.join_as(hello, Access::Edit).unwrap();
+ let Some(Outgoing::To(_, welcome)) = messages.into_iter().next() else { panic!("no welcome") };
+ let mut client = Client::join(welcome).unwrap();
+ store.changed(&id, &mut server);
+ let mut edited = client.document().clone();
+ let page = edited.first_page().unwrap();
+ edited.node_mut(page).unwrap().name = "Kept".into();
+ let change = client.edit(&edited).unwrap().unwrap();
+ assert!(!server.receive(client.id(), change).is_empty());
+ store.changed(&id, &mut server);
+ assert!(store.flush().is_empty(), "the edit must reach disk");
+ assert_eq!(page_name(&server), "Kept");
+ let dir = data.join(FILES).join(&id);
+ assert!(!disk::read_log(&fs::read(dir.join(LOG)).unwrap()).unwrap().entries.is_empty());
+ assert_eq!(disk::decode_snapshot(&fs::read(dir.join(SNAPSHOT)).unwrap()).unwrap().1.seq, 0, "the rename is only in the log");
+ drop(store);
+ (id, server)
+}
+
+/// Reopen the data directory: the file's first page name and the problems reported.
+fn reopen(data: &Path, id: &str) -> (String, Vec) {
+ let mut store = Store::open(data, Config::default().store()).unwrap();
+ let server = store.open(id).unwrap();
+ (page_name(&server), store.problems().to_vec())
+}
+
+fn flip(path: &Path, at: usize) {
+ let mut bytes = fs::read(path).unwrap();
+ bytes[at] ^= 1;
+ fs::write(path, bytes).unwrap();
+}
+
+/// The generation field's first byte in both headers (after the magic and the format byte).
+const GENERATION_AT: usize = 5;
+
+#[test]
+fn an_intact_log_restores_its_edits_without_a_report() {
+ let fixture = Fixture::new();
+ let (id, _) = renamed_and_stopped(&fixture.0);
+ let (name, problems) = reopen(&fixture.0, &id);
+ assert_eq!(name, "Kept");
+ assert!(problems.is_empty(), "{problems:?}");
+}
+
+#[test]
+fn a_damaged_log_generation_keeps_the_edits_and_is_reported() {
+ let fixture = Fixture::new();
+ let (id, _) = renamed_and_stopped(&fixture.0);
+ let log = fixture.0.join(FILES).join(&id).join(LOG);
+ flip(&log, GENERATION_AT);
+ // The records themselves still read: only the header's generation changed.
+ let read = disk::read_log(&fs::read(&log).unwrap()).unwrap();
+ assert!(read.damaged.is_none() && !read.entries.is_empty());
+ let (name, problems) = reopen(&fixture.0, &id);
+ assert_eq!(name, "Kept", "the flushed rename must survive");
+ assert!(problems.iter().any(|p| p.contains(&id) && p.contains("generation")), "{problems:?}");
+ // And it stays: the recovered edit is now in the file's snapshot.
+ assert_eq!(reopen(&fixture.0, &id).0, "Kept");
+}
+
+#[test]
+fn a_damaged_snapshot_generation_keeps_the_edits_and_is_reported() {
+ let fixture = Fixture::new();
+ let (id, _) = renamed_and_stopped(&fixture.0);
+ let snapshot = fixture.0.join(FILES).join(&id).join(SNAPSHOT);
+ flip(&snapshot, GENERATION_AT);
+ assert!(disk::check_snapshot(&fs::read(&snapshot).unwrap()).is_ok(), "the generation is outside the checksum");
+ let (name, problems) = reopen(&fixture.0, &id);
+ assert_eq!(name, "Kept", "the flushed rename must survive");
+ assert!(problems.iter().any(|p| p.contains(&id) && p.contains("generation")), "{problems:?}");
+ assert_eq!(reopen(&fixture.0, &id).0, "Kept");
+}
+
+#[test]
+fn a_damaged_log_format_is_still_reported() {
+ let fixture = Fixture::new();
+ let (id, _) = renamed_and_stopped(&fixture.0);
+ flip(&fixture.0.join(FILES).join(&id).join(LOG), 4);
+ let (_, problems) = reopen(&fixture.0, &id);
+ assert!(problems.iter().any(|p| p.contains(&id) && p.contains("format")), "{problems:?}");
+}
+
+#[test]
+fn a_log_left_by_a_compaction_cut_short_restores_without_a_report() {
+ let fixture = Fixture::new();
+ let (id, server) = renamed_and_stopped(&fixture.0);
+ // The next snapshot was written (it holds the rename); the old log wasn't replaced yet.
+ let bytes = disk::encode_snapshot(2, &server.state().unwrap()).unwrap();
+ fs::write(fixture.0.join(FILES).join(&id).join(SNAPSHOT), bytes).unwrap();
+ let (name, problems) = reopen(&fixture.0, &id);
+ assert_eq!(name, "Kept");
+ assert!(problems.is_empty(), "a leftover log is expected, not damage: {problems:?}");
+}
diff --git a/apps/figcraft-web/Cargo.toml b/apps/figcraft-web/Cargo.toml
index 2f1a8190f..ffd44f3bc 100644
--- a/apps/figcraft-web/Cargo.toml
+++ b/apps/figcraft-web/Cargo.toml
@@ -26,4 +26,4 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
wasm-bindgen = "0.2"
js-sys = "0.3"
wasm-bindgen-futures = "0.4"
-web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlElement", "HtmlAnchorElement", "Node", "Blob", "BlobPropertyBag", "Url", "Location", "MediaQueryList", "Navigator", "Gamepad", "GamepadButton", "GamepadMappingType"] }
+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlElement", "HtmlAnchorElement", "Node", "Blob", "BlobPropertyBag", "File", "FileList", "HtmlInputElement", "EventTarget", "Url", "Location", "MediaQueryList", "Navigator", "Gamepad", "GamepadButton", "GamepadMappingType"] }
diff --git a/apps/figcraft-web/src/main.rs b/apps/figcraft-web/src/main.rs
index 587fd60b8..7eed2ffb3 100644
--- a/apps/figcraft-web/src/main.rs
+++ b/apps/figcraft-web/src/main.rs
@@ -14,7 +14,16 @@
//! join from other machines.
//!
//! URL query flag: `?webgl` forces the WebGL2 backend instead of WebGPU.
+//!
+//! URL fragment: `#join=` joins that live session once the page has
+//! loaded, so a bookmark opens a shared file. `join` takes the rest of the fragment: put it last.
+//! The link carries the session's secret; a fragment is never sent to the web host, but the address
+//! bar and the browser history keep it, so the URL is as private as the link itself.
+#[cfg(any(target_arch = "wasm32", test))]
+mod query;
+#[cfg(test)]
+mod query_tests;
#[cfg(target_arch = "wasm32")]
mod web;
diff --git a/apps/figcraft-web/src/query.rs b/apps/figcraft-web/src/query.rs
new file mode 100644
index 000000000..befeb36b7
--- /dev/null
+++ b/apps/figcraft-web/src/query.rs
@@ -0,0 +1,15 @@
+//! The page's URL: the invite link its fragment names.
+
+/// The invite link in `#join= ` (`fragment` is `location.hash`, with or without its `#`), still
+/// escaped. The fragment, unlike the query, never leaves the browser, so the link's secret stays out
+/// of the web host's logs and `Referer` headers. `join` takes the rest of the fragment, so a pasted
+/// `figcraft://join?host=…&file=…&token=…` keeps its own `&`s. Anything longer than an escaped invite
+/// link can be is ignored; what is left is checked by `collab.join` like a link the desktop app is
+/// opened with.
+pub fn join_link(fragment: &str) -> Option<&str> {
+ // An invite link is at most 2 KiB; every byte of it escaped is three.
+ const MAX: usize = 3 * 2048;
+ let fragment = fragment.strip_prefix('#').unwrap_or(fragment);
+ let start = if fragment.starts_with("join=") { 0 } else { fragment.find("&join=")? + 1 };
+ fragment.get(start + "join=".len()..).filter(|link| !link.is_empty() && link.len() <= MAX)
+}
diff --git a/apps/figcraft-web/src/query_tests.rs b/apps/figcraft-web/src/query_tests.rs
new file mode 100644
index 000000000..261ebaeb6
--- /dev/null
+++ b/apps/figcraft-web/src/query_tests.rs
@@ -0,0 +1,29 @@
+//! `#join=` in the page's URL.
+
+use crate::query::join_link;
+
+#[test]
+fn join_takes_the_rest_of_the_fragment() {
+ let link = "figcraft://join?host=192.168.1.20:47900&file=abc&token=AbCdEfGhIjKlMnOpQrStUv";
+ assert_eq!(join_link(&format!("#join={link}")), Some(link), "a pasted link keeps its own &s");
+ assert_eq!(join_link(&format!("#x=1&join={link}")), Some(link), "after other entries");
+ assert_eq!(join_link("#join=figcraft%3A%2F%2Fjoin%3Fhost%3Dh"), Some("figcraft%3A%2F%2Fjoin%3Fhost%3Dh"), "escaped, decoded later");
+ assert_eq!(join_link("join=K7M-2QX-9TD"), Some("K7M-2QX-9TD"), "a join code, no leading #");
+}
+
+#[test]
+fn no_join_without_the_entry() {
+ assert_eq!(join_link(""), None);
+ assert_eq!(join_link("#"), None);
+ assert_eq!(join_link("#join="), None);
+ assert_eq!(join_link("#rejoin=x"), None, "only the whole entry name");
+ assert_eq!(join_link("#xjoin=x&a=1"), None);
+ assert_eq!(join_link("?join=x"), None, "the query isn't read: it goes to the web host");
+}
+
+#[test]
+fn an_overlong_link_is_ignored() {
+ let long = format!("#join=figcraft://join?host=h&file=f&token={}", "a".repeat(7000));
+ assert_eq!(join_link(&long), None);
+ assert_eq!(join_link(&format!("#join={}", "é".repeat(4000))), None, "length counts bytes");
+}
diff --git a/apps/figcraft-web/src/web.rs b/apps/figcraft-web/src/web.rs
index 8cadb0138..f08ca90f2 100644
--- a/apps/figcraft-web/src/web.rs
+++ b/apps/figcraft-web/src/web.rs
@@ -1,7 +1,7 @@
//! The browser shell: web `Services` and the eframe web runner.
use figcraft_engine::Session;
-use figcraft_ui_egui::{FigApp, Services};
+use figcraft_ui_egui::{ContentsFuture, FigApp, Services};
use wasm_bindgen::JsCast as _;
const CANVAS_ID: &str = "figcraft_canvas";
@@ -40,7 +40,13 @@ pub fn start() {
// on the socket wakes the page for a frame.
let ctx = cc.egui_ctx.clone();
session.live.install(Box::new(figcraft_collab_net::NetLink::new(std::sync::Arc::new(move || ctx.request_repaint()))));
- let fig = FigApp::new(session, Box::new(WebServices { reduce_motion, ctx: cc.egui_ctx.clone() }));
+ let mut fig = FigApp::new(session, Box::new(WebServices { reduce_motion, ctx: cc.egui_ctx.clone() }));
+ // `#join= `: join that session, as opening an invite link does on the desktop.
+ let hash = web_sys::window().and_then(|w| w.location().hash().ok()).unwrap_or_default();
+ if let Some(link) = crate::query::join_link(&hash) {
+ let link = js_sys::decode_uri_component(link).ok().and_then(|s| s.as_string()).unwrap_or_else(|| link.to_string());
+ figcraft_ui_egui::live::open_invite(&mut fig, &link);
+ }
Ok(Box::new(WebShell { fig }))
}),
)
@@ -69,9 +75,10 @@ impl eframe::App for WebShell {
}
}
-/// Browser services. Open dialogs return nothing for now (the trait's defaults); files are saved
-/// as downloads. Copies go to the system clipboard through egui's output; pastes arrive as paste
-/// events with their text (a page can't read the clipboard when it likes).
+/// Browser services. Files are opened and imported through the browser's file picker, which hands
+/// over their contents (pickers that need a path return nothing, the trait's defaults); files are
+/// saved as downloads. Copies go to the system clipboard through egui's output; pastes arrive as
+/// paste events with their text (a page can't read the clipboard when it likes).
struct WebServices {
/// `prefers-reduced-motion: reduce` (it follows the setting while the page is open).
reduce_motion: Option,
@@ -79,6 +86,16 @@ struct WebServices {
}
impl Services for WebServices {
+ /// An ` ` taking `exts`, clicked; its file is read once picked.
+ fn pick_open_contents(&mut self, _title: &str, exts: &[&str]) -> Option {
+ let accept = exts.iter().map(|e| format!(".{e}")).collect::>().join(",");
+ Some(Box::pin(async move {
+ pick_file(&accept).await.unwrap_or_else(|e| {
+ log::error!("couldn't open a file: {e:?}");
+ None
+ })
+ }))
+ }
fn downloads(&self) -> bool {
true
}
@@ -130,6 +147,90 @@ impl Services for WebServices {
}
}
+/// The file picked in the browser's file picker (`accept`: the extensions it offers), with its
+/// name; `None` when the picker is cancelled, `Some(Err)` with what to tell the user when the file
+/// can't be read.
+async fn pick_file(accept: &str) -> Result), String>>, wasm_bindgen::JsValue> {
+ let window = web_sys::window().ok_or("no window")?;
+ let document = window.document().ok_or("no document")?;
+ let body = document.body().ok_or("no body")?;
+ let input: web_sys::HtmlInputElement = document.create_element("input")?.dyn_into()?;
+ input.set_type("file");
+ input.set_accept(accept);
+ input.set_hidden(true);
+ // Some browsers (older Safari) open the picker only for an input in the page.
+ body.append_child(&input)?;
+ let (closed, picker) = PickerClosed::new(&window, input.clone());
+ input.click();
+ let result = wasm_bindgen_futures::JsFuture::from(closed).await;
+ let file = input.files().and_then(|files| files.get(0));
+ drop(picker);
+ result?;
+ let Some(file) = file else { return Ok(None) };
+ let name = file.name();
+ if let Err(why) = figcraft_ui_egui::browser_can_read(&name, file.size()) {
+ return Ok(Some(Err(why)));
+ }
+ Ok(Some(match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
+ Ok(buffer) => Ok((name, js_sys::Uint8Array::new(&buffer).to_vec())),
+ Err(e) => {
+ log::error!("couldn't read {name}: {e:?}");
+ Err(figcraft_ui_egui::unreadable(&name))
+ }
+ }))
+}
+
+/// How long after the page gets focus back the file picker counts as closed (milliseconds): a
+/// picked file's `change` can come just after the focus, and must win. A `change` later than this
+/// (a slow cloud-backed file in a browser that never sends `cancel`) counts as a cancel.
+const PICKER_FOCUS_SETTLE_MS: i32 = 1_000;
+
+/// Settles a file picker's promise once: on `change` (a file was picked), on `cancel` (closed
+/// without one) or shortly after the page gets focus back, for browsers that never send `cancel`
+/// (Safari before 16.4), where the pick would otherwise stay pending and block every later one.
+/// Dropping it (also when the pick is abandoned) removes the input, the focus listener and its timer.
+struct PickerClosed {
+ window: web_sys::Window,
+ input: web_sys::HtmlInputElement,
+ _settle: wasm_bindgen::closure::Closure,
+ on_focus: wasm_bindgen::closure::Closure,
+ timer: std::rc::Rc>>,
+}
+
+impl PickerClosed {
+ fn new(window: &web_sys::Window, input: web_sys::HtmlInputElement) -> (js_sys::Promise, Self) {
+ let resolve = std::rc::Rc::new(std::cell::RefCell::new(None::));
+ let slot = resolve.clone();
+ let closed = js_sys::Promise::new(&mut |res, _rej| *slot.borrow_mut() = Some(res));
+ let settle = wasm_bindgen::closure::Closure::::new(move || {
+ if let Some(res) = resolve.borrow_mut().take() {
+ let _ = res.call0(&wasm_bindgen::JsValue::NULL);
+ }
+ });
+ let _ = input.add_event_listener_with_callback("change", settle.as_ref().unchecked_ref());
+ let _ = input.add_event_listener_with_callback("cancel", settle.as_ref().unchecked_ref());
+ let timer = std::rc::Rc::new(std::cell::Cell::new(None));
+ let (w, t, f) = (window.clone(), timer.clone(), settle.as_ref().unchecked_ref::().clone());
+ let on_focus = wasm_bindgen::closure::Closure::::new(move || {
+ if t.get().is_none() {
+ t.set(w.set_timeout_with_callback_and_timeout_and_arguments_0(&f, PICKER_FOCUS_SETTLE_MS).ok());
+ }
+ });
+ let _ = window.add_event_listener_with_callback("focus", on_focus.as_ref().unchecked_ref());
+ (closed, Self { window: window.clone(), input, _settle: settle, on_focus, timer })
+ }
+}
+
+impl Drop for PickerClosed {
+ fn drop(&mut self) {
+ if let Some(t) = self.timer.take() {
+ self.window.clear_timeout_with_handle(t);
+ }
+ let _ = self.window.remove_event_listener_with_callback("focus", self.on_focus.as_ref().unchecked_ref());
+ self.input.remove();
+ }
+}
+
fn download(name: &str, bytes: &[u8]) -> Result<(), wasm_bindgen::JsValue> {
let window = web_sys::window().ok_or("no window")?;
let document = window.document().ok_or("no document")?;
diff --git a/apps/figcraft/Cargo.toml b/apps/figcraft/Cargo.toml
index bafb6da14..fac4842b1 100644
--- a/apps/figcraft/Cargo.toml
+++ b/apps/figcraft/Cargo.toml
@@ -21,7 +21,7 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
serde_json = { workspace = true }
log = { workspace = true }
rfd = { workspace = true }
-arboard = { workspace = true, features = ["image-data"] }
+arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
webbrowser = { workspace = true }
image = { workspace = true }
env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] }
@@ -43,3 +43,9 @@ wat = { workspace = true }
[build-dependencies]
winresource = "0.1"
+
+[target.'cfg(target_os = "linux")'.dependencies]
+# Use vector window controls without a title-font renderer or embedded Cantarell.
+winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
+raw-window-handle = "0.6"
+wayland-client = "0.31"
diff --git a/apps/figcraft/src/apple_events.rs b/apps/figcraft/src/apple_events.rs
index 6b7920944..41ae5cc36 100644
--- a/apps/figcraft/src/apple_events.rs
+++ b/apps/figcraft/src/apple_events.rs
@@ -50,7 +50,7 @@ pub fn poll(inbox: &Inbox, fig: &mut FigApp, ctx: &egui::Context) {
/// Open `paths` as File › Open does; a file that fails shows its error and the others still open.
pub fn open_documents(fig: &mut FigApp, paths: Vec) {
for p in paths {
- if fig.run("file.open", json!({"path": p.to_string_lossy()})).is_some() {
+ if fig.run_user("file.open", json!({"path": p.to_string_lossy()})).is_some() {
fig.ui.home = false;
}
}
diff --git a/apps/figcraft/src/args.rs b/apps/figcraft/src/args.rs
index 2e3099cbf..436df61f8 100644
--- a/apps/figcraft/src/args.rs
+++ b/apps/figcraft/src/args.rs
@@ -1,16 +1,26 @@
-//! The command line: `figcraft [--control ] [files…] [figcraft://join?…]`. An invite link
+//! The command line: `figcraft [--control ] [--automation-read-root ]…
+//! [--automation-write-root ]… [files…] [figcraft://join?…]`. An invite link
//! (what the system passes when a `figcraft://` link is opened) joins that session once the window
//! is up; everything else that isn't a flag is a file to open, as a path or a `file://` URL (the
-//! Linux desktop entry passes URLs, `%U`, so that it can also hand over invite links).
+//! Linux desktop entry passes URLs, `%U`, so that it can also hand over invite links). Any other
+//! `--flag` is unknown and stops the app at startup (#836): a mistyped root flag must never leave
+//! the app running unconfined. After a bare `--`, every argument is a file.
/// What the app was started with.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Args {
- /// `--control `: the JSON-lines control server.
+ /// `--control ` (or `--control=`): the JSON-lines control server.
pub control: Option,
pub files: Vec,
/// The last invite link given.
pub join: Option,
+ /// `--automation-read-root ` / `--automation-write-root ` (each repeatable; `=` works
+ /// too): the folders the app's file access is confined to. A flag without a value gives `""`,
+ /// which is refused at startup.
+ pub read_roots: Vec,
+ pub write_roots: Vec,
+ /// `--flags` the app doesn't know, as given.
+ pub unknown: Vec,
}
/// An invite link rather than a file (`figcraft:` links, in any case).
@@ -49,13 +59,27 @@ pub fn parse(args: &[String]) -> Args {
let mut out = Args::default();
let mut it = args.iter();
while let Some(a) = it.next() {
- if a == "--control" {
- out.control = it.next().and_then(|p| p.parse().ok());
+ if a == "--" {
+ out.files.extend(it.by_ref().cloned());
+ break;
+ }
+ let (flag, inline) = a.split_once('=').map_or((a.as_str(), None), |(f, v)| (f, Some(v.to_string())));
+ let roots = match flag {
+ "--automation-read-root" => Some(&mut out.read_roots),
+ "--automation-write-root" => Some(&mut out.write_roots),
+ _ => None,
+ };
+ if let Some(roots) = roots {
+ roots.push(inline.or_else(|| it.next().cloned()).unwrap_or_default());
+ } else if flag == "--control" {
+ out.control = inline.or_else(|| it.next().cloned()).and_then(|p| p.parse().ok());
} else if is_invite(a) {
out.join = Some(a.clone());
} else if let Some(path) = file_url_path(a) {
out.files.push(path);
- } else if !a.starts_with("--") {
+ } else if a.starts_with("--") {
+ out.unknown.push(a.clone());
+ } else {
out.files.push(a.clone());
}
}
diff --git a/apps/figcraft/src/args_tests.rs b/apps/figcraft/src/args_tests.rs
index 0ed404c8f..b274bedab 100644
--- a/apps/figcraft/src/args_tests.rs
+++ b/apps/figcraft/src/args_tests.rs
@@ -9,13 +9,44 @@ fn args(a: &[&str]) -> Vec {
#[test]
fn files_and_the_control_port() {
assert_eq!(parse(&args(&[])), Args::default());
- let a = parse(&args(&["--control", "4242", "a.figcraft", "--verbose", "b.svg"]));
- assert_eq!(a, Args { control: Some(4242), files: args(&["a.figcraft", "b.svg"]), join: None });
+ let a = parse(&args(&["--control", "4242", "a.figcraft", "b.svg"]));
+ assert_eq!(a, Args { control: Some(4242), files: args(&["a.figcraft", "b.svg"]), ..Args::default() });
// A missing or bad port is ignored, not taken as a file.
assert_eq!(parse(&args(&["--control"])), Args::default());
assert_eq!(parse(&args(&["--control", "nope"])).control, None);
}
+#[test]
+fn the_control_port_accepts_the_equals_form() {
+ let a = parse(&args(&["--control=7980", "a.figcraft"]));
+ assert_eq!(a, Args { control: Some(7980), files: args(&["a.figcraft"]), ..Args::default() });
+ // A bad port is ignored, not taken as a file.
+ assert_eq!(parse(&args(&["--control=nope"])), Args::default());
+}
+
+#[test]
+fn automation_roots_repeat_and_are_never_files() {
+ let a = parse(&args(&["--automation-read-root", "in", "--automation-write-root=out", "--automation-read-root=more", "a.figcraft"]));
+ assert_eq!(a.read_roots, args(&["in", "more"]));
+ assert_eq!(a.write_roots, args(&["out"]));
+ assert_eq!(a.files, args(&["a.figcraft"]));
+ // A flag without its folder is kept as an empty one, which startup refuses.
+ assert_eq!(parse(&args(&["--automation-write-root"])).write_roots, args(&[""]));
+}
+
+#[test]
+fn unknown_flags_are_refused_never_ignored() {
+ // #836: a mistyped root flag (or one an older release lacks) must stop the app, not start it
+ // unconfined. Both forms, with and without `=`.
+ let a = parse(&args(&["--automation-write-roots", "out", "--automation-write-dir=out", "--verbose", "a.figcraft"]));
+ assert_eq!(a.unknown, args(&["--automation-write-roots", "--automation-write-dir=out", "--verbose"]));
+ assert!(a.write_roots.is_empty());
+ // Single-dash arguments are left as they were (files); after `--` everything is a file.
+ let a = parse(&args(&["--control", "1", "--", "--odd.figcraft", "--automation-write-root=x"]));
+ assert_eq!(a.files, args(&["--odd.figcraft", "--automation-write-root=x"]));
+ assert!(a.unknown.is_empty() && a.write_roots.is_empty());
+}
+
#[test]
fn invite_links_join_instead_of_opening() {
let link = "figcraft://join?host=192.168.1.20:47900&file=abc&token=AbCdEfGhIjKlMnOpQrStUv";
diff --git a/apps/figcraft/src/control_server_tests.rs b/apps/figcraft/src/control_server_tests.rs
index d243fb916..008170fbb 100644
--- a/apps/figcraft/src/control_server_tests.rs
+++ b/apps/figcraft/src/control_server_tests.rs
@@ -160,7 +160,11 @@ fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() {
assert_eq!(workers.len(), 1);
client.write_all(b"invalid\n").unwrap();
assert_eq!(reply(&mut BufReader::new(client.try_clone().unwrap()))["ok"], false);
- client.shutdown(Shutdown::Both).unwrap();
+ // The server closes this connection after answering an invalid request, and shutting down
+ // a socket whose peer has already closed is ENOTCONN on macOS and the BSDs where Linux
+ // returns Ok. Closing the client is what the worker is waiting for, so the result is moot:
+ // the other shutdowns in this file run while the peer is still open and stay checked.
+ let _ = client.shutdown(Shutdown::Both);
workers.pop().unwrap().join().unwrap();
}
diff --git a/apps/figcraft/src/linux_window.rs b/apps/figcraft/src/linux_window.rs
new file mode 100644
index 000000000..f47b61e03
--- /dev/null
+++ b/apps/figcraft/src/linux_window.rs
@@ -0,0 +1,112 @@
+//! Request winit's frame only on Wayland compositors without xdg-decoration.
+//! Desktop/session names cannot identify the backend of an individual window.
+
+use std::os::unix::net::UnixStream;
+use std::path::PathBuf;
+use std::sync::mpsc;
+use std::time::Duration;
+
+use raw_window_handle::{HasDisplayHandle, RawDisplayHandle};
+use wayland_client::globals::{GlobalListContents, registry_queue_init};
+use wayland_client::protocol::wl_registry;
+use wayland_client::{Connection, Dispatch, QueueHandle};
+
+/// Capture the socket path before winit consumes an inherited WAYLAND_SOCKET.
+/// Never consume, duplicate or query that inherited connection: there may be no
+/// independently addressable display, or WAYLAND_DISPLAY may name another server.
+pub fn display_socket() -> Option {
+ if std::env::var_os("WAYLAND_SOCKET").is_some_and(|s| !s.is_empty()) {
+ return None;
+ }
+ let display = std::env::var_os("WAYLAND_DISPLAY").filter(|s| !s.is_empty())?;
+ let path = PathBuf::from(display);
+ if path.is_absolute() {
+ Some(path)
+ } else {
+ std::env::var_os("XDG_RUNTIME_DIR").filter(|s| !s.is_empty()).map(|dir| PathBuf::from(dir).join(path))
+ }
+}
+
+pub fn needs_native_frame(cc: &eframe::CreationContext<'_>, socket: Option) -> bool {
+ let wayland = cc.display_handle().is_ok_and(|h| matches!(h.as_raw(), RawDisplayHandle::Wayland(_)));
+ if !wayland {
+ log::debug!("window controls: non-Wayland window, retaining custom controls");
+ return false;
+ }
+ let server_decorations = socket.and_then(probe);
+ log::debug!("window controls: Wayland xdg-decoration available: {server_decorations:?}");
+ native_frame(wayland, server_decorations)
+}
+
+fn native_frame(wayland: bool, server_decorations: Option) -> bool {
+ wayland && server_decorations == Some(false)
+}
+
+fn probe(socket: PathBuf) -> Option {
+ // The compositor must not be able to block startup on a registry roundtrip.
+ // On failure/timeout retain FigCraft's own working title bar and buttons.
+ let (send, receive) = mpsc::sync_channel(1);
+ std::thread::Builder::new()
+ .name("wayland-decorations".into())
+ .spawn(move || {
+ let _ = send.send(registry_has_decorations(socket));
+ })
+ .ok()?;
+ receive.recv_timeout(Duration::from_millis(500)).ok().flatten()
+}
+
+fn registry_has_decorations(socket: PathBuf) -> Option {
+ // A fresh connection leaves winit's event queue and inherited descriptors alone.
+ let stream = UnixStream::connect(socket).ok()?;
+ let connection = Connection::from_socket(stream).ok()?;
+ let (globals, _queue) = registry_queue_init::(&connection).ok()?;
+ Some(globals.contents().with_list(|list| list.iter().any(|g| g.interface == "zxdg_decoration_manager_v1")))
+}
+
+struct Registry;
+
+impl Dispatch for Registry {
+ fn event(
+ _state: &mut Self,
+ _registry: &wl_registry::WlRegistry,
+ _event: wl_registry::Event,
+ _data: &GlobalListContents,
+ _connection: &Connection,
+ _queue: &QueueHandle,
+ ) {
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn only_wayland_without_server_decorations_uses_the_frame() {
+ for (wayland, server_decorations, expected) in [
+ (false, None, false),
+ (false, Some(false), false),
+ (false, Some(true), false),
+ (true, Some(true), false),
+ (true, Some(false), true),
+ (true, None, false),
+ ] {
+ assert_eq!(super::native_frame(wayland, server_decorations), expected);
+ }
+ }
+
+ #[test]
+ fn an_unavailable_display_keeps_the_custom_controls() {
+ assert_eq!(super::probe("/nonexistent/figcraft-wayland-test".into()), None);
+ }
+
+ #[test]
+ fn an_unresponsive_display_cannot_block_window_startup() -> std::io::Result<()> {
+ let socket = std::env::temp_dir().join(format!("figcraft-decoration-timeout-{}", std::process::id()));
+ let listener = std::os::unix::net::UnixListener::bind(&socket)?;
+ let start = std::time::Instant::now();
+ assert_eq!(super::probe(socket.clone()), None);
+ assert!(start.elapsed() < std::time::Duration::from_secs(2));
+ drop(listener);
+ let _ = std::fs::remove_file(socket);
+ Ok(())
+ }
+}
diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs
index fdcc66f9e..00856c5d5 100644
--- a/apps/figcraft/src/main.rs
+++ b/apps/figcraft/src/main.rs
@@ -6,6 +6,12 @@
//! `--control ` (or `FIGCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server:
//! `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":0,"y":0,"width":100,"height":100}}}`
//! → `{"id":1,"ok":true,"result":{…}}`. Methods: `figcraft_ui_egui::control`.
+//!
+//! `--automation-read-root ` / `--automation-write-root ` (each repeatable) confine the
+//! files the window and the control channel read and write (`figcraft_engine::file_access`); the
+//! app's own folders (settings, recovery copies, installed plugins) and opening the files given on
+//! the command line are not. A root that isn't an existing folder stops the app at startup, and so
+//! does any flag the app doesn't know (a mistyped root flag must not start the app unconfined).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
@@ -15,6 +21,8 @@ mod args;
mod control_server;
mod gamepad;
mod graphics;
+#[cfg(target_os = "linux")]
+mod linux_window;
mod recovery;
mod services;
mod startup;
@@ -100,10 +108,13 @@ impl eframe::App for App {
}
fn on_exit(&mut self) {
- with_app(|fig| services::save_state(fig));
- if let Some(r) = recovery::lock(&self.recovery).take() {
- r.finish();
- }
+ // With the app out of reach (busy), its recovery copies stay for the next start.
+ let copies = recovery::lock(&self.recovery).take();
+ with_app(|fig| services::shutdown(fig, services::config_dir().as_deref(), copies));
+ // Everything is kept: end before the windows' teardown, where AppKit's Touch Bar support
+ // throws on the content view AccessKit restores (craft-libs#3, #781).
+ #[cfg(target_os = "macos")]
+ std::process::exit(0);
}
}
@@ -119,6 +130,23 @@ fn main() -> eframe::Result {
return Ok(());
}
let args = args::parse(&args);
+ if let Some(flag) = args.unknown.first() {
+ eprintln!(
+ "FigCraft: unknown option {flag}\nUsage: figcraft [--control PORT] [--automation-read-root DIR]... [--automation-write-root DIR]... [FILE | figcraft://join?...]..."
+ );
+ std::process::exit(2);
+ }
+ let roots = match (
+ args.read_roots.is_empty() && args.write_roots.is_empty(),
+ figcraft_engine::file_access::Roots::new(&args.read_roots, &args.write_roots),
+ ) {
+ (true, _) => None,
+ (false, Ok(r)) => Some(Arc::new(r)),
+ (false, Err(e)) => {
+ eprintln!("FigCraft: {e}");
+ std::process::exit(2);
+ }
+ };
let port = args.control.or_else(|| std::env::var("FIGCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()));
// System fonts: index them in the background, then wake the UI (an idle window draws no frames)
// to lay text out again with them.
@@ -143,6 +171,7 @@ fn main() -> eframe::Result {
log::error!("{f}: {e}");
}
}
+ let opened: Vec = session.docs.iter().map(|d| d.uid).collect();
// Documents a crashed or killed run left unsaved come back; this run keeps its own copies.
let recovery_root = services::config_dir().map(|d| d.join("Recovery"));
// The preferences first: they hold the online files a recovered document may be one of.
@@ -164,17 +193,18 @@ fn main() -> eframe::Result {
// default, never a build from source unless asked).
session.live.links = figcraft_collab_net::links::system();
session.invite_links_startup();
- // A first run (no settings kept yet, nothing to open) starts on the home screen, with its
- // tips and templates; later runs start in a new file.
let first_run = svc.prefs.is_none() && args.join.is_none();
- if session.docs.is_empty() && !first_run {
+ if session.docs.is_empty() && opens_new_file(first_run, session.prefs.start_on_home, port.is_some()) {
let _ = session.execute("file.new", &json!({}));
}
// The interface language from the first frame on, and for the message when the window can't
// open (no frame then).
figcraft_ui_egui::i18n::set(&session.prefs.language, figcraft_ui_egui::Services::system_language(&svc).as_deref());
let mut fig = FigApp::new(session, Box::new(svc));
+ fig.automation_roots = roots;
fig.ui.home = false;
+ // Files named on the command line are the user's too: their missing fonts are listed.
+ fig.ui.font_checks = opened;
fig.note_recovered(recovered.copies);
if let Some(link) = &args.join {
figcraft_ui_egui::live::open_invite(&mut fig, link);
@@ -192,21 +222,18 @@ fn main() -> eframe::Result {
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([800.0, 500.0])
.with_drag_and_drop(true);
- // The tab strip is the title bar: macOS keeps its window buttons inset into it; elsewhere the
- // window is frameless and FigCraft draws the buttons and resize edges.
- if cfg!(target_os = "macos") {
- viewport = viewport.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false);
- fig.ui.title_bar = figcraft_ui_egui::TitleBar::Inset;
- } else {
- viewport = viewport.with_decorations(false);
- fig.ui.title_bar = figcraft_ui_egui::TitleBar::Custom;
- }
+ // Start frameless on Linux; the app creator checks the actual display backend
+ // before enabling a client-side frame. Other windows inherit that decision.
+ fig.ui.title_bar = desktop_title_bar();
+ viewport = window_chrome(viewport, fig.ui.title_bar);
if let Some(icon) = icon {
viewport = viewport.with_icon(icon);
}
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, ..Default::default() };
graphics::configure(&mut options.wgpu_options);
figcraft_ui_egui::windows::install(fig);
+ #[cfg(target_os = "linux")]
+ let linux_display = linux_window::display_socket();
// Registered before the event loop starts, so it catches the Finder event that launched the app
// as well as later ones. Lives until the event loop returns; the app creator only borrows it.
#[cfg(target_os = "macos")]
@@ -217,6 +244,11 @@ fn main() -> eframe::Result {
"FigCraft",
options,
Box::new(move |_cc| {
+ #[cfg(target_os = "linux")]
+ if linux_window::needs_native_frame(_cc, linux_display) {
+ let _ = with_app(|fig| fig.ui.title_bar = figcraft_ui_egui::TitleBar::Native);
+ _cc.egui_ctx.send_viewport_cmd(egui::ViewportCommand::Decorations(true));
+ }
Ok(Box::new(App {
queue,
ctx_slot,
@@ -233,3 +265,49 @@ fn main() -> eframe::Result {
}
result
}
+
+/// With nothing to open, whether the window starts in a new file rather than on the home screen.
+/// A first run (no settings kept yet) shows the home screen's tips and templates, and later runs
+/// start in a new file unless the preference asks for Home, which `--control` overrides: its
+/// callers expect a document to act on.
+fn opens_new_file(first_run: bool, start_on_home: bool, control: bool) -> bool {
+ !first_run && (!start_on_home || control)
+}
+
+fn desktop_title_bar() -> figcraft_ui_egui::TitleBar {
+ use figcraft_ui_egui::TitleBar;
+ if cfg!(target_os = "macos") { TitleBar::Inset } else { TitleBar::Custom }
+}
+
+fn window_chrome(viewport: egui::ViewportBuilder, title_bar: figcraft_ui_egui::TitleBar) -> egui::ViewportBuilder {
+ use figcraft_ui_egui::TitleBar;
+ match title_bar {
+ TitleBar::Inset => viewport.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false),
+ TitleBar::Native => viewport.with_decorations(true),
+ TitleBar::Custom => viewport.with_decorations(false),
+ }
+}
+
+#[cfg(all(test, target_os = "linux"))]
+mod linux_window_tests {
+ #[test]
+ fn linux_starts_with_the_existing_frameless_title_bar() {
+ let bar = super::desktop_title_bar();
+ assert_eq!(bar, figcraft_ui_egui::TitleBar::Custom);
+ let viewport = super::window_chrome(egui::ViewportBuilder::default(), bar);
+ assert_eq!(viewport.decorations, Some(false));
+ }
+}
+
+#[cfg(test)]
+mod start_tests {
+ use super::opens_new_file;
+
+ #[test]
+ fn the_home_preference_starts_on_home_except_for_control_callers() {
+ assert!(opens_new_file(false, false, false), "a new file by default");
+ assert!(!opens_new_file(false, true, false), "Home when the preference asks");
+ assert!(opens_new_file(false, true, true), "--control still starts with a document");
+ assert!(!opens_new_file(true, false, false), "a first run shows the home screen");
+ }
+}
diff --git a/apps/figcraft/src/recovery.rs b/apps/figcraft/src/recovery.rs
index b2614598f..06b0cbeb7 100644
--- a/apps/figcraft/src/recovery.rs
+++ b/apps/figcraft/src/recovery.rs
@@ -120,8 +120,7 @@ impl Recovery {
(0..10).find_map(|n| {
let dir = root.join(if n == 0 { pid.to_string() } else { format!("{pid}-{n}") });
std::fs::create_dir_all(&dir).ok()?;
- let lock = File::options().write(true).create(true).truncate(false).open(dir.join(LOCK)).ok()?;
- lock.try_lock().ok()?;
+ let lock = lock_folder(&dir).ok()?;
Some(Self { dir, _lock: lock, written: HashMap::new(), next: 0.0, waiting: Vec::new() })
})
}
@@ -250,6 +249,17 @@ impl Recovery {
self.written.insert(uid, Copy { done: None, flight: Some((vec![revision], writer)) });
}
+ /// Quitting: a normal quit ([`finish`](Self::finish)) when the unsaved-changes question was
+ /// `asked` or nothing is unsaved. Otherwise (macOS's Quit menu ends the app without asking) the
+ /// unsaved documents are copied and the copies stay for the next start, as after a crash.
+ pub fn quit(mut self, s: &Session, asked: bool) {
+ if asked || !s.docs.iter().any(|d| needs_copy(s, d)) {
+ return self.finish();
+ }
+ self.write(s, true);
+ self.settle(s);
+ }
+
/// A normal quit: the documents were saved or their changes discarded on purpose. (Earlier
/// runs' copies still waiting for their outcome stay for the next start.)
pub fn finish(self) {
@@ -282,6 +292,17 @@ fn remove_kept(w: Waiting) {
/// The extension of the note beside the copy of a document that is one of your online files.
const ONLINE: &str = "online";
+/// How long the startup waits, once, for folder locks that may free themselves (#334).
+#[cfg(unix)]
+const LOCK_WAIT: std::time::Duration = std::time::Duration::from_millis(100);
+
+/// Lock the folder `dir` (`WouldBlock` while another process holds it).
+fn lock_folder(dir: &Path) -> Result {
+ let lock = File::options().write(true).create(true).truncate(false).open(dir.join(LOCK)).map_err(std::fs::TryLockError::Error)?;
+ lock.try_lock()?;
+ Ok(lock)
+}
+
/// The copy at `file` is of one of your online files: join that file again as its owner, keeping
/// the copy to compare with what arrives. The session, or `None` when the copy isn't one (or its
/// file isn't recorded any more, or is open already): then it opens as any other copy.
@@ -351,6 +372,7 @@ pub fn recover_all(root: &Path, s: &mut Session) -> Recovered {
}
}
};
+ let (mut free, mut held) = (Vec::new(), Vec::new());
for e in entries.flatten() {
let path = e.path();
if !path.is_dir() {
@@ -358,10 +380,22 @@ pub fn recover_all(root: &Path, s: &mut Session) -> Recovered {
continue;
}
// Still running (another window of the app), or not ours to take.
- let Ok(lock) = File::options().write(true).create(true).truncate(false).open(path.join(LOCK)) else { continue };
- if lock.try_lock().is_err() {
- continue;
+ match lock_folder(&path) {
+ Ok(lock) => free.push((path, lock)),
+ Err(std::fs::TryLockError::WouldBlock) => held.push(path),
+ Err(_) => {}
}
+ }
+ // A child between its `fork` and its `exec` shares the run's open descriptors, and a `flock`
+ // lasts while any of them is open, so an ended run's folder can look held for a moment. Wait
+ // once, however many folders are held, and try those again (#334). Windows doesn't pass the
+ // lock to child processes.
+ #[cfg(unix)]
+ if !held.is_empty() {
+ std::thread::sleep(LOCK_WAIT);
+ free.extend(held.into_iter().filter_map(|path| lock_folder(&path).ok().map(|lock| (path, lock))));
+ }
+ for (path, lock) in free {
let lock = Arc::new(lock);
let files: Vec = std::fs::read_dir(&path).into_iter().flatten().flatten().map(|f| f.path()).collect();
for f in &files {
diff --git a/apps/figcraft/src/recovery_tests.rs b/apps/figcraft/src/recovery_tests.rs
index a3d608f9d..0322e2374 100644
--- a/apps/figcraft/src/recovery_tests.rs
+++ b/apps/figcraft/src/recovery_tests.rs
@@ -167,6 +167,23 @@ fn a_normal_quit_removes_the_recovered_copies_it_took_over() {
let _ = std::fs::remove_dir_all(&root);
}
+#[test]
+fn quitting_without_the_unsaved_question_keeps_copies_for_the_next_start() {
+ let root = root("quitunasked");
+ // macOS's Quit menu: nothing asked, so the unsaved document comes back next time.
+ let s = edited();
+ Recovery::start(&root).unwrap().quit(&s, false);
+ let mut next = Session::empty();
+ assert_eq!(recover(&root, &mut next), 1);
+ let _ = std::fs::remove_dir_all(&root);
+ // Asked (saved or discarded on purpose), or nothing unsaved: nothing is left.
+ for (s, asked) in [(edited(), true), (Session::new(), false)] {
+ Recovery::start(&root).unwrap().quit(&s, asked);
+ assert!(std::fs::read_dir(&root).unwrap().next().is_none(), "asked: {asked}");
+ }
+ let _ = std::fs::remove_dir_all(&root);
+}
+
#[test]
fn a_run_whose_folder_name_is_still_held_takes_another() {
let root = root("pidreuse");
@@ -186,6 +203,29 @@ fn a_run_whose_folder_name_is_still_held_takes_another() {
let _ = std::fs::remove_dir_all(&root);
}
+/// #334: a lock that frees itself is not a run that is still going. A child between its `fork` and
+/// its `exec` inherits the run's open descriptors and a `flock` lasts while any descriptor for the
+/// file is open, so a crashed run's copies must still come back once that child has exec'd.
+#[cfg(unix)]
+#[test]
+fn a_lock_freed_a_moment_later_is_not_a_run_that_is_still_going() {
+ let root = root("fork-window");
+ crashed(&edited(), &root);
+ // Hold the crashed run's folder lock on a second descriptor, the way a child forked before its
+ // exec holds it, and free it shortly after.
+ let lock = std::fs::File::options().write(true).create(true).truncate(false).open(root.join("crashed").join("lock")).unwrap();
+ lock.try_lock().unwrap();
+ let freed = std::thread::spawn(move || {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ drop(lock);
+ });
+ // The next start waits for that lock rather than reading the run as still going.
+ let mut next = Session::empty();
+ assert_eq!(recover(&root, &mut next), 1, "the copies come back once the lock frees itself");
+ freed.join().unwrap();
+ let _ = std::fs::remove_dir_all(&root);
+}
+
/// The rectangles in `doc`.
fn rectangles(doc: &figcraft_engine::doc::Document) -> usize {
doc.nodes().filter(|n| matches!(n.kind, figcraft_engine::doc::NodeKind::Rectangle)).count()
diff --git a/apps/figcraft/src/services.rs b/apps/figcraft/src/services.rs
index bd8a42043..7ee41ada0 100644
--- a/apps/figcraft/src/services.rs
+++ b/apps/figcraft/src/services.rs
@@ -167,10 +167,18 @@ fn reveal(path: &Path) -> std::io::Result<()> {
/// The preferences' file in the config folder.
const STATE: &str = "state.json";
-pub fn save_state(app: &FigApp) {
- if let Some(dir) = config_dir() {
- write_prefs(&dir, &app.session.prefs);
+/// Everything quitting keeps, all done when it returns (macOS then ends the process): the
+/// preferences in `dir`, this run's recovery copies ([`Recovery::quit`](crate::recovery::Recovery::quit))
+/// and the live sessions' ends (one this app hosts tells everyone and stops; a joined one leaves).
+pub fn shutdown(app: &mut FigApp, dir: Option<&Path>, recovery: Option) {
+ if let Some(dir) = dir {
+ write_prefs(dir, &app.session.prefs);
}
+ // Before the sessions end: a recovered online file's copy waits for its session's outcome.
+ if let Some(r) = recovery {
+ r.quit(&app.session, app.ui.quit);
+ }
+ drop(std::mem::take(&mut app.session.live));
}
/// Write `prefs` to `dir` atomically (a temporary file renamed over the old one: a crash leaves
@@ -223,12 +231,47 @@ fn picked(pick: impl Future> + 'static) -> Dial
Box::pin(async move { pick.await.map(|f| f.path().to_path_buf()) })
}
+/// How long a clipboard read may wait on the app that copied (Linux and the BSDs).
+#[cfg(all(unix, not(target_os = "macos")))]
+const CLIPBOARD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
+
+/// Read the clipboard. On Linux and the BSDs the read runs on a helper thread with its own handle
+/// and gives up after [`CLIPBOARD_TIMEOUT`]: a Wayland read waits on the app that copied with no
+/// timeout of its own, so an app that hangs must not hang the window too.
+#[cfg(all(unix, not(target_os = "macos")))]
+fn read_clipboard(_: &mut arboard::Clipboard, read: fn(&mut arboard::Clipboard) -> Option) -> Option {
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = tx.send(arboard::Clipboard::new().ok().and_then(|mut c| read(&mut c)));
+ });
+ rx.recv_timeout(CLIPBOARD_TIMEOUT).ok().flatten()
+}
+
+/// Read the clipboard (the system's own reads don't wait on the app that copied).
+#[cfg(not(all(unix, not(target_os = "macos"))))]
+fn read_clipboard(c: &mut arboard::Clipboard, read: fn(&mut arboard::Clipboard) -> Option) -> Option {
+ read(c)
+}
+
+/// Native Save as filters; other callers keep their existing combined filter.
+fn save_filters<'a>(exts: &'a [&'a str]) -> Vec<(&'static str, &'a [&'a str])> {
+ if exts == ["figcraft", "fig"] {
+ vec![("FigCraft (.figcraft)", &exts[..1]), (figcraft_ui_egui::i18n::tr(".fig (experimental)"), &exts[1..])]
+ } else {
+ vec![("File", exts)]
+ }
+}
+
impl Services for Desktop {
fn pick_open(&mut self, title: &str, exts: &[&str]) -> DialogFuture {
picked(dialog(title).add_filter("Supported files", exts).pick_file())
}
fn pick_save(&mut self, title: &str, name: &str, exts: &[&str]) -> DialogFuture {
- picked(dialog(title).set_file_name(name).add_filter("File", exts).save_file())
+ let mut dialog = dialog(title).set_file_name(name);
+ for (label, extensions) in save_filters(exts) {
+ dialog = dialog.add_filter(label, extensions);
+ }
+ picked(dialog.save_file())
}
fn pick_folder(&mut self, title: &str) -> DialogFuture {
picked(dialog(title).pick_folder())
@@ -239,7 +282,10 @@ impl Services for Desktop {
}
}
fn clipboard_get_text(&mut self) -> Option {
- self.clipboard.as_mut()?.get_text().ok()
+ read_clipboard(self.clipboard.as_mut()?, |c| c.get_text().ok())
+ }
+ fn clipboard_get_html(&mut self) -> Option {
+ read_clipboard(self.clipboard.as_mut()?, |c| c.get().html().ok())
}
fn clipboard_set_png(&mut self, w: u32, h: u32, rgba: &[u8]) {
if let Some(c) = self.clipboard.as_mut() {
@@ -247,7 +293,7 @@ impl Services for Desktop {
}
}
fn clipboard_get_image(&mut self) -> Option<(u32, u32, Vec)> {
- let img = self.clipboard.as_mut()?.get_image().ok()?;
+ let img = read_clipboard(self.clipboard.as_mut()?, |c| c.get_image().ok())?;
let (w, h) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?);
// Refuse absurd sizes (and mismatched buffers) rather than allocate.
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > 100_000_000 || img.bytes.len() != (w as usize) * (h as usize) * 4 {
@@ -297,3 +343,24 @@ pub fn window_icon() -> Option {
let (w, h) = img.dimensions();
Some(egui::IconData { rgba: img.into_raw(), width: w, height: h })
}
+
+#[cfg(test)]
+mod save_filter_tests {
+ use super::save_filters;
+
+ #[test]
+ fn native_and_fig_save_filters_are_separate_with_native_first() {
+ let extensions = ["figcraft", "fig"];
+ assert_eq!(
+ save_filters(&extensions),
+ vec![("FigCraft (.figcraft)", &extensions[..1]), (figcraft_ui_egui::i18n::tr(".fig (experimental)"), &extensions[1..])]
+ );
+ }
+
+ #[test]
+ fn other_save_filters_keep_one_combined_group() {
+ for extensions in [&["figcraft"][..], &["fig"][..], &["png"][..], &["png", "jpg", "webp"][..], &[][..]] {
+ assert_eq!(save_filters(extensions), vec![("File", extensions)]);
+ }
+ }
+}
diff --git a/apps/figcraft/src/services_tests.rs b/apps/figcraft/src/services_tests.rs
index 2390b92fc..2abec5bba 100644
--- a/apps/figcraft/src/services_tests.rs
+++ b/apps/figcraft/src/services_tests.rs
@@ -82,3 +82,38 @@ fn preferences_are_readable_by_their_owner_only() {
assert_eq!(mode(&dir.join("state.json")), 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// A live link that only records the sessions it was told to leave.
+struct Leaves(Arc>>);
+
+impl figcraft_engine::live::LiveLink for Leaves {
+ fn host(&mut self, _: u64, _: figcraft_engine::live::HostOptions) -> Result {
+ Err("not in this test".into())
+ }
+ fn join(&mut self, _: u64, _: &str, _: &str) -> Result<(), String> {
+ Ok(())
+ }
+ fn leave(&mut self, session: u64) {
+ self.0.lock().unwrap().push(session);
+ }
+ fn presence(&mut self, _: u64, _: &figcraft_engine::live::Presence) {}
+ fn send(&mut self, _: u64, _: figcraft_engine::figcraft_collab::message::ClientMsg) {}
+ fn poll(&mut self) -> Vec<(u64, figcraft_engine::live::Event)> {
+ Vec::new()
+ }
+}
+
+#[test]
+fn quitting_keeps_the_preferences_and_ends_the_live_sessions() {
+ let dir = root("shutdown");
+ let mut fig = start(&dir);
+ let left = Arc::new(Mutex::new(Vec::new()));
+ fig.session.live.install(Box::new(Leaves(left.clone())));
+ let joined = fig.run("collab.join", json!({"link": "ws://127.0.0.1:9/?file=f1&token=EditSecretEditSecret00"})).unwrap();
+ fig.session.prefs.user_name = "Ada".into();
+ crate::services::shutdown(&mut fig, Some(&dir), None);
+ assert_eq!(*left.lock().unwrap(), [joined["session"].as_u64().unwrap()], "the session was left");
+ assert!(!fig.session.live.available(), "nothing is left to send on");
+ assert_eq!(start(&dir).session.prefs.user_name, "Ada", "the preferences were kept");
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/contributors/people.toml b/contributors/people.toml
index bc8cf71bb..b91728912 100644
--- a/contributors/people.toml
+++ b/contributors/people.toml
@@ -37,6 +37,11 @@ real_name = "Justin John"
[people.Losminek]
+[people.alrifatsabbir]
+real_name = "Al Rifat Sabbir"
+display_name = "Al Rifat Sabbir"
+sync_github_name = true
+
[people.RevDonz]
[people.Nael-Nathanael]
@@ -44,3 +49,21 @@ sync_github_name = true
[people.volkovskey]
real_name = "Andrii Volkov"
+
+[people.marcoarnulfo]
+real_name = "Marco Arnulfo"
+display_name = "Marco Arnulfo"
+sync_github_name = false
+
+[people.krinry]
+display_name = "krinry"
+sync_github_name = true
+
+[people.pechnikov2026-star]
+sync_github_name = true
+
+[people.MortenHusted]
+sync_github_name = true
+
+[people.AganzeFelicite]
+sync_github_name = true
diff --git a/crates/collab-net/src/driver.rs b/crates/collab-net/src/driver.rs
index b8f6c1541..4ebbec157 100644
--- a/crates/collab-net/src/driver.rs
+++ b/crates/collab-net/src/driver.rs
@@ -16,7 +16,7 @@ use figcraft_engine::live::{Event, Status};
use web_time::Instant;
use crate::inbox::Inbox;
-use crate::join::{GuestConfig, Next, Outcome, Resuming, Seen, Taken, after, closed, hello, resolved, take, unresolved};
+use crate::join::{GuestConfig, Next, Outcome, Resuming, Seen, Taken, after, closed, hello, resolved, take, too_large, unresolved};
use crate::throttle::{PRESENCE_INTERVAL, Throttle, earliest};
/// A WebSocket the driver opens, writes and closes; what it receives comes back through the
@@ -114,6 +114,9 @@ impl Driver {
/// A binary message from the host.
pub(crate) fn message(&mut self, bytes: &[u8], now: Instant) {
let Some(c) = self.conn.as_mut() else { return };
+ if bytes.len() > self.cfg.limits.max_server_message {
+ return self.end(too_large(&self.cfg.limits), now);
+ }
c.last_heard = now;
let taken = match message::decode::(bytes, self.cfg.limits.max_server_message) {
// The join code's answer: join the file it opens, on a new connection.
diff --git a/crates/collab-net/src/driver_tests.rs b/crates/collab-net/src/driver_tests.rs
index ca6563c5f..5e395b981 100644
--- a/crates/collab-net/src/driver_tests.rs
+++ b/crates/collab-net/src/driver_tests.rs
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
use figcraft_collab::message::{self, ClientMsg, Presence, ServerMsg};
use figcraft_collab::{Client, Limits, Outgoing, Server};
use figcraft_doc::{Document, NodeId};
-use figcraft_engine::live::{Event, Status};
+use figcraft_engine::live::{Event, Status, TOO_LARGE_TO_JOIN};
use tungstenite::protocol::WebSocket;
use tungstenite::{Bytes, Message};
@@ -262,6 +262,15 @@ fn refusals_and_the_end_of_the_session_are_final() {
assert!(d.done());
assert!(matches!(statuses(&inbox.drain()).last(), Some(Status::Failed { reason }) if reason.starts_with("The host refused")));
}
+ // A message over the size limit: the file is too large for this app, not refused by the host.
+ let inbox = Inbox::new(Arc::new(|| {}));
+ let mut cfg = GuestConfig::new(invite(), "Ada".into());
+ cfg.limits.max_server_message = 2 << 20;
+ let mut d = Driver::start(Script::default(), cfg, inbox.clone(), t0);
+ d.opened(t0);
+ d.message(&vec![0; (2 << 20) + 1], t0);
+ assert!(d.done());
+ assert!(matches!(statuses(&inbox.drain()).last(), Some(Status::Failed { reason }) if *reason == TOO_LARGE_TO_JOIN.replace("{mb}", "2")));
}
#[test]
diff --git a/crates/collab-net/src/guest.rs b/crates/collab-net/src/guest.rs
index eb899b8df..2e1d5046c 100644
--- a/crates/collab-net/src/guest.rs
+++ b/crates/collab-net/src/guest.rs
@@ -26,7 +26,7 @@ use tungstenite::{Bytes, Message};
use crate::inbox::Inbox;
use crate::invite::{Endpoint, Invite};
pub use crate::join::GuestConfig;
-use crate::join::{Next, Outcome, Resuming, Seen, Taken, after, closed, hello, resolved, take, unresolved};
+use crate::join::{Next, Outcome, Resuming, Seen, Taken, after, closed, hello, resolved, take, too_large, unresolved};
use crate::manage;
use crate::net::{Duplex, NetLimits, config, open, shutdown};
use crate::throttle::{PRESENCE_INTERVAL, Throttle, earliest};
@@ -367,7 +367,7 @@ fn read_loop(mut ws: WebSocket, ctx: &ReaderCtx) {
Ok(Message::Close(f)) => break f.map_or_else(|| closed(0, ""), |f| closed(f.code.into(), &f.reason)),
Ok(Message::Text(_)) => break Outcome::Refused("the host sent a text message".into()),
Ok(_) => {}
- Err(tungstenite::Error::Capacity(_)) => break Outcome::Refused("the host sent a message over the size limit".into()),
+ Err(tungstenite::Error::Capacity(_)) => break too_large(&ctx.cfg.limits),
Err(e) => break Outcome::Retry(e.to_string()),
}
};
diff --git a/crates/collab-net/src/invite.rs b/crates/collab-net/src/invite.rs
index bfa2e606e..e5d86bf29 100644
--- a/crates/collab-net/src/invite.rs
+++ b/crates/collab-net/src/invite.rs
@@ -203,7 +203,7 @@ fn pairs(query: &str) -> Result, String> {
fn with_port(authority: &str, default: u16) -> String {
let has_port = match authority.rsplit_once(':') {
// `[v6]` alone has colons inside the brackets only.
- Some((h, p)) => !(h.starts_with('[') && !h.ends_with(']')) && !p.contains(']'),
+ Some((h, p)) => (!h.starts_with('[') || h.ends_with(']')) && !p.contains(']'),
None => false,
};
if has_port { authority.to_string() } else { format!("{authority}:{default}") }
@@ -220,7 +220,8 @@ fn valid_host(s: &str) -> bool {
return true;
}
let Some((name, port)) = s.rsplit_once(':') else { return false };
- port.parse::().is_ok_and(|p| p != 0)
+ port.bytes().all(|b| b.is_ascii_digit())
+ && port.parse::().is_ok_and(|p| p != 0)
&& (1..=253).contains(&name.len())
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.')
&& !name.starts_with(['-', '.'])
@@ -239,6 +240,9 @@ fn percent_decode(s: &str) -> Option {
while let Some(&b) = bytes.get(i) {
if b == b'%' {
let hex = bytes.get(i + 1..i + 3)?;
+ if !hex.iter().all(u8::is_ascii_hexdigit) {
+ return None;
+ }
out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
i += 3;
} else {
diff --git a/crates/collab-net/src/invite_tests.rs b/crates/collab-net/src/invite_tests.rs
index 02017517d..b7618dc28 100644
--- a/crates/collab-net/src/invite_tests.rs
+++ b/crates/collab-net/src/invite_tests.rs
@@ -123,3 +123,19 @@ proptest! {
prop_assert_eq!(Invite::parse(&i.url()), Ok(i));
}
}
+
+#[test]
+fn plus_or_sign_inside_a_percent_escape_is_broken() {
+ assert!(Endpoint::parse("ws://example.org/a/?key=%41").is_ok());
+ for bad in ["%+1", "%-1", "%1", "%+a"] {
+ assert!(Endpoint::parse(&format!("ws://example.org/a/?key={bad}")).is_err(), "{bad}");
+ }
+}
+
+#[test]
+fn port_must_be_all_digits() {
+ assert!(Endpoint::parse("ws://localhost:80/").is_ok());
+ for bad in ["ws://localhost:+80/", "ws://localhost:-80/", "ws://localhost:/"] {
+ assert!(Endpoint::parse(bad).is_err(), "accepted {bad}");
+ }
+}
diff --git a/crates/collab-net/src/join.rs b/crates/collab-net/src/join.rs
index 81cd2437c..cc3be839f 100644
--- a/crates/collab-net/src/join.rs
+++ b/crates/collab-net/src/join.rs
@@ -7,7 +7,7 @@ use std::time::Duration;
use figcraft_collab::Client;
use figcraft_collab::message::{ClientMsg, Peer, Resume, ServerMsg};
-use figcraft_engine::live::{Event, Role, SessionInfo, Status};
+use figcraft_engine::live::{Event, Role, SessionInfo, Status, TOO_LARGE_TO_JOIN};
use crate::inbox::Inbox;
use crate::invite::Invite;
@@ -95,6 +95,12 @@ pub(crate) fn unresolved(cfg: &GuestConfig, outcome: Outcome) -> Outcome {
})
}
+/// The host sent a message over this app's size limit (the file's welcome, usually): final, and
+/// not the host's doing.
+pub(crate) fn too_large(limits: &NetLimits) -> Outcome {
+ Outcome::Failed(TOO_LARGE_TO_JOIN.replace("{mb}", &(limits.max_server_message >> 20).to_string()))
+}
+
/// The server's answer to the join code: the invite is whole now.
pub(crate) fn resolved(cfg: &mut GuestConfig, file: String, token: String) -> Result<(), Outcome> {
if !crate::invite::valid_id(&file, 1, 64) || !crate::invite::valid_id(&token, 16, 128) {
diff --git a/crates/collab-net/src/limits.rs b/crates/collab-net/src/limits.rs
index c31118767..a0647fa6a 100644
--- a/crates/collab-net/src/limits.rs
+++ b/crates/collab-net/src/limits.rs
@@ -12,7 +12,9 @@ pub struct NetLimits {
/// before: its hello.
pub max_client_message: usize,
pub max_hello: usize,
- /// Largest message a client accepts from the host (a welcome carries the whole document).
+ /// Largest message a client accepts from the host (a welcome carries the whole document): 1 GiB,
+ /// room for any file up to 1023 MiB and well past the servers' defaults, while a hostile server
+ /// (any link can name one) can't make the app or a browser tab buffer more than that.
pub max_server_message: usize,
/// Messages a client may send per second on average, and in a burst; beyond that it is
/// disconnected.
@@ -61,7 +63,7 @@ impl Default for NetLimits {
max_connections: 64,
max_client_message: figcraft_collab::Limits::default().max_message_bytes,
max_hello: 64 << 10,
- max_server_message: figcraft_collab::Limits::default().max_message_bytes,
+ max_server_message: 1 << 30,
rate: 100.0,
burst: 400.0,
hello_timeout: Duration::from_secs(10),
diff --git a/crates/collab-net/src/loopback_tests.rs b/crates/collab-net/src/loopback_tests.rs
index 32c86bd0c..a043d8c79 100644
--- a/crates/collab-net/src/loopback_tests.rs
+++ b/crates/collab-net/src/loopback_tests.rs
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
use figcraft_collab::message::{self, ClientMsg, Hello, Presence, ServerMsg, Signal};
use figcraft_collab::{Client, Limits};
use figcraft_doc::{Document, NodeId};
-use figcraft_engine::live::{Event, PEOPLE, Status};
+use figcraft_engine::live::{Event, PEOPLE, Status, TOO_LARGE_TO_JOIN};
use tungstenite::protocol::WebSocket;
use tungstenite::{Bytes, Message};
@@ -642,3 +642,31 @@ fn the_host_removes_someone_and_they_cant_come_back() {
host.stop();
assert_eq!(host.connections(), 0);
}
+
+#[test]
+fn a_welcome_over_the_size_limit_says_the_file_is_too_large() {
+ let mut doc = Document::new("B".repeat(1 << 20));
+ doc.repair();
+ let probe = Probe::new();
+ let cfg = HostConfig {
+ addr: SocketAddr::from(([127, 0, 0, 1], 0)),
+ any_port_if_taken: false,
+ file: FILE.into(),
+ token: TOKEN.into(),
+ doc,
+ name: "Hana".into(),
+ limits: fast_limits(),
+ core: Limits::default(),
+ };
+ let mut host = Host::start(cfg, probe.inbox.clone()).unwrap();
+ let invite = Invite::new(host.addr().to_string(), FILE, TOKEN);
+
+ let mut guest_cfg = quick(GuestConfig::new(invite, "Ada".into()));
+ guest_cfg.limits = NetLimits { max_server_message: 1 << 20, ..fast_limits() };
+ let mut gp = Probe::new();
+ let _g = Guest::start(guest_cfg, gp.inbox.clone()).unwrap();
+ let too_large = TOO_LARGE_TO_JOIN.replace("{mb}", "1");
+ gp.wait("the file too large to join", |e| e.iter().any(|ev| matches!(ev, Event::Status(Status::Failed { reason }) if *reason == too_large)));
+ assert!(!welcomed(&gp.events));
+ host.stop();
+}
diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs
index 32a491843..0608ba67c 100644
--- a/crates/collab/src/change.rs
+++ b/crates/collab/src/change.rs
@@ -87,8 +87,9 @@ macro_rules! node_props {
($($variant:ident => $field:ident),* $(,)?) => {
/// A node property: the tree position (`parent`, `position`) or one saved field of
/// [`Node`]. List-valued fields (fills, text runs, vector networks…) are one property each,
- /// replaced whole (three-way merges line fills, strokes and effects up item by item, see
- /// [`merge`](crate::merge)). New properties go at the end (the binary form numbers them).
+ /// replaced whole (three-way merges line the lists whose items stand on their own, such as
+ /// fills, up item by item, see [`merge`](crate::merge)). New properties go at the end (the
+ /// binary form numbers them).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Prop {
diff --git a/crates/collab/src/merge.rs b/crates/collab/src/merge.rs
index bb18e661e..5132ce75f 100644
--- a/crates/collab/src/merge.rs
+++ b/crates/collab/src/merge.rs
@@ -4,12 +4,13 @@
//!
//! A conflict is the same property (or document-level entry) changed on both sides to different
//! values, or a layer deleted on one side while the other side edited it or something inside it
-//! (including adding layers to it or moving layers into or out of it). Fills, strokes and effects
-//! merge item by item: both sides changing different items of the list (or one adding items at its
-//! end) is no conflict, only the same item changed both ways or the list shortened on a side
-//! while the other changed it. Nothing that conflicts is
-//! merged until it is resolved: each conflict is resolved for one side, and the other side's
-//! changes to it are left out. Everything else from both sides is kept.
+//! (including adding layers to it or moving layers into or out of it). The layer lists whose items
+//! stand on their own (fills, strokes, effects, layout grids, export settings, guides, prototype
+//! interactions, accessibility annotations and Dev Mode resources) merge item by item: both sides
+//! changing different items of the list (or one adding items at its end) is no conflict, only the
+//! same item changed both ways or the list shortened on a side while the other changed it. Nothing
+//! that conflicts is merged until it is resolved: each conflict is resolved for one side, and the
+//! other side's changes to it are left out. Everything else from both sides is kept.
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
@@ -159,8 +160,23 @@ fn by_key(changes: &[Change]) -> BTreeMap> {
out
}
-/// List properties whose items merge one by one.
-const PER_ITEM: &[Prop] = &[Prop::Fills, Prop::Strokes, Prop::Effects];
+/// List properties whose items merge one by one: the items stand on their own, so both sides
+/// changing different ones (or one side adding at its end) is no conflict. Sets and keyed maps
+/// (`bound`, `varModes`, `overrides`, `propRefs`, `pluginData`) are not here: their items line up
+/// by key, not by position.
+const PER_ITEM: &[Prop] = &[
+ Prop::Fills,
+ Prop::Strokes,
+ Prop::Effects,
+ Prop::Grids,
+ Prop::Exports,
+ Prop::Guides,
+ Prop::Interactions,
+ Prop::Annotations,
+ // Not `CodeLinks`: there is one per language, and lining them up by position could leave two
+ // for one language (the second hidden), so they merge whole.
+ Prop::DevResources,
+];
/// Both sides' writes `b` and `m` of list property `key` merged item by item against the base
/// (see [`merge_items`]); `None` when `key` isn't such a list or the writes conflict.
diff --git a/crates/collab/src/merge_list_tests.rs b/crates/collab/src/merge_list_tests.rs
index 436e6b6f3..e92f6bbbf 100644
--- a/crates/collab/src/merge_list_tests.rs
+++ b/crates/collab/src/merge_list_tests.rs
@@ -1,8 +1,10 @@
-//! Fills, strokes and effects merge item by item: different items changed on each side merge,
-//! the same item changed both ways conflicts.
+//! The layer lists whose items stand on their own (fills, strokes, effects, layout grids, export
+//! settings, guides, prototype interactions, accessibility annotations and Dev Mode resources)
+//! merge item by item: different items changed on each side merge, the same item changed both ways
+//! conflicts.
use figcraft_color::{Color, Paint};
-use figcraft_doc::{Document, Effect, NodeId, NodeKind};
+use figcraft_doc::{Document, Effect, LayoutGrid, NodeId, NodeKind, proto};
use serde_json::{Value, json};
use crate::merge::{Key, Side, merge_items, plan};
@@ -100,19 +102,113 @@ fn the_same_item_changed_both_ways_conflicts() {
}
#[test]
-fn other_lists_still_conflict_as_a_whole() {
- // Docs silent: lists other than fills, strokes and effects (export settings here) still
- // conflict whole when both sides change them.
+fn the_other_item_lists_merge_one_by_one_too() {
+ // Layout grids, export settings, guides, accessibility annotations and Dev Mode resources are
+ // item lists like fills: both sides changing different items merges.
let (mut base, _, _, r) = files();
let export = |suffix: &str| figcraft_doc::ExportSetting { suffix: suffix.into(), ..Default::default() };
- base.get_mut(r).unwrap().exports = vec![export("@1"), export("@2")];
+ let guide = |vertical: bool, offset: f64| figcraft_doc::Guide { vertical, offset };
+ let annot = |label: &str| figcraft_doc::Annotation { label: label.into(), properties: Vec::new(), category: None };
+ let grid = |size: f64| LayoutGrid { size, ..Default::default() };
+ let res = |url: &str| figcraft_doc::DevResource { url: url.into(), name: String::new() };
+ let n = base.get_mut(r).unwrap();
+ n.exports = vec![export("@1"), export("@2")];
+ n.guides = vec![guide(true, 10.0), guide(false, 20.0)];
+ n.annotations = vec![annot("a1"), annot("a2")];
+ n.grids = vec![grid(10.0), grid(20.0)];
+ n.dev_resources = vec![res("https://a.test"), res("https://b.test")];
let (mut branch, mut main) = (base.clone(), base.clone());
branch.set_client_id(base.highest_id_space() + 1);
- branch.get_mut(r).unwrap().exports[0] = export("@b");
- main.get_mut(r).unwrap().exports[1] = export("@m");
+ // The branch changes the first item of each list; main the second.
+ let b = branch.get_mut(r).unwrap();
+ (b.exports[0].suffix, b.guides[0].offset, b.annotations[0].label, b.grids[0].size, b.dev_resources[0].url) =
+ ("@b".into(), 11.0, "b1".into(), 12.0, "https://branch.test".into());
+ let m = main.get_mut(r).unwrap();
+ (m.exports[1].suffix, m.guides[1].offset, m.annotations[1].label, m.grids[1].size, m.dev_resources[1].url) =
+ ("@m".into(), 22.0, "m2".into(), 24.0, "https://main.test".into());
+ both_ways(&base, &branch, &main, |doc| {
+ let n = doc.node(r).unwrap();
+ let suffixes: Vec<&str> = n.exports.iter().map(|e| e.suffix.as_str()).collect();
+ assert_eq!(suffixes, ["@b", "@m"], "export settings");
+ let offsets: Vec = n.guides.iter().map(|g| g.offset).collect();
+ assert_eq!(offsets, [11.0, 22.0], "guides");
+ let labels: Vec<&str> = n.annotations.iter().map(|a| a.label.as_str()).collect();
+ assert_eq!(labels, ["b1", "m2"], "annotations");
+ let sizes: Vec = n.grids.iter().map(|g| g.size).collect();
+ assert_eq!(sizes, [12.0, 24.0], "layout grids");
+ let urls: Vec<&str> = n.dev_resources.iter().map(|d| d.url.as_str()).collect();
+ assert_eq!(urls, ["https://branch.test", "https://main.test"], "dev resources");
+ });
+}
+
+#[test]
+fn the_same_item_of_another_list_changed_both_ways_conflicts() {
+ let (mut base, _, _, r) = files();
+ let link = |language: &str| figcraft_doc::CodeLink { language: language.into(), ..Default::default() };
+ let n = base.get_mut(r).unwrap();
+ n.exports = vec![
+ figcraft_doc::ExportSetting { suffix: "@1".into(), ..Default::default() },
+ figcraft_doc::ExportSetting { suffix: "@2".into(), ..Default::default() },
+ ];
+ n.code_links = vec![link("react"), link("vue")];
+ let (mut branch, mut main) = (base.clone(), base.clone());
+ branch.set_client_id(base.highest_id_space() + 1);
+ branch.get_mut(r).unwrap().exports[0].suffix = "@b".into();
+ main.get_mut(r).unwrap().exports[0].suffix = "@m".into();
+ // Code links are one per language, not an item list: different links changed still conflict.
+ branch.get_mut(r).unwrap().code_links[0].name = "B".into();
+ main.get_mut(r).unwrap().code_links[1].name = "M".into();
let p = plan(&base, &branch, &main).unwrap();
- let keys: Vec = p.conflicts.iter().map(|c| c.key.to_string()).collect();
- assert_eq!(keys, [format!("{r}/exports")]);
+ let mut keys: Vec = p.conflicts.iter().map(|c| c.key.to_string()).collect();
+ keys.sort();
+ let mut want = [format!("{r}/codeLinks"), format!("{r}/exports")];
+ want.sort();
+ assert_eq!(keys, want);
+}
+
+#[test]
+fn interactions_merge_item_by_item() {
+ let ia = |duration_ms: u32| proto::Interaction {
+ trigger: Default::default(),
+ actions: vec![proto::Action::Back],
+ transition: Default::default(),
+ duration_ms,
+ easing: Default::default(),
+ delay_ms: 0,
+ };
+ let durations = |doc: &Document, r: NodeId| doc.node(r).unwrap().interactions.iter().map(|i| i.duration_ms).collect::>();
+ let (mut base, _, _, r) = files();
+ base.get_mut(r).unwrap().interactions = vec![ia(100), ia(200)];
+ let fork = || {
+ let (mut branch, main) = (base.clone(), base.clone());
+ branch.set_client_id(base.highest_id_space() + 1);
+ (branch, main)
+ };
+ // The branch changes the first interaction and adds one; main changes the second.
+ let (mut branch, mut main) = fork();
+ branch.get_mut(r).unwrap().interactions[0].duration_ms = 150;
+ branch.get_mut(r).unwrap().interactions.push(ia(300));
+ main.get_mut(r).unwrap().interactions[1].duration_ms = 250;
+ both_ways(&base, &branch, &main, |doc| assert_eq!(durations(doc, r), [150, 250, 300]));
+ // The branch deletes one while main leaves them alone.
+ let (mut branch, mut main) = fork();
+ branch.get_mut(r).unwrap().interactions.remove(0);
+ main.get_mut(r).unwrap().fills[0] = red();
+ both_ways(&base, &branch, &main, |doc| assert_eq!(durations(doc, r), [200]));
+ // The same interaction changed both ways, or one deleted while the other side changed the
+ // list, conflicts.
+ for delete in [false, true] {
+ let (mut branch, mut main) = fork();
+ if delete {
+ branch.get_mut(r).unwrap().interactions.remove(0);
+ } else {
+ branch.get_mut(r).unwrap().interactions[1].duration_ms = 220;
+ }
+ main.get_mut(r).unwrap().interactions[1].duration_ms = 250;
+ let p = plan(&base, &branch, &main).unwrap();
+ let keys: Vec = p.conflicts.iter().map(|c| c.key.to_string()).collect();
+ assert_eq!(keys, [format!("{r}/interactions")], "delete: {delete}");
+ }
}
#[test]
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index d6859a510..8e9f98d92 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -61,7 +61,7 @@ impl<'de> Deserialize<'de> for Color {
}
fn clamp01(v: f32) -> f32 {
- if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
+ if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }
}
impl Default for Color {
diff --git a/crates/color/src/tests.rs b/crates/color/src/tests.rs
index 68a838e05..4cf875bbf 100644
--- a/crates/color/src/tests.rs
+++ b/crates/color/src/tests.rs
@@ -80,7 +80,7 @@ fn blend_names() {
#[test]
fn nan_inputs_are_sanitized() {
let c = Color::new(f32::NAN, 2.0, -1.0, f32::INFINITY);
- assert_eq!(c.to_rgba8(), [0, 255, 0, 0]);
+ assert_eq!(c.to_rgba8(), [0, 255, 0, 255]);
}
#[test]
@@ -106,3 +106,11 @@ fn crop_defaults_to_fill_and_roundtrips() {
assert!((a - b).abs() < 1e-9);
}
}
+
+#[test]
+fn infinite_channels_clamp() {
+ let c = Color::parse_css("rgb(1e40, 0, 0)").unwrap();
+ assert_eq!(c.r, 1.0);
+ let c = Color::new(f32::INFINITY, f32::NEG_INFINITY, f32::NAN, f32::INFINITY);
+ assert_eq!((c.r, c.g, c.b, c.a), (1.0, 0.0, 0.0, 1.0));
+}
diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs
index 06596ddcd..2a7b42a64 100644
--- a/crates/doc/src/geometry.rs
+++ b/crates/doc/src/geometry.rs
@@ -51,6 +51,10 @@ pub fn is_closed(n: &Node) -> bool {
}
}
+/// How much further than `tol` a stroke with nothing filled reaches: a thin line or stroke-only path
+/// is hard to land on with the plain tolerance, so it gets a wider band (5 screen px for the usual 2 px tolerance).
+const STROKE_REACH: f64 = 2.5;
+
/// Whether `pt` hits `n` itself; in `outline` mode (nothing filled on the canvas) a shape only where
/// its outline is.
fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, outline: bool) -> bool {
@@ -62,7 +66,7 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
NodeKind::Group | NodeKind::BooleanOp { .. } | NodeKind::Page { .. } => false,
NodeKind::Text(_) | NodeKind::Slice => n.local_rect().inflate(tol_l, tol_l).contains(lp),
NodeKind::Line => {
- let half = (n.stroke.weight / 2.0).max(tol_l);
+ let half = (n.stroke.weight / 2.0).max(tol_l * STROKE_REACH);
lp.x >= -half && lp.x <= n.width + half && lp.y.abs() <= half
}
NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. } | NodeKind::Section { .. } => {
@@ -78,7 +82,9 @@ fn hits_path(n: &Node, path: &BezPath, lp: Point, tol: f64, inside: bool) -> boo
if inside && (n.fills.iter().any(|f| f.visible) || !n.has_visible_stroke()) {
return true;
}
- let reach = (n.stroke.max_weight() / 2.0).max(tol);
+ // Only a stroke with nothing filled gets the wider band: a filled shape's edge keeps the plain one.
+ let stroke_only = n.has_visible_stroke() && !n.fills.iter().any(|f| f.visible);
+ let reach = (n.stroke.max_weight() / 2.0).max(if stroke_only { tol * STROKE_REACH } else { tol });
if !path.bounding_box().inflate(reach, reach).contains(lp) {
return false;
}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 71c6da393..d131b2f08 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -77,17 +77,19 @@ pub enum DocError {
pub type DocResult = Result;
-/// The set of touched node ids, and whether any layer is a mask (worked out when first asked
-/// after a change: hit testing skips its mask checks without one). Never part of equality or
+/// The set of touched node ids, whether any layer is a mask (hit testing skips its mask checks
+/// without one) and the largest background blur radius (renders keep that much overlap between
+/// their bands), both worked out when first asked after a change. Never part of equality or
/// serialisation.
#[derive(Clone, Debug, Default)]
-pub struct Dirty(pub std::collections::BTreeSet, std::sync::OnceLock);
+pub struct Dirty(pub std::collections::BTreeSet, std::sync::OnceLock, std::sync::OnceLock);
impl Dirty {
/// Record node `id` as touched (edited, added or removed).
fn touch(&mut self, id: NodeId) {
self.0.insert(id);
self.1 = std::sync::OnceLock::new();
+ self.2 = std::sync::OnceLock::new();
}
}
@@ -254,6 +256,11 @@ impl Document {
*self.dirty.1.get_or_init(|| self.nodes.values().any(|n| n.is_mask))
}
+ /// The largest background blur or glass radius of any layer's effects (0 without any).
+ pub fn max_backdrop_radius(&self) -> f64 {
+ *self.dirty.2.get_or_init(|| self.nodes.values().flat_map(|n| n.effects.iter()).map(Effect::backdrop_radius).fold(0.0, f64::max))
+ }
+
/// Node ids touched so far (without clearing).
pub fn dirty(&self) -> &std::collections::BTreeSet {
&self.dirty.0
@@ -942,21 +949,39 @@ impl Document {
self.styles.iter().find(|s| s.id == id || s.name == id)
}
- /// The effective variable modes for a node (walking up its ancestors).
+ /// The effective variable modes for a node: the ones it sets over [`Self::inherited_modes`].
pub fn modes_for(&self, id: NodeId) -> BTreeMap {
- let mut out = BTreeMap::new();
- let mut chain = vec![id];
- chain.extend(self.ancestors(id));
- for c in chain.into_iter().rev() {
- if let Some(n) = self.node(c) {
- for (k, v) in &n.var_modes {
- out.insert(k.clone(), v.clone());
- }
- }
+ let mut out = self.inherited_modes(id);
+ if let Some(n) = self.node(id) {
+ out.extend(n.var_modes.iter().map(|(k, v)| (k.clone(), v.clone())));
}
out
}
+ /// The modes a node is on where it sets none (Auto): its ancestors', and for an instance the
+ /// ones its main component sets, which are closer than any container's.
+ pub fn inherited_modes(&self, id: NodeId) -> BTreeMap {
+ let mut out = BTreeMap::new();
+ for c in self.ancestors(id).into_iter().rev() {
+ if let Some(n) = self.node(c) {
+ out.extend(self.main_modes(n).chain(&n.var_modes).map(|(k, v)| (k.clone(), v.clone())));
+ }
+ }
+ if let Some(n) = self.node(id) {
+ out.extend(self.main_modes(n).map(|(k, v)| (k.clone(), v.clone())));
+ }
+ out
+ }
+
+ /// The modes an instance's main component sets (none for other layers).
+ fn main_modes<'a>(&'a self, n: &Node) -> impl Iterator- {
+ let main = match n.kind {
+ NodeKind::Instance { component, .. } => self.node(component),
+ _ => None,
+ };
+ main.into_iter().flat_map(|m| &m.var_modes)
+ }
+
/// Check structural invariants (used by tests and after loading untrusted files).
pub fn validate(&self) -> Vec
{
let mut issues = Vec::new();
@@ -1117,8 +1142,14 @@ impl Document {
/// mask with the layers above it up to the next mask, or a single layer. An auto layout frame
/// whose first child paints on top paints the runs in reverse (see [`Node::paint_order`]).
pub fn paint_runs(&self, n: &Node) -> Vec> {
- let kids = &n.children;
- let node = |i: usize| kids.get(i).and_then(|k| self.node(*k));
+ let kids: Vec> = n.children.iter().map(|k| self.node(*k)).collect();
+ Self::paint_runs_of(&kids, n.layout.as_ref().is_some_and(|l| l.reverse_z))
+ }
+
+ /// [`Self::paint_runs`] of children already looked up (`None`: not in the document), last run
+ /// first when `reverse_z`.
+ pub fn paint_runs_of(kids: &[Option<&Node>], reverse_z: bool) -> Vec> {
+ let node = |i: usize| kids.get(i).copied().flatten();
let mut runs = Vec::new();
let mut i = 0;
while i < kids.len() {
@@ -1131,7 +1162,7 @@ impl Document {
runs.push(i..j);
i = j;
}
- if n.layout.as_ref().is_some_and(|l| l.reverse_z) {
+ if reverse_z {
runs.reverse();
}
runs
diff --git a/crates/doc/src/proto.rs b/crates/doc/src/proto.rs
index 91d2e8eb8..a844774c5 100644
--- a/crates/doc/src/proto.rs
+++ b/crates/doc/src/proto.rs
@@ -860,7 +860,35 @@ pub struct Device {
impl PrototypeSettings {
/// The devices to pick from ("None" presents the frame at its own size).
- pub const DEVICES: [Device; 6] = [
+ pub const DEVICES: [Device; 19] = [
+ Device {
+ name: "iPhone 17",
+ width: 402.0,
+ height: 874.0,
+ rotates: true,
+ colors: &[c("Black", 0x38, 0x39, 0x3D), c("White", 0xE9, 0xE9, 0xE5)],
+ },
+ Device {
+ name: "iPhone 17 Pro",
+ width: 402.0,
+ height: 874.0,
+ rotates: true,
+ colors: &[c("Black", 0x38, 0x39, 0x3D), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
+ Device {
+ name: "iPhone 17 Pro Max",
+ width: 440.0,
+ height: 956.0,
+ rotates: true,
+ colors: &[c("Black", 0x38, 0x39, 0x3D), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
+ Device {
+ name: "iPhone Air",
+ width: 420.0,
+ height: 912.0,
+ rotates: true,
+ colors: &[c("Black", 0x38, 0x39, 0x3D), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
Device {
name: "iPhone 16",
width: 393.0,
@@ -874,6 +902,13 @@ impl PrototypeSettings {
c("Blue", 0x72, 0x84, 0xD4),
],
},
+ Device {
+ name: "iPhone 16 Pro",
+ width: 402.0,
+ height: 874.0,
+ rotates: true,
+ colors: &[c("Black", 0x3B, 0x3A, 0x38), c("White", 0xEC, 0xEB, 0xE6)],
+ },
Device {
name: "iPhone 16 Pro Max",
width: 440.0,
@@ -881,6 +916,55 @@ impl PrototypeSettings {
rotates: true,
colors: &[c("Black", 0x3B, 0x3A, 0x38), c("White", 0xEC, 0xEB, 0xE6), c("Natural", 0xBF, 0xB9, 0xAF), c("Sand", 0xC6, 0xAC, 0x8F)],
},
+ Device {
+ name: "iPhone 16 Plus",
+ width: 430.0,
+ height: 932.0,
+ rotates: true,
+ colors: &[c("Black", 0x3A, 0x3B, 0x3F), c("White", 0xEE, 0xED, 0xE8)],
+ },
+ Device {
+ name: "iPhone 15 Pro",
+ width: 393.0,
+ height: 852.0,
+ rotates: true,
+ colors: &[c("Black", 0x3B, 0x3A, 0x38), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
+ Device {
+ name: "iPhone 15 Pro Max",
+ width: 430.0,
+ height: 932.0,
+ rotates: true,
+ colors: &[c("Black", 0x3B, 0x3A, 0x38), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
+ Device {
+ name: "iPhone 15 Plus",
+ width: 430.0,
+ height: 932.0,
+ rotates: true,
+ colors: &[c("Black", 0x3A, 0x3B, 0x3F), c("White", 0xEE, 0xED, 0xE8)],
+ },
+ Device {
+ name: "iPhone 14 Pro",
+ width: 393.0,
+ height: 852.0,
+ rotates: true,
+ colors: &[c("Black", 0x3B, 0x3A, 0x38), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
+ Device {
+ name: "iPhone 14 Pro Max",
+ width: 430.0,
+ height: 932.0,
+ rotates: true,
+ colors: &[c("Black", 0x3B, 0x3A, 0x38), c("Silver", 0xD7, 0xD7, 0xD5)],
+ },
+ Device {
+ name: "iPhone 14",
+ width: 390.0,
+ height: 844.0,
+ rotates: true,
+ colors: &[c("Black", 0x3A, 0x3B, 0x3F), c("White", 0xEE, 0xED, 0xE8)],
+ },
Device {
name: "Android Compact",
width: 412.0,
@@ -888,6 +972,13 @@ impl PrototypeSettings {
rotates: true,
colors: &[c("Black", 0x2E, 0x2F, 0x33), c("Silver", 0xD6, 0xD8, 0xDB), c("Green", 0xA6, 0xC0, 0xA3)],
},
+ Device {
+ name: "Android Medium",
+ width: 700.0,
+ height: 840.0,
+ rotates: true,
+ colors: &[c("Black", 0x2E, 0x2F, 0x33), c("Silver", 0xD6, 0xD8, 0xDB)],
+ },
Device {
name: "iPad mini",
width: 744.0,
diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs
index b294151bb..097dd189b 100644
--- a/crates/doc/src/text.rs
+++ b/crates/doc/src/text.rs
@@ -215,6 +215,10 @@ pub struct ParaList {
pub list: ListStyle,
/// Nesting level (0 = outermost; plain paragraphs are always 0).
pub indent: u8,
+ /// A numbered list that starts counting at this paragraph counts from `start_offset + 1`
+ /// (items that go on counting ignore it; other paragraphs are always 0).
+ #[serde(skip_serializing_if = "crate::node::is_default")]
+ pub start_offset: u32,
}
/// Character style. In runs, every field is an override; `None` means "inherit the base".
@@ -637,13 +641,13 @@ impl TextData {
/// Paragraph `p`'s list settings.
pub fn para_list(&self, p: usize) -> ParaList {
- self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, indent: 0 })
+ self.paragraphs.get(p).copied().unwrap_or(ParaList { list: self.list, ..ParaList::default() })
}
/// Spell out every paragraph's list settings in `paragraphs` (and drop extra entries).
fn fill_paragraphs(&mut self) {
let n = self.paragraph_count();
- let fill = ParaList { list: self.list, indent: 0 };
+ let fill = ParaList { list: self.list, ..ParaList::default() };
self.paragraphs.resize(n, fill);
}
@@ -657,17 +661,23 @@ impl TextData {
}
/// Apply `f` to the list settings of the paragraphs chars `start..end` touch (plain
- /// paragraphs stay at level 0, levels stop at [`MAX_LIST_INDENT`]); one style for all with
- /// no nesting folds back into `list`.
+ /// paragraphs stay at level 0, only numbered ones keep a start, levels stop at
+ /// [`MAX_LIST_INDENT`]); one style for all with no nesting or start folds back into `list`.
pub fn set_para_lists(&mut self, start: usize, end: usize, f: impl Fn(&mut ParaList)) {
let (a, b) = self.para_span(start, end);
self.fill_paragraphs();
for pl in self.paragraphs.get_mut(a..=b).unwrap_or(&mut []) {
f(pl);
- pl.indent = if pl.list == ListStyle::None { 0 } else { pl.indent.min(MAX_LIST_INDENT) };
+ if pl.list == ListStyle::None {
+ pl.indent = 0;
+ }
+ if pl.list != ListStyle::Numbered {
+ pl.start_offset = 0;
+ }
+ pl.indent = pl.indent.min(MAX_LIST_INDENT);
}
if let Some(first) = self.paragraphs.first().copied()
- && first.indent == 0
+ && first == (ParaList { list: first.list, ..ParaList::default() })
&& self.paragraphs.iter().all(|p| *p == first)
{
self.list = first.list;
@@ -675,11 +685,12 @@ impl TextData {
}
}
- /// The list settings shared by the paragraphs chars `start..end` touch, or None when they differ.
+ /// The list style and level shared by the paragraphs chars `start..end` touch (the first
+ /// one's settings), or None when they differ. Start numbers don't count.
pub fn common_para_list(&self, start: usize, end: usize) -> Option {
let (a, b) = self.para_span(start, end);
let first = self.para_list(a);
- (a..=b).all(|p| self.para_list(p) == first).then_some(first)
+ (a..=b).all(|p| self.para_list(p).list == first.list && self.para_list(p).indent == first.indent).then_some(first)
}
/// Link chars `start..end` (all of them when the range is empty or the whole text) to text
@@ -782,4 +793,29 @@ mod case_tests {
assert_eq!(st.variations.keys().collect::>(), ["wdth"]);
assert!(valid_axis_tag("wght") && !valid_axis_tag("weight"));
}
+
+ #[test]
+ fn list_starts_load_from_old_files_and_follow_edits() {
+ use ListStyle::{Bulleted as B, None as P, Numbered as N};
+ // Files written before start numbers load with none, and write the same bytes.
+ let old = r#"{"list":"numbered","indent":1}"#;
+ let pl: ParaList = serde_json::from_str(old).unwrap();
+ assert_eq!(pl, ParaList { list: N, indent: 1, start_offset: 0 });
+ assert_eq!(serde_json::to_string(&pl).unwrap(), old);
+ // One numbered paragraph with a start keeps it (it doesn't fold into `list`).
+ let mut t = TextData { characters: "Next".into(), ..Default::default() };
+ t.set_para_lists(0, 0, |p| *p = ParaList { list: N, indent: 0, start_offset: 1 });
+ assert_eq!(t.para_list(0), ParaList { list: N, indent: 0, start_offset: 1 });
+ // Enter copies it to the new item; different starts don't make the list mixed.
+ t.replace_range(4, 4, "\nMore");
+ assert_eq!(t.para_list(1).start_offset, 1);
+ t.set_para_lists(5, 5, |p| p.start_offset = 0);
+ assert!(t.common_para_list(0, t.char_count()).is_some_and(|p| p.list == N));
+ // Bullets have no number, so no start.
+ t.set_para_lists(0, 0, |p| *p = ParaList { list: B, indent: 1, start_offset: 4 });
+ assert_eq!(t.para_list(0), ParaList { list: B, indent: 1, start_offset: 0 });
+ // A plain paragraph has none.
+ t.set_para_lists(0, 0, |p| p.list = P);
+ assert_eq!(t.para_list(0), ParaList::default());
+ }
}
diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs
index fd0a0f7ed..1165bd600 100644
--- a/crates/doc/src/vector.rs
+++ b/crates/doc/src/vector.rs
@@ -468,9 +468,9 @@ impl VectorNetwork {
start_dir(&self.outward(seg, at_a)?)
}
- /// Whether any point has a stroke cap or join of its own.
- pub fn has_point_styles(&self) -> bool {
- self.vertices.iter().any(|v| v.cap.is_some() || v.join.is_some())
+ /// Whether any point has a stroke cap of its own or a join other than the layer's `layer_join`.
+ pub fn has_point_styles(&self, layer_join: StrokeJoin) -> bool {
+ self.vertices.iter().any(|v| v.cap.is_some() || v.join.is_some_and(|j| j != layer_join))
}
/// The fill path: every region's loops.
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index f610c38b3..545d872cc 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -20,6 +20,7 @@ figcraft-render = { workspace = true }
figcraft-format = { workspace = true }
figcraft-svg = { workspace = true }
figcraft-pdf = { workspace = true }
+craft-docpath = { workspace = true }
figcraft-plugin = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/engine/clippy.toml b/crates/engine/clippy.toml
new file mode 100644
index 000000000..3ceac8998
--- /dev/null
+++ b/crates/engine/clippy.toml
@@ -0,0 +1,39 @@
+# The workspace settings (../../clippy.toml; clippy reads only the nearest file), plus the engine's
+# own rule: shipped engine code reaches the file system only through `file_access`, which enforces
+# the automation roots (#715), so every command is confined without a check of its own.
+allow-unwrap-in-tests = true
+allow-expect-in-tests = true
+allow-panic-in-tests = true
+too-many-arguments-threshold = 10
+disallowed-methods = [
+ { path = "std::fs::read", reason = "use file_access::read (automation roots)" },
+ { path = "std::fs::read_to_string", reason = "use file_access::read (automation roots)" },
+ { path = "std::fs::write", reason = "use file_access::write (automation roots)" },
+ { path = "std::fs::metadata", reason = "use file_access::metadata (automation roots)" },
+ { path = "std::fs::symlink_metadata", reason = "use file_access (automation roots)" },
+ { path = "std::fs::read_dir", reason = "use file_access::read_dir (automation roots)" },
+ { path = "std::fs::canonicalize", reason = "use file_access (automation roots)" },
+ { path = "std::fs::copy", reason = "use file_access (automation roots)" },
+ { path = "std::fs::rename", reason = "use file_access (automation roots)" },
+ { path = "std::fs::create_dir", reason = "use file_access::create_dir_all (automation roots)" },
+ { path = "std::fs::create_dir_all", reason = "use file_access::create_dir_all (automation roots)" },
+ { path = "std::fs::remove_file", reason = "use file_access (automation roots)" },
+ { path = "std::fs::remove_dir", reason = "use file_access (automation roots)" },
+ { path = "std::fs::remove_dir_all", reason = "use file_access (automation roots)" },
+ { path = "std::fs::hard_link", reason = "use file_access (automation roots)" },
+ { path = "std::fs::File::open", reason = "use file_access::open (automation roots)" },
+ { path = "std::fs::File::create", reason = "use file_access::write (automation roots)" },
+ { path = "std::fs::File::create_new", reason = "use file_access::write (automation roots)" },
+ { path = "std::fs::OpenOptions::open", reason = "use file_access (automation roots)" },
+ { path = "std::path::Path::exists", reason = "use file_access::exists (automation roots)" },
+ { path = "std::path::Path::try_exists", reason = "use file_access::exists (automation roots)" },
+ { path = "std::path::Path::is_file", reason = "use file_access::metadata (automation roots)" },
+ { path = "std::path::Path::is_dir", reason = "use file_access::is_dir (automation roots)" },
+ { path = "std::path::Path::metadata", reason = "use file_access::metadata (automation roots)" },
+ { path = "std::path::Path::symlink_metadata", reason = "use file_access (automation roots)" },
+ { path = "std::path::Path::read_dir", reason = "use file_access::read_dir (automation roots)" },
+ { path = "std::path::Path::canonicalize", reason = "use file_access (automation roots)" },
+ { path = "figcraft_format::write_file_atomic", reason = "use file_access::write (automation roots)" },
+ { path = "figcraft_format::save_file", reason = "use file_access::write (automation roots)" },
+ { path = "figcraft_format::load_file", reason = "use file_access::read (automation roots)" },
+]
diff --git a/crates/engine/src/a11y_keys_tests.rs b/crates/engine/src/a11y_keys_tests.rs
index 6687886cd..e4892bcae 100644
--- a/crates/engine/src/a11y_keys_tests.rs
+++ b/crates/engine/src/a11y_keys_tests.rs
@@ -55,3 +55,51 @@ fn reduce_motion_is_a_preference_that_persists() {
let old: crate::Prefs = serde_json::from_value(json!({"theme": "dark"})).unwrap();
assert!(!old.reduce_motion);
}
+
+#[test]
+fn interface_size_is_relative_to_the_system_and_persists() {
+ let mut s = Session::new();
+ assert_eq!(s.prefs.ui_scale, 1.0, "the system's own size by default");
+ assert_eq!(s.execute("pref.uiScale", &json!({})).unwrap()["scale"], 1.0);
+ assert_eq!(s.execute("pref.uiScale", &json!({"scale": 1.25})).unwrap()["scale"], 1.25);
+ assert_eq!(s.prefs.ui_scale, 1.25);
+ // Reading changes nothing; "auto" (older scripts) is the system's own size.
+ assert_eq!(s.execute("pref.uiScale", &json!({})).unwrap()["scale"], 1.25);
+ assert_eq!(s.execute("pref.uiScale", &json!({"scale": "Auto"})).unwrap()["scale"], 1.0);
+ // Nothing to undo: the document didn't change.
+ assert!(!s.ds().map(|d| d.is_dirty()).unwrap_or(false));
+ // Saved with the other preferences and read back.
+ s.prefs.ui_scale = 0.9;
+ let v = serde_json::to_value(&s.prefs).unwrap();
+ assert_eq!(v["ui_scale"], 0.9);
+ let back: crate::Prefs = serde_json::from_value(v).unwrap();
+ assert_eq!(back.ui_scale, 0.9);
+}
+
+#[test]
+fn interface_size_stops_at_the_ends_and_junk_never_changes_it() {
+ let mut s = Session::new();
+ assert_eq!(s.execute("pref.uiScale", &json!({"scale": 0.01})).unwrap()["scale"], crate::UI_SCALE_MIN);
+ assert_eq!(s.execute("pref.uiScale", &json!({"scale": -4})).unwrap()["scale"], crate::UI_SCALE_MIN);
+ assert_eq!(s.execute("pref.uiScale", &json!({"scale": 1e308})).unwrap()["scale"], crate::UI_SCALE_MAX);
+ // The size is a factor (1.25), not a percentage: 125 is far past the end and stops there.
+ assert_eq!(s.execute("pref.uiScale", &json!({"scale": 125})).unwrap()["scale"], crate::UI_SCALE_MAX);
+ s.prefs.ui_scale = 1.5;
+ for junk in [json!({"scale": "NaN"}), json!({"scale": "big"}), json!({"scale": [1]}), json!({"scale": {"x": 1}})] {
+ assert!(s.execute("pref.uiScale", &junk).is_err(), "{junk}");
+ assert_eq!(s.prefs.ui_scale, 1.5, "{junk}");
+ }
+}
+
+#[test]
+fn a_settings_file_without_or_with_a_wrong_interface_size_reads_as_the_systems_size_and_keeps_the_rest() {
+ let old: crate::Prefs = serde_json::from_value(json!({"theme": "dark"})).unwrap();
+ assert_eq!(old.ui_scale, 1.0);
+ for bad in [json!("big"), json!(null), json!([2]), json!(true)] {
+ let p: crate::Prefs = serde_json::from_value(json!({"theme": "dark", "ui_scale": bad})).unwrap();
+ assert_eq!((p.ui_scale, p.theme.as_str()), (1.0, "dark"), "{bad}");
+ }
+ // A number out of range is clamped rather than refused.
+ let p: crate::Prefs = serde_json::from_value(json!({"ui_scale": 99, "theme": "dark"})).unwrap();
+ assert_eq!((p.ui_scale, p.theme.as_str()), (crate::UI_SCALE_MAX, "dark"));
+}
diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs
index 5d34d5860..4659a5973 100644
--- a/crates/engine/src/al_behaviour_tests.rs
+++ b/crates/engine/src/al_behaviour_tests.rs
@@ -180,6 +180,23 @@ fn vertical_wrap_columns_take_arrows_and_drops() {
assert_eq!(line, Some([30.0, 48.0, 50.0, 48.0]));
}
+#[test]
+fn adding_auto_layout_to_a_frame_keeps_its_size() {
+ // An existing frame with content hugs it (padding inferred, so the size is preserved);
+ // an empty one keeps its size instead of collapsing to its padding.
+ let mut s = Session::new();
+ let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap());
+ rect(&mut s, f, 40.0, 20.0, "#FF0000");
+ s.execute("layout.add", &json!({"ids": [f]})).unwrap();
+ assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
+ assert_eq!(size(&s, f), (300.0, 200.0));
+ // An empty frame keeps its size too.
+ let e = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200})).unwrap());
+ s.execute("layout.add", &json!({"ids": [e]})).unwrap();
+ assert_eq!(sizing(&s, e), (Sizing::Fixed, Sizing::Fixed));
+ assert_eq!(size(&s, e), (300.0, 200.0));
+}
+
#[test]
fn canvas_stacking_paints_and_exports_the_first_child_on_top() {
// Documented: the last child is on top by default; "first on top" flips which one is drawn
diff --git a/crates/engine/src/binding_lists_tests.rs b/crates/engine/src/binding_lists_tests.rs
index 493c8f60d..9db9975a9 100644
--- a/crates/engine/src/binding_lists_tests.rs
+++ b/crates/engine/src/binding_lists_tests.rs
@@ -46,7 +46,7 @@ fn a_bound_fill_colour_keeps_the_other_fills() {
let fills = s.doc().unwrap().node(r).unwrap().fills.clone();
assert_eq!(fills.len(), 2, "the second fill stays");
assert_eq!(fills[0].kind, PaintKind::Solid { color: Color::from_rgb8_const(0xFF, 0, 0) });
- assert_eq!(fills[0].opacity, 0.5, "the bound paint keeps its opacity");
+ assert_eq!(fills[0].opacity, 1.0, "the variable brings the whole colour, alpha included");
assert_eq!(fills[1].kind, PaintKind::Solid { color: Color::from_rgb8_const(0, 0xFF, 0) });
// Removing the bound (first) fill takes the binding with it.
ex(&mut s, "fill.remove", json!({"ids": [r], "index": 0}));
@@ -97,3 +97,77 @@ fn effect_moves_and_removals_reject_junk() {
ex(&mut s, "effect.remove", json!({"ids": [r], "index": 7}));
assert_eq!(s.doc().unwrap().node(r).unwrap().effects.len(), 1);
}
+
+fn fill_hex(s: &Session, r: NodeId) -> Vec {
+ s.doc().unwrap().node(r).unwrap().fills.iter().filter_map(|p| p.solid_color()).map(|c| c.to_hex()).collect()
+}
+
+fn brand_id(s: &Session) -> String {
+ s.doc().unwrap().variables.get("brand").unwrap().id.clone()
+}
+
+#[test]
+fn explicit_paint_edits_detach_the_colour_binding() {
+ // An edit that reported success keeps its colour: the binding it overwrote lets go (as
+ // selection colours already do), instead of putting the variable's colour back.
+ let edits = [
+ ("fill.set", json!({"color": "#00FF00"})),
+ ("node.set", json!({"props": {"fill": "#00FF00"}})),
+ ("node.set", json!({"props": {"fills": ["#00FF00"]}})),
+ ];
+ for (cmd, mut p) in edits {
+ let (mut s, r) = setup();
+ ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "brand"}));
+ p["ids"] = json!([r]);
+ ex(&mut s, cmd, p.clone());
+ assert_eq!(fill_hex(&s, r), ["00FF00"], "{cmd} {p}");
+ assert!(bound(&s, r).is_empty(), "{cmd} {p}");
+ ex(&mut s, "variable.set", json!({"variable": "brand", "value": "#123456"}));
+ assert_eq!(fill_hex(&s, r), ["00FF00"], "{cmd} {p}: no longer follows the variable");
+ }
+ for (cmd, mut p) in [("stroke.set", json!({"color": "#00FF00"})), ("node.set", json!({"props": {"stroke": "#00FF00"}}))] {
+ let (mut s, r) = setup();
+ ex(&mut s, "node.set", json!({"ids": [r], "props": {"strokes": ["#000000"]}}));
+ ex(&mut s, "variable.bind", json!({"ids": [r], "field": "stroke", "variable": "brand"}));
+ p["ids"] = json!([r]);
+ ex(&mut s, cmd, p);
+ let n = s.doc().unwrap().node(r).unwrap();
+ assert_eq!(n.strokes[0].solid_color().map(|c| c.to_hex()).as_deref(), Some("00FF00"), "{cmd}");
+ assert!(n.bound.is_empty(), "{cmd}");
+ }
+}
+
+#[test]
+fn clearing_bound_fills_adds_no_paint_back() {
+ let (mut s, r) = setup();
+ ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "brand"}));
+ ex(&mut s, "node.set", json!({"ids": [r], "props": {"fills": []}}));
+ assert!(s.doc().unwrap().node(r).unwrap().fills.is_empty());
+ assert!(bound(&s, r).is_empty());
+ ex(&mut s, "variable.set", json!({"variable": "brand", "value": "#123456"}));
+ assert!(s.doc().unwrap().node(r).unwrap().fills.is_empty(), "the variable doesn't bring the fill back");
+}
+
+#[test]
+fn paint_opacity_edits_keep_the_colour_binding() {
+ let (mut s, r) = setup();
+ ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "brand"}));
+ ex(&mut s, "fill.set", json!({"ids": [r], "opacity": 0.5}));
+ ex(&mut s, "variable.set", json!({"variable": "brand", "value": "#0000FF"}));
+ assert_eq!(fill_hex(&s, r), ["0000FF"], "the colour still follows the variable");
+ assert_eq!(s.doc().unwrap().node(r).unwrap().fills[0].opacity, 0.5);
+ // The same colour with another opacity, through node.set, keeps it too.
+ ex(&mut s, "node.set", json!({"ids": [r], "props": {"fills": [{"type": "solid", "color": "#0000FF", "opacity": 0.25}]}}));
+ assert_eq!(bound(&s, r).len(), 1);
+ assert_eq!(s.doc().unwrap().node(r).unwrap().fills[0].opacity, 0.25);
+}
+
+#[test]
+fn paints_set_with_their_binding_in_the_same_call_keep_it() {
+ let (mut s, r) = setup();
+ ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "brand"}));
+ let brand = brand_id(&s);
+ ex(&mut s, "node.set", json!({"ids": [r], "props": {"fills": ["#00FF00"], "boundVariables": {"fill": brand}}}));
+ assert_eq!(bound(&s, r), [("fill".to_string(), brand)]);
+ assert_eq!(fill_hex(&s, r), ["FF0000"], "the binding given with the paints applies");
+}
diff --git a/crates/engine/src/booleans.rs b/crates/engine/src/booleans.rs
index 87d901533..c3de51cbe 100644
--- a/crates/engine/src/booleans.rs
+++ b/crates/engine/src/booleans.rs
@@ -124,7 +124,7 @@ pub(crate) fn apply(s: &mut Session, cmd: &str, p: &Value, op: BoolOp) -> Result
}
return Ok(json!({"ids": ids, "operation": op}));
}
- let out = crate::cmd::structure::wrap_boolean(s, p, op)?;
+ let out = crate::cmd::structure::wrap_boolean(s, p, cmd, op)?;
// Operands of a new group follow its operation.
if let Some(g) = crate::params::id_of(&out["id"]) {
let doc = s.doc_mut()?;
diff --git a/crates/engine/src/bound_alpha_tests.rs b/crates/engine/src/bound_alpha_tests.rs
new file mode 100644
index 000000000..b7210f0f7
--- /dev/null
+++ b/crates/engine/src/bound_alpha_tests.rs
@@ -0,0 +1,131 @@
+//! A colour variable's alpha applies once to the paint it is bound to (#802): a `#RRGGBBAA` fill keeps
+//! its alpha in the paint opacity, and binding a variable with alpha hands the variable the whole
+//! colour, so the two alphas don't multiply (canvas, SVG, `.fig` round trips, mode switches).
+
+use figcraft_doc::NodeId;
+use serde_json::json;
+
+use crate::Session;
+
+/// 0x80 / 255 and 0x40 / 255.
+const HALF: f32 = 128.0 / 255.0;
+const QUARTER: f32 = 64.0 / 255.0;
+
+fn ex(s: &mut Session, cmd: &str, p: serde_json::Value) {
+ s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
+}
+
+/// A rectangle filled `#0D6EFD80` and a colour variable `tint` (Light `light`, Dark `dark`).
+fn setup(light: &str, dark: &str) -> (Session, NodeId) {
+ let mut s = Session::new();
+ let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "props": {"fill": "#0D6EFD80"}})).unwrap();
+ let r = NodeId(r["id"].as_u64().unwrap());
+ ex(&mut s, "variable.createCollection", json!({"name": "Tokens", "modes": ["Light", "Dark"]}));
+ ex(&mut s, "variable.create", json!({"collection": "Tokens", "name": "tint", "type": "color", "value": light}));
+ ex(&mut s, "variable.set", json!({"variable": "tint", "mode": "Dark", "value": dark}));
+ (s, r)
+}
+
+/// The fill's effective alpha (colour alpha times paint opacity).
+fn alpha(s: &Session, r: NodeId) -> f32 {
+ s.doc().unwrap().node(r).unwrap().fills[0].solid_color().unwrap().a
+}
+
+/// The alpha byte of the rectangle rendered on its own (transparent backdrop).
+fn pixel_alpha(s: &Session, r: NodeId) -> u8 {
+ let pix = figcraft_render::render_node(s.doc().unwrap(), r, 1.0).unwrap();
+ let i = ((5 * pix.width() + 5) * 4 + 3) as usize;
+ pix.data()[i]
+}
+
+fn near(a: f32, b: f32) -> bool {
+ (a - b).abs() < 2e-3
+}
+
+#[test]
+fn a_hex_with_alpha_keeps_its_alpha_in_the_opacity() {
+ let (s, r) = setup("#0D6EFD80", "#0D6EFD40");
+ let p = &s.doc().unwrap().node(r).unwrap().fills[0];
+ assert_eq!(p.kind, figcraft_color::PaintKind::Solid { color: figcraft_color::Color::from_rgb8_const(0x0D, 0x6E, 0xFD) });
+ assert!(near(p.opacity, HALF));
+ assert_eq!(pixel_alpha(&s, r), 128);
+}
+
+#[test]
+fn a_bound_variable_alpha_applies_once() {
+ // The fill and the variable are both #0D6EFD80: the result is 50%, not 25%.
+ let (mut s, r) = setup("#0D6EFD80", "#0D6EFD40");
+ ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": "tint"}));
+ assert!(near(alpha(&s, r), HALF), "{}", alpha(&s, r));
+ assert_eq!(pixel_alpha(&s, r), 128);
+ let svg = figcraft_svg::export_svg(s.doc().unwrap(), &[r], &figcraft_svg::SvgOptions::default()).unwrap();
+ assert!(svg.contains("fill=\"#0D6EFD\" fill-opacity=\"0.502\""), "{svg}");
+ // Binding the same variable again changes nothing.
+ ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": "tint"}));
+ assert!(near(alpha(&s, r), HALF));
+}
+
+#[test]
+fn unbinding_keeps_the_colour_with_its_alpha_in_the_opacity() {
+ let (mut s, r) = setup("#0D6EFD40", "#0D6EFD");
+ ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": "tint"}));
+ assert_eq!(pixel_alpha(&s, r), 64);
+ ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": null}));
+ let p = &s.doc().unwrap().node(r).unwrap().fills[0];
+ assert_eq!(p.kind, figcraft_color::PaintKind::Solid { color: figcraft_color::Color::from_rgb8_const(0x0D, 0x6E, 0xFD) });
+ assert!(near(p.opacity, QUARTER), "{}", p.opacity);
+ assert_eq!(pixel_alpha(&s, r), 64);
+ // Undo restores the binding and its paint.
+ ex(&mut s, "edit.undo", json!({}));
+ assert!(!s.doc().unwrap().node(r).unwrap().bound.is_empty());
+ assert_eq!(pixel_alpha(&s, r), 64);
+}
+
+#[test]
+fn modes_switch_the_alpha_without_accumulating() {
+ let (mut s, r) = setup("#0D6EFD40", "#0D6EFD80");
+ ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": "tint"}));
+ for (mode, want) in [("Dark", HALF), ("Light", QUARTER), ("Dark", HALF), ("Light", QUARTER)] {
+ ex(&mut s, "variable.setMode", json!({"collection": "Tokens", "mode": mode}));
+ assert!(near(alpha(&s, r), want), "{mode}: {}", alpha(&s, r));
+ }
+ // An opacity set while bound multiplies on top and survives mode switches.
+ ex(&mut s, "fill.set", json!({"ids": [r.0], "index": 0, "opacity": 0.5}));
+ ex(&mut s, "variable.setMode", json!({"collection": "Tokens", "mode": "Dark"}));
+ assert!(near(alpha(&s, r), HALF * 0.5));
+}
+
+#[test]
+fn node_set_and_style_bindings_apply_the_alpha_once() {
+ let (mut s, r) = setup("#0D6EFD80", "#0D6EFD40");
+ let var = s.doc().unwrap().variables.get("tint").unwrap().id.clone();
+ ex(&mut s, "node.set", json!({"id": r.0, "props": {"boundVariables": {"fill": var}}}));
+ assert!(near(alpha(&s, r), HALF));
+ ex(&mut s, "node.set", json!({"id": r.0, "props": {"boundVariables": {"fill": null}}}));
+ assert!(near(s.doc().unwrap().node(r).unwrap().fills[0].opacity, HALF));
+ // A paint style made from a `#RRGGBBAA` colour, bound to the variable.
+ let st = s.execute("style.create", &json!({"type": "paint", "name": "Tint", "value": "#0D6EFD80"})).unwrap()["id"].clone();
+ ex(&mut s, "style.bind", json!({"style": st, "field": "fills/0/color", "variable": "tint"}));
+ ex(&mut s, "style.apply", json!({"ids": [r.0], "style": st}));
+ assert!(near(alpha(&s, r), HALF), "{}", alpha(&s, r));
+}
+
+#[test]
+fn a_fig_round_trip_keeps_the_alpha_once() {
+ let (mut s, r) = setup("#0D6EFD80", "#0D6EFD40");
+ ex(&mut s, "variable.bind", json!({"ids": [r.0], "field": "fill", "variable": "tint"}));
+ ex(&mut s, "fill.set", json!({"ids": [r.0], "index": 0, "opacity": 0.5}));
+ let (bytes, _) = figcraft_format::fig::export(s.doc().unwrap(), None).unwrap();
+ let back = crate::cmd::file::load_fig(&bytes, "x").unwrap().unwrap().doc;
+ let n = back.nodes().find(|n| !n.bound.is_empty()).unwrap();
+ let a = n.fills[0].solid_color().unwrap().a;
+ assert!(near(a, HALF * 0.5), "{a}");
+}
+
+#[test]
+fn code_gives_a_translucent_stroke_its_alpha_once() {
+ let (mut s, r) = setup("#0D6EFD80", "#0D6EFD40");
+ ex(&mut s, "stroke.add", json!({"ids": [r.0], "color": "#FF000080"}));
+ let code = s.execute("inspect.code", &json!({"id": r.0})).unwrap()["code"].as_str().unwrap_or_default().to_string();
+ assert!(code.contains("solid rgba(255, 0, 0, 0.50)"), "{code}");
+}
diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs
index c8f34fc15..4b6cd3fcc 100644
--- a/crates/engine/src/catalog.rs
+++ b/crates/engine/src/catalog.rs
@@ -213,6 +213,8 @@ pub static MENU: &[MenuItem] = &[
m!("Text/Case", "Uppercase", "text.caseUpper"),
m!("Text/Case", "Lowercase", "text.caseLower"),
m!("Text/Case", "Title case", "text.caseTitle"),
+ m!("Text", SEP, ""),
+ m!("Text", "Missing fonts…", "text.missingFonts"),
// Arrange
m!("Arrange", "Align left", "align.left"),
m!("Arrange", "Align horizontal centers", "align.hcenter"),
@@ -287,7 +289,7 @@ pub fn items() -> impl Iterator- {
}
/// Items of FigCraft's own that the parity count leaves out (as it does the `collab.` ones).
-const OWN: [&str; 2] = ["file.newFromTemplate", "help.gettingStarted"];
+const OWN: [&str; 3] = ["file.newFromTemplate", "help.gettingStarted", "text.missingFonts"];
/// Coverage: (implemented, total, missing ids). `extra` lists ids implemented by the UI layer.
pub fn parity(extra: &[&str]) -> (usize, usize, Vec<&'static str>) {
diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs
index 43cfcf3c0..10ad13e54 100644
--- a/crates/engine/src/cmd/arrange.rs
+++ b/crates/engine/src/cmd/arrange.rs
@@ -19,7 +19,21 @@ pub fn specs() -> Vec
{
spec!("align.bottom", "Align bottom", "{ids?}", true, |s, p| align(s, p, Al::Bottom)),
spec!("distribute.horizontal", "Distribute horizontal spacing", "{ids?, spacing?}", true, |s, p| distribute(s, p, true)),
spec!("distribute.vertical", "Distribute vertical spacing", "{ids?, spacing?}", true, |s, p| distribute(s, p, false)),
+ spec!(
+ "arrange.spacing",
+ "Spacing",
+ "{ids?, horizontal?, vertical?, fromGesture?} (page units; fromGesture uses the interaction snapshot)",
+ true,
+ spacing
+ ),
spec!("arrange.tidy", "Tidy up", "{ids?, spacing?}", true, tidy),
+ spec!(
+ "arrange.reorder",
+ "Reorder selection",
+ "{ids?, source, target, swap?, fromGesture?} (insert at target's visual slot; no hierarchy changes)",
+ true,
+ reorder
+ ),
spec!("arrange.packH", "Pack horizontal", "{ids?}", true, |s, p| pack(s, p, true)),
spec!("arrange.packV", "Pack vertical", "{ids?}", true, |s, p| pack(s, p, false)),
spec!("arrange.roundToPixels", "Round to pixels", "{ids?}", true, round_px),
@@ -521,6 +535,7 @@ pub(crate) fn resize_cmd(s: &mut Session, p: &Value) -> Result {
let (col, row) = string(p, "anchor").and_then(|a| crate::tools::anchor_of(&a)).unwrap_or((0, 0));
let (ax, ay) = (f64::from(col) / 2.0, f64::from(row) / 2.0);
let doc = s.doc_mut()?;
+ let before = super::styles::bound_before(doc, &ids);
for i in ids {
let n = doc.get(i)?;
let (ow, oh) = (n.width, n.height);
@@ -544,5 +559,98 @@ pub(crate) fn resize_cmd(s: &mut Session, p: &Value) -> Result {
}
super::props::restore_worlds(doc, &kept)?;
}
+ super::styles::detach_edited(doc, &before);
+ ok()
+}
+
+/// Reorder visual slots without rebuilding or reparenting layers.
+fn reorder(s: &mut Session, p: &Value) -> Result {
+ let cmd = "arrange.reorder";
+ let ids = req_targets(cmd, s, p)?;
+ let source = req_id(cmd, p, "source")?;
+ let target = req_id(cmd, p, "target")?;
+ let ds = s.ds()?;
+ let base = ds.interaction.as_ref().filter(|_| boolean(p, "fromGesture") == Some(true)).map(|i| i.doc.clone()).unwrap_or_else(|| ds.doc.clone());
+ let layout =
+ crate::selection_reorder::ReorderLayout::new(&base, &ids).ok_or_else(|| bad(cmd, "select a regular row, column or complete aligned grid"))?;
+ let positions = layout
+ .positions(source, target, boolean(p, "swap") == Some(true))
+ .ok_or_else(|| bad(cmd, "source and target must belong to the selection"))?;
+ // Validate every delta before editing; absolute targets always come from the gesture's
+ // snapshot so crossing several slots and returning to the start does not accumulate edits.
+ let doc = s.doc()?;
+ let mut moves = Vec::new();
+ for (id, at) in positions {
+ let now = doc.world_bounds(id).ok_or_else(|| bad(cmd, "layer is no longer available"))?;
+ let (dx, dy) = (at.x - now.x0, at.y - now.y0);
+ if !dx.is_finite() || !dy.is_finite() {
+ return Err(bad(cmd, "non-finite reorder result"));
+ }
+ if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
+ let node = doc.get(id)?;
+ let parent = node.parent.map(|p| doc.world_transform(p)).unwrap_or(Affine::IDENTITY);
+ let transform = parent.inverse() * Affine::translate((dx, dy)) * parent * node.transform;
+ if !transform.as_coeffs().iter().all(|v| v.is_finite()) {
+ return Err(bad(cmd, "non-finite local transform"));
+ }
+ moves.push((id, dx, dy));
+ }
+ }
+ if !moves.is_empty() {
+ let doc = s.doc_mut()?;
+ for (id, dx, dy) in moves {
+ move_world(doc, id, dx, dy)?;
+ }
+ }
+ ok()
+}
+
+/// Set the distances between smart-selection tracks without rebuilding/reparenting the layers.
+fn spacing(s: &mut Session, p: &Value) -> Result {
+ let ids = req_targets("arrange.spacing", s, p)?;
+ // A scrub is absolute from the interaction snapshot, even if tracks overlap or cross.
+ let ds = s.ds()?;
+ let base = ds.interaction.as_ref().filter(|_| boolean(p, "fromGesture") == Some(true)).map(|i| i.doc.clone()).unwrap_or_else(|| ds.doc.clone());
+ let layout = crate::selection_spacing::selection_spacing(&base, &ids);
+ let mut offsets = std::collections::BTreeMap::, Option)>::new();
+ let mut any = false;
+ for (key, axis, vertical) in [("horizontal", &layout.horizontal, false), ("vertical", &layout.vertical, true)] {
+ if get(p, key).is_none() {
+ continue;
+ }
+ let value = req_num("arrange.spacing", p, key)?;
+ if value.abs() > 1_000_000.0 {
+ return Err(bad("arrange.spacing", "spacing out of range"));
+ }
+ let axis = axis.as_ref().ok_or_else(|| bad("arrange.spacing", "selection has no spacing on this axis"))?;
+ any = true;
+ for (id, delta) in axis.offsets(value) {
+ if !delta.is_finite() {
+ return Err(bad("arrange.spacing", "non-finite spacing result"));
+ }
+ let pair = offsets.entry(id).or_default();
+ if vertical {
+ pair.1 = Some(delta);
+ } else {
+ pair.0 = Some(delta);
+ }
+ }
+ }
+ if !any {
+ return Err(bad("arrange.spacing", "pass horizontal or vertical spacing"));
+ }
+ let doc = s.doc_mut()?;
+ let mut moves = Vec::new();
+ for (id, (dx, dy)) in offsets {
+ let (Some(before), Some(now)) = (base.world_bounds(id), doc.world_bounds(id)) else { continue };
+ let (dx, dy) = (dx.map_or(0.0, |d| before.x0 + d - now.x0), dy.map_or(0.0, |d| before.y0 + d - now.y0));
+ if !dx.is_finite() || !dy.is_finite() {
+ return Err(bad("arrange.spacing", "non-finite spacing result"));
+ }
+ moves.push((id, dx, dy));
+ }
+ for (id, dx, dy) in moves {
+ move_world(doc, id, dx, dy)?;
+ }
ok()
}
diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs
index 0fb648167..bf99c5920 100644
--- a/crates/engine/src/cmd/component.rs
+++ b/crates/engine/src/cmd/component.rs
@@ -68,7 +68,7 @@ pub fn specs() -> Vec {
let cmd = "instance.create";
let c = req_id(cmd, p, "component")?;
let page = s.page()?;
- let parent = id(p, "parent").unwrap_or(page);
+ let parent = crate::params::opt_id(cmd, p, "parent")?.unwrap_or(page);
let doc = s.doc_mut()?;
let c = main_of(doc, c).ok_or_else(|| bad(cmd, "`component` must be a component or component set"))?;
let (x, y) = match (num(p, "x"), num(p, "y")) {
@@ -472,6 +472,7 @@ fn detach(s: &mut Session, p: &Value) -> Result {
// Own layers lose their link (slot content stays as it is); nested instances stay
// instances of their own mains.
let nested = unlink_layers(doc, i, Some(i));
+ keep_main_modes(doc, i)?;
let n = doc.get_mut(i)?;
n.kind = NodeKind::Frame;
n.source = None;
@@ -491,6 +492,19 @@ fn detach(s: &mut Session, p: &Value) -> Result {
Ok(json!({"ids": out}))
}
+/// Make the variable modes instance `i` takes from its main its own (it's being detached).
+fn keep_main_modes(doc: &mut Document, i: NodeId) -> Result<()> {
+ let modes = match doc.get(i)?.kind {
+ NodeKind::Instance { component, .. } => doc.node(component).map(|m| m.var_modes.clone()).unwrap_or_default(),
+ _ => return Ok(()),
+ };
+ let own = &mut doc.get_mut(i)?.var_modes;
+ for (c, m) in modes {
+ own.entry(c).or_insert(m);
+ }
+ Ok(())
+}
+
fn reset_instance(s: &mut Session, p: &Value) -> Result {
let cmd = "component.resetInstance";
let ids = req_targets(cmd, s, p)?;
@@ -608,7 +622,7 @@ fn make_slot(s: &mut Session, p: &Value) -> Result {
let owner = Owner::resolve(doc, id).ok_or_else(|| bad(cmd, "the frame isn't inside a component"))?;
let name = string(p, "name").unwrap_or_else(|| fresh_prop_name(doc, &owner, &n.name));
let preferred = get(p, "preferred").cloned().unwrap_or(Value::Null);
- add_prop(s, &json!({"id": id, "layer": id, "name": name, "type": "slot", "preferred": preferred}))
+ add_prop_for(cmd, s, &json!({"id": id, "layer": id, "name": name, "type": "slot", "preferred": preferred}))
}
fn remove_slot(s: &mut Session, p: &Value) -> Result {
@@ -678,8 +692,8 @@ fn push_changes(s: &mut Session, p: &Value) -> Result {
if !doc.contains(component) {
return Err(EngineError::Disabled(cmd.into(), "the main component was deleted (use component.restoreMain)".into()));
}
- // Copy every overridden layer's values to its source in the main (geometry, swaps, property
- // values and slot content stay with the instance).
+ // Copy every overridden layer's values to its source in the main (geometry, resizing, swaps,
+ // property values and slot content stay with the instance).
let mut pushed = 0;
for d in doc.subtree(inst) {
let Some(n) = doc.node(d).cloned() else { continue };
@@ -691,7 +705,7 @@ fn push_changes(s: &mut Session, p: &Value) -> Result {
let groups: BTreeSet = n
.overrides
.iter()
- .filter(|g| !matches!(g.as_str(), "size" | "position" | "component" | "props" | SLOT) && !(d == inst && g.as_str() == "name"))
+ .filter(|g| !(matches!(g.as_str(), "size" | "resizing" | "position" | "component" | "props" | SLOT) || d == inst && g.as_str() == "name"))
.cloned()
.collect();
for g in &groups {
@@ -1039,7 +1053,12 @@ fn valid_prop_name(cmd: &str, name: &str) -> Result {
}
fn add_prop(s: &mut Session, p: &Value) -> Result {
- let cmd = "component.addProperty";
+ add_prop_for("component.addProperty", s, p)
+}
+
+/// Add a component property for command `cmd`, which errors name (`component.makeSlot` adds its
+/// slot property here).
+fn add_prop_for(cmd: &str, s: &mut Session, p: &Value) -> Result {
let target = targets(s, p).first().copied().ok_or_else(|| bad(cmd, "select a component"))?;
let name = valid_prop_name(cmd, &req_string(cmd, p, "name")?)?;
let t = req_string(cmd, p, "type")?;
diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs
index 2150701a9..3a9f6d67f 100644
--- a/crates/engine/src/cmd/create.rs
+++ b/crates/engine/src/cmd/create.rs
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
use super::{CommandSpec, ok};
use crate::params::*;
-use crate::{EngineError, Result, Session, bad, spec};
+use crate::{Result, Session, bad, spec};
/// Frame presets shown by the Frame tool (category, name, width, height).
pub const FRAME_PRESETS: &[(&str, &str, f64, f64)] = &[
@@ -73,9 +73,13 @@ pub fn specs() -> Vec {
spec!("text.create", "Text", "{text, x, y, parent?, width? (fixed width wraps), props? (fontSize, fontFamily, …)}", true, |s, p| {
create_kind(s, p, "text")
}),
- spec!("vector.create", "Vector", "{path (SVG path data) | points [[x,y],..], closed?, x?, y?, parent?, props?}", true, |s, p| create_kind(
- s, p, "vector"
- )),
+ spec!(
+ "vector.create",
+ "Vector",
+ "{path (SVG path data) | points [[x,y],..], closed?, x?, y?, width?, height? (scale the path; one keeps its proportion), parent?, props?}",
+ true,
+ |s, p| create_kind(s, p, "vector")
+ ),
spec!(
"image.place",
"Place image",
@@ -162,12 +166,43 @@ pub fn parse_path_data(d: &str) -> Option {
figcraft_geom::BezPath::from_svg(d).ok()
}
+/// How much a vector's path is scaled to take the size asked for: with both sides, each scales
+/// independently (as resizing a vector does); with one, the other keeps its proportion. A size on
+/// an axis the geometry has none of is an error unless it is 0 (a line's height), and a size of 0
+/// or less on an axis it has is refused rather than flattening it.
+fn vector_scale(width: Option, height: Option, bw: f64, bh: f64, what: &str) -> std::result::Result<(f64, f64), String> {
+ let fit = |asked: Option, have: f64, axis: &str| match asked {
+ None => Ok(1.0),
+ Some(a) if have <= 1e-9 => {
+ if a == 0.0 {
+ Ok(1.0)
+ } else {
+ Err(format!("`{axis}` can't size {what} with no {} extent", if axis == "width" { "horizontal" } else { "vertical" }))
+ }
+ }
+ Some(a) if a > 0.0 && (a / have).is_finite() => Ok(a / have),
+ Some(_) => Err(format!("`{axis}` must be a positive, finite size: 0 or less would flatten {what}")),
+ };
+ Ok(match (width, height) {
+ (Some(_), Some(_)) => (fit(width, bw, "width")?, fit(height, bh, "height")?),
+ (Some(_), None) => {
+ let s = fit(width, bw, "width")?;
+ (s, s)
+ }
+ (None, Some(_)) => {
+ let s = fit(height, bh, "height")?;
+ (s, s)
+ }
+ (None, None) => (1.0, 1.0),
+ })
+}
+
pub fn create(s: &mut Session, p: &Value) -> Result {
let cmd = "node.create";
let t = string(p, "type").ok_or_else(|| bad(cmd, "`type` is required"))?;
let (mut kind, base) = kind_for(&t).ok_or_else(|| bad(cmd, format!("unknown type `{t}`")))?;
let page = s.page()?;
- let parent = id(p, "parent").unwrap_or(page);
+ let parent = crate::params::opt_id(cmd, p, "parent")?.unwrap_or(page);
let doc = s.doc()?;
let pn = doc.get(parent)?;
if !pn.kind.is_container() {
@@ -187,20 +222,32 @@ pub fn create(s: &mut Session, p: &Value) -> Result {
"Section" => (num_or(p, "width", 400.0), num_or(p, "height", 300.0)),
_ => (num_or(p, "width", 100.0), num_or(p, "height", 100.0)),
};
- // Vectors: path data or points define the shape and its box.
+ // Vectors: path data or points define the shape and its box. `width`/`height`, when asked
+ // for, scale the geometry: both sides independently, one side proportionally.
let mut offset = (0.0, 0.0);
+ let asked = (num(p, "width"), num(p, "height"));
if let NodeKind::Vector { network } = &mut kind {
if let Some(d) = string(p, "path") {
let mut path = parse_path_data(&d).ok_or_else(|| bad(cmd, "`path` is not valid SVG path data"))?;
use figcraft_geom::Shape;
let bb = path.bounding_box();
+ if bb.width() <= 1e-9 && bb.height() <= 1e-9 {
+ return Err(bad(cmd, "`path` draws nothing: a vector needs a visible line or area"));
+ }
path.apply_affine(figcraft_geom::Affine::translate((-bb.x0, -bb.y0)));
+ let (sx, sy) = vector_scale(asked.0, asked.1, bb.width(), bb.height(), "a path").map_err(|e| bad(cmd, e))?;
+ if sx != 1.0 || sy != 1.0 {
+ path.apply_affine(figcraft_geom::Affine::scale_non_uniform(sx, sy));
+ }
*network = VectorNetwork::from_path(&path);
+ if network.segments.is_empty() {
+ return Err(bad(cmd, "`path` draws nothing: a vector needs a visible line or area"));
+ }
if boolean(p, "closed") == Some(false) {
network.regions.clear();
}
- w = bb.width();
- h = bb.height();
+ w = bb.width() * sx;
+ h = bb.height() * sy;
offset = (bb.x0, bb.y0);
} else if let Some(Value::Array(pts)) = get(p, "points") {
let pts: Vec = pts.iter().filter_map(|v| Some(Point::new(f64_of(v.get(0)?)?, f64_of(v.get(1)?)?))).collect();
@@ -208,10 +255,14 @@ pub fn create(s: &mut Session, p: &Value) -> Result {
return Err(bad(cmd, "`points` needs at least two [x, y] pairs"));
}
let bb = figcraft_geom::points_bounds(pts.iter().copied()).unwrap_or_default();
- let local: Vec = pts.iter().map(|q| Point::new(q.x - bb.x0, q.y - bb.y0)).collect();
+ if bb.width() <= 1e-9 && bb.height() <= 1e-9 {
+ return Err(bad(cmd, "`points` draws nothing: a vector needs a visible line or area"));
+ }
+ let (sx, sy) = vector_scale(asked.0, asked.1, bb.width(), bb.height(), "a point set").map_err(|e| bad(cmd, e))?;
+ let local: Vec = pts.iter().map(|q| Point::new((q.x - bb.x0) * sx, (q.y - bb.y0) * sy)).collect();
*network = VectorNetwork::from_points(&local, boolean(p, "closed").unwrap_or(false));
- w = bb.width();
- h = bb.height();
+ w = bb.width() * sx;
+ h = bb.height() * sy;
offset = (bb.x0, bb.y0);
}
}
@@ -255,7 +306,7 @@ pub fn create(s: &mut Session, p: &Value) -> Result {
node.width = tw;
node.height = th;
}
- let index = num(p, "index").map(|i| i.max(0.0) as usize);
+ let index = crate::params::opt_index(cmd, p, "index")?;
doc.insert(node, parent, index)?;
if let Some(Value::Object(props)) = get(p, "props") {
super::props::apply(cmd, doc, nid, props)?;
@@ -313,12 +364,12 @@ fn free_spot(s: &Session, w: f64, h: f64) -> Result<(f64, f64)> {
#[cfg(not(target_arch = "wasm32"))]
fn read_path(path: &str) -> Result> {
- std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+ crate::file_access::read(path)
}
#[cfg(target_arch = "wasm32")]
fn read_path(path: &str) -> Result> {
- Err(EngineError::Other(format!("{path}: files can't be read in the browser")))
+ Err(crate::EngineError::Other(format!("{path}: files can't be read in the browser")))
}
/// Place an image as a rectangle with an image fill (Figma's image layer).
@@ -340,7 +391,7 @@ pub fn place_image(s: &mut Session, p: &Value) -> Result {
_ => ImageScaleMode::Fill,
};
let page = s.page()?;
- let parent = id(p, "parent").unwrap_or(page);
+ let parent = crate::params::opt_id(cmd, p, "parent")?.unwrap_or(page);
let ds = s.ds_mut()?;
let doc = ds.doc_mut();
let (hash, iw, ih) = figcraft_format::add_image(doc, bytes).map_err(|e| bad(cmd, e.to_string()))?;
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index 2c767b933..a16fbb386 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -18,13 +18,26 @@ pub fn specs() -> Vec {
spec!(
"edit.duplicate",
"Duplicate",
- "{ids?, dx?, dy? (page offset; default: the offset of the last duplicate when ids are its copies, still selected; else top-level frames to the right with a 100 gap, everything else in place)}",
+ "{ids?, dx?, dy? (page offset; default: the offset of the last duplicate when ids are its copies, still selected; else top-level frames to the right with a 100 gap, everything else in place)} a main component's copy is an instance of it (a variant stays a new variant in its set)",
true,
duplicate
),
spec!("edit.copy", "Copy", "{ids?}", false, copy),
spec!("edit.cut", "Cut", "{ids?}", true, cut),
- spec!("edit.paste", "Paste", "{parent?, x?, y? (page coordinates of the pasted top-left)}", true, paste),
+ spec!(
+ "edit.paste",
+ "Paste",
+ "{parent?, x?, y? (page coordinates of the pasted top-left)} a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
+ true,
+ paste
+ ),
+ spec!(
+ "edit.pasteDesignLayers",
+ "Paste design layers",
+ "{html (the clipboard's HTML) | data (base64 of the clipboard's design data, at most 256 MB), parent?, x?, y?} layers copied from another design app (a .fig canvas in the clipboard's HTML), read like a .fig file (best effort, with `warnings`), pasted as edit.paste pastes",
+ true,
+ paste_design_layers
+ ),
spec!("edit.pasteOver", "Paste over selection", "{}", true, paste_over),
spec!("edit.pasteReplace", "Paste to replace", "{ids?}", true, paste_replace),
spec!("edit.copyProperties", "Copy properties", "{id?}", false, copy_props),
@@ -254,7 +267,7 @@ pub fn specs() -> Vec {
}),
spec!("effect.set", "Set effect", "{ids?, index, effect {..}}", true, |s, p| {
let i = req_index("effect.set", p, "index")?;
- let e: Effect = parse("effect.set", p, "effect")?.ok_or_else(|| bad("effect.set", "`effect` required"))?;
+ let e = super::props::effect_from("effect.set", p, "effect")?.ok_or_else(|| bad("effect.set", "`effect` required"))?;
for id in req_targets("effect.set", s, p)? {
let n = s.doc_mut()?.get_mut(id)?;
if let Some(slot) = n.effects.get_mut(i) {
@@ -459,7 +472,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result {
let top_frame = doc.node(parent).is_some_and(Node::is_page) && n.kind.is_frame_like();
let idx = doc.index_in_parent(i).map(|x| x + 1);
let w = n.width;
- let nid = doc.duplicate_into(i, parent, idx)?;
+ let nid = crate::components::copy_in_file(doc, i, parent, idx)?;
let (dx, dy) = match (num(p, "dx"), num(p, "dy")) {
(Some(dx), dy) => (dx, dy.unwrap_or(0.0)),
(None, Some(dy)) => (0.0, dy),
@@ -474,7 +487,8 @@ fn duplicate(s: &mut Session, p: &Value) -> Result {
nn.transform = Affine::translate((dx, dy)) * nn.transform;
}
}
- if rename {
+ // An instance keeps the name instances get by default.
+ if rename && !matches!(doc.get(nid)?.kind, NodeKind::Instance { .. }) {
let nn = doc.get_mut(nid)?;
nn.name = bump_name(&nn.name);
}
@@ -496,9 +510,34 @@ fn bump_name(n: &str) -> String {
}
/// The copied form of the selection.
-pub fn copy_to_clipboard(s: &mut Session, ids: &[NodeId]) -> Result<()> {
+pub fn copy_to_clipboard(s: &mut Session, cmd: &str, ids: &[NodeId]) -> Result<()> {
let ds = s.ds()?;
- let doc = &ds.doc;
+ // Pages are not layers: they can't be pasted anywhere.
+ let layers: Vec = ids.iter().copied().filter(|i| !ds.doc.node(*i).is_some_and(Node::is_page)).collect();
+ if layers.is_empty() && !ids.is_empty() {
+ return Err(EngineError::Disabled(cmd.into(), "pages can't be copied; use page.duplicate".into()));
+ }
+ let (nodes, images, bounds) = copied(&ds.doc, &layers);
+ let (source, source_path, uid) = (ds.doc.clone(), ds.path.clone(), ds.uid);
+ s.clipboard.source = Some(source);
+ s.clipboard.source_path = source_path;
+ s.clipboard.source_doc = uid;
+ s.clipboard.copied_components = nodes
+ .iter()
+ .filter(|(_, sub)| {
+ cmd == "edit.copy" && sub.first().is_some_and(|n| matches!(n.kind, NodeKind::Component { .. } | NodeKind::ComponentSet { .. }))
+ })
+ .map(|(root, _)| *root)
+ .collect();
+ s.clipboard.nodes = nodes;
+ s.clipboard.images = images;
+ s.clipboard.bounds = bounds;
+ Ok(())
+}
+
+type Copied = (Vec<(NodeId, Vec)>, BTreeMap, Option);
+
+fn copied(doc: &Document, ids: &[NodeId]) -> Copied {
let ids = z_sorted(doc, &roots(doc, ids));
let mut nodes = Vec::new();
let mut images = BTreeMap::new();
@@ -521,28 +560,74 @@ pub fn copy_to_clipboard(s: &mut Session, ids: &[NodeId]) -> Result<()> {
nodes.push((*i, sub));
}
let bounds = doc.bounds_of(&ids);
- let uid = ds.uid;
- let source = Some(ds.doc.clone());
- let source_path = ds.path.clone();
- s.clipboard.source = source;
- s.clipboard.source_path = source_path;
- s.clipboard.nodes = nodes;
- s.clipboard.images = images;
- s.clipboard.bounds = bounds;
- s.clipboard.source_doc = uid;
- Ok(())
+ (nodes, images, bounds)
+}
+
+/// The markers around the copied layers in the clipboard's HTML, spelt as that format spells them.
+pub const CLIP_OPEN: &str = "(figma)";
+pub const CLIP_CLOSE: &str = "(/figma)";
+/// Largest design data read from the clipboard: the `.fig` import's own canvas cap (256 MB). Its
+/// base64 is checked first, so neither the text nor the decoded bytes can pass it.
+const MAX_CLIP_DATA: usize = 256 * 1024 * 1024;
+const MAX_CLIP_BASE64: usize = MAX_CLIP_DATA.div_ceil(3) * 4;
+
+/// Base64 `text` (whitespace ignored, padding optional) when it fits [`MAX_CLIP_DATA`].
+fn clip_base64(text: &str) -> Option> {
+ use base64::Engine as _;
+ if text.bytes().filter(|b| !b.is_ascii_whitespace()).count() > MAX_CLIP_BASE64 {
+ return None;
+ }
+ let b64: String = text.chars().filter(|c| !c.is_ascii_whitespace()).collect();
+ base64::engine::general_purpose::STANDARD.decode(&b64).or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&b64)).ok()
+}
+
+/// Layers copied from another design app travel in the clipboard's HTML as a `.fig` canvas in
+/// base64 between [`CLIP_OPEN`] and [`CLIP_CLOSE`]. This gives those bytes, or `None` when the HTML
+/// holds no readable design data (it may just mention the marker).
+pub fn design_clipboard_buffer(html: &str) -> Option> {
+ let start = html.find(CLIP_OPEN)? + CLIP_OPEN.len();
+ let len = html.get(start..)?.find(CLIP_CLOSE)?;
+ let bytes = clip_base64(html.get(start..start + len)?)?;
+ figcraft_format::fig::is_fig(&bytes).then_some(bytes)
+}
+
+fn paste_design_layers(s: &mut Session, p: &Value) -> Result {
+ const CMD: &str = "edit.pasteDesignLayers";
+ let bytes = match (string(p, "html"), string(p, "data")) {
+ (Some(html), _) => design_clipboard_buffer(&html).ok_or_else(|| bad(CMD, "the HTML holds no copied design layers"))?,
+ (None, Some(d)) => clip_base64(&d).ok_or_else(|| bad(CMD, "`data` is not base64 of at most 256 MB"))?,
+ (None, None) => return Err(bad(CMD, "pass `html` or `data`")),
+ };
+ let other = super::file::load_fig(&bytes, "Pasted layers").ok_or_else(|| bad(CMD, "the data is not copied design layers"))??;
+ let doc = std::sync::Arc::new(other.doc);
+ let tops: Vec = doc.pages.iter().filter_map(|pg| doc.node(*pg)).flat_map(|pg| pg.children.iter().copied()).collect();
+ if tops.is_empty() {
+ return Err(EngineError::Disabled(CMD.into(), "the copied layers came in empty".into()));
+ }
+ let (nodes, images, bounds) = copied(&doc, &tops);
+ let props = s.clipboard.props.take();
+ // No open file has id 0. So paste treats this copy as a copy from a different file.
+ s.clipboard =
+ crate::Clipboard { nodes, images, props, bounds, source_doc: 0, source: Some(doc), source_path: None, copied_components: BTreeSet::new() };
+ let mut out = paste(s, p)?;
+ if !other.issues.is_empty() {
+ out["warnings"] = json!(other.issues);
+ }
+ Ok(out)
}
fn copy(s: &mut Session, p: &Value) -> Result {
let ids = req_targets("edit.copy", s, p)?;
- copy_to_clipboard(s, &ids)?;
+ copy_to_clipboard(s, "edit.copy", &ids)?;
Ok(json!({"copied": s.clipboard.nodes.len()}))
}
fn cut(s: &mut Session, p: &Value) -> Result {
let ids = req_targets("edit.cut", s, p)?;
- copy_to_clipboard(s, &ids)?;
- delete(s, &json!({"ids": ids}))
+ copy_to_clipboard(s, "edit.cut", &ids)?;
+ let doc = s.doc()?;
+ let layers: Vec = ids.into_iter().filter(|i| !doc.node(*i).is_some_and(Node::is_page)).collect();
+ delete(s, &json!({"ids": layers}))
}
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords).
@@ -553,6 +638,7 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
}
// From another file: its instances follow the mains this file can have.
let foreign = clip.source.as_ref().filter(|_| s.ds().is_ok_and(|d| d.uid != clip.source_doc));
+ let copy_local = s.ds()?.uid == clip.source_doc;
let doc = s.doc_mut()?;
for (k, v) in &clip.images {
doc.images.entry(k.clone()).or_insert_with(|| v.clone());
@@ -566,6 +652,16 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
let mut out = Vec::new();
let mut all = BTreeMap::new();
for (root, nodes) in &clip.nodes {
+ if copy_local
+ && clip.copied_components.contains(root)
+ && let Some(n) = nodes.first().filter(|n| matches!(n.kind, NodeKind::Component { .. }))
+ && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))
+ {
+ let instance = crate::components::create_instance(doc, *root, parent, 0.0, 0.0)?;
+ doc.get_mut(instance)?.transform = doc.world_transform(parent).inverse() * shift * n.transform;
+ out.push(instance);
+ continue;
+ }
let mut map = BTreeMap::new();
for n in nodes {
map.insert(n.id, doc.alloc_id());
@@ -591,10 +687,12 @@ fn paste(s: &mut Session, p: &Value) -> Result {
// else in the frame's centre; otherwise in place on the page (or the viewport centre).
let sel = s.selection();
let doc = s.doc()?;
+ let copy_local = s.ds()?.uid == s.clipboard.source_doc;
let target = id(p, "parent").or_else(|| {
sel.first()
.copied()
.filter(|i| sel.len() == 1 && doc.node(*i).is_some_and(|n| n.kind.is_frame_like() && !matches!(n.kind, NodeKind::Instance { .. })))
+ .filter(|i| !copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, *i)))
});
let parent = target.unwrap_or(page);
let at = match (num(p, "x"), num(p, "y")) {
@@ -861,9 +959,13 @@ pub fn opacity_from_digits(digits: &str) -> Option {
fn opacity_keys(s: &mut Session, p: &Value) -> Result {
let digits = req_string("object.opacityKeys", p, "digits")?;
let o = opacity_from_digits(&digits).ok_or_else(|| bad("object.opacityKeys", "`digits` must be one or two digits"))?;
- for i in req_targets("object.opacityKeys", s, p)? {
- s.doc_mut()?.get_mut(i)?.opacity = o;
+ let ids = req_targets("object.opacityKeys", s, p)?;
+ let doc = s.doc_mut()?;
+ let before = super::styles::bound_before(doc, &ids);
+ for i in ids {
+ doc.get_mut(i)?.opacity = o;
}
+ super::styles::detach_edited(doc, &before);
Ok(json!({"opacity": o}))
}
@@ -1086,10 +1188,37 @@ fn set(s: &mut Session, p: &Value) -> Result {
.collect(),
None => Vec::new(),
};
- let doc = s.doc_mut()?;
- for i in ids {
- super::props::apply("node.set", doc, i, &props)?;
+ let mut warnings = font_style_warnings(&s.ds()?.doc, &ids, &props);
+ // Auto layout keys go to the layers that can have auto layout; with none among the targets,
+ // the first refuses them (`props::layout_mut`).
+ let layout_keys: Vec<&str> = props.keys().map(String::as_str).filter(|k| super::props::LAYOUT_KEYS.contains(k)).collect();
+ let mut without_layout = props.clone();
+ let mut skipped = BTreeSet::new();
+ if !layout_keys.is_empty() {
+ let doc = &s.ds()?.doc;
+ let frame_like = |i: &NodeId| doc.node(*i).is_some_and(|n| n.kind.is_frame_like());
+ if ids.iter().any(frame_like) {
+ skipped = ids.iter().copied().filter(|i| !frame_like(i)).collect();
+ without_layout.retain(|k, _| !layout_keys.contains(&k.as_str()));
+ }
+ if !skipped.is_empty() {
+ let names: Vec =
+ skipped.iter().take(10).filter_map(|i| doc.node(*i)).map(|n| format!("{} “{}” ({})", n.id, n.name, n.kind.type_name())).collect();
+ let more = if skipped.len() > names.len() { format!(" and {} more", skipped.len() - names.len()) } else { String::new() };
+ warnings.push(format!(
+ "{} skipped on {}{more}: only frames, components and instances have auto layout",
+ layout_keys.iter().map(|k| format!("`{k}`")).collect::>().join(", "),
+ names.join(", ")
+ ));
+ }
}
+ let doc = s.doc_mut()?;
+ let before = super::styles::bound_before(doc, &ids);
+ for i in ids {
+ let props = if skipped.contains(&i) { &without_layout } else { &props };
+ super::props::apply("node.set", doc, i, props)?;
+ }
+ super::styles::detach_edited(doc, &before);
if let Some(o) = pivot {
for (i, q) in pinned {
let d = o - doc.world_transform(i) * q;
@@ -1098,7 +1227,43 @@ fn set(s: &mut Session, p: &Value) -> Result {
}
}
}
- ok()
+ if warnings.is_empty() { ok() } else { Ok(json!({"ok": true, "warnings": warnings})) }
+}
+
+/// A `fontStyle` draws in the family's face nearest to it, as a text layer resolves it. When that
+/// face has another weight or slant than the name asks for ("Black" on a family whose heaviest is
+/// Bold), say which face it is. Families that aren't installed, and names that match a style or a
+/// named instance (spelled any way: "SemiBold", "Semi Bold"), say nothing.
+fn font_style_warnings(doc: &figcraft_doc::Document, ids: &[NodeId], props: &serde_json::Map) -> Vec {
+ let Some(style) = props.get("fontStyle").and_then(Value::as_str) else { return Vec::new() };
+ let mut families: Vec = match props.get("fontFamily").and_then(Value::as_str) {
+ Some(f) => vec![f.to_string()],
+ None => ids
+ .iter()
+ .filter_map(|i| doc.node(*i))
+ .filter_map(|n| n.kind.text())
+ .flat_map(|t| t.spans().into_iter().map(|(_, _, st)| st.font_family.clone()).collect::>())
+ .collect(),
+ };
+ families.sort();
+ families.dedup();
+ let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], "");
+ let (want_w, want_i) = (i32::from(figcraft_doc::style_weight(style)), style.to_lowercase().contains("italic"));
+ families
+ .into_iter()
+ .filter_map(|family| {
+ let styles = figcraft_text::family_styles(&family);
+ if styles.is_empty() || styles.iter().any(|x| norm(x) == norm(style)) {
+ return None;
+ }
+ let face = figcraft_text::find_face(&family, style).filter(|f| f.family.eq_ignore_ascii_case(&family))?;
+ let w = face.axis("wght").map_or(i32::from(face.weight), |a| a.clamp(f64::from(want_w)).round() as i32);
+ if face.instance(style).is_some() || (w == want_w && face.italic == want_i) {
+ return None;
+ }
+ Some(format!("{family} has no `{style}` style: it draws in {}, the nearest (it has: {})", face.style, styles.join(", ")))
+ })
+ .collect()
}
/// `stroke.widthProfile`: a preset or points (through `node.set`'s `widthProfile`, so instances
@@ -1177,7 +1342,7 @@ fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> Result Result {
let cmd = if fills { "fill.set" } else { "stroke.set" };
let ids = req_targets(cmd, s, p)?;
- let idx = num(p, "index").map(|x| x.max(0.0) as usize);
+ let idx = opt_index(cmd, p, "index")?;
let new_paint = match get(p, "paint") {
Some(v) => Some(paint_of(v).ok_or_else(|| bad(cmd, "invalid paint"))?),
None => None,
@@ -1211,7 +1376,7 @@ fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result {
if let Some(b) = blend(p, "blend") {
slot.blend = b;
}
- super::lists::remap_stop_bindings(n, fills, at, &old);
+ super::lists::rebind_edited_paint(n, fills, at, &old);
if fills {
n.styles.fill = None;
} else {
@@ -1225,7 +1390,7 @@ fn pattern_fill(s: &mut Session, p: &Value) -> Result {
const CMD: &str = "fill.pattern";
let src = req_id(CMD, p, "source")?;
let doc = s.doc()?;
- if !doc.node(src).is_some_and(|n| !n.is_page()) {
+ if doc.node(src).is_none_or(|n| n.is_page()) {
return Err(bad(CMD, "`source` must be a layer"));
}
if req_targets(CMD, s, p)?.iter().any(|t| doc.is_ancestor(*t, src)) {
@@ -1245,8 +1410,8 @@ fn pattern_fill(s: &mut Session, p: &Value) -> Result {
}
fn effect_add(s: &mut Session, p: &Value) -> Result {
- let e: Effect = match get(p, "effect") {
- Some(v) => serde_json::from_value(v.clone()).map_err(|e| bad("effect.add", e.to_string()))?,
+ let e: Effect = match super::props::effect_from("effect.add", p, "effect")? {
+ Some(e) => e,
None => {
let ty = string(p, "type").unwrap_or_else(|| "dropShadow".into());
Effect::of_type(&ty).ok_or_else(|| bad("effect.add", format!("unknown effect type `{ty}`")))?
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 5e27c5726..8e59b3031 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -30,7 +30,7 @@ pub fn specs() -> Vec {
spec!(
"file.open",
"Open",
- "{path | data (base64) + name (tells the format; opens as a new unsaved document), variables? (REST: the local variables JSON as an object, JSON text or a path; default `.variables.json` or `variables.json` next to the file)} (.figcraft, .json: FigCraft or REST API file JSON, .fig (best effort), .svg, .png, .jpg …); REST and .fig imports return `warnings`",
+ "{path | data (base64) + name (tells the format; opens as a new unsaved document), variables? (REST: the local variables JSON as an object, JSON text or a path; default `.variables.json` or `variables.json` next to the file)} (.figcraft, .json: FigCraft or REST API file JSON, .fig (best effort), .svg, .png, .jpg …); REST and .fig imports return `warnings`; a file opened anew returns `summary` {name, pages, layers, images} (one that was already open just returns its `index`)",
false,
open
),
@@ -41,8 +41,20 @@ pub fn specs() -> Vec {
false,
open_recent
),
- spec!("file.save", "Save", "{path?} (programmatic saves need a path the first time)", false, save),
- spec!("file.saveAs", "Save as", "{path}", false, save_as),
+ spec!(
+ "file.save",
+ "Save",
+ "{path?} (programmatic saves need a path the first time); a .fig path writes an experimental export copy of the shown document with `warnings`, keeping the native path, unsaved changes and version preview",
+ false,
+ save
+ ),
+ spec!(
+ "file.saveAs",
+ "Save as",
+ "{path} (no extension adds .figcraft); a .fig path writes an experimental export copy of the shown document with `warnings`, keeping the native path, unsaved changes and version preview",
+ false,
+ save_as
+ ),
spec!(
"file.export",
"Export",
@@ -74,12 +86,26 @@ pub fn specs() -> Vec {
spec!(
"file.import",
"Import",
- "{path | data (base64) + name, x?, y?, center? (SVG: centre it on x, y), variables? (REST: the local variables JSON as an object, JSON text or a path)} SVG becomes an editable frame (shapes, text, gradients, masks, effects; with `warnings` for what it left out), images become image layers, .figcraft, REST API file JSON and .fig pages are appended with their variables and flows (REST and .fig: with `warnings`)",
+ "{path | data (base64) + name, x?, y?, center? (SVG: centre it on x, y), variables? (REST: the local variables JSON as an object, JSON text or a path)} SVG becomes an editable frame (shapes, text, gradients, masks, effects; with `warnings` for what it left out), images become image layers, .figcraft, REST API file JSON and .fig pages are appended with their variables and flows (REST and .fig: with `warnings`; those return `summary` {name, pages, layers, images} of the file read)",
true,
import
),
spec!("file.placeImage", "Place image", "{path | data, x?, y?}", true, super::create::place_image),
spec!("file.close", "Close tab", "{index?, force? (discard unsaved changes)}", false, close),
+ spec!("file.moveTab", "Move tab", "{from, to} (indices among open documents)", false, |s, p| {
+ let from = req_index("file.moveTab", p, "from")?;
+ let to = req_index("file.moveTab", p, "to")?;
+ if from >= s.docs.len() || to >= s.docs.len() {
+ return Err(bad("file.moveTab", "no such document"));
+ }
+ if from != to {
+ let active_uid = s.docs.get(s.active).map(|d| d.uid);
+ let doc = s.docs.remove(from);
+ s.docs.insert(to, doc);
+ s.active = active_uid.and_then(|uid| s.docs.iter().position(|d| d.uid == uid)).unwrap_or(0);
+ }
+ Ok(json!({"index": to}))
+ }),
spec!(
"file.recover",
"Recover file",
@@ -423,7 +449,7 @@ pub(crate) fn recovered(path: &str) -> Result {
#[cfg(not(target_arch = "wasm32"))]
fn read(path: &str) -> Result> {
- std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+ crate::file_access::read(path)
}
#[cfg(target_arch = "wasm32")]
@@ -433,11 +459,7 @@ fn read(path: &str) -> Result> {
/// The bytes of file `path`, refused when it's larger than `max`.
pub(crate) fn read_capped(path: &str, max: u64) -> Result> {
- let meta = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- if !meta.is_file() || meta.len() > max {
- return Err(EngineError::Other(format!("{path}: not a file of at most {max} bytes")));
- }
- read(path)
+ crate::file_access::read_capped(path, max)
}
/// Write `bytes` to `path` through a uniquely named, exclusively created staging file and one
@@ -445,7 +467,7 @@ pub(crate) fn read_capped(path: &str, max: u64) -> Result> {
/// truncates `path`, and no file or symlink at a staging name is ever written through.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn write(path: &str, bytes: &[u8]) -> Result<()> {
- figcraft_format::write_file_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+ crate::file_access::write(path, bytes)
}
#[cfg(target_arch = "wasm32")]
@@ -461,6 +483,11 @@ fn file_stem(path: &str) -> String {
std::path::Path::new(path).file_stem().and_then(|e| e.to_str()).unwrap_or("Untitled").to_string()
}
+/// The counts the import report shows for a freshly loaded document.
+fn import_summary(doc: &Document) -> Value {
+ json!({"name": doc.name, "pages": doc.pages.len(), "layers": doc.nodes().filter(|n| !n.is_page()).count(), "images": doc.images.len()})
+}
+
/// Load a document from any supported file (REST API file JSON images come from an `images`
/// folder next to the file).
pub fn load(path: &str) -> Result<(Document, Vec)> {
@@ -506,10 +533,8 @@ fn load_with(
Ok((doc.into(), false))
}
_ => {
- if let Some(r) = figcraft_format::fig::try_import(bytes, &file_stem(name_hint)) {
- let (mut doc, warnings) = r.map_err(|e| EngineError::Other(e.to_string()))?;
- link_instances(&mut doc);
- return Ok((figcraft_format::Loaded { issues: warnings, ..doc.into() }, true));
+ if let Some(r) = load_fig(bytes, &file_stem(name_hint)) {
+ return Ok((r?, true));
}
if let Some(r) = figcraft_format::rest::try_import_with(bytes, variables, images) {
let (mut doc, warnings) = r.map_err(|e| EngineError::Other(e.to_string()))?;
@@ -525,10 +550,21 @@ fn load_with(
}
}
+/// Gives `None` when `bytes` are not a `.fig` file. Then other readers can try.
+pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option> {
+ let r = figcraft_format::fig::try_import(bytes, name)?;
+ Some(r.map_err(|e| EngineError::Other(e.to_string())).map(|(mut doc, warnings)| {
+ link_instances(&mut doc);
+ figcraft_format::Loaded { issues: warnings, ..doc.into() }
+ }))
+}
+
/// Link imported instances to their mains (layer sources, overrides found by comparing values),
/// innermost first so outer instances settle last.
fn link_instances(doc: &mut Document) {
+ super::styles::unfold_imported_bound_alpha(doc);
crate::style_vars::after_load(doc);
+ super::styles::apply_paint_bindings_on_load(doc);
let mut insts: Vec<(usize, NodeId)> =
doc.nodes().filter(|n| matches!(n.kind, NodeKind::Instance { .. })).map(|n| (doc.ancestors(n.id).len(), n.id)).collect();
insts.sort_by_key(|a| std::cmp::Reverse(a.0));
@@ -552,11 +588,9 @@ fn rest_images(path: &str) -> impl Fn(&str) -> Option> {
return None;
}
let dir = dir.as_ref()?;
- ["", ".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().find_map(|e| {
- let p = dir.join(format!("{r}{e}"));
- let meta = std::fs::metadata(&p).ok()?;
- if meta.is_file() && meta.len() <= MAX_IMAGE_FILE { std::fs::read(&p).ok() } else { None }
- })
+ ["", ".png", ".jpg", ".jpeg", ".gif", ".webp"]
+ .iter()
+ .find_map(|e| crate::file_access::read_capped(dir.join(format!("{r}{e}")), MAX_IMAGE_FILE).ok())
}
}
@@ -579,11 +613,7 @@ fn sibling_variables(path: &str) -> Option {
let file = std::path::Path::new(path);
let dir = file.parent()?;
[format!("{}.variables.json", file_stem(path)), "variables.json".to_string()].iter().map(|n| dir.join(n)).filter(|c| c != file).find_map(|c| {
- let meta = std::fs::metadata(&c).ok()?;
- if !meta.is_file() || meta.len() > MAX_VARIABLES_FILE {
- return None;
- }
- let v: Value = serde_json::from_slice(&std::fs::read(&c).ok()?).ok()?;
+ let v: Value = serde_json::from_slice(&crate::file_access::read_capped(c, MAX_VARIABLES_FILE).ok()?).ok()?;
figcraft_format::rest::is_variables_json(&v).then_some(v)
})
}
@@ -621,20 +651,29 @@ fn remember(s: &mut Session, path: &str) {
}
fn open_recent(s: &mut Session, p: &Value) -> Result {
+ use crate::file_access::{Access, allow, allowed};
const CMD: &str = "file.openRecent";
+ // Confined to automation roots, the recent files outside them are never listed, opened, removed
+ // or named: `index` counts the files listed.
+ let listed = |r: &String| allowed(r, Access::Read);
if p.get("clear").and_then(Value::as_bool) == Some(true) {
- s.prefs.recent_files.clear();
+ s.prefs.recent_files.retain(|r| !listed(r));
}
if let Some(gone) = string(p, "remove") {
- s.prefs.recent_files.retain(|r| *r != gone);
+ s.prefs.recent_files.retain(|r| *r != gone || !listed(r));
}
let path = match (string(p, "path"), num(p, "index")) {
- (Some(path), _) => Some(path),
- (None, Some(i)) => Some(s.prefs.recent_files.get(i.max(0.0) as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?),
+ (Some(path), _) => {
+ allow(&path, Access::Read)?;
+ Some(path)
+ }
+ (None, Some(i)) => {
+ Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i.max(0.0) as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
+ }
_ => None,
};
if let Some(path) = path {
- if !std::path::Path::new(&path).exists() {
+ if !crate::file_access::exists(&path) {
s.prefs.recent_files.retain(|r| *r != path);
return Err(bad(CMD, format!("{path} no longer exists")));
}
@@ -644,9 +683,10 @@ fn open_recent(s: &mut Session, p: &Value) -> Result {
.prefs
.recent_files
.iter()
+ .filter(|r| listed(r))
.map(|r| {
let name = std::path::Path::new(r).file_name().map_or_else(|| r.clone(), |f| f.to_string_lossy().into_owned());
- json!({"path": r, "name": name, "exists": std::path::Path::new(r).exists()})
+ json!({"path": r, "name": name, "exists": crate::file_access::exists(r)})
})
.collect();
Ok(json!({"files": files}))
@@ -677,9 +717,10 @@ fn open(s: &mut Session, p: &Value) -> Result {
more => format!("{}: {} problems were repaired or left out while opening it, e.g. {}", file_stem(&path), more.len(), more[0]),
});
}
+ let summary = import_summary(&loaded.doc);
s.docs.push(DocState::new(loaded.doc, native.then_some(path)).with_versions(loaded.versions).with_branches(loaded.branches));
s.active = s.docs.len() - 1;
- let mut out = json!({"index": s.active});
+ let mut out = json!({"index": s.active, "summary": summary});
out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues);
Ok(out)
}
@@ -692,9 +733,10 @@ fn open_data(s: &mut Session, data: &str, p: &Value, variables: Option<&Value>)
let bytes = base64::engine::general_purpose::STANDARD.decode(data.trim()).map_err(|e| bad("file.open", e.to_string()))?;
let (loaded, rest) = load_with(&bytes, &name, variables, &figcraft_format::rest::no_images)?;
let warnings = rest || ext(&name) == "svg";
+ let summary = import_summary(&loaded.doc);
s.docs.push(DocState::new(loaded.doc, None).with_versions(loaded.versions).with_branches(loaded.branches));
s.active = s.docs.len() - 1;
- let mut out = json!({"index": s.active});
+ let mut out = json!({"index": s.active, "summary": summary});
out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues);
Ok(out)
}
@@ -795,8 +837,20 @@ fn color_profile(s: &mut Session, p: &Value) -> Result {
Ok(json!({"profile": profile.id(), "changed": changed}))
}
-/// Save the file of the active tab (the main file for a branch tab, with its branches).
+/// Native saves act on the current document; a `.fig` copy exports the version shown, and a
+/// pending Save As choice must leave it shown until its destination is known.
+pub(crate) fn save_ends_preview(s: &Session, cmd: &str, p: &Value) -> bool {
+ let path =
+ string(p, "path").or_else(|| if cmd == "file.save" { s.docs.get(crate::branches::file_tab(s)).and_then(|ds| ds.path.clone()) } else { None });
+ path.is_some_and(|path| ext(&path) != "fig")
+}
+
+/// Save the file of the active tab (the main file for a branch tab, with its branches), or export
+/// the active document as an experimental `.fig` copy without changing its native save state.
fn save_to(s: &mut Session, path: String) -> Result {
+ if ext(&path) == "fig" {
+ return export_fig(s, &json!({"path": path}));
+ }
let i = crate::branches::file_tab(s);
let ds = s.docs.get_mut(i).ok_or(EngineError::NoDocument)?;
let bytes = file_bytes(ds)?;
@@ -815,6 +869,11 @@ fn save(s: &mut Session, p: &Value) -> Result {
return save_to(s, path);
}
match s.docs.get(crate::branches::file_tab(s)).ok_or(EngineError::NoDocument)?.path.clone() {
+ // Earlier builds wrote native data under a .fig name: never overwrite that file with an export.
+ Some(path) if ext(&path) == "fig" => {
+ s.request_ui("dialog.saveAs", json!({}));
+ Err(EngineError::Disabled("file.save".into(), "the saved path ends in .fig: choose Save as or pass `path`".into()))
+ }
Some(path) => save_to(s, path),
None => {
s.request_ui("dialog.saveAs", json!({}));
@@ -1139,7 +1198,7 @@ fn export_layers(s: &mut Session, p: &Value) -> Result {
let path = std::path::Path::new(d).join(&job.file);
// A layer name with slashes exports into folders.
if let Some(parent) = path.parent() {
- let _ = std::fs::create_dir_all(parent);
+ let _ = crate::file_access::create_dir_all(parent);
}
let path = path.to_string_lossy().to_string();
write(&path, &bytes)?;
@@ -1235,8 +1294,9 @@ fn import(s: &mut Session, p: &Value) -> Result {
};
let sibling = if variables.is_none() { path.as_deref().and_then(sibling_variables) } else { None };
let (other, rest) = load_with(&bytes, &name, variables.as_ref().or(sibling.as_ref()), images)?;
+ let summary = import_summary(&other.doc);
let pages = append_pages(s.doc_mut()?, &other.doc)?;
- let mut out = json!({"pages": pages});
+ let mut out = json!({"pages": pages, "summary": summary});
if rest {
out["warnings"] = json!(other.issues);
}
@@ -1272,6 +1332,19 @@ fn append_pages(doc: &mut Document, other: &Document) -> Result> {
map.insert(id, doc.alloc_id());
}
}
+ // Library copies a .fig import keeps (cached definitions) have no library record to follow:
+ // the layers of its store come along into the store of `doc`. Recorded copies are left to
+ // `merge_store`, which shares them with copies `doc` already has.
+ let cached: Vec = other
+ .library_store()
+ .and_then(|s| other.node(s))
+ .map(|s| s.children.iter().copied().filter(|root| other.libraries.import_of(*root).is_none()).collect())
+ .unwrap_or_default();
+ for root in &cached {
+ for id in other.subtree(*root) {
+ map.insert(id, doc.alloc_id());
+ }
+ }
let mut new_pages = Vec::new();
for pg in &other.pages {
let Some(pn) = other.node(*pg) else { continue };
@@ -1289,6 +1362,13 @@ fn append_pages(doc: &mut Document, other: &Document) -> Result> {
}
new_pages.push(np);
}
+ if !cached.is_empty() {
+ let store = doc.ensure_library_store();
+ for root in &cached {
+ let nodes: Vec = other.subtree(*root).into_iter().filter_map(|i| other.node(i).cloned()).collect();
+ doc.paste_nodes(&nodes, &map, *root, store, None)?;
+ }
+ }
for new in map.values() {
let src = doc.node(*new).and_then(|n| n.source).and_then(|s| map.get(&s).copied());
if let (Some(src), Some(n)) = (src, doc.node_mut(*new)) {
@@ -1308,14 +1388,36 @@ fn close(s: &mut Session, p: &Value) -> Result {
return Err(EngineError::Disabled("file.close".into(), "the document has unsaved changes (pass force: true to discard)".into()));
}
let uid = ds.uid;
+ let active_uid = s.docs.get(s.active).map(|d| d.uid);
s.docs.remove(i);
- if s.active >= s.docs.len() {
- s.active = s.docs.len().saturating_sub(1);
- }
+ // Removing a tab before the active one shifts its index; keep the same document selected.
+ s.active = active_uid.and_then(|a| s.docs.iter().position(|d| d.uid == a)).unwrap_or(i.min(s.docs.len().saturating_sub(1)));
crate::branches::close_tabs(s, uid, None);
ok()
}
+#[cfg(test)]
+mod tab_order_tests {
+ use super::*;
+
+ #[test]
+ fn moving_and_closing_inactive_tabs_preserves_the_active_document() {
+ let mut session = Session::new();
+ for name in ["Two", "Three", "Four"] {
+ session.execute("file.new", &json!({"name": name})).unwrap();
+ }
+ session.execute("doc.switch", &json!({"index": 2})).unwrap();
+ let active_uid = session.docs[session.active].uid;
+ let moved_uid = session.docs[0].uid;
+ session.execute("file.moveTab", &json!({"from": 0, "to": 2})).unwrap();
+ assert_eq!(session.docs[2].uid, moved_uid);
+ assert_eq!(session.docs[session.active].uid, active_uid);
+ session.execute("file.close", &json!({"index": 0})).unwrap();
+ assert_eq!(session.docs[session.active].uid, active_uid);
+ assert!(session.execute("file.moveTab", &json!({"from": 0, "to": 99})).is_err());
+ }
+}
+
/// Ctrl+Tab / Ctrl+Shift+Tab: the next or previous open document, wrapping around.
fn cycle_doc(s: &mut Session, dir: i64) -> Result {
let n = s.docs.len() as i64;
@@ -1354,6 +1456,70 @@ mod rest_import_tests {
doc.nodes().find(|n| matches!(n.kind, NodeKind::Instance { .. })).unwrap()
}
+ /// What a .fig import with a cached library component leaves: the main in the hidden store, a
+ /// visible instance of it and a layer linked to the main's layer.
+ fn cached_import() -> Document {
+ let mut doc = Document::new("Cached");
+ let page = doc.first_page().unwrap();
+ let store = doc.ensure_library_store();
+ let main = doc
+ .create(store, NodeKind::Component { description: String::new(), props: Default::default() }, "Cached main", 0.0, 0.0, 20.0, 20.0)
+ .unwrap();
+ let body = doc.create(main, NodeKind::Rectangle, "Body", 0.0, 0.0, 20.0, 20.0).unwrap();
+ let inst =
+ doc.create(page, NodeKind::Instance { component: main, props: Default::default() }, "Cached instance", 0.0, 0.0, 20.0, 20.0).unwrap();
+ let mut copy = doc.node(body).unwrap().clone();
+ copy.id = doc.alloc_id();
+ copy.parent = None;
+ copy.source = Some(body);
+ let copy_id = copy.id;
+ doc.insert(copy, inst, None).unwrap();
+ assert!(doc.is_remote(main) && doc.node(copy_id).unwrap().source == Some(body));
+ doc
+ }
+
+ /// Pasting layers that use a cached main into another document leaves the main behind, as it
+ /// does for other mains that are not published: no link points at a layer of the target.
+ #[test]
+ fn pasting_instances_of_cached_components_leaves_no_dangling_links() {
+ let src = cached_import();
+ let mut doc = Document::new("Target");
+ let page = doc.first_page().unwrap();
+ for i in 0..8 {
+ doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 5.0, 5.0).unwrap();
+ }
+ let inst = src.nodes().find(|n| n.name == "Cached instance").unwrap().id;
+ let ids = src.subtree(inst);
+ let map: std::collections::BTreeMap = ids.iter().map(|i| (*i, doc.alloc_id())).collect();
+ let nodes: Vec = ids.iter().filter_map(|i| src.node(*i).cloned()).collect();
+ doc.paste_nodes(&nodes, &map, inst, page, None).unwrap();
+ crate::library::adopt_pasted(&mut doc, &src, None, &map).unwrap();
+ let pasted = doc.node(map[&inst]).unwrap();
+ let NodeKind::Instance { component, .. } = pasted.kind else { panic!() };
+ assert!(!doc.contains(component), "the main stays behind: {component:?}");
+ assert!(doc.node(pasted.children[0]).unwrap().source.is_none_or(|s| !doc.contains(s)));
+ }
+
+ #[test]
+ fn appending_pages_with_cached_library_components_brings_the_components() {
+ let other = cached_import();
+ let mut doc = Document::new("Target");
+ let page = doc.first_page().unwrap();
+ // Ids of the target that would collide with the other document's store.
+ for i in 0..8 {
+ doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 5.0, 5.0).unwrap();
+ }
+ append_pages(&mut doc, &other).unwrap();
+ assert!(doc.validate().is_empty(), "{:?}", doc.validate());
+ assert!(crate::components::mirror_issues(&doc).is_empty(), "{:?}", crate::components::mirror_issues(&doc));
+ let inst = doc.nodes().find(|n| n.name == "Cached instance").unwrap();
+ let NodeKind::Instance { component, .. } = inst.kind else { panic!() };
+ assert_eq!(doc.node(component).unwrap().name, "Cached main");
+ assert!(doc.is_remote(component), "the main comes along into the store");
+ let layer = doc.node(inst.children[0]).unwrap();
+ assert_eq!(layer.source, doc.node(component).unwrap().children.first().copied());
+ }
+
#[test]
fn rest_json_loads_with_linked_instances() {
let bytes = serde_json::to_vec(&kit()).unwrap();
diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs
index 5643ac706..da1301ec0 100644
--- a/crates/engine/src/cmd/layout.rs
+++ b/crates/engine/src/cmd/layout.rs
@@ -149,6 +149,35 @@ mod tests {
assert!(s.execute("node.set", &json!({"id": b, "props": {"absolute": "maybe"}})).is_err());
}
+ /// Each side key writes its own padding slot and leaves the other three alone.
+ #[test]
+ fn each_side_padding_sets_its_side_alone() {
+ let mut s = Session::new();
+ let (f, _, _) = al_frame(&mut s);
+ // One side at a time: the other three stay 0 ([top, right, bottom, left]).
+ for (key, v, want) in [
+ ("paddingTop", 8.0, [8.0, 0.0, 0.0, 0.0]),
+ ("paddingRight", 12.0, [0.0, 12.0, 0.0, 0.0]),
+ ("paddingBottom", 16.0, [0.0, 0.0, 16.0, 0.0]),
+ ("paddingLeft", 20.0, [0.0, 0.0, 0.0, 20.0]),
+ ] {
+ ex(&mut s, "node.set", json!({"id": f, "props": {"padding": 0}}));
+ ex(&mut s, "node.set", json!({"id": f, "props": {key: v}}));
+ assert_eq!(node(&s, f).layout.as_ref().unwrap().padding, want, "{key}");
+ }
+ // The [t, r, b, l] array and the axis pairs agree with the four sides.
+ ex(&mut s, "node.set", json!({"id": f, "props": {"padding": [8, 12, 16, 20]}}));
+ assert_eq!(node(&s, f).layout.as_ref().unwrap().padding, [8.0, 12.0, 16.0, 20.0]);
+ ex(&mut s, "node.set", json!({"id": f, "props": {"paddingHorizontal": 4}}));
+ assert_eq!(node(&s, f).layout.as_ref().unwrap().padding, [8.0, 4.0, 16.0, 4.0]);
+ ex(&mut s, "node.set", json!({"id": f, "props": {"paddingVertical": 2}}));
+ assert_eq!(node(&s, f).layout.as_ref().unwrap().padding, [2.0, 4.0, 2.0, 4.0]);
+ // Negatives clamp to 0; junk is refused.
+ ex(&mut s, "node.set", json!({"id": f, "props": {"paddingTop": -5}}));
+ assert_eq!(node(&s, f).layout.as_ref().unwrap().padding[0], 0.0);
+ assert!(s.execute("node.set", &json!({"id": f, "props": {"paddingLeft": "wide"}})).is_err());
+ }
+
#[test]
fn baseline_alignment_lines_up_text() {
let mut s = Session::new();
diff --git a/crates/engine/src/cmd/lists.rs b/crates/engine/src/cmd/lists.rs
index 769d0a29c..287c9ddd0 100644
--- a/crates/engine/src/cmd/lists.rs
+++ b/crates/engine/src/cmd/lists.rs
@@ -112,7 +112,8 @@ pub fn stop_binding(field: &str) -> Option {
/// Keep the gradient stop bindings of paint `index` of `n`'s fills (or strokes) on their stops after
/// the paint changed from `old`: one stop removed shifts the later ones down (the removed one's
/// binding goes); a paint that is no longer a gradient drops them. Other edits keep stop indices.
-pub(crate) fn remap_stop_bindings(n: &mut Node, fills: bool, index: usize, old: &figcraft_color::Paint) {
+/// Returns the removed stop's index.
+pub(crate) fn remap_stop_bindings(n: &mut Node, fills: bool, index: usize, old: &figcraft_color::Paint) -> Option {
use figcraft_color::PaintKind;
let list = if fills { BoundList::Fills } else { BoundList::Strokes };
let new = if fills { n.fills.get(index) } else { n.strokes.get(index) };
@@ -122,11 +123,11 @@ pub(crate) fn remap_stop_bindings(n: &mut Node, fills: bool, index: usize, old:
// The first stop that differs is the removed one when the rest moved down unchanged.
let k = a.stops.iter().zip(&b.stops).position(|(x, y)| x != y).unwrap_or(b.stops.len());
if a.stops.get(k + 1..) != b.stops.get(k..) {
- return;
+ return None;
}
Some(k)
}
- (_, Some(PaintKind::Gradient(_))) => return,
+ (_, Some(PaintKind::Gradient(_))) => return None,
_ => None,
};
let keys: Vec<(String, Option)> = n
@@ -150,6 +151,42 @@ pub(crate) fn remap_stop_bindings(n: &mut Node, fills: bool, index: usize, old:
}
}
n.bound.extend(kept);
+ removed
+}
+
+/// After an explicit edit changed paint `index` of `n`'s fills (or strokes) from `old`: its stop
+/// bindings follow a removed stop, then each binding whose value the edit changed (the colour, the
+/// opacity, a stop's colour) lets go, so the edit stays instead of being put back from the
+/// variable. Bindings whose value the edit kept stay; a paint that is gone takes its bindings.
+pub(crate) fn rebind_edited_paint(n: &mut Node, fills: bool, index: usize, old: &figcraft_color::Paint) {
+ let removed = remap_stop_bindings(n, fills, index, old);
+ let mut old = old.clone();
+ if let (Some(k), figcraft_color::PaintKind::Gradient(g)) = (removed, &mut old.kind)
+ && k < g.stops.len()
+ {
+ g.stops.remove(k);
+ }
+ let list = if fills { BoundList::Fills } else { BoundList::Strokes };
+ let new = if fills { n.fills.get(index) } else { n.strokes.get(index) }.cloned();
+ n.bound.retain(|key, _| match list_binding(key) {
+ Some((l, i, field)) if l == list && i == index => new.as_ref().is_some_and(|new| paint_field_kept(&old, new, field)),
+ _ => true,
+ });
+}
+
+/// Whether a paint's bound `field` (`color`, `opacity`, `stops//color`, …) has the same value in
+/// `new` as in `old`.
+fn paint_field_kept(old: &figcraft_color::Paint, new: &figcraft_color::Paint, field: &str) -> bool {
+ use figcraft_color::PaintKind;
+ match field {
+ "color" => matches!((&old.kind, &new.kind), (PaintKind::Solid { color: a }, PaintKind::Solid { color: b }) if a == b),
+ "opacity" => old.opacity == new.opacity,
+ _ => match (stop_binding(field), &old.kind, &new.kind) {
+ (Some(j), PaintKind::Gradient(a), PaintKind::Gradient(b)) => a.stops.get(j).map(|s| s.color) == b.stops.get(j).map(|s| s.color),
+ (Some(_), _, _) => false,
+ _ => old == new,
+ },
+ }
}
/// Where item `k` lands when the item at `from` moves to `to`.
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 6579494ca..f011238d9 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -71,6 +71,7 @@ fn registry() -> &'static Registry {
list.extend(create::specs());
list.extend(edit::specs());
list.extend(lists::specs());
+ list.extend(crate::selection_colors::specs());
list.extend(arrange::specs());
list.extend(structure::specs());
list.extend(section::specs());
@@ -79,6 +80,7 @@ fn registry() -> &'static Registry {
list.extend(page::specs());
list.extend(view::specs());
list.extend(text::specs());
+ list.extend(crate::fonts::specs());
list.extend(styles::specs());
list.extend(image::specs());
list.extend(variables::specs());
diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs
index 598be752f..f180b53c8 100644
--- a/crates/engine/src/cmd/props.rs
+++ b/crates/engine/src/cmd/props.rs
@@ -61,6 +61,48 @@ pub fn snake(v: &Value) -> Value {
}
}
+/// `v` as an effect list, refusing keys an effect doesn't read: serde dropped them without a word,
+/// so a shadow given `offsetY` kept the default offset.
+pub fn effects_from(cmd: &str, v: &Value) -> Result> {
+ let effects: Vec = serde_json::from_value(snake(v)).map_err(|e| bad(cmd, format!("effects: {e}")))?;
+ for (i, given) in v.as_array().into_iter().flatten().enumerate() {
+ refuse_ignored_effect_keys(cmd, &format!("effects[{i}]"), given, |v| serde_json::from_value(snake(v)).ok())?;
+ }
+ Ok(effects)
+}
+
+/// `p[key]` as one effect, read as serde reads it (its aliases too), refusing keys it doesn't read.
+pub fn effect_from(cmd: &str, p: &Value, key: &str) -> Result> {
+ let Some(v) = get(p, key) else { return Ok(None) };
+ let effect: Effect = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("`{key}`: {e}")))?;
+ refuse_ignored_effect_keys(cmd, &format!("`{key}`"), v, |v| serde_json::from_value(v.clone()).ok())?;
+ Ok(Some(effect))
+}
+
+/// Refuse the keys of effect `given` that `parse` ignores, naming the keys the effect takes. Set to
+/// null, a key it reads fails to parse or changes the effect; a key it ignores changes nothing.
+fn refuse_ignored_effect_keys(cmd: &str, at: &str, given: &Value, parse: impl Fn(&Value) -> Option) -> Result<()> {
+ let Some(fields) = given.as_object() else { return Ok(()) };
+ let parsed = parse(given);
+ let ignored: Vec<&str> = fields
+ .iter()
+ .filter(|(_, v)| !v.is_null())
+ .filter(|(k, _)| {
+ let mut probe = fields.clone();
+ probe.insert((*k).clone(), Value::Null);
+ parse(&Value::Object(probe)).is_some_and(|e| Some(e) == parsed)
+ })
+ .map(|(k, _)| k.as_str())
+ .collect();
+ if ignored.is_empty() {
+ return Ok(());
+ }
+ let takes = parsed.and_then(|e| serde_json::to_value(e).ok()).map(crate::inspect::camel).unwrap_or_default();
+ let kind = takes.get("type").and_then(Value::as_str).unwrap_or("effect").to_string();
+ let names: Vec<&str> = takes.as_object().into_iter().flatten().map(|(k, _)| k.as_str()).collect();
+ Err(bad(cmd, format!("{at}: unknown properties: {} (a {kind} takes {})", ignored.join(", "), names.join(", "))))
+}
+
pub(crate) fn enum_of(v: &Value) -> Option {
let s = v.as_str()?;
// Accept camelCase, snake/upper-case and spaced variants.
@@ -265,18 +307,88 @@ fn ensure_layout(n: &mut Node) -> &mut AutoLayout {
n.layout.get_or_insert_with(|| AutoLayout { padding: [0.0; 4], gap: 0.0, ..Default::default() })
}
-/// Apply a property map to one node. `x`/`y` are relative to the parent.
-pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map) -> Result<()> {
- let mut unknown = Vec::new();
- // Geometry keys first so rotation applies to the final size.
- let order = |k: &str| match k {
+/// The keys that set a frame's auto layout (through [`layout_mut`]).
+pub const LAYOUT_KEYS: &[&str] = &[
+ "gap",
+ "itemSpacing",
+ "columnGap",
+ "crossGap",
+ "counterAxisSpacing",
+ "rowGap",
+ "padding",
+ "paddingTop",
+ "paddingRight",
+ "paddingBottom",
+ "paddingLeft",
+ "paddingHorizontal",
+ "paddingVertical",
+ "mainAlign",
+ "primaryAxisAlignItems",
+ "crossAlign",
+ "counterAxisAlignItems",
+ "contentAlign",
+ "counterAxisAlignContent",
+ "wrap",
+ "gridColumns",
+ "gridRows",
+ "strokesIncluded",
+ "reverseZ",
+ "columnTracks",
+ "gridColumnTracks",
+ "rowTracks",
+ "gridRowTracks",
+];
+
+/// Drop the bindings of auto layout fields (gap, padding…): they go with the auto layout, or
+/// re-applying them would bring it back.
+pub fn drop_layout_bindings(n: &mut Node) {
+ n.bound.retain(|k, _| !LAYOUT_KEYS.contains(&k.as_str()));
+}
+
+/// The auto layout of a frame-like node, created when it has none yet. Other nodes can't hold an
+/// auto layout: an auto layout key on them is refused, not stored where nothing reads it
+/// (`node.set` on several layers skips them instead, see `edit::set`).
+fn layout_mut<'a>(cmd: &str, k: &str, n: &'a mut Node) -> Result<&'a mut AutoLayout> {
+ if !n.kind.is_frame_like() {
+ return Err(bad(
+ cmd,
+ format!(
+ "`{k}` is an auto layout property, and layer {} “{}” is a {} (only frames, components and instances have auto layout)",
+ n.id,
+ n.name,
+ n.kind.type_name()
+ ),
+ ));
+ }
+ Ok(ensure_layout(n))
+}
+
+/// Replace a node's fills (or strokes). Bindings on the paints whose bound values the new list
+/// changed let go, as an explicit edit does (see `lists::rebind_edited_paint`).
+fn set_paints(n: &mut Node, fills: bool, paints: Vec) {
+ let old = std::mem::replace(if fills { &mut n.fills } else { &mut n.strokes }, paints);
+ for (i, p) in old.iter().enumerate() {
+ super::lists::rebind_edited_paint(n, fills, i, p);
+ }
+}
+
+/// The order [`apply`] takes keys in: geometry first so rotation applies to the final size, variable
+/// bindings last so paints set in the same call don't detach them.
+fn apply_order(k: &str) -> u8 {
+ match k {
"width" | "height" | "w" | "h" => 0,
"rotation" => 2,
"x" | "y" => 3,
+ "boundVariables" => 4,
_ => 1,
- };
+ }
+}
+
+/// Apply a property map to one node. `x`/`y` are relative to the parent.
+pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map) -> Result<()> {
+ let mut unknown = Vec::new();
let mut keys: Vec<(&String, &Value)> = props.iter().collect();
- keys.sort_by_key(|(k, _)| order(k));
+ keys.sort_by_key(|(k, _)| apply_order(k));
for (k, v) in keys {
let k = k.as_str();
match k {
@@ -348,15 +460,15 @@ pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map