Merge upstream into ka-update

This commit is contained in:
Davit Matchakhelidze committed 2026-11-19 21:21:38 +04:00
commit 3fa7d30e48
232 files changed
+12459 -1573

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# This file is machine-generated by `gh actions-lock`.
# Do not edit by hand; run `gh actions-lock` to update.
# Docs: https://gh.io/actions-lockfile
version: 'v0.0.3'
workflows:
'.github/workflows/ci.yml': []
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nix.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
dependencies:
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/harden-runner@v2.22.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
+34
View File
@@ -0,0 +1,34 @@
name: Lockfile
# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin
# no longer verifies upstream, so a moved tag cannot slip a different commit into a run.
# Docs: https://gh.io/actions-lockfile
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
env:
GH_TOKEN: ${{ github.token }}
jobs:
lockfile:
name: Lockfile is in sync
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install gh-actions-lock
run: gh extension install github/gh-actions-lock --pin v0.4.1
- name: Verify the lockfile
run: gh actions-lock --verify
+2 -2
View File
@@ -30,10 +30,10 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
+5 -1
View File
@@ -59,7 +59,7 @@ inspection. It runs natively on macOS, Windows, Linux and FreeBSD, and in the br
Siblings: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop-class), `../designcraft`
(InDesign-class) and the other Crafting Apps; same conventions.
Repos don't share code.
Share reusable code through craft-libs; do not depend on sibling application crates.
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, estimates) and
@@ -182,3 +182,7 @@ commit. Grade by behaviour against the incumbent, not by whether a menu item exi
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
## Shared Craft libraries
Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage.
Generated
+416 -31
View File
@@ -138,12 +138,33 @@ dependencies = [
"memchr",
]
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "ambient-authority"
version = "0.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
[[package]]
name = "android-activity"
version = "0.6.1"
@@ -520,6 +541,12 @@ dependencies = [
"serde",
]
[[package]]
name = "bit_field"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -605,6 +632,16 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -693,6 +730,24 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "cap-primitives"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
dependencies = [
"ambient-authority",
"fs-set-times",
"io-extras",
"io-lifetimes 3.0.1",
"ipnet",
"maybe-owned",
"rustix 1.1.5",
"rustix-linux-procfs",
"windows-sys 0.61.2",
"winx",
]
[[package]]
name = "cc"
version = "1.10.0"
@@ -1001,24 +1056,32 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"rustix 1.1.5",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"rayon",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-fig"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-figma-rest",
"craft-kiwi",
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c)",
"craft-zip",
"flate2",
"kurbo",
"ruzstd",
@@ -1029,9 +1092,9 @@ dependencies = [
[[package]]
name = "craft-figcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee#976eb51c59edb0a37f24105850f52d921c8518ee"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee)",
"craft-zip",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1041,7 +1104,7 @@ dependencies = [
[[package]]
name = "craft-figma-rest"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"serde",
"serde_json",
@@ -1051,39 +1114,48 @@ dependencies = [
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"fontique",
"harfrust 0.13.3",
"kurbo",
"skrifa 0.47.0",
"thiserror 2.0.21",
"unicode-bidi",
"unicode-segmentation",
"windows-registry",
]
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"cap-primitives",
"craft-atomic",
"craft-font-catalog",
"flate2",
"log",
"ruzstd",
"serde",
"serde_json",
"sha2",
"skrifa 0.47.0",
"tar",
"thiserror 2.0.21",
"toml",
"ureq",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1103,10 +1175,53 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-dds",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-metadata",
"craft-tiff",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
"png",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"egui",
"serde",
@@ -1116,12 +1231,12 @@ dependencies = [
[[package]]
name = "craft-kiwi"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-keymap",
"craft-quit",
@@ -1131,10 +1246,42 @@ dependencies = [
"objc2-app-kit 0.3.2",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"krilla",
"thiserror 2.0.21",
]
[[package]]
name = "craft-penpot"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-zip",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"dispatch2",
"egui",
@@ -1145,7 +1292,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-atomic",
"dirs",
@@ -1153,10 +1300,49 @@ dependencies = [
"toml_edit",
]
[[package]]
name = "craft-sketch"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-figma-rest",
"craft-zip",
"kurbo",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-image-codecs",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"data-url",
"flate2",
"kurbo",
"quick-xml 0.41.0",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg",
"vectorcraft-geom",
"vectorcraft-pathops",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1176,7 +1362,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"chrono",
"dunce",
@@ -1203,7 +1389,7 @@ dependencies = [
[[package]]
name = "craft-vectordrawable"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7#5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7"
dependencies = [
"kurbo",
]
@@ -1211,7 +1397,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"js-sys",
"serde_json",
@@ -1222,7 +1408,7 @@ dependencies = [
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"wasm-bindgen",
"web-sys",
@@ -1231,7 +1417,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"wayland-client",
]
@@ -1239,26 +1425,27 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=976eb51c59edb0a37f24105850f52d921c8518ee#976eb51c59edb0a37f24105850f52d921c8518ee"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"flate2",
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
"zip 9.1.1",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d13ac58a15c45d618f25910772502e38c4ce1d4c#d13ac58a15c45d618f25910772502e38c4ce1d4c"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -1835,6 +2022,22 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "exr"
version = "1.74.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
dependencies = [
"bit_field",
"half",
"lebe",
"miniz_oxide 0.8.9",
"multiversion",
"rayon-core",
"smallvec",
"zune-inflate",
]
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -2017,6 +2220,9 @@ dependencies = [
"craft-fig",
"craft-figcraft-format",
"craft-figma-rest",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33)",
"craft-penpot",
"craft-sketch",
"figcraft-doc",
"figcraft-layout",
"figcraft-pathops",
@@ -2068,13 +2274,14 @@ version = "0.18.1"
dependencies = [
"figcraft-doc",
"figcraft-geom",
"linesweeper",
"linesweeper 0.4.0",
]
[[package]]
name = "figcraft-pdf"
version = "0.18.1"
dependencies = [
"craft-pdf",
"figcraft-color",
"figcraft-doc",
"figcraft-geom",
@@ -2150,7 +2357,8 @@ name = "figcraft-svg"
version = "0.18.1"
dependencies = [
"base64 0.22.1",
"craft-xml",
"craft-svg",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc)",
"figcraft-color",
"figcraft-doc",
"figcraft-geom",
@@ -2170,6 +2378,7 @@ dependencies = [
"craft-font-catalog",
"figcraft-doc",
"figcraft-geom",
"flate2",
"harfrust 0.13.3",
"icu_segmenter",
"log",
@@ -2425,6 +2634,17 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fs-set-times"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix 1.1.5",
"windows-sys 0.52.0",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -2741,6 +2961,15 @@ dependencies = [
"foldhash 0.2.0",
]
[[package]]
name = "hayro-jpeg2000"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
dependencies = [
"fearless_simd",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -3019,6 +3248,7 @@ dependencies = [
"moxcms",
"num-traits",
"png",
"qoi",
"tiff",
"zune-core",
"zune-jpeg",
@@ -3078,6 +3308,34 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "io-extras"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.52.0",
]
[[package]]
name = "io-lifetimes"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
[[package]]
name = "io-lifetimes"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
[[package]]
name = "ipnet"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -3204,6 +3462,12 @@ dependencies = [
"libc",
]
[[package]]
name = "jpeg-encoder"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
[[package]]
name = "js-sys"
version = "0.3.106"
@@ -3245,7 +3509,7 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -3288,6 +3552,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "lebe"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
[[package]]
name = "libc"
version = "0.2.191"
@@ -3341,6 +3611,19 @@ dependencies = [
"smallvec",
]
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
dependencies = [
"arrayvec",
"kurbo",
"polycool",
"rustc-hash 2.1.3",
"smallvec",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -3383,6 +3666,12 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "maybe-owned"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "memchr"
version = "2.8.3"
@@ -3455,6 +3744,28 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multiversion"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
dependencies = [
"multiversion-macros",
"target-features",
]
[[package]]
name = "multiversion-macros"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"target-features",
]
[[package]]
name = "naga"
version = "30.0.1"
@@ -4308,6 +4619,15 @@ version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qoi"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
dependencies = [
"bytemuck",
]
[[package]]
name = "quick-error"
version = "1.2.3"
@@ -4668,6 +4988,16 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rustix-linux-procfs"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
dependencies = [
"once_cell",
"rustix 1.1.5",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -5284,6 +5614,12 @@ dependencies = [
"libc",
]
[[package]]
name = "target-features"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -5798,6 +6134,27 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo",
"linesweeper 0.5.0",
"thiserror 2.0.21",
"vectorcraft-geom",
]
[[package]]
name = "vello_common"
version = "0.2.0"
@@ -6719,6 +7076,16 @@ version = "0.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6"
[[package]]
name = "winx"
version = "0.36.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.52.0",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
@@ -7139,6 +7506,15 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-inflate"
version = "0.2.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
@@ -7148,6 +7524,15 @@ dependencies = [
"zune-core",
]
[[package]]
name = "zune-jpegxl"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core",
]
[[package]]
name = "zvariant"
version = "5.15.1"
+23 -18
View File
@@ -13,8 +13,10 @@ rust-version = "1.95"
repository = "https://github.com/storytold/figcraft"
[workspace.dependencies]
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", default-features = false, features = ["tree"] }
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5cd16f2b9ac2a84c4c0794e609914e2bbf848bd7" }
craft-pdf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890" }
# internal
figcraft-geom = { path = "crates/geom" }
figcraft-color = { path = "crates/color" }
@@ -35,35 +37,38 @@ figcraft-mcp = { path = "crates/mcp" }
figcraft-collab-net = { path = "crates/collab-net" }
figcraft-plugin = { path = "crates/plugin" }
# Keep coupled craft-libs crates on one rev. craft-update has no sibling-crate
# dependencies and is pinned separately for the suite updater rollout.
# Keep every craft-libs crate on one rev.
# 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 = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Who draws the window frame on Linux — the compositor or the app — so every Craft app shows the
# same native titlebar per desktop (craft-libs). FigCraft only reads the probe result and maps it
# to its own `TitleBar`, so it does not enable craft-window's optional `egui` helpers (which would
# pull a second egui family version).
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] }
# The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto
# indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Shared dropdown menus: a combo box whose menu grows back after shrinking (craft-libs).
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# The macOS app menu whose Quit (⌘Q) asks the app before quitting, like the window's close button
# (craft-libs; the menu it replaces quits straight through `terminate:` and loses unsaved work).
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Where the settings live: the suite's folder rules, portable mode included (craft-libs).
craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# Penpot export container only; JSON values cross this boundary, not shared model types.
craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
# The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of
# a .fig message onto the REST file JSON, and that JSON's shared helpers. These crates share
# types, so they stay on one rev; they share none with the crates above.
craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "976eb51c59edb0a37f24105850f52d921c8518ee" }
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "d13ac58a15c45d618f25910772502e38c4ce1d4c" }
# a .fig message onto the REST file JSON, and that JSON's shared helpers.
craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -192,4 +197,4 @@ winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457
# craft-libs' vendored krilla 0.8.2: decoded PNGs are capped at 1 GiB and reserved fallibly, and a
# panic while drawing unwinds without aborting.
krilla = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
+9 -2
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (code blocks, first step: a dark panel of monospace text as tall as its lines, in one of 16 languages (`board.codeBlock`, `board.setLanguage`, #2237); library analytics count insertions and detachments of styles and variables; web builds with craft-fonts embed Noto Sans Arabic by default so Persian and Arabic text draws without extra build flags (#1902); the browser build uses team libraries and plugin directories on a server; CLI post-parse errors escape terminal controls in paths and failure text; M6 `.fig` export writes text on a path (#2323), list spacing, hanging punctuation and lists, vertical trim (#2305), vector region paints (#2302), image adjustments (#2297) and a page's prototype background (#2326); M8 Tidy up keeps a row's or column's order and sizes and evens the gaps, rounds the gap, tidies overlapping rows and grids along their longer axis, and raises a negative gap so no layer reaches the one two before it, as measured in Figma (#2319); a polygon's or star's Count handle and a double-click on a layer's icon (zoom, range anchor) follow Figma; Tab while renaming moves only the rename and wraps from the last layer; Align is unavailable for a layer in an auto layout frame's flow; the Scale tool pivots on the opposite handle and starts its origin at the centre; Paste over selection puts the copies just above the selected layer; Crop from the image fill's menu crops with a drag (#2307); M10 code export writes every colour and gradient fill in paint order for CSS, SwiftUI, Compose and Flutter (#2271), CSS as one layered background; 24 pt icon buttons draw 16 pt glyphs (#2227, #2238); M5 marquee selection follows Figma's measured rules and Select layer lists locked layers with a padlock (#1560); M7 the Design panel shows the page's variable modes with nothing selected (#2215); M12 mind maps in a section or frame without a place centre on the view, stickies take a Small–Huge text-size menu, and M9 `.jam` shapes with text import as native board shapes (#1808); M4 a boolean group's corner radius rounds its result (#2222), Flatten bakes a point's corner radius into its path (#2195) and loops close through a joining segment (#1951); library links survive moving or cloning the project folder (#2132); renaming a variable group to a path with `/` nests it (#2353); SVG import, widget images, batches and grids take bounded work, and a host's server key is never sent over plain `ws://` to another machine (#1923); CI prefetches dependencies for Sonar coverage and runs Harden-Runner on every job; releases FigCraft v0.18.0 and v0.18.1 (Flatpak update fix); readiness estimates unchanged) · **Target:** Figma Design (desktop app 126.10.7)
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
@@ -105,7 +105,7 @@ native speakers' reviews of the nine language drafts need people.
| Traditional Chinese (Taiwan) | zh-Hant | 2,647 / 2,647 entries (100%, counted 2026-11-03) | 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 | 2,508 / 2,508 entries (100%, counted 2026-10-28) | draft; the window mirrors (panels swap sides); native review and mirrored panel rows pending |
| Arabic | ar | 2,508 / 2,508 entries (100%, counted 2026-10-28) | draft; the window, the Design panel's rows and the layers mirror; web builds with craft-fonts offer Arabic by default; native review and the rest of the mirroring pending |
| French | fr | 95% | draft (needs native review) |
| Portuguese (Brazil) | pt-BR | 95% | draft (needs native review) |
| Indonesian | id | 99% | draft (needs native review) |
@@ -134,6 +134,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
## Progress log
- **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged.
- **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged.
- **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row.
- **2026-11-05** · M10, #2014: the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic (`bidi::script_fallbacks`: one sample letter per script, the system's families for each; Bengali and Thai keep `crate::cjk`'s choice), so a layer name or a String variable's Amharic value draws in the panels instead of boxes. Test: `bidi::tests::other_scripts_take_an_installed_system_face`.
@@ -365,8 +366,14 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
| Date | Change | Summary |
|---|---|---|
| 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged |
| 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. |
| 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. |
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
| 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`, 繁體中文(台灣)) draft catalog: every UI string (1,975), command label (641) and menu wording (31), translated clean-room from the English source; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant` read it while an explicit Hans stays Simplified; the desktop UI prefers an installed Noto Sans CJK TC, then Microsoft JhengHei, PingFang TC and Heiti TC; no font is bundled; native review pending. Numbers unchanged |
| 2026-11-06 | patch | M1, #2028: Edit ▸ Set default properties gives new rectangles, ellipses, polygons and stars drawn with the tools (and, set from a text layer, new text) the selected layer's properties; it only copied them for Paste properties. Tests: `default_props_tests` (3). Numbers unchanged |
| 2026-11-06 | patch | M5, #2027: `proto.settings` refuses an unknown device name with the list of devices (it saved any string, and the presenter showed no device), takes known names in any case, and answers the page's prototype settings, so `proto.settings {}` reads them back over MCP. Test: `proto_present_tests::unknown_devices_are_refused_and_settings_read_back`. Numbers unchanged |
+16 -1
View File
@@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result<usize, ValueError> {
/// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1.
fn attach(s: &str) -> Result<String, ValueError> {
if s.contains(':') {
if let Some((host, port)) = s.rsplit_once(':') {
if host.is_empty() || port.parse::<u16>().is_err() {
return Err(ValueError::Attach);
}
return Ok(s.to_owned());
}
let port: u16 = s.parse().map_err(|_| ValueError::Attach)?;
@@ -461,6 +464,12 @@ mod tests {
assert_eq!(a.attach.as_deref(), Some("127.0.0.1:7979"));
let Command::Mcp(a) = ok(&["mcp", "--attach=localhost:7979"]) else { panic!("mcp") };
assert_eq!(a.attach.as_deref(), Some("localhost:7979"));
for address in ["127.0.0.1:7979", "[::1]:7979", "[fe80::1%3]:7979", "localhost:0"] {
let Command::Mcp(a) = ok(&["mcp", "--attach", address]) else { panic!("mcp") };
assert_eq!(a.attach.as_deref(), Some(address));
}
let Command::Mcp(a) = ok(&["mcp", "--attach", "0"]) else { panic!("mcp") };
assert_eq!(a.attach.as_deref(), Some("127.0.0.1:0"));
let Command::Mcp(a) = ok(&["mcp", "--attach", "7979", "--timeout", "300"]) else { panic!("mcp") };
assert_eq!(a.timeout, Some(300));
let Command::Mcp(a) = ok(&["mcp", "--automation-read-root", "in", "--automation-write-root", "out"]) else { panic!("mcp") };
@@ -514,6 +523,11 @@ mod tests {
(&["perf", "--layers", "10,x"], ValueValidation),
(&["perf", "--layers", "10", "--layers", "20"], ArgumentConflict),
(&["mcp", "--attach", "notaport"], ValueValidation),
(&["mcp", "--attach", ":7979"], ValueValidation),
(&["mcp", "--attach", "localhost:"], ValueValidation),
(&["mcp", "--attach", "localhost:notaport"], ValueValidation),
(&["mcp", "--attach", "localhost:65536"], ValueValidation),
(&["mcp", "--attach", "[::1]"], ValueValidation),
(&["mcp", "--attach", "7979", "--timeout", "0"], ValueValidation),
(&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation),
(&["mcp", "--timeout", "300"], MissingRequiredArgument),
@@ -543,6 +557,7 @@ mod tests {
&["export", "x.figcraft", "-o", "out", "--help"],
&["export", "-o", "--help"],
&["mcp", "--attach", "notaport", "--help"],
&["mcp", "--attach", "localhost:notaport", "--help"],
&["mcp", "--bogus", "-h"],
&["--no-system-fonts", "plugin", "publish", "--bogus", "--help"],
] {
+19 -2
View File
@@ -12,7 +12,7 @@ use crate::{CliError, CliResult};
/// A document's or plugin's text as a terminal should show it: control characters escaped, and
/// everything else (quotes, backslashes in paths) left as it is.
fn plain(text: &str) -> String {
pub(crate) fn plain(text: &str) -> String {
text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect()
}
@@ -242,7 +242,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult<ExitCode> {
fn sanitize(name: &str) -> String {
let s = figcraft_engine::cmd::file::safe_file_name(name);
let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace());
if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() }
let cap = |s: &str| s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect::<String>();
// Truncation can expose a device name; its escape must still fit the limits.
let s = figcraft_engine::file_access::escape_device_names(&cap(s));
if s.is_empty() { "layer".into() } else { cap(&s) }
}
/// What `export` exports and how.
@@ -543,6 +546,10 @@ mod tests {
assert_eq!(sanitize("Home / Hero"), "Home _ Hero");
assert_eq!(sanitize("../.."), "_");
assert_eq!(sanitize(""), "layer");
assert_eq!(sanitize("CON"), "_CON");
assert_eq!(sanitize(" .nul.txt. "), "_nul.txt");
assert_eq!(sanitize("COM1"), "_COM1");
assert_eq!(sanitize("HomeCON"), "HomeCON");
// The same characters the app's export keeps (#1154): only what file systems refuse goes.
assert_eq!(sanitize("Homepage - desktop (live + verbeteringen)"), "Homepage - desktop (live + verbeteringen)");
assert_eq!(sanitize("Q&A, 50% #1 [v2] {x} ~é"), "Q&A, 50% #1 [v2] {x} ~é");
@@ -553,6 +560,16 @@ mod tests {
assert_eq!(sanitize(&"\u{1F600}".repeat(100)), "\u{1F600}".repeat(50), "at most 200 bytes, whole characters");
}
#[test]
fn sanitizes_names_that_become_devices_at_the_character_limit() {
assert_eq!(sanitize(&format!("CON{}X", " ".repeat(97))), format!("_CON{}", " ".repeat(96)));
}
#[test]
fn sanitizes_names_that_become_devices_at_the_byte_limit() {
assert_eq!(sanitize(&format!("NUL{} X", "\u{2003}".repeat(65))), format!("_NUL{} ", "\u{2003}".repeat(65)));
}
#[test]
fn default_page_skips_leading_divider() {
let mut doc = Document::new("divider");
+3 -2
View File
@@ -38,14 +38,15 @@ fn main() -> ExitCode {
return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2));
}
};
// Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable.
match run(cli) {
Ok(code) => code,
Err(CliError::Usage(msg)) => {
eprintln!("error: {msg}\n\nFor more information, try '--help'.");
eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg));
ExitCode::from(2)
}
Err(CliError::Failed(msg)) => {
eprintln!("error: {msg}");
eprintln!("error: {}", files::plain(&msg));
ExitCode::from(1)
}
}
+16
View File
@@ -106,6 +106,22 @@ fn bad_arguments_exit_2_without_panicking() {
assert_eq!(out.status.code(), Some(1));
}
#[test]
fn post_parse_errors_escape_terminal_controls() {
let missing = format!("__figcraft_missing_diagnostic_{}_\u{1b}[31m\n.figcraft", std::process::id());
let failed = ["info", missing.as_str()];
let usage = ["connect", "publish", "invalid-\u{1b}[31m\n.txt"];
for (args, expected) in [(&failed[..], 1), (&usage[..], 2)] {
let out = bin().arg("--no-system-fonts").args(args).output().unwrap();
let error = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(expected), "{args:?}: {error:?}");
assert!(error.starts_with("error: "), "{args:?}: {error:?}");
assert!(!error.contains('\u{1b}'), "{args:?}: {error:?}");
assert!(error.contains(r"\u{1b}[31m\n"), "{args:?}: {error:?}");
assert!(out.stdout.is_empty(), "{args:?}");
}
}
/// `--help` / `-h` after a subcommand prints that subcommand's help on stdout and exits 0, as it
/// does first (#1155), whatever else is on the line; nothing runs.
#[test]
+1
View File
@@ -28,6 +28,7 @@ pub const LINKS: &str = "links.json";
pub const LIBRARY: &str = "library.bin";
pub const USAGE: &str = "usage.json";
pub const ACTIONS: &str = "actions.json";
pub const ASSET_ACTIONS: &str = "asset-actions.json";
const SNAP_MAGIC: &[u8; 4] = b"FCSN";
const LOG_MAGIC: &[u8; 4] = b"FCLG";
@@ -5,12 +5,15 @@
use std::time::{Duration, Instant};
use figcraft_collab::message::{Access, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg};
use figcraft_collab::message::{
Access, AssetActions, AssetUsage, ClientMsg, LibraryReply, LibraryReq, MAX_ASSET_USAGE, OpenLibrary, PROTOCOL, ServerMsg, Usage,
};
use figcraft_collab_net::Invite;
use figcraft_doc::NodeId;
use figcraft_engine::Session;
use serde_json::{Value, json};
use crate::store::{MAX_USERS, Store};
use crate::test_util::{Raw, TempDir, config, publish, session};
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
@@ -79,7 +82,7 @@ fn styles_and_variables_are_counted_per_layer_and_file() {
// Bo takes the style off one layer and the variable off its only one.
ex(&mut b, "style.detach", json!({"ids": [two], "which": "fill"}));
ex(&mut b, "variable.bind", json!({"ids": [three], "field": "fill"}));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"].as_array().is_some_and(Vec::is_empty));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["layers"] == 1 && u["variables"][0]["layers"] == 0);
assert_eq!(u["styles"].as_array().unwrap().len(), 1, "{u}");
server.stop();
}
@@ -143,3 +146,76 @@ fn answer(raw: &mut Raw) -> LibraryReply {
other => panic!("not a library answer: {other:?}"),
}
}
#[test]
fn inserts_and_detaches_count_per_style_and_variable_in_the_period() {
let dir = TempDir::new("library-asset-actions");
let cfg = config(dir.path());
let mut server = crate::start(&cfg).unwrap();
let addr = server.addr();
let mut a = session("Ada");
let r = rect(&mut a, 0);
ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let collection = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"}));
ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": collection["id"], "value": "#0D99FF"}));
let p = publish(&mut a, dir.path(), addr);
ex(&mut a, "library.publishToServer", json!({}));
let mut b = session("Bo");
let lid = ex(&mut b, "library.add", json!({"path": p.view}))["id"].as_str().unwrap().to_string();
let (one, two) = (rect(&mut b, 0), rect(&mut b, 100));
ex(&mut b, "library.applyStyle", json!({"library": lid, "style": "Brand", "ids": [one.0, two.0]}));
ex(&mut b, "style.detach", json!({"ids": [two.0], "which": "fill"}));
ex(&mut b, "library.bindVariable", json!({"library": lid, "variable": "Accent", "ids": [two.0], "field": "fill"}));
let u = usage_when(&mut a, &mut b, |u| {
u["assetActionsKnown"] == true
&& u["styles"][0]["insertions"] == 2
&& u["styles"][0]["detachments"] == 1
&& u["variables"][0]["insertions"] == 1
});
assert_eq!(u["assetActionsKnown"], true, "{u}");
assert_eq!(u["styles"][0]["detachments"], 1, "{u}");
assert_eq!(u["variables"][0]["detachments"], 0, "{u}");
assert_eq!(u["insertions"], 0, "components count on their own: {u}");
// An undo and a redo count once, and a style no layer uses any more stays listed.
ex(&mut b, "edit.undo", json!({}));
ex(&mut b, "edit.redo", json!({}));
ex(&mut b, "style.detach", json!({"ids": [one.0], "which": "fill"}));
let u = usage_when(&mut a, &mut b, |u| u["styles"][0]["detachments"] == 2 && u["styles"][0]["layers"] == 0);
assert_eq!((u["styles"][0]["insertions"].clone(), u["styles"][0]["layers"].clone()), (json!(2), json!(0)), "{u}");
assert_eq!(u["variables"][0]["insertions"], 1, "{u}");
server.stop();
}
#[test]
fn evicting_capped_usage_rows_keeps_asset_peaks_so_a_repeat_report_is_not_counted_twice() {
let dir = TempDir::new("library-asset-peaks-evict");
let cfg = config(dir.path());
let mut server = crate::start(&cfg).unwrap();
let addr = server.addr();
let mut a = session("Ada");
let r = rect(&mut a, 0);
ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let p = publish(&mut a, dir.path(), addr);
ex(&mut a, "library.publishToServer", json!({}));
let file = Invite::parse(&p.edit).unwrap().file;
server.stop();
drop(server);
let mut store = Store::open(dir.path(), cfg.store()).unwrap();
for i in 0..MAX_USERS {
store.report_usage(&file, Usage { file: format!("Old{i}"), components: Vec::new() }).unwrap();
}
let actions = AssetActions { file: "Kept".into(), inserted: vec![("Brand".into(), 2)], detached: Vec::new() };
store.report_asset_actions(&file, actions.clone()).unwrap();
// One more usage-only file would evict "Kept" if asset activity did not count for retention.
store.report_usage(&file, Usage { file: "Extra".into(), components: Vec::new() }).unwrap();
store.report_asset_actions(&file, actions).unwrap();
let weeks = store.library_asset_actions(&file).unwrap();
let brand: Vec<_> = weeks.iter().filter(|w| w.component == "Brand").collect();
assert_eq!(brand.len(), 1, "{weeks:?}");
assert_eq!(brand[0].insertions, 2, "lost peaks would grow the same totals again: {weeks:?}");
assert_eq!(brand[0].detachments, 0, "{weeks:?}");
}
+12 -5
View File
@@ -40,8 +40,8 @@ use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use figcraft_collab::message::{
Access, Admin, AdminReply, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply, LibraryReq,
LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
Access, Admin, AdminReply, AssetActions, AssetUsage, ClientMsg, Detached, FileDetached, FileInfo, FileRow, FileUsage, HostInfo, LibraryReply,
LibraryReq, LinkInfo, MAX_OWNED, NewLink, OwnedFile, PluginReply, PluginReq, ReportInfo, Usage, WeekActions,
};
use figcraft_collab::{Change, NodeId, Replica, Server, same_secret};
use figcraft_collab_net::hub::{Admission, Backend, Closing, Handled, OpenFile, ip_blocks, ip_key};
@@ -52,7 +52,7 @@ use sha2::{Digest, Sha256};
use crate::abuse::{Abuse, AbuseConfig, Action};
use crate::codes::{self, Sealed};
use crate::directory::{Directory, DirectoryConfig};
use crate::disk::{self, ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE};
use crate::disk::{self, ACTIONS, ASSET_ACTIONS, LIBRARY, LINKS, LOG, LOG_HEADER, META, SNAPSHOT, USAGE};
mod backend;
mod files;
@@ -103,7 +103,7 @@ pub const NO_PUBLIC_LIBRARY: &str = "on this public server only files published
/// Most files whose usage of one library is kept (the least recently changed go first), and most
/// components one file's report keeps.
const MAX_USERS: usize = 200;
pub(crate) const MAX_USERS: usize = 200;
const MAX_REPORTED: usize = 1_000;
/// Largest `usage.json` (and `actions.json`) read.
const MAX_USAGE_FILE: u64 = 16 << 20;
@@ -298,6 +298,8 @@ struct UsageCache {
list: Vec<UsageEntry>,
/// Insertions and detachments week by week, over every file (kept in `actions.json`).
weeks: Vec<WeekActions>,
/// The same for styles and variables (kept in `asset-actions.json`).
asset_weeks: Vec<WeekActions<String>>,
dirty: bool,
written: u64,
}
@@ -321,6 +323,11 @@ struct UsageEntry {
styles: Vec<(String, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
variables: Vec<(String, u32)>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
asset_peaks: Vec<(String, u32, u32)>,
/// When this file last reported style or variable insertions or detachments (seconds since 1970, UTC).
#[serde(default, skip_serializing_if = "is_zero")]
asset_updated: u64,
}
fn is_zero(n: &u64) -> bool {
@@ -560,7 +567,7 @@ impl Store {
/// A file folder's description and links, after checking its snapshot and log. Leftover
/// temporary files (writes cut short) are removed.
fn check(&self, path: &Path) -> Result<Entry, String> {
for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS] {
for name in [SNAPSHOT, LOG, META, LINKS, USAGE, ACTIONS, ASSET_ACTIONS] {
let tmp = disk::temp_of(&path.join(name));
if tmp.exists() {
let _ = fs::remove_file(&tmp);
@@ -278,6 +278,8 @@ impl Backend for Store {
LibraryReq::Actions => self.library_actions(file).map_or_else(failed, LibraryReply::Actions),
LibraryReq::ReportAssets(a) => self.report_assets(file, a).map_or_else(failed, |()| LibraryReply::Noted),
LibraryReq::Assets => self.library_assets(file).map_or_else(failed, LibraryReply::Assets),
LibraryReq::ReportAssetActions(a) => self.report_asset_actions(file, a).map_or_else(failed, |()| LibraryReply::Noted),
LibraryReq::AssetActions => self.library_asset_actions(file).map_or_else(failed, LibraryReply::AssetActions),
}
}
+92 -33
View File
@@ -1,9 +1,9 @@
use figcraft_collab::message::MAX_ASSET_USAGE;
use super::{
ACTIONS, Action, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY, LibraryMeta, LibraryReply,
MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY, NodeId, Path, PathBuf,
Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json,
ACTIONS, ASSET_ACTIONS, Action, AssetActions, AssetUsage, BUSY_DOWNLOADS, Cursor, Detached, FILES, FileDetached, FileUsage, IpAddr, LIBRARY,
LibraryMeta, LibraryReply, MAX_FIRST_LIBRARY_VERSION, MAX_REPORTED, MAX_USAGE_FILE, MAX_USERS, MAX_WEEK_ROWS, MAX_WEEKS, META, NO_PUBLIC_LIBRARY,
NodeId, Path, PathBuf, Store, USAGE, USAGE_WRITE_EVERY, Usage, UsageCache, UsageEntry, WeekActions, clean_name, disk, fs, now, write_json,
};
/// Which of a file's totals a report brings.
@@ -46,49 +46,55 @@ fn read_kept<T: serde::de::DeserializeOwned>(path: &Path) -> Vec<T> {
disk::read_capped(path, MAX_USAGE_FILE).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
/// Raise the highest `kind` totals in `peaks` to `counts`, each from what `last` says was reported
/// before them; what grew past them, by how much.
fn grow<K: PartialEq + Clone>(peaks: &mut Vec<(K, u32, u32)>, counts: &[(K, u32)], kind: Count, last: impl Fn(&K) -> u32) -> Vec<(K, u32)> {
let mut grown = Vec::new();
for (c, n) in counts {
let at = match peaks.iter().position(|p| p.0 == *c) {
Some(at) => at,
None if peaks.len() < MAX_REPORTED => {
peaks.push((c.clone(), 0, 0));
peaks.len() - 1
}
None => continue,
};
let Some(p) = peaks.get_mut(at) else { continue };
let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 };
let base = (*peak).max(last(c));
if *n > base {
grown.push((c.clone(), *n - base));
}
*peak = base.max(*n);
}
grown
}
impl UsageEntry {
/// Raise this file's highest `kind` totals to `counts`; what grew past them, by how much.
/// A detach total reported before peaks were kept starts from that report.
fn grow_peaks(&mut self, counts: &[(NodeId, u32)], kind: Count) -> Vec<(NodeId, u32)> {
let mut grown = Vec::new();
for &(c, n) in counts {
let last = if kind == Count::Detached { self.detached.iter().find(|d| d.0 == c).map_or(0, |d| d.1) } else { 0 };
let at = match self.peaks.iter().position(|p| p.0 == c) {
Some(at) => at,
None if self.peaks.len() < MAX_REPORTED => {
self.peaks.push((c, 0, 0));
self.peaks.len() - 1
}
None => continue,
};
let Some(p) = self.peaks.get_mut(at) else { continue };
let peak = if kind == Count::Inserted { &mut p.1 } else { &mut p.2 };
let base = (*peak).max(last);
if n > base {
grown.push((c, n - base));
}
*peak = base.max(n);
}
grown
let detached = &self.detached;
grow(&mut self.peaks, counts, kind, |c| if kind == Count::Detached { detached.iter().find(|d| d.0 == *c).map_or(0, |d| d.1) } else { 0 })
}
}
/// Add `grown` to this week's `kind` counts in `weeks`, dropping weeks older than [`MAX_WEEKS`]
/// and, past [`MAX_WEEK_ROWS`], the oldest rows.
fn add_to_week(weeks: &mut Vec<WeekActions>, grown: &[(NodeId, u32)], kind: Count, t: u64) {
fn add_to_week<K: PartialEq + Clone>(weeks: &mut Vec<WeekActions<K>>, grown: &[(K, u32)], kind: Count, t: u64) {
let week = week_of(t);
weeks.retain(|w| w.week.saturating_add(MAX_WEEKS * WEEK) > week);
for &(component, n) in grown {
let at = match weeks.iter().position(|w| w.week == week && w.component == component) {
for (component, n) in grown {
let at = match weeks.iter().position(|w| w.week == week && w.component == *component) {
Some(at) => at,
None => {
weeks.push(WeekActions { week, component, insertions: 0, detachments: 0 });
weeks.push(WeekActions { week, component: component.clone(), insertions: 0, detachments: 0 });
weeks.len() - 1
}
};
if let Some(w) = weeks.get_mut(at) {
let slot = if kind == Count::Inserted { &mut w.insertions } else { &mut w.detachments };
*slot = slot.saturating_add(n);
*slot = slot.saturating_add(*n);
}
}
if weeks.len() > MAX_WEEK_ROWS {
@@ -184,8 +190,9 @@ impl Store {
}
if !self.usage.contains_key(file) {
let path = self.dir(file).join(USAGE);
let (list, weeks) = (read_kept(&path), read_kept(&self.dir(file).join(ACTIONS)));
self.usage.insert(file.to_string(), UsageCache { list, weeks, dirty: false, written: now() });
let dir = self.dir(file);
let (list, weeks, asset_weeks) = (read_kept(&path), read_kept(&dir.join(ACTIONS)), read_kept(&dir.join(ASSET_ACTIONS)));
self.usage.insert(file.to_string(), UsageCache { list, weeks, asset_weeks, dirty: false, written: now() });
}
Ok(self.usage.get_mut(file))
}
@@ -234,6 +241,37 @@ impl Store {
})
}
/// A file's library's styles' and variables' insertions and detachments week by week, over
/// the last [`MAX_WEEKS`] weeks (none when it has no library).
pub fn library_asset_actions(&mut self, file: &str) -> Result<Vec<WeekActions<String>>, String> {
let since = week_of(now()).saturating_sub((MAX_WEEKS - 1) * WEEK);
let weeks = self.usage_of(file)?.map(|u| u.asset_weeks.as_slice()).unwrap_or_default();
Ok(weeks.iter().filter(|w| w.week >= since).cloned().collect())
}
/// Note how many times one file has inserted and detached a file's library's styles and
/// variables: what its totals grew past their highest counts in this week.
pub fn report_asset_actions(&mut self, file: &str, actions: AssetActions) -> Result<(), String> {
for (counts, kind) in [(actions.inserted, Count::Inserted), (actions.detached, Count::Detached)] {
let mut grown = Vec::new();
self.report(file, &actions.file, known_assets(counts), |e, counts| {
grown = grow(&mut e.asset_peaks, &counts, kind, |_| 0);
if grown.is_empty() {
return false;
}
// Heard from for retention: evicting the row would drop asset_peaks, the
// baseline grow uses so a later identical report is not counted twice.
e.asset_updated = now();
true
})?;
if let (false, Some(u)) = (grown.is_empty(), self.usage.get_mut(file)) {
add_to_week(&mut u.asset_weeks, &grown, kind, now());
u.dirty = true;
}
}
Ok(())
}
/// Keep how many layers of one file use a file's library's styles and variables (as
/// [`Self::report_usage`] keeps its usage, beside it).
pub fn report_assets(&mut self, file: &str, assets: AssetUsage) -> Result<(), String> {
@@ -297,7 +335,7 @@ impl Store {
let at = match u.list.iter().position(|e| e.usage.file == name) {
Some(at) => at,
None => {
u.list.push(UsageEntry { usage: Usage { file: name, components: Vec::new() }, ..UsageEntry::default() });
u.list.push(UsageEntry { usage: Usage { file: name.clone(), components: Vec::new() }, ..UsageEntry::default() });
u.list.len() - 1
}
};
@@ -306,7 +344,13 @@ impl Store {
return Ok(());
}
if u.list.len() > MAX_USERS {
u.list.sort_by_key(|e| std::cmp::Reverse(e.updated.max(e.detached_updated)));
// The file just heard from stays, even when several share a timestamp (now() is
// seconds). Asset-action reports use asset_updated so their peaks are not dropped
// in favour of a usage-only row from the same second.
u.list.sort_by_key(|e| {
let recent = e.usage.file == name;
std::cmp::Reverse((e.updated.max(e.detached_updated).max(e.asset_updated), recent))
});
u.list.truncate(MAX_USERS);
}
u.dirty = true;
@@ -325,7 +369,8 @@ impl Store {
if let Err(e) = write_json(&root.join(file).join(USAGE), &u.list) {
log::warn!("file {file}: library usage couldn't be kept: {e}");
}
if let Err(e) = write_json(&root.join(file).join(ACTIONS), &u.weeks) {
let actions = write_json(&root.join(file).join(ACTIONS), &u.weeks);
if let Err(e) = actions.and_then(|()| write_json(&root.join(file).join(ASSET_ACTIONS), &u.asset_weeks)) {
log::warn!("file {file}: library analytics couldn't be kept: {e}");
}
(u.dirty, u.written) = (false, t);
@@ -345,3 +390,17 @@ fn library_file(dir: &Path, version: u64) -> PathBuf {
let path = dir.join(library_name(version));
if path.exists() { path } else { dir.join(LIBRARY) }
}
#[cfg(test)]
mod grow_tests {
use super::*;
#[test]
fn a_new_key_is_dropped_once_peaks_are_full() {
let mut peaks: Vec<(u32, u32, u32)> = (0..MAX_REPORTED as u32).map(|i| (i, 1, 0)).collect();
let grown = grow(&mut peaks, &[(MAX_REPORTED as u32, 3)], Count::Inserted, |_| 0);
assert!(grown.is_empty(), "a key past the cap must not start a peak or count as growth");
assert_eq!(peaks.len(), MAX_REPORTED);
assert!(peaks.iter().all(|p| p.0 < MAX_REPORTED as u32));
}
}
+2 -2
View File
@@ -21,8 +21,8 @@ figcraft-collab-net = { workspace = true }
figcraft-text = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): the request plumbing behind window.figcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", version = "0.1.0" }
base64 = { workspace = true }
egui = { workspace = true }
log = { workspace = true }
+1 -2
View File
@@ -17,8 +17,7 @@ figcraft-collab-net = { workspace = true }
figcraft-format = { workspace = true }
figcraft-text = { workspace = true }
# Shared decision of who draws the window frame on Linux (compositor vs. app), replacing the
# bespoke Wayland xdg-decoration probe. See `[workspace.dependencies]`: pinned to the unmerged
# craft-libs#217 branch and must be repointed to a merged `rev` before this PR is mergeable.
# bespoke Wayland xdg-decoration probe. The `rev` is set in `[workspace.dependencies]`.
craft-window = { workspace = true }
# The suite's settings folder: `FIGCRAFT_CONFIG_DIR`, a portable marker, then the platform folder.
craft-settings = { workspace = true }
+10
View File
@@ -118,3 +118,13 @@ real_name = "Ashok Ram"
[people.GiovanniBot]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
[people.Aathish-D]
real_name = "Aathish Duraiswamy"
sync_github_name = true
[people.B-uchi]
real_name = "Ibuchukwu Umeano"
+6
View File
@@ -152,6 +152,12 @@ impl<S: Socket> Driver<S> {
None => self.done = true,
}
}
exchange::Next::Tell(events, then) => {
for e in events {
self.inbox.push(e);
}
self.follow(*then, now);
}
}
}
+93 -12
View File
@@ -7,11 +7,17 @@
//! Publishing ([`publish`]) uploads the document, makes the links and codes others join with when
//! it shares, then joins the new file with its edit link; [`background`] sends the hosting and
//! sharing requests the engine sends in the background (asking a server about its hosting,
//! starting and stopping a share).
//! starting and stopping a share) and those about team libraries and plugin directories;
//! [`libraries`] the checks of a file's team libraries.
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use figcraft_collab::message::{self, Admin, AdminReply, ClientMsg, HostInfo, Manage, OpenHosting, PROTOCOL, ServerMsg};
use figcraft_collab::message::{
self, Admin, AdminReply, ClientMsg, HostInfo, LibraryReply, LibraryReq, Manage, OpenHosting, OpenLibrary, OpenPlugins, PROTOCOL, PluginReply,
PluginReq, ServerMsg,
};
use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status};
use crate::invite::{Endpoint, Invite};
@@ -21,7 +27,7 @@ use crate::requests::{self, Publish, REFUSED};
pub(crate) struct Exchange {
pub(crate) server: Endpoint,
open: ClientMsg,
requests: VecDeque<Admin>,
requests: VecDeque<ClientMsg>,
answers: Answers,
/// The server let the connection in (its first answer came).
ready: bool,
@@ -35,6 +41,9 @@ pub(crate) struct Exchange {
pub(crate) struct Answers {
pub(crate) hosting: Option<HostInfo>,
pub(crate) replies: Vec<AdminReply>,
/// The answer on a library or plugin directory connection.
pub(crate) library: Option<LibraryReply>,
pub(crate) plugins: Option<PluginReply>,
}
/// What follows an exchange's answers (or why it failed).
@@ -46,6 +55,8 @@ pub(crate) enum Next {
Ask(Box<Exchange>, Then),
/// Done: tell the UI these, then join the file this invite names (`None`: nothing to join).
Done(Vec<Event>, Option<Invite>),
/// Tell the UI these now, then go on with what follows.
Tell(Vec<Event>, Box<Next>),
}
impl Exchange {
@@ -61,7 +72,23 @@ impl Exchange {
owner: owner.to_string(),
}),
};
Self { server, open, requests: requests.into(), answers: Answers::default(), ready: false, asked: false }
Self::opened(server, open, requests.into_iter().map(ClientMsg::Admin).collect())
}
/// Ask the library of the file behind `invite` one thing.
pub(crate) fn library(invite: Invite, req: LibraryReq) -> Self {
let open = OpenLibrary { protocol: PROTOCOL, file: invite.file, token: invite.token, client_version: message::client_version() };
Self::opened(invite.server, ClientMsg::OpenLibrary(open), VecDeque::from([ClientMsg::Library(req)]))
}
/// Ask the plugin directory of `server` one thing, with its `key` (empty: only browsing).
pub(crate) fn plugins(server: Endpoint, key: String, req: PluginReq) -> Self {
let open = OpenPlugins { protocol: PROTOCOL, key, client_version: message::client_version() };
Self::opened(server, ClientMsg::OpenPlugins(open), VecDeque::from([ClientMsg::Plugins(req)]))
}
fn opened(server: Endpoint, open: ClientMsg, requests: VecDeque<ClientMsg>) -> Self {
Self { server, open, requests, answers: Answers::default(), ready: false, asked: false }
}
/// The connection's first message.
@@ -81,7 +108,11 @@ impl Exchange {
/// Why the exchange failed with `e`, as the app says it: a server older than open hosting
/// can't read the opening.
pub(crate) fn failed(&self, e: String) -> String {
if self.ready || !matches!(self.open, ClientMsg::OpenHosting(_)) { e } else { requests::hosting_error(&self.server, e) }
match self.open {
ClientMsg::OpenHosting(_) if !self.ready => requests::hosting_error(&self.server, e),
ClientMsg::OpenPlugins(_) if !self.ready => requests::directory_error(&self.server, e),
_ => e,
}
}
/// Take in one message from the server: the next request to send, if one is due; an error
@@ -99,13 +130,22 @@ impl Exchange {
self.ready = true;
self.answers.hosting = Some(*info);
}
ServerMsg::Library(r) if self.asked => self.answers.library = Some(*r),
ServerMsg::Library(r) if !self.ready => match *r {
LibraryReply::Ready { .. } => self.ready = true,
other => return Err(format!("the server answered {other:?} instead of opening the library")),
},
ServerMsg::Plugins(r) if self.asked => self.answers.plugins = Some(*r),
ServerMsg::Plugins(r) if !self.ready => match *r {
PluginReply::Ready { .. } => self.ready = true,
other => return Err(format!("the server answered {other:?} instead of opening its plugin directory")),
},
_ => return Err("the server sent something other than an answer".into()),
}
self.asked = false;
Ok(self.requests.pop_front().map(|r| {
self.asked = true;
ClientMsg::Admin(r)
}))
let next = self.requests.pop_front();
self.asked = next.is_some();
Ok(next)
}
}
@@ -204,9 +244,35 @@ fn codes(s: Sharing, links: requests::Links, then: LinksThen) -> Next {
)
}
/// The answer to a library request, from what its exchange got.
fn library_reply(answers: Result<Answers, String>) -> Result<LibraryReply, String> {
answers.and_then(|a| a.library.ok_or_else(|| "the server didn't answer".to_string()))
}
/// Ask about the team libraries `jobs` `(link, request)`, in order, each on a connection of its
/// own. A fetch's answer goes to the UI as it comes, before the next connection, as the desktop's
/// does, so a slow or silent server further on holds no library back; the others' answers are left
/// out (a report's says nothing, and an older server refuses it). `fetching` goes down at the end.
pub(crate) fn libraries(mut jobs: VecDeque<(String, LibraryReq)>, fetching: Arc<AtomicBool>) -> Next {
let Some((link, req)) = jobs.pop_front() else {
fetching.store(false, Ordering::SeqCst);
return Next::Done(Vec::new(), None);
};
let fetch = matches!(req, LibraryReq::Fetch { .. });
let invite = Invite::parse(&link);
let then = move |reply: Result<LibraryReply, String>| {
let rest = libraries(jobs, fetching);
if fetch { Next::Tell(vec![Event::Library { link, reply }], Box::new(rest)) } else { rest }
};
match invite {
Err(e) => then(Err(e)),
Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |answers| then(library_reply(answers)))),
}
}
/// Background request `req` (answered as [`Event::Net`] with `job`), for the requests the
/// browser sends: about a server's hosting, and changing who else gets into a file. `None` for
/// the others.
/// browser sends: about a server's hosting, changing who else gets into a file, its team libraries
/// and its plugin directory. `None` for the others.
pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
let answer = move |reply: NetReply| Next::Done(vec![Event::Net { job, reply: Box::new(reply) }], None);
Some(match req {
@@ -231,6 +297,21 @@ pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
share_links(Sharing { server, key, file, owner, revoke, create }, Box::new(move |r| answer(NetReply::Share(r))))
}
},
NetRequest::Plugins { .. } | NetRequest::Library { .. } | NetRequest::Upload(_) => return None,
NetRequest::Library { link, req } => match Invite::parse(&link) {
Err(e) => answer(NetReply::Library(Err(e))),
Ok(invite) => Next::Ask(Box::new(Exchange::library(invite, req)), Box::new(move |a| answer(NetReply::Library(library_reply(a))))),
},
NetRequest::Plugins { server, req } => match Endpoint::parse(&server) {
Err(e) => answer(NetReply::Plugins(Err(e))),
Ok((server, query)) => {
let key = query.into_iter().find(|(k, _)| k == "key").map(|(_, v)| v).unwrap_or_default();
let ex = Exchange::plugins(server, key.trim().to_string(), req);
Next::Ask(
Box::new(ex),
Box::new(move |a| answer(NetReply::Plugins(a.and_then(|a| a.plugins.ok_or_else(|| "the server didn't answer".to_string()))))),
)
}
},
NetRequest::Upload(_) => return None,
})
}
+112 -3
View File
@@ -4,9 +4,13 @@
//! background requests the browser can send.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use figcraft_collab::message::{self, Access, Admin, AdminReply, ClientMsg, FileInfo, HostInfo, LinkInfo, NewLink, Presence, ServerMsg};
use figcraft_collab::message::{
self, Access, Admin, AdminReply, ClientMsg, Detached, FileInfo, HostInfo, LibraryReply, LibraryReq, LinkInfo, NewLink, PluginReply, PluginReq,
Presence, ServerMsg,
};
use figcraft_doc::{Document, NodeId};
use figcraft_engine::live::{Event, NetReply, NetRequest, Shared, Status};
@@ -344,6 +348,111 @@ fn background_requests_ask_about_hosting_and_sharing() {
let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") };
assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Hosting(Err(_)) | NetReply::Share(Err(_)))));
}
let plugins = NetRequest::Plugins { server: SERVER.into(), req: figcraft_collab::message::PluginReq::List { query: String::new() } };
assert!(exchange::background(1, plugins).is_none());
}
fn library(r: LibraryReply) -> ServerMsg {
ServerMsg::Library(Box::new(r))
}
fn directory(r: PluginReply) -> ServerMsg {
ServerMsg::Plugins(Box::new(r))
}
fn link() -> String {
format!("figcraft://join?host=127.0.0.1:47910&file={FILE}&token={TOKEN}")
}
/// The browser opens a team library, asks, and takes the answer; failures come back as answers.
#[test]
fn background_requests_ask_a_team_library() {
let ready = library(LibraryReply::Ready { access: Access::View });
let req = |req| NetRequest::Library { link: link(), req };
let (reply, sent) = background(req(LibraryReq::Usage), &[ready.clone(), library(LibraryReply::Usage(Vec::new()))]);
assert!(matches!(reply, NetReply::Library(Ok(LibraryReply::Usage(u))) if u.is_empty()));
assert!(matches!(sent.as_slice(), [ClientMsg::OpenLibrary(o), ClientMsg::Library(LibraryReq::Usage)] if o.file == FILE && o.token == TOKEN));
// A refusal, and a link that isn't one.
let (reply, _) = background(req(LibraryReq::Usage), &[ServerMsg::Refused { reason: "that link was revoked".into() }]);
assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("revoked")));
let bad = NetRequest::Library { link: "nope".into(), req: LibraryReq::Usage };
let Some(Next::Done(events, None)) = exchange::background(1, bad) else { panic!("not answered at once") };
assert!(matches!(events.as_slice(), [Event::Net { reply, .. }] if matches!(**reply, NetReply::Library(Err(_)))));
// Anything but the opening's answer first is no answer.
let (reply, _) = background(req(LibraryReq::Usage), &[library(LibraryReply::Empty)]);
assert!(matches!(reply, NetReply::Library(Err(e)) if e.contains("instead of opening the library")));
}
/// The browser asks a plugin directory, with the address's key when it has one.
#[test]
fn background_requests_ask_a_plugin_directory() {
let ready = directory(PluginReply::Ready { publisher: true });
let req = PluginReq::List { query: String::new() };
let ask = NetRequest::Plugins { server: format!("{SERVER}?key=k3y"), req: req.clone() };
let (reply, sent) = background(ask, &[ready, directory(PluginReply::List(Vec::new()))]);
assert!(matches!(reply, NetReply::Plugins(Ok(PluginReply::List(entries))) if entries.is_empty()));
assert!(matches!(sent.as_slice(), [ClientMsg::OpenPlugins(o), ClientMsg::Plugins(_)] if o.key == "k3y"));
// A server from before directories can't read the opening.
let older = NetRequest::Plugins { server: SERVER.into(), req };
let (reply, _) = background(older, &[ServerMsg::Refused { reason: "that couldn't be read".into() }]);
assert!(matches!(reply, NetReply::Plugins(Err(e)) if e.contains("has no plugin directory")));
let bad = NetRequest::Plugins { server: "nope".into(), req: PluginReq::List { query: String::new() } };
assert!(matches!(exchange::background(1, bad), Some(Next::Done(..))));
}
/// A file's check of its team libraries runs its requests in order, each on a connection of its
/// own; only fetches come back, whatever a report's answer, and a bad link doesn't stop the rest.
#[test]
fn a_library_check_runs_in_order_and_answers_only_its_fetches() {
let fetch = LibraryReq::Fetch { have: None, usage: None };
let jobs = vec![
("nope".to_string(), fetch.clone()),
(link(), fetch),
(link(), LibraryReq::ReportDetached(Detached::default())),
(link(), LibraryReq::ReportInserted(Detached::default())),
];
let fetching = Arc::new(AtomicBool::new(true));
let t0 = Instant::now();
let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0);
let ready = library(LibraryReply::Ready { access: Access::View });
d.opened(t0);
say(&mut d, &ready, t0);
say(&mut d, &library(LibraryReply::Empty), t0);
d.opened(t0);
say(&mut d, &ready, t0);
// An older server refuses the report: the check goes on.
say(&mut d, &library(LibraryReply::Failed { reason: "no".into() }), t0);
d.opened(t0);
say(&mut d, &ServerMsg::Refused { reason: "couldn't be read".into() }, t0);
assert!(!fetching.load(Ordering::SeqCst), "the next check may start");
let events = inbox.drain();
let replies: Vec<_> = events.iter().filter_map(|e| if let Event::Library { reply, .. } = e { Some(reply) } else { None }).collect();
assert_eq!(replies.len(), 2, "{events:#?}");
assert!(replies[0].is_err());
assert!(matches!(replies[1], Ok(LibraryReply::Empty)));
}
/// A fetch's answer reaches the UI as it comes, not at the end of the check: a report after it
/// whose server never answers holds the first library back no longer than its own connection.
#[test]
fn a_library_check_hands_each_fetch_over_as_it_comes() {
let fetch = LibraryReq::Fetch { have: None, usage: None };
let jobs = vec![(link(), fetch.clone()), (link(), LibraryReq::ReportDetached(Detached::default())), (link(), fetch)];
let fetching = Arc::new(AtomicBool::new(true));
let t0 = Instant::now();
let (mut d, inbox) = run(exchange::libraries(jobs.into(), fetching.clone()), t0);
let fetched = |events: &[Event]| events.iter().filter(|e| matches!(e, Event::Library { .. })).count();
let ready = library(LibraryReply::Ready { access: Access::View });
d.opened(t0);
say(&mut d, &ready, t0);
say(&mut d, &library(LibraryReply::Empty), t0);
assert_eq!(fetched(&inbox.drain()), 1, "the first library is in while the report's server is asked");
// The report's connection never opens: the check gives up on it and goes on, saying nothing.
let t1 = t0 + Duration::from_secs(5);
d.tick(t1);
assert_eq!(fetched(&inbox.drain()), 0);
assert!(fetching.load(Ordering::SeqCst), "the check is still running");
d.opened(t1);
say(&mut d, &ready, t1);
say(&mut d, &library(LibraryReply::Empty), t1);
assert_eq!(fetched(&inbox.drain()), 1);
assert!(!fetching.load(Ordering::SeqCst) && d.done());
}
+3 -2
View File
@@ -8,8 +8,9 @@
//! engine's `collab.*` commands drive it and the UI reads the engine's live state. Network
//! threads wake the UI through a [`Waker`] only when something arrives; nothing polls.
//!
//! The browser build's [`NetLink`] joins sessions and publishes files to servers through the
//! browser's WebSocket API (`web-sys`); hosting a session needs the desktop app. Its connection
//! The browser build's [`NetLink`] joins sessions, publishes files to servers and asks them about
//! team libraries and plugin directories through the browser's WebSocket API (`web-sys`); hosting
//! a session needs the desktop app. Its connection
//! logic (`driver.rs`, `exchange.rs`) is target-independent and tested natively.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+4 -1
View File
@@ -277,7 +277,10 @@ impl LiveLink for NetLink {
let spawned = std::thread::Builder::new().name("library-fetch".into()).spawn(move || {
for (link, req) in jobs {
// A report's answer says nothing about the library (and an older server refuses it).
let report = matches!(req, LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_));
let report = matches!(
req,
LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_)
);
let reply = manage::library(&link, req, &limits, CONNECT);
if !report {
inbox.push(Event::Library { link, reply });
+2 -3
View File
@@ -17,7 +17,7 @@ use crate::invite::{Endpoint, Invite, Lookup};
use crate::join::ask;
use crate::net::{Duplex, NetLimits, config, open};
pub(crate) use crate::requests::REFUSED;
use crate::requests::{code_requests, comment_request, hosting_error, link_requests, made_comment, made_links, shared};
use crate::requests::{code_requests, comment_request, directory_error, hosting_error, link_requests, made_comment, made_links, shared};
type Ws = WebSocket<Duplex>;
@@ -165,8 +165,7 @@ pub fn plugins(server: &Endpoint, key: &str, req: PluginReq, limits: &NetLimits,
match reply(&mut ws, limits, pick) {
Ok(PluginReply::Ready { .. }) => {}
// An older server can't read the request at all.
Err(e) if e.contains("couldn't be read") => return Err(format!("{} has no plugin directory (update the server)", server.display())),
Err(e) => return Err(e),
Err(e) => return Err(directory_error(server, e)),
Ok(other) => return Err(format!("the server answered {other:?} instead of opening its plugin directory")),
}
send(&mut ws, &ClientMsg::Plugins(req))?;
+6
View File
@@ -43,6 +43,12 @@ pub(crate) fn key_over_tls(server: &Endpoint, key: Option<&str>) -> Result<(), S
/// Why asking `server` about its hosting failed with `e`: a server older than open hosting can't
/// read the question.
/// Why opening `server`'s plugin directory failed with `e`: a server from before directories can't
/// read the opening.
pub(crate) fn directory_error(server: &Endpoint, e: String) -> String {
if e.contains("couldn't be read") { format!("{} has no plugin directory (update the server)", server.display()) } else { e }
}
pub(crate) fn hosting_error(server: &Endpoint, e: String) -> String {
if e.contains("couldn't be read") {
format!("{} takes files only with its key (it is older than this app): add ?key=… to the address", server.display())
+23 -8
View File
@@ -17,8 +17,10 @@
use std::cell::{Cell, RefCell};
use std::collections::BTreeMap;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use figcraft_collab::message::{ClientMsg, Presence};
use figcraft_collab::message::{ClientMsg, LibraryReq, Presence};
use figcraft_engine::live::{Event, HostOptions, LiveLink, NO_SESSION, NetRequest, PublishOptions, SessionId, SessionInfo};
use wasm_bindgen::JsCast as _;
use wasm_bindgen::closure::Closure;
@@ -163,19 +165,29 @@ fn socket() -> (u64, BrowserSocket) {
(id, BrowserSocket { id, ws: None })
}
/// The browser's [`LiveLink`]: joins sessions and publishes files to servers; hosting a session
/// needs the desktop app.
/// The browser's [`LiveLink`]: joins sessions, publishes files to servers and asks them about team
/// libraries and plugin directories; hosting a session needs the desktop app.
pub struct NetLink {
/// Each session's number in the thread-local table.
sessions: Sessions<u64>,
/// Answers to requests sent in the background (outlives sessions).
background: Inbox,
/// A check of the team libraries is out.
fetching: Arc<AtomicBool>,
}
impl NetLink {
/// `wake` is called whenever something arrives for the UI (egui's `request_repaint`).
pub fn new(wake: Waker) -> Self {
Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake) }
Self { background: Inbox::new(wake.clone()), sessions: Sessions::new(wake), fetching: Arc::default() }
}
/// Run `next` on a connection of its own, its answers for the background.
fn ask(&self, next: exchange::Next) {
let (id, sock) = socket();
// The exchanges name their own servers.
let cfg = GuestConfig::new(Invite::new("", "", ""), String::new());
run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now()));
}
/// Session `session` runs on connection `id` now (the one it had ends).
@@ -229,13 +241,16 @@ impl LiveLink for NetLink {
fn background(&mut self, job: u64, req: NetRequest) -> bool {
let Some(next) = exchange::background(job, req) else { return false };
let (id, sock) = socket();
// The exchanges name their own servers.
let cfg = GuestConfig::new(Invite::new("", "", ""), String::new());
run(id, Driver::asking(sock, cfg, next, self.background.clone(), Instant::now()));
self.ask(next);
true
}
fn library_background(&mut self, jobs: Vec<(String, LibraryReq)>) {
if !jobs.is_empty() && !self.fetching.swap(true, Ordering::SeqCst) {
self.ask(exchange::libraries(jobs.into(), self.fetching.clone()));
}
}
fn leave(&mut self, session: SessionId) {
if let Some(id) = self.sessions.remove(session) {
with_driver(id, |d, now| d.leave(now));
+18 -2
View File
@@ -629,6 +629,15 @@ pub struct AssetUsage {
pub variables: Vec<(String, u32)>,
}
/// How many times one file has inserted and detached a library's styles and variables, as its app
/// reports them: its name and its totals of each (by their ids in the library).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetActions {
pub file: String,
pub inserted: Vec<(String, u32)>,
pub detached: Vec<(String, u32)>,
}
/// A file's last usage report, with when it came (seconds since 1970, UTC).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileUsage {
@@ -655,9 +664,9 @@ pub struct FileDetached {
/// 1970 UTC, a Monday at 00:00), over every file that reported it: instances inserted (placed,
/// pasted or duplicated) and detached, counted when the server first heard of them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WeekActions {
pub struct WeekActions<K = NodeId> {
pub week: u64,
pub component: NodeId,
pub component: K,
pub insertions: u32,
pub detachments: u32,
}
@@ -692,6 +701,12 @@ pub enum LibraryReq {
ReportAssets(AssetUsage),
/// The style and variable reports of the files that use the library.
Assets,
/// How many times the asking file has inserted and detached the library's styles and variables
/// (answered with [`LibraryReply::Noted`]).
ReportAssetActions(AssetActions),
/// The library's styles' and variables' insertions and detachments week by week (answered with
/// [`LibraryReply::AssetActions`]).
AssetActions,
}
/// The answer to a [`LibraryReq`] (the first one on a connection answers [`OpenLibrary`]).
@@ -727,6 +742,7 @@ pub enum LibraryReply {
Detached(Vec<FileDetached>),
Actions(Vec<WeekActions>),
Assets(Vec<AssetUsage>),
AssetActions(Vec<WeekActions<String>>),
}
/// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach
+13 -2
View File
@@ -10,7 +10,7 @@ use figcraft_geom::kurbo::{Ellipse, RoundedRect};
use figcraft_geom::{BezPath, Point, Rect, Shape, Vec2};
use serde::{Deserialize, Serialize};
use crate::NodeId;
use crate::{CodeLanguage, NodeId};
/// What a file is for: designing screens, or a board to think together on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -65,6 +65,12 @@ pub enum BoardItem {
/// A mind map's node: a frame hugging its text, with no outline. What it hangs from is the
/// branch (a connector with `branch`) arriving at it.
MindNode,
/// A code block: a dark panel holding one monospace text (its first text layer), as wide as
/// it was made and as tall as its lines. `language` picks the highlighting.
CodeBlock {
#[serde(default)]
language: CodeLanguage,
},
}
impl BoardItem {
@@ -79,12 +85,16 @@ impl BoardItem {
| BoardItem::Stamp { .. }
| BoardItem::Table
| BoardItem::MindNode
| BoardItem::CodeBlock { .. }
)
}
/// Objects whose first text layer is their text (a double-click or Enter edits it).
pub fn has_text(&self) -> bool {
matches!(self, BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode)
matches!(
self,
BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode | BoardItem::CodeBlock { .. }
)
}
/// Who made it (stickies and stamps; empty when unknown).
@@ -127,6 +137,7 @@ impl BoardItem {
BoardItem::Ink => "ink",
BoardItem::Table => "table",
BoardItem::MindNode => "mindNode",
BoardItem::CodeBlock { .. } => "codeBlock",
}
}
}
+118
View File
@@ -0,0 +1,118 @@
//! Code blocks (#2237): the languages a block is highlighted as, and the numbers of its look.
//! Pure data: the engine makes the block ([`crate::BoardItem::CodeBlock`]).
use figcraft_color::Color;
use serde::{Deserialize, Serialize};
/// The language a code block is highlighted as.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CodeLanguage {
Bash,
Cpp,
Css,
Go,
Graphql,
Html,
Javascript,
Json,
Kotlin,
PlainText,
Python,
Ruby,
Rust,
Sql,
Swift,
#[default]
Typescript,
}
impl CodeLanguage {
/// In menu order: by name.
pub const ALL: [CodeLanguage; 16] = [
CodeLanguage::Bash,
CodeLanguage::Cpp,
CodeLanguage::Css,
CodeLanguage::Go,
CodeLanguage::Graphql,
CodeLanguage::Html,
CodeLanguage::Javascript,
CodeLanguage::Json,
CodeLanguage::Kotlin,
CodeLanguage::PlainText,
CodeLanguage::Python,
CodeLanguage::Ruby,
CodeLanguage::Rust,
CodeLanguage::Sql,
CodeLanguage::Swift,
CodeLanguage::Typescript,
];
/// The id used in commands and saved files ("cpp", "plainText", "typescript").
pub fn id(self) -> &'static str {
self.names().0
}
/// The name shown in the UI ("C++", "Plain text", "TypeScript").
pub fn label(self) -> &'static str {
self.names().1
}
/// The id and the name shown.
fn names(self) -> (&'static str, &'static str) {
match self {
CodeLanguage::Bash => ("bash", "Bash"),
CodeLanguage::Cpp => ("cpp", "C++"),
CodeLanguage::Css => ("css", "CSS"),
CodeLanguage::Go => ("go", "Go"),
CodeLanguage::Graphql => ("graphql", "GraphQL"),
CodeLanguage::Html => ("html", "HTML"),
CodeLanguage::Javascript => ("javascript", "JavaScript"),
CodeLanguage::Json => ("json", "JSON"),
CodeLanguage::Kotlin => ("kotlin", "Kotlin"),
CodeLanguage::PlainText => ("plainText", "Plain text"),
CodeLanguage::Python => ("python", "Python"),
CodeLanguage::Ruby => ("ruby", "Ruby"),
CodeLanguage::Rust => ("rust", "Rust"),
CodeLanguage::Sql => ("sql", "SQL"),
CodeLanguage::Swift => ("swift", "Swift"),
CodeLanguage::Typescript => ("typescript", "TypeScript"),
}
}
/// By id or by name, in any case, trimmed ("cpp", "C++", "plain text").
pub fn from_id(s: &str) -> Option<CodeLanguage> {
let s = s.trim();
CodeLanguage::ALL.into_iter().find(|l| l.id().eq_ignore_ascii_case(s) || l.label().eq_ignore_ascii_case(s))
}
}
/// The font code is set in (always this family; the machine finds the nearest when it is absent).
pub const CODE_FONT: &str = "Liberation Mono";
pub const CODE_FONT_SIZE: f64 = 16.0;
/// A line of code: 150% of the size.
pub const CODE_LINE: f64 = 24.0;
/// Room around the code: top, right, bottom, left (the left holds the line numbers).
pub const CODE_PAD: [f64; 4] = [16.0, 16.0, 16.0, 64.0];
pub const CODE_MIN_LINES: usize = 4;
/// A block's least height: four lines.
pub const CODE_MIN_H: f64 = 128.0;
pub const CODE_WIDTH: f64 = 576.0;
pub const CODE_MIN_W: f64 = 210.0;
pub const CODE_MAX_W: f64 = 100_000.0;
/// The room between a block and the next one made beside it.
pub const CODE_GAP: f64 = 128.0;
pub const CODE_RADIUS: f64 = 10.0;
/// What Tab types in a block.
pub const CODE_TAB: &str = " ";
/// The most characters `board.codeBlock` takes.
pub const CODE_MAX_CHARS: usize = 100_000;
/// The panel: the board's ink.
pub const CODE_PANEL: Color = Color::from_rgb8_const(0x1E, 0x1E, 0x1E);
/// Plain code: the board's gray.
pub const CODE_TEXT: Color = Color::from_rgb8_const(0xE3, 0xE1, 0xDD);
/// A block's height holding `lines` visual lines (four at least): 32 + 24 a line.
pub fn code_height(lines: usize) -> f64 {
CODE_PAD[0] + CODE_PAD[2] + CODE_LINE * lines.clamp(CODE_MIN_LINES, 1_000_000) as f64
}
+58
View File
@@ -0,0 +1,58 @@
//! Code blocks (#2237): the languages, the saved item, the height rule and the colours.
use serde_json::json;
use crate::BoardItem;
use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, code_height};
#[test]
fn sixteen_languages_by_name_with_typescript_the_default() {
assert_eq!(CodeLanguage::ALL.len(), 16);
let ids: std::collections::BTreeSet<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect();
assert_eq!(ids.len(), 16, "ids are unique");
let labels: Vec<String> = CodeLanguage::ALL.iter().map(|l| l.label().to_lowercase()).collect();
assert!(labels.windows(2).all(|w| w[0] < w[1]), "labels ascend: {labels:?}");
for l in CodeLanguage::ALL {
assert_eq!(CodeLanguage::from_id(l.id()), Some(l));
assert_eq!(CodeLanguage::from_id(l.label()), Some(l));
assert_eq!(serde_json::to_value(l).unwrap(), json!(l.id()));
}
assert_eq!(CodeLanguage::from_id("CPP"), Some(CodeLanguage::Cpp));
assert_eq!(CodeLanguage::from_id("c++"), Some(CodeLanguage::Cpp));
assert_eq!(CodeLanguage::from_id(" plain text "), Some(CodeLanguage::PlainText));
assert_eq!(CodeLanguage::from_id("markdown"), None);
assert_eq!(CodeLanguage::from_id(""), None);
assert_eq!(CodeLanguage::default(), CodeLanguage::Typescript);
}
#[test]
fn a_code_block_item_saves_its_language() {
let item = BoardItem::CodeBlock { language: CodeLanguage::Rust };
let v = json!({"type": "codeBlock", "language": "rust"});
assert_eq!(serde_json::to_value(&item).unwrap(), v);
assert_eq!(serde_json::from_value::<BoardItem>(v).unwrap(), item);
let plain: BoardItem = serde_json::from_value(json!({"type": "codeBlock"})).unwrap();
assert_eq!(plain, BoardItem::CodeBlock { language: CodeLanguage::Typescript });
assert!(serde_json::from_value::<BoardItem>(json!({"type": "codeBlock", "language": "klingon"})).is_err());
assert_eq!(item.kind_id(), "codeBlock");
assert!(item.is_atom());
assert!(item.has_text());
}
#[test]
fn the_height_is_32_and_24_a_line_from_four_lines_up() {
assert_eq!(code_height(0), 128.0);
assert_eq!(code_height(1), 128.0);
assert_eq!(code_height(4), 128.0);
assert_eq!(code_height(5), 152.0);
assert_eq!(code_height(9), 248.0);
assert!(code_height(usize::MAX).is_finite());
assert_eq!(CODE_MIN_H, code_height(0));
assert_eq!(CODE_PAD[0] + CODE_PAD[2], 32.0);
assert_eq!(CODE_PAD[1] + CODE_PAD[3], 80.0);
}
#[test]
fn plain_code_reads_on_the_panel() {
assert!(CODE_TEXT.contrast(CODE_PANEL) >= 4.5, "{}", CODE_TEXT.contrast(CODE_PANEL));
}
+6
View File
@@ -9,6 +9,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod board;
mod board_code;
mod board_mindmap;
mod board_route;
pub mod colors;
@@ -28,6 +29,7 @@ pub mod vector_faces;
pub mod vector_regions;
pub use board::*;
pub use board_code::*;
pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, MindBox, mind_layout};
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
pub use colors::*;
@@ -1321,6 +1323,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap<NodeId, NodeId>) {
#[cfg(test)]
mod blur_tests;
#[cfg(test)]
mod board_code_tests;
#[cfg(test)]
mod board_mindmap_tests;
#[cfg(test)]
mod board_route_tests;
@@ -1355,6 +1359,8 @@ mod proto_overlay_anchor_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod vector_radius_tests;
#[cfg(test)]
mod vector_regions_tests;
#[cfg(test)]
mod width_sides_tests;
+31
View File
@@ -217,6 +217,10 @@ pub struct Libraries {
/// or duplicated; reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] components.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inserted: Vec<DetachCount>,
/// How often this document has inserted and detached each library style and variable
/// (reported like [`Self::detached`]), at most [`MAX_DETACH_COUNTS`] of them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub asset_counts: Vec<AssetCount>,
}
/// Most library components a document counts detaches for.
@@ -233,6 +237,17 @@ pub struct DetachCount {
pub count: u32,
}
/// Inserts and detaches of one library style or variable in a document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetCount {
/// The library's id.
pub library: String,
/// Its id in the library.
pub key: String,
pub inserted: u32,
pub detached: u32,
}
/// Count one more instance of component `key` of library `library` in `list` (a component not
/// counted yet is left out once [`MAX_DETACH_COUNTS`] are).
fn count(list: &mut Vec<DetachCount>, library: &str, key: NodeId) {
@@ -256,6 +271,21 @@ impl Libraries {
count(&mut self.inserted, library, key);
}
/// Count `n` more inserts (or, with `detach`, detaches) of style or variable `key` of library
/// `library` (one not counted yet is left out once [`MAX_DETACH_COUNTS`] are).
pub fn count_asset(&mut self, library: &str, key: &str, detach: bool, n: u32) {
let at = self.asset_counts.iter().position(|c| c.library == library && c.key == key);
let at = at.or_else(|| {
let room = self.asset_counts.len() < MAX_DETACH_COUNTS;
room.then(|| self.asset_counts.push(AssetCount { library: library.to_string(), key: key.to_string(), inserted: 0, detached: 0 }))?;
Some(self.asset_counts.len() - 1)
});
if let Some(c) = at.and_then(|at| self.asset_counts.get_mut(at)) {
let total = if detach { &mut c.detached } else { &mut c.inserted };
*total = total.saturating_add(n);
}
}
/// Whether nothing is enabled, kept or counted.
pub fn is_empty(&self) -> bool {
self.enabled.is_empty()
@@ -266,6 +296,7 @@ impl Libraries {
&& self.variables.is_empty()
&& self.detached.is_empty()
&& self.inserted.is_empty()
&& self.asset_counts.is_empty()
}
/// Serde helper: leave the field out of files that use no libraries.
+49 -11
View File
@@ -145,6 +145,25 @@ struct Corner {
cut2: f64,
}
/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the
/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from
/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths.
struct Turn {
v: usize,
r: f64,
s1: usize,
a1: bool,
s2: usize,
a2: bool,
c1: CubicBez,
c2: CubicBez,
u1: Vec2,
u2: Vec2,
angle: f64,
l1: f64,
l2: f64,
}
/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to
/// those ends, and the point it ends at.
struct CornerCurve {
@@ -391,10 +410,11 @@ impl VectorNetwork {
}
/// The network with its rounded points drawn in: each sharp point with a corner radius becomes
/// an arc between its two segments (the radius shrinks so the arc fits in half of each
/// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps
/// the rest of its curve, the arc leaving along its direction there. `None` when no point is
/// rounded.
/// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other
/// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose
/// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where
/// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there.
/// `None` when no point is rounded.
pub fn rounded(&self) -> Option<VectorNetwork> {
self.rounded_smoothed(0.0)
}
@@ -424,7 +444,9 @@ impl VectorNetwork {
*x = true;
}
}
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect();
let turns: Vec<Option<Turn>> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect();
let rounds: Vec<bool> = turns.iter().map(Option::is_some).collect();
let corners: Vec<Corner> = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect();
let mut out = self.clone();
for v in &mut out.vertices {
v.radius = 0.0;
@@ -558,10 +580,9 @@ impl VectorNetwork {
joining.next().is_none().then_some(first)
}
/// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments
/// run on smoothly or fold back. With `smoothing`, a point between two straight segments that
/// are both `on_loop` gets a smoothed corner.
fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option<Corner> {
/// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two
/// segments that neither run on smoothly nor fold back there.
fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option<Turn> {
let r = self.vertices.get(v)?.radius;
let [(s1, a1), (s2, a2)] = *incident else { return None };
if !(r > 0.0 && r.is_finite()) || s1 == s2 {
@@ -577,6 +598,23 @@ impl VectorNetwork {
if !(l1 > 1e-9 && l2 > 1e-9) {
return None;
}
Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 })
}
/// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner
/// there may reach: all of it when the other end stays sharp, half when that end is rounded
/// too (`rounds`, by point) and takes the other half.
fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 {
let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a });
if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l }
}
/// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as
/// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point
/// between two straight segments that are both `on_loop` gets a smoothed corner.
fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option<Corner> {
let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p;
let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds));
let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t };
let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false);
if smoothing > 0.0
@@ -584,7 +622,7 @@ impl VectorNetwork {
&& is_line(&c2)
&& closed(s1)
&& closed(s2)
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing)
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing)
&& let (Some(first), Some(last)) = (curves.first(), curves.last())
{
let (a, b) = (first.p0, last.p3);
@@ -595,7 +633,7 @@ impl VectorNetwork {
let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2);
return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) });
}
let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0);
let t = (r / (angle / 2.0).tan()).min(reach);
let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2));
// A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between
// them and ρ the radius of the circle through both ends (the corner radius between lines).
+118
View File
@@ -0,0 +1,118 @@
//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the
//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single
//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other.
use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg};
use figcraft_geom::{BezPath, Point};
use crate::vector::VectorNetwork;
/// A 100 × 100 square's points: top left, top right, bottom right, bottom left.
const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
/// A network through `pts` (closed or open) whose points have radii `radii`.
fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork {
let mut n = VectorNetwork::from_points(pts, closed);
for (v, r) in n.vertices.iter_mut().zip(radii) {
v.radius = *r;
}
n
}
/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight).
fn curves(path: &BezPath) -> Vec<CubicBez> {
path.segments()
.filter_map(|s| match s {
PathSeg::Cubic(c) => Some(c),
_ => None,
})
.collect()
}
/// Whether `a` and `b` are the same point to within rounding.
fn near(a: Point, b: Point) -> bool {
(a - b).hypot() < 1e-9
}
/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc
/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the
/// circle's radius is `t`), and no other curve.
fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) {
let got = curves(path);
assert_eq!(got.len(), want.len(), "{why}: {got:?}");
for &(corner, prev, next, t) in want {
let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t;
let (a, b) = (toward(prev), toward(next));
let center = a + (b - corner);
let mid = center + (corner - center) / (corner - center).hypot() * t;
// Two arcs can share both ends (opposite corners of a square), so the middle picks one.
let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a));
let passing: Vec<Point> = got.iter().filter(ends).map(|c| c.eval(0.5)).collect();
assert!(
passing.iter().any(|&m| near(m, mid)),
"{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}"
);
}
}
#[test]
fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() {
let [tl, tr, br, bl] = SQUARE;
// (radii of [top left, top right, bottom right, bottom left], each arc as (point, its
// neighbours, how far it reaches along both), derivation)
#[allow(clippy::type_complexity)]
let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![
([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"),
([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"),
([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"),
([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"),
(
[0.0, 10.0, 100.0, 0.0],
vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)],
"the segment to the rounded top right is shared, half each, and the shorter room wins",
),
(
[100.0, 0.0, 100.0, 0.0],
vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)],
"opposite points share no segment: each reaches its sharp neighbours (a lens)",
),
(
[100.0; 4],
vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)],
"every point rounded: a circle, as before",
),
];
for (radii, want, why) in rows {
let net = network(&SQUARE, true, &radii);
assert_arcs(&net.fill_path(), &want, why);
assert_arcs(&net.stroke_path(), &want, why);
// The stored radii stay as they were set.
assert_eq!(net.vertices.iter().map(|p| p.radius).collect::<Vec<_>>(), radii.to_vec(), "{why}");
}
}
#[test]
fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() {
let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)];
// (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no
// room from the middle point.
let rows: Vec<([f64; 3], &str)> =
vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")];
for (radii, why) in rows {
let net = network(&pts, false, &radii);
assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why);
}
}
#[test]
fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() {
// Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100
// side (50) would cut smoothing down; the whole side next to sharp points leaves all of it.
let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]);
let path = net.rounded_smoothed(0.6).unwrap().fill_path();
let ends: Vec<Point> = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect();
for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] {
assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}");
}
assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}");
}
+121
View File
@@ -72,6 +72,127 @@ fn fill_on_a_child_turns_the_hugging_parent_fixed() {
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
}
fn name_of(s: &Session, node: NodeId) -> String {
s.doc().unwrap().node(node).unwrap().name.clone()
}
/// Measured in Figma web (2026-11-08): across the flow a Fill child
/// leaves its hugging parent hugging and takes the line's cross size; the parent turns Fixed (with
/// a notice) only when no non-Fill child is left on that axis.
#[test]
fn fill_across_a_hugging_parent_keeps_it_hugging_and_takes_the_line() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let a = rect(&mut s, f, 4.0, 20.0, "#FF0000");
let b = rect(&mut s, f, 50.0, 40.0, "#0000FF");
assert_eq!(size(&s, f), (54.0, 40.0));
s.message = None;
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug), "a non-Fill sibling is left: the parent keeps hugging");
assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fill));
assert_eq!((size(&s, a), size(&s, f)), ((4.0, 40.0), (54.0, 40.0)));
assert_eq!(s.message, None, "no notice");
// The sibling grows: the bar and the parent follow.
set(&mut s, b, json!({"height": 60}));
assert_eq!((size(&s, a), size(&s, f)), ((4.0, 60.0), (54.0, 60.0)));
// The last non-Fill child fills too: the parent turns Fixed at its current height, with a notice.
set(&mut s, b, json!({"sizingV": "fill"}));
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Fixed));
assert_eq!(s.message, Some(format!("Height set to Fixed for {}", name_of(&s, f))));
assert_eq!((size(&s, a), size(&s, b), size(&s, f)), ((4.0, 60.0), (50.0, 60.0), (54.0, 60.0)));
set(&mut s, f, json!({"height": 80}));
assert_eq!((size(&s, a), size(&s, b)), ((4.0, 80.0), (50.0, 80.0)));
// One undo step puts the sizing back.
s.undo().unwrap();
s.undo().unwrap();
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
assert_eq!(sizing(&s, b), (Sizing::Fixed, Sizing::Fixed));
}
#[test]
fn fill_along_a_hugging_parent_notes_that_the_width_is_fixed() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let a = rect(&mut s, f, 50.0, 20.0, "#FF0000");
rect(&mut s, f, 30.0, 40.0, "#0000FF");
s.message = None;
set(&mut s, a, json!({"sizingH": "fill"}));
assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug));
assert_eq!(s.message, Some(format!("Width set to Fixed for {}", name_of(&s, f))));
// A Fill that changes nothing about the parent has no notice.
s.message = None;
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(s.message, None);
}
#[test]
fn hugging_a_row_notes_the_child_that_filled_its_width_turned_fixed() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "fixed", "sizingV": "fixed"}));
let a = rect(&mut s, f, 50.0, 20.0, "#FF0000");
rect(&mut s, f, 30.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingH": "fill"}));
assert_eq!(sizing(&s, a).0, Sizing::Fill);
s.message = None;
set(&mut s, f, json!({"sizingH": "hug"}));
assert_eq!(sizing(&s, a).0, Sizing::Fixed);
assert_eq!(s.message, Some(format!("Width set to Fixed for {}", name_of(&s, a))));
}
#[test]
fn hugging_a_row_keeps_and_does_not_note_the_child_that_fills_across_it() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "fixed", "sizingV": "fixed"}));
let a = rect(&mut s, f, 50.0, 20.0, "#FF0000");
rect(&mut s, f, 30.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingV": "fill"}));
s.message = None;
set(&mut s, f, json!({"sizingV": "hug"}));
assert_eq!(sizing(&s, a).1, Sizing::Fill);
assert_eq!(s.message, None);
}
#[test]
fn a_fill_childs_min_counts_toward_the_hugging_size() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
let a = rect(&mut s, f, 4.0, 20.0, "#FF0000");
let b = rect(&mut s, f, 50.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingV": "fill"}));
set(&mut s, a, json!({"minHeight": 50}));
assert_eq!(sizing(&s, f), (Sizing::Hug, Sizing::Hug));
assert_eq!((size(&s, a), size(&s, b), size(&s, f)), ((4.0, 50.0), (50.0, 40.0), (54.0, 50.0)));
}
#[test]
fn a_parent_set_back_to_hug_keeps_the_child_that_fills_across_it() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "fixed", "height": 100}));
let a = rect(&mut s, f, 4.0, 20.0, "#FF0000");
rect(&mut s, f, 50.0, 40.0, "#0000FF");
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(size(&s, a), (4.0, 100.0));
set(&mut s, f, json!({"sizingV": "hug"}));
assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fill), "a non-Fill sibling is left on that axis");
assert_eq!((size(&s, a), size(&s, f)), ((4.0, 40.0), (54.0, 40.0)));
}
#[test]
fn fill_across_a_wrapping_row_that_hugs_that_axis_is_not_offered() {
let mut s = Session::new();
let f = al_frame(&mut s, json!({"wrap": true, "sizingH": "fixed", "sizingV": "hug", "width": 120}));
let a = rect(&mut s, f, 40.0, 20.0, "#FF0000");
let r = s.execute("node.set", &json!({"id": a, "props": {"sizingV": "fill"}}));
assert!(r.is_err(), "Fill height in a wrapping row that hugs its height");
assert_eq!(sizing(&s, a), (Sizing::Fixed, Sizing::Fixed));
assert_eq!(sizing(&s, f), (Sizing::Fixed, Sizing::Hug));
// Along the flow a wrapping row still takes Fill width, and with a fixed height Fill height.
set(&mut s, a, json!({"sizingH": "fill"}));
set(&mut s, f, json!({"sizingV": "fixed"}));
set(&mut s, a, json!({"sizingV": "fill"}));
assert_eq!(sizing(&s, a), (Sizing::Fill, Sizing::Fill));
}
#[test]
fn a_child_resized_to_the_full_available_space_becomes_fill() {
// Documented: "Child objects of an auto layout frame will also be set to Fill container if
+23 -1
View File
@@ -336,6 +336,28 @@ fn index_old_layers(doc: &Document, inst: NodeId, spare: BTreeMap<NodeId, std::s
(old, by_source, by_src)
}
/// The `ChildLayout` of an instance's rebuilt root. Its placement is its own (absolute position,
/// grid cell, min and max). `sizing_h` / `sizing_v` serve two roles: how a frame sizes its own
/// content (Hug, Fixed), which follows the main unless the instance overrides its size (measured in
/// Figma: a plain instance turns Fixed when its main does and back to Hug with it; a typed width
/// stays), and Fill in an auto layout parent, which is the instance's own and is kept.
fn instance_child_layout(doc: &Document, root: &Node, comp: &Node) -> figcraft_doc::ChildLayout {
let mut cl = root.child_layout.clone();
// One "size" override covers both axes, as in Figma ("Reset size"): it keeps both.
if root.overrides.contains("size") || root.overrides.contains("resizing") {
return cl;
}
let in_flow = root.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some());
let take = |own: &mut figcraft_doc::Sizing, main: figcraft_doc::Sizing| {
if !(in_flow && *own == figcraft_doc::Sizing::Fill) && main != figcraft_doc::Sizing::Fill {
*own = main;
}
};
take(&mut cl.sizing_h, comp.child_layout.sizing_h);
take(&mut cl.sizing_v, comp.child_layout.sizing_v);
cl
}
/// The rebuilt root of instance `inst` of `comp`.
fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, component: NodeId, map: &BTreeMap<NodeId, NodeId>) -> Node {
// Root: follows the main except its own placement, name, size and overrides.
@@ -351,7 +373,7 @@ fn fresh_root(doc: &Document, root: &mut Node, comp: &Node, inst: NodeId, compon
let nested_copy = inside_instance(doc, inst);
fresh.source = if nested_copy { root.source } else { Some(component) };
fresh.constraints = root.constraints;
fresh.child_layout = root.child_layout.clone();
fresh.child_layout = instance_child_layout(doc, root, comp);
fresh.interactions = root.interactions.clone();
fresh.exports = root.exports.clone();
fresh.prop_refs = root.prop_refs.clone();
+106 -21
View File
@@ -83,14 +83,66 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option<NodeId> {
chain.into_iter().rfind(|c| doc.node(*c).is_some_and(is_asset))
}
/// The styles and variables layer `n` links to, each once.
fn asset_links(n: &Node) -> BTreeSet<&str> {
style_links(n).map(String::as_str).chain(n.bound.values().map(String::as_str)).collect()
}
/// The library and the id there of a local copy of a library style or variable.
fn asset_record<'a>(doc: &'a Document, local: &str) -> Option<&'a ImportedRecord> {
doc.libraries.styles.iter().chain(&doc.libraries.variables).find(|r| r.local == local)
}
/// How many layers link to each local copy of a library style or variable. An instance and the
/// layers in it don't count: an instance counts as its component alone, as in [`count_inserted`].
fn library_links(doc: &Document) -> BTreeMap<String, u32> {
let mut links = BTreeMap::new();
if doc.libraries.styles.is_empty() && doc.libraries.variables.is_empty() {
return links;
}
let mut stack = doc.pages.clone();
while let Some(id) = stack.pop() {
let Some(n) = doc.node(id) else { continue };
if matches!(n.kind, NodeKind::Instance { .. }) {
continue;
}
stack.extend(n.children.iter().copied());
for local in asset_links(n).into_iter().filter(|l| asset_record(doc, l).is_some()) {
*links.entry(local.to_string()).or_default() += 1;
}
}
links
}
/// Run `edit`, a user's applying (or, with `detach`, detaching) of styles or variables, and count
/// the layers it links to library copies (or unlinks from them) for the libraries' analytics. A
/// style replaced by another isn't a detach: only what the action names counts.
pub(crate) fn counting_links<T>(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result<T>) -> Result<T> {
let before = library_links(s.doc()?);
let out = edit(s)?;
let after = library_links(s.doc()?);
let (from, to) = if detach { (&after, &before) } else { (&before, &after) };
let grown: Vec<_> = to.iter().map(|(l, n)| (l, n.saturating_sub(from.get(l).copied().unwrap_or(0)))).filter(|g| g.1 > 0).collect();
for (local, n) in grown {
let doc = s.doc_mut()?;
if let Some(r) = asset_record(doc, local).cloned() {
doc.libraries_mut().count_asset(&r.library, &r.key, detach, n);
}
}
Ok(out)
}
/// Count the instances of library components among `roots` (new layers: placed, pasted or
/// duplicated) and in what they hold as inserted, for the libraries' analytics. An instance inside
/// another instance is part of it and isn't counted on its own.
/// duplicated) and in what they hold as inserted, and the library styles and variables of the
/// rest, for the libraries' analytics. An instance inside another instance is part of it and isn't
/// counted on its own, and what an instance uses is counted as the instance alone.
pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) {
if doc.libraries.components.is_empty() {
let l = &doc.libraries;
if l.components.is_empty() && l.styles.is_empty() && l.variables.is_empty() {
return;
}
let mut found = Vec::new();
let mut assets = Vec::new();
let mut stack = roots.to_vec();
while let Some(id) = stack.pop() {
let Some(n) = doc.node(id) else { continue };
@@ -99,12 +151,18 @@ pub(crate) fn count_inserted(doc: &mut Document, roots: &[NodeId]) {
let root = asset_root(doc, component);
found.extend(doc.libraries.components.iter().find(|r| Some(r.root) == root).map(|r| (r.library.clone(), r.key)));
}
_ => stack.extend(n.children.iter().copied()),
_ => {
stack.extend(n.children.iter().copied());
assets.extend(asset_links(n).into_iter().filter_map(|l| asset_record(doc, l)).cloned());
}
}
}
for (library, key) in found {
doc.libraries_mut().count_insert(&library, key);
}
for r in assets {
doc.libraries_mut().count_asset(&r.library, &r.key, false, 1);
}
}
/// Components the layers of `root` use: mains of instances, instance swap defaults and values.
@@ -378,7 +436,8 @@ pub fn publish(doc: &Document, prev: Option<&PublishedLibrary>, sel: &Selection,
.map(|v| v.id.as_str())
.collect();
let (bound, mode_colls) = used_variables(doc, &units);
let var_ids = alias_closure(&doc.variables, offered_vars.iter().map(ToString::to_string).chain(bound));
let style_vars = snap.styles.iter().flat_map(|s| s.bound.values().cloned());
let var_ids = alias_closure(&doc.variables, offered_vars.iter().map(ToString::to_string).chain(bound).chain(style_vars));
snap.variables.variables = doc.variables.variables.iter().filter(|v| var_ids.contains(&v.id)).cloned().collect();
let coll_ids: BTreeSet<&str> = snap
.variables
@@ -389,6 +448,16 @@ pub fn publish(doc: &Document, prev: Option<&PublishedLibrary>, sel: &Selection,
.chain(mode_colls.iter().map(String::as_str))
.collect();
snap.variables.collections = doc.variables.collections.iter().filter(|c| coll_ids.contains(c.id.as_str())).cloned().collect();
// Where its copies of other libraries' styles, variables and collections come from, so that a
// file linking those libraries too files them under them (#2414).
let kept = |recs: &[ImportedRecord], has: &dyn Fn(&str) -> bool| recs.iter().filter(|r| has(&r.local)).cloned().collect::<Vec<_>>();
let from = (
kept(&doc.libraries.styles, &|l| snap.styles.iter().any(|s| s.id == l)),
kept(&doc.libraries.variables, &|l| snap.variables.variables.iter().any(|v| v.id == l)),
kept(&doc.libraries.collections, &|l| snap.variables.collections.iter().any(|c| c.id == l)),
);
let libs = snap.libraries_mut();
(libs.styles, libs.variables, libs.collections) = from;
for h in used_images(&snap) {
if let Some(img) = doc.images.get(&h) {
snap.images.insert(h, img.clone());
@@ -748,12 +817,22 @@ fn local_key(lid: &str, key: &str, taken: impl Fn(&str) -> bool) -> String {
(1..10_000).map(|k| if k == 1 { base.clone() } else { format!("{base}#{k}") }).find(|l| !taken(l)).unwrap_or(base)
}
/// Where library `lib`'s style, variable or collection `key` (at `version`) comes from: when `lib`
/// has it from another library this file links too, that library, its key and version there, so the
/// copy is that library's (one copy, bound, following its modes: #2414); else `lib` itself.
fn origin<'a>(doc: &Document, lib: &'a PublishedLibrary, theirs: &'a [ImportedRecord], key: &'a str, version: u64) -> (&'a str, &'a str, u64) {
let linked = |id: &str| doc.libraries.enabled.iter().any(|l| l.id == id);
match theirs.iter().find(|r| r.local == key && r.library != lib.manifest.id && linked(&r.library)) {
Some(r) => (&r.library, &r.key, r.version),
None => (&lib.manifest.id, key, version),
}
}
/// Copy library styles `keys` into `doc` as linked remote styles (with `update`, copies older than
/// the library's are refreshed). The variables a written copy binds are imported too and its
/// bindings point at their copies (never at this file's variables of the same ids). Returns library
/// style id → local id.
pub fn import_styles(doc: &mut Document, lib: &PublishedLibrary, keys: &BTreeSet<String>, update: bool) -> BTreeMap<String, String> {
let lid = lib.manifest.id.clone();
let mut out = BTreeMap::new();
let mut hashes = BTreeSet::new();
// Local ids of the copies written now, with the library style they copy.
@@ -761,7 +840,8 @@ pub fn import_styles(doc: &mut Document, lib: &PublishedLibrary, keys: &BTreeSet
for key in keys {
let Some(style) = lib.doc.styles.iter().find(|s| s.id == *key) else { continue };
let version = lib.manifest.style(key).map_or(lib.manifest.version, |s| s.version);
let local = match record_of(&doc.libraries.styles, &lid, key, |l| doc.styles.iter().any(|s| s.id == l)) {
let (from, from_key, version) = origin(doc, lib, &lib.doc.libraries.styles, key, version);
let local = match record_of(&doc.libraries.styles, from, from_key, |l| doc.styles.iter().any(|s| s.id == l)) {
Some(r) => {
if update
&& version > r.version
@@ -774,9 +854,10 @@ pub fn import_styles(doc: &mut Document, lib: &PublishedLibrary, keys: &BTreeSet
r.local
}
None => {
let local = local_key(&lid, key, |l| doc.styles.iter().any(|s| s.id == l));
let local = local_key(from, from_key, |l| doc.styles.iter().any(|s| s.id == l));
doc.styles.push(Style { id: local.clone(), ..style.clone() });
set_record(&mut doc.libraries_mut().styles, ImportedStyle { library: lid.clone(), key: key.clone(), local: local.clone(), version });
let rec = ImportedStyle { library: from.to_string(), key: from_key.to_string(), local: local.clone(), version };
set_record(&mut doc.libraries_mut().styles, rec);
written.push((local.clone(), style));
local
}
@@ -819,7 +900,7 @@ pub fn import_variables(
collections: &BTreeSet<CollectionId>,
update: bool,
) -> VariableMap {
let (lid, m, src) = (lib.manifest.id.as_str(), &lib.manifest, &lib.doc.variables);
let (m, src) = (&lib.manifest, &lib.doc.variables);
let vars = alias_closure(src, keys.iter().cloned());
let colls: BTreeSet<&CollectionId> = collections.iter().chain(vars.iter().filter_map(|v| src.get_by_id(v)).map(|v| &v.collection)).collect();
let mut out = VariableMap::default();
@@ -827,8 +908,9 @@ pub fn import_variables(
for key in colls {
let Some(c) = src.collections.iter().find(|c| c.id == *key) else { continue };
let version = m.collection(key).map_or(m.version, |x| x.version);
let (from, from_key, version) = origin(doc, lib, &lib.doc.libraries.collections, key, version);
let exists = |d: &Document, l: &str| d.variables.collections.iter().any(|x| x.id == l);
let local = match record_of(&doc.libraries.collections, lid, key, |l| exists(doc, l)) {
let local = match record_of(&doc.libraries.collections, from, from_key, |l| exists(doc, l)) {
Some(r) => {
if update
&& version > r.version
@@ -840,9 +922,9 @@ pub fn import_variables(
r.local
}
None => {
let local = local_key(lid, key, |l| exists(doc, l));
let local = local_key(from, from_key, |l| exists(doc, l));
doc.variables.collections.push(Collection { id: local.clone(), extends: None, ..c.clone() });
let rec = ImportedRecord { library: lid.to_string(), key: key.clone(), local: local.clone(), version };
let rec = ImportedRecord { library: from.to_string(), key: from_key.to_string(), local: local.clone(), version };
set_record(&mut doc.libraries_mut().collections, rec);
local
}
@@ -850,27 +932,28 @@ pub fn import_variables(
out.collections.insert(key.clone(), local);
}
// Local ids first (the copies alias each other), then the values.
let mut write: Vec<(&Variable, VariableId, u64, bool)> = Vec::new();
let mut write: Vec<(&Variable, VariableId, u64, bool, &str, &str)> = Vec::new();
for key in &vars {
let Some(v) = src.variables.iter().find(|x| x.id == *key).filter(|v| out.collections.contains_key(&v.collection)) else { continue };
let version = m.variable(key).map_or(m.version, |x| x.version);
let local = match record_of(&doc.libraries.variables, lid, key, |l| doc.variables.variables.iter().any(|x| x.id == l)) {
let (from, from_key, version) = origin(doc, lib, &lib.doc.libraries.variables, &v.id, version);
let local = match record_of(&doc.libraries.variables, from, from_key, |l| doc.variables.variables.iter().any(|x| x.id == l)) {
Some(r) => {
if update && version > r.version {
write.push((v, r.local.clone(), version, false));
write.push((v, r.local.clone(), version, false, from, from_key));
}
r.local
}
None => {
let taken = |l: &str| doc.variables.variables.iter().any(|x| x.id == l) || out.variables.values().any(|x| x == l);
let local = local_key(lid, key, taken);
write.push((v, local.clone(), version, true));
let local = local_key(from, from_key, taken);
write.push((v, local.clone(), version, true, from, from_key));
local
}
};
out.variables.insert(key.clone(), local);
}
for (v, local, version, new) in write {
for (v, local, version, new, from, from_key) in write {
let Some(collection) = out.collections.get(&v.collection).cloned() else { continue };
let mut values = BTreeMap::new();
for (mode, val) in &v.values {
@@ -894,7 +977,7 @@ pub fn import_variables(
Some(slot) => *slot = copy,
None => doc.variables.variables.push(copy),
}
set_record(&mut doc.libraries_mut().variables, ImportedRecord { library: lid.to_string(), key: v.id.clone(), local, version });
set_record(&mut doc.libraries_mut().variables, ImportedRecord { library: from.to_string(), key: from_key.to_string(), local, version });
}
out
}
@@ -1158,10 +1241,12 @@ pub fn prune(doc: &mut Document, library: &str) -> Result<()> {
doc.styles.retain(|s| !unused.contains(&s.id));
doc.libraries_mut().styles.retain(|r| !unused.contains(&r.local));
}
// Variables layers bind or set, local variables alias or extend (with what those alias).
// Variables layers bind or set, styles bind, local variables alias or extend (with what those
// alias).
let seeds = doc
.nodes()
.flat_map(|n| n.bound.values().map(String::as_str).chain(action_variables(n)))
.chain(doc.styles.iter().flat_map(|s| s.bound.values().map(String::as_str)))
.chain(doc.variables.variables.iter().filter_map(|v| v.extends.as_deref()))
.map(str::to_string)
.chain(
+40 -2
View File
@@ -15,7 +15,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::io::Cursor;
use std::sync::Arc;
use figcraft_collab::message::{AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
use figcraft_collab::message::{AssetActions, AssetUsage, Detached, LibraryReply, LibraryReq, MAX_ASSET_USAGE, Usage};
use figcraft_doc::{DetachCount, Document, ImportedRecord, NodeId, NodeKind, PublishedLibrary};
use crate::live::{NetReply, NetRequest};
@@ -123,6 +123,43 @@ pub fn asset_usage(doc: &Document, library: &str) -> Option<AssetUsage> {
Some(AssetUsage { file: doc.name.clone(), styles: most_used(styles), variables: most_used(variables) })
}
/// How many times `doc` has inserted and detached `library`'s styles and variables, its totals;
/// `None` when it has done neither. Every count the document keeps is included (up to
/// [`figcraft_doc::MAX_DETACH_COUNTS`]); the wire message is capped at [`MAX_ASSET_USAGE`], so
/// [`asset_action_reports`] splits them into batches an older server still accepts.
pub fn asset_actions(doc: &Document, library: &str) -> Option<AssetActions> {
let counts: Vec<_> = doc.libraries.asset_counts.iter().filter(|c| c.library == library).collect();
let totals = |n: fn(&figcraft_doc::AssetCount) -> u32| counts.iter().filter(|c| n(c) > 0).map(|c| (c.key.clone(), n(c))).collect();
(!counts.is_empty()).then(|| AssetActions { file: doc.name.clone(), inserted: totals(|c| c.inserted), detached: totals(|c| c.detached) })
}
/// Reports for the server, each with at most [`MAX_ASSET_USAGE`] inserted and detached counts.
pub fn asset_action_reports(doc: &Document, library: &str) -> Vec<AssetActions> {
let Some(full) = asset_actions(doc, library) else { return Vec::new() };
chunk_asset_actions(full)
}
fn chunk_asset_actions(actions: AssetActions) -> Vec<AssetActions> {
let AssetActions { file, inserted, detached } = actions;
if inserted.is_empty() && detached.is_empty() {
return Vec::new();
}
let mut out = Vec::new();
let mut i = 0;
let mut d = 0;
loop {
let ins: Vec<_> = inserted.get(i..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect();
let det: Vec<_> = detached.get(d..).unwrap_or(&[]).iter().take(MAX_ASSET_USAGE).cloned().collect();
if ins.is_empty() && det.is_empty() {
break;
}
i += ins.len();
d += det.len();
out.push(AssetActions { file: file.clone(), inserted: ins, detached: det });
}
out
}
/// `counts`, the most used first, at most [`MAX_ASSET_USAGE`].
fn most_used(counts: BTreeMap<&str, u32>) -> Vec<(String, u32)> {
let mut list: Vec<(String, u32)> = counts.into_iter().map(|(k, n)| (k.to_string(), n)).collect();
@@ -271,8 +308,9 @@ impl Session {
inserted(doc, &l.id).map(LibraryReq::ReportInserted),
asset_usage(doc, &l.id).map(LibraryReq::ReportAssets),
];
let asset_reports = asset_action_reports(doc, &l.id).into_iter().map(LibraryReq::ReportAssetActions);
let fetch = LibraryReq::Fetch { have, usage: Some(usage(doc, &l.id)) };
std::iter::once(fetch).chain(reports.into_iter().flatten()).map(|req| (l.path.clone(), req))
std::iter::once(fetch).chain(reports.into_iter().flatten()).chain(asset_reports).map(|req| (l.path.clone(), req))
})
.collect();
// Confined to automation roots, nothing reaches a server (#1095).
+60 -2
View File
@@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40;
/// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute
/// is refused as well, rather than left to what comes next.
fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option<Unresolved> {
// Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given.
if has_trimmed_name(path) {
return Some(Unresolved::Linked);
}
// Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a
// bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes
// `..` by name, so `link\..\x` is `x` and never goes through the link.
@@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool {
/// the way is opened in turn while the path is resolved, and the device behind a name such as
/// `LPT1` can be a printer on another computer.
fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option<Refused> {
// A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names.
if is_native_name(Path::new(p)) {
return Some(Refused::Device);
}
match craft_docpath::resolve(p, None) {
// With a root passed as the document path (what a link would be relative to), a path on
// that root's share is allowed.
@@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool {
let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else {
return false;
};
volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}')
let bytes = volume.as_bytes();
bytes.len() == 44
&& volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{"))
&& volume.ends_with('}')
&& bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() })
}
/// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`]
@@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -
Entry::Link(target) => target,
};
let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true };
// Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive,
// and Win32 trims a trailing period or space that the kernel follows as it is.
if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) {
return true;
}
// A relative target is relative to the link's folder; an absolute one replaces it.
let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path()));
return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look);
@@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) -
false
}
/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link
/// may hold: no prefix for `std`, yet the system follows it to wherever it names.
fn is_native_name(path: &Path) -> bool {
let bytes = path.as_os_str().as_encoded_bytes();
[&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| {
bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\'))
})
}
/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no
/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names.
fn is_rooted_without_drive(path: &Path) -> bool {
matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\'))
}
/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up.
fn has_trimmed_name(path: &Path) -> bool {
path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' '))))
}
/// `p` with its `.` and `..` taken by name, as Windows takes them.
fn lexical(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
@@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool {
matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f))
}
/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a
/// path that resolving would not be allowed to open (on another computer, or a device: see
/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the
/// callers guard against overwriting a file through another name for it, so it counts as the same:
/// the guard keeps asking (a path like that can't be written anyway). A local path outside the
/// roots is compared.
pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
let (a, b) = (a.as_ref(), b.as_ref());
a == b || same_file::is_same_file(a, b).unwrap_or(false)
if a == b {
return true;
}
if let Some(scope) = current() {
let roots = [scope.read.as_slice(), scope.write.as_slice()].concat();
if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) {
return true;
}
}
same_file::is_same_file(a, b).unwrap_or(false)
}
/// `p` without Windows' `\\?\` prefix, for messages.
@@ -345,6 +397,12 @@ fn device_name(n: &str) -> bool {
&& stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³')))
}
/// Prefix Windows device-name components of a generated export path with `_`.
/// Apply after character filtering and suffix construction, so a safe suffix stays unchanged.
pub fn escape_device_names(path: &str) -> String {
path.split('/').map(|name| if device_name(name) { format!("_{name}") } else { name.to_string() }).collect::<Vec<_>>().join("/")
}
thread_local! {
static ROOTS: RefCell<Option<Arc<Roots>>> = const { RefCell::new(None) };
}
@@ -9,6 +9,27 @@ use serde_json::json;
use super::{Access, Roots, allow, confined, current};
use crate::Session;
#[test]
fn generated_export_paths_escape_device_components_and_preserve_other_names() {
for (path, expected) in [
("CON", "_CON"),
("CoN.txt", "_CoN.txt"),
("nul.txt", "_nul.txt"),
("PRN/icon", "_PRN/icon"),
("folder/COM1", "folder/_COM1"),
("LPT9.png", "_LPT9.png"),
("COM¹", "_COM¹"),
("LPT²/icon", "_LPT²/icon"),
("CONIN$", "_CONIN$"),
("HomeCON", "HomeCON"),
("COM10", "COM10"),
("CON@2x", "CON@2x"),
("folder/.NUL", "folder/.NUL"),
] {
assert_eq!(super::escape_device_names(path), expected, "{path}");
}
}
/// A fresh folder for one test: `<tmp>/figcraft-roots-<name>-<pid>`, holding `root/`, `root2/`
/// (a sibling whose name starts like the root's) and `outside/`.
struct Fixture(PathBuf);
@@ -229,6 +250,8 @@ fn spellings_of_other_computers_and_devices_are_refused() {
r"C:\work\LPT³\x.png",
r"C:\work\conout$",
r"C:\work\aux:stream",
// A volume name that is not a GUID could be an alias of anything.
r"\\?\Volume{remote}\x.png",
// After a name `craft_docpath` refuses for another reason.
r"C:\work\a:b\prn.png",
];
@@ -402,6 +425,34 @@ fn a_parent_after_a_link_is_taken_by_name() {
assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root");
}
/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the
/// same file as one inside, even when it is another name for it (a hard link outside the roots).
#[test]
fn same_file_does_not_open_a_path_outside_the_roots() {
let f = Fixture::new("same-file");
let inside = f.p("root/in.txt");
let outside = f.p("outside/linked.txt");
if std::fs::hard_link(&inside, &outside).is_err() {
eprintln!("skipped: hard links can't be made here");
return;
}
assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file");
let roots = Arc::new(f.rw());
confined(Some(&roots), || {
assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file");
if cfg!(windows) {
assert!(
super::same_file(&inside, r"\\192.0.2.1\share\x"),
"a path on another computer is never opened, and counts as the same so that the guard keeps asking"
);
}
assert!(super::same_file(&inside, &inside), "a path is the same file as itself");
let other = f.p("root/sub/other.txt");
std::fs::write(&other, b"other").unwrap();
assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ");
});
}
/// A path on another computer and a device path are refused before anything is opened: resolving
/// them made Windows contact the server, which may send it the signed-in user's credentials
/// (#1094). Each is refused with a message that only the check before resolving gives: had the
@@ -468,6 +519,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() {
assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok());
}
/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the
/// rest of the path after it, reaches `\Device\Mup\...`.
#[test]
fn native_names_are_told_with_or_without_the_closing_separator() {
for p in
[r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"]
{
assert!(super::is_native_name(Path::new(p)), "{p}");
}
for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] {
assert!(!super::is_native_name(Path::new(p)), "{p}");
}
}
/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the
/// link's drive, whichever directory it names.
#[test]
fn rooted_link_targets_without_a_drive_are_refused() {
for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] {
assert!(super::is_rooted_without_drive(Path::new(p)), "{p}");
}
for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] {
assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}");
}
}
/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a
/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the
/// others where it looks a name up but not where the kernel follows a link.
#[test]
#[cfg(windows)]
fn native_names_and_names_windows_trims_are_refused_as_written() {
let f = Fixture::new("native-trimmed");
let r = f.rw();
if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native"))
|| !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed"))
{
eprintln!("skipped: this system doesn't let tests make symbolic links");
return;
}
let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be");
// However the system stores the native name, the link is refused.
let native = f.p("root/native/x.png");
assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}");
let p = f.p("root/trimmed/x.png");
let e = r.check(Path::new(&p), Access::Read).expect_err(&p);
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
let p = f.p("root/remote /x.png");
let e = r.check(Path::new(&p), Access::Write).expect_err(&p);
assert!(e.starts_with(&standard(&p)), "{p}: {e}");
assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device));
}
#[test]
fn a_scope_confines_the_thread_and_ends_with_it() {
let f = Fixture::new("scope");
+40 -1
View File
@@ -1,6 +1,6 @@
//! Document inspection as JSON, so agents can verify their work without screenshots.
use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeJoin, TextData, TextDecoration};
use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, StrokeJoin, TextAlignV, TextCase, TextData, TextDecoration};
use serde_json::{Value, json};
use crate::Session;
@@ -27,6 +27,7 @@ pub const NODE_KEYS: &[&str] = &[
"constraints",
"cornerRadius",
"cornerSmoothing",
"dashCap",
"dashes",
"description",
"devChanged",
@@ -34,7 +35,10 @@ pub const NODE_KEYS: &[&str] = &[
"devResources",
"devStatus",
"effects",
"endCap",
"exports",
"exposedInstance",
"features",
"fills",
"flows",
"fontFamily",
@@ -76,13 +80,17 @@ pub const NODE_KEYS: &[&str] = &[
"opacity",
"operandOperation",
"overrides",
"paragraphIndent",
"paragraphSpacing",
"pluginData",
"pointCount",
"propertyReferences",
"rotation",
"sectionContentsHidden",
"segments",
"sizing",
"slot",
"startCap",
"strokeAlign",
"strokeJoin",
"strokeSides",
@@ -91,7 +99,9 @@ pub const NODE_KEYS: &[&str] = &[
"styledRuns",
"styles",
"textAlign",
"textAlignVertical",
"textAutoResize",
"textCase",
"textDecoration",
"textDecorationColor",
"textDecorationOffset",
@@ -102,6 +112,7 @@ pub const NODE_KEYS: &[&str] = &[
"textPath",
"textStyleRanges",
"type",
"variableModes",
"vertices",
"visible",
"width",
@@ -263,6 +274,11 @@ fn paint_props(n: &Node, o: &mut serde_json::Map<String, Value>, options: &Inspe
if !n.stroke.dashes.is_empty() {
insert_prop(o, options, "dashes", || json!(n.stroke.dashes));
}
for (k, cap) in [("startCap", n.stroke.cap_start), ("endCap", n.stroke.cap_end)] {
if cap != StrokeCap::None {
insert_prop(o, options, k, || json!(cap));
}
}
if let Some(cap) = n.stroke.dash_cap {
insert_prop(o, options, "dashCap", || json!(cap));
}
@@ -383,6 +399,15 @@ fn dev_props(doc: &Document, n: &Node, o: &mut serde_json::Map<String, Value>, o
if !n.bound.is_empty() {
insert_prop(o, options, "boundVariables", || json!(n.bound));
}
if !n.var_modes.is_empty() {
insert_prop(o, options, "variableModes", || json!(n.var_modes));
}
if !n.prop_refs.is_empty() {
insert_prop(o, options, "propertyReferences", || json!(n.prop_refs));
}
if n.exposed {
insert_prop(o, options, "exposedInstance", || json!(true));
}
if !n.overrides.is_empty() {
insert_prop(o, options, "overrides", || json!(n.overrides));
}
@@ -417,7 +442,21 @@ fn text_props(t: &TextData, o: &mut serde_json::Map<String, Value>, options: &In
insert_prop(o, options, "lineHeight", || json!(t.style.line_height.label()));
insert_prop(o, options, "letterSpacing", || json!(t.style.letter_spacing.label()));
insert_prop(o, options, "textAlign", || json!(t.align_h));
if t.align_v != TextAlignV::default() {
insert_prop(o, options, "textAlignVertical", || json!(t.align_v));
}
insert_prop(o, options, "textAutoResize", || json!(t.auto_resize));
if t.style.case != TextCase::default() {
insert_prop(o, options, "textCase", || json!(t.style.case));
}
for (k, v) in [("paragraphSpacing", t.paragraph_spacing), ("paragraphIndent", t.paragraph_indent)] {
if v != 0.0 {
insert_prop(o, options, k, || json!(v));
}
}
if !t.features.is_empty() {
insert_prop(o, options, "features", || json!(t.features));
}
if t.max_lines > 0 {
insert_prop(o, options, "maxLines", || json!(t.max_lines));
}
+57
View File
@@ -652,3 +652,60 @@ fn a_continue_batch_reports_runtime_errors_and_runs_later_steps() {
assert_eq!(results[6]["ok"], true);
assert_eq!(s.doc().unwrap().node(s.page().unwrap()).unwrap().name, "Done");
}
#[test]
fn a_refused_step_names_its_step_and_keeps_its_kind() {
let mut s = Session::new();
let comp = id(&s.execute("node.create", &json!({"type": "component", "name": "Button", "width": 100, "height": 40})).unwrap());
let inst = id(&s.execute("instance.create", &json!({"component": comp})).unwrap());
let before = s.doc().unwrap().clone();
let undo = s.undo_depth();
let result = s.execute(
"command.batch",
&json!({"commands": [
{"command": "node.create", "params": {"type": "rectangle", "parent": inst, "width": 10, "height": 10}}
]}),
);
match result {
Err(EngineError::Disabled(cmd, msg)) => {
assert_eq!(cmd, "node.create");
assert!(msg.starts_with("step 0: "), "{msg}");
assert!(msg.contains("can't be added"), "{msg}");
}
other => panic!("expected Disabled, got {other:?}"),
}
assert_eq!(s.doc().unwrap(), &before, "the batch rolled back");
assert_eq!(s.undo_depth(), undo, "no undo step for the refused batch");
// Outside a batch the same refusal keeps its kind and says no step.
match s.execute("node.create", &json!({"type": "rectangle", "parent": inst, "width": 10, "height": 10})) {
Err(EngineError::Disabled(_, msg)) => assert!(!msg.contains("step "), "{msg}"),
other => panic!("expected Disabled, got {other:?}"),
}
}
#[test]
fn an_internal_step_says_which_step_without_changing_kind() {
use crate::derived;
let mut s = Session::new();
let r = id(&s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap());
let before = s.doc().unwrap().clone();
derived::PANIC.with(|p| p.set(true));
let result = s.execute(
"command.batch",
&json!({"commands": [
{"command": "node.set", "params": {"ids": [r], "props": {"name": "Renamed"}}}
]}),
);
derived::PANIC.with(|p| p.set(false));
match result {
Err(EngineError::Internal { cmd, msg }) => {
assert_eq!(cmd, "node.set");
assert!(msg.starts_with("step 0: "), "{msg}");
}
other => panic!("expected Internal, got {other:?}"),
}
assert_eq!(s.doc().unwrap(), &before, "the panicking step is rolled back");
// Kinds without a message are left as they are.
assert!(matches!(EngineError::NoNode(figcraft_doc::NodeId(7)).at_step(2), EngineError::NoNode(_)));
assert!(matches!(EngineError::Waiting.at_step(2), EngineError::Waiting));
}
+541
View File
@@ -0,0 +1,541 @@
//! Code blocks (#2237): `board.codeBlock` and `board.setLanguage`, the pass that keeps a block as
//! tall as its lines and its text plain code, and the text editor's three literal-typing lines.
use figcraft_color::{Color, Paint};
use figcraft_doc::{
BoardItem, CODE_FONT, CODE_MAX_CHARS, CodeLanguage, EffectKind, FileKind, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, Sizing,
TextAlignH, TextAutoResize, TextCase, TextData, TextDecoration,
};
use figcraft_geom::Rect;
use serde_json::{Value, json};
use crate::board::{is_code_text, text_of};
use crate::board_tests::{board, id, node};
use crate::collab_live_tests::Room;
use crate::tools::{PointerEvent, PointerKind};
use crate::{EngineError, Session};
fn bx(s: &Session, id: NodeId) -> Rect {
s.doc().unwrap().world_bounds(id).unwrap()
}
fn td(s: &Session, block: NodeId) -> TextData {
let t = text_of(s.doc().unwrap(), block).unwrap();
match node(s, t).kind {
NodeKind::Text(td) => td,
other => panic!("not text: {other:?}"),
}
}
/// `board.codeBlock` with `p`: the frame and its text.
fn block(s: &mut Session, p: Value) -> (NodeId, NodeId) {
let out = s.execute("board.codeBlock", &p).unwrap();
(id(&out, "id"), id(&out, "text"))
}
/// How many visual lines the text lays out in.
fn lines(s: &Session, text: NodeId) -> usize {
let n = node(s, text);
figcraft_text::layout_node(&n).map_or(0, |(l, _)| l.lines.len())
}
fn solid(hex: (u8, u8, u8)) -> Vec<Paint> {
vec![Paint::solid(Color::from_rgb8_const(hex.0, hex.1, hex.2))]
}
fn ten(n: usize) -> String {
vec!["x"; n].join("\n")
}
fn drag(s: &mut Session, from: (f64, f64), to: (f64, f64)) {
s.pointer(&PointerEvent::at(PointerKind::Down, from.0, from.1, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Move, (from.0 + to.0) / 2.0, (from.1 + to.1) / 2.0, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Move, to.0, to.1, 1.0)).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Up, to.0, to.1, 1.0)).unwrap();
}
fn undo(s: &mut Session) {
s.execute("edit.undo", &json!({})).unwrap();
}
#[test]
fn a_code_block_is_a_dark_panel_576_by_128_holding_one_monospace_text() {
let mut s = board();
let before = s.doc().unwrap().ids().count();
let depth = s.undo_depth().0;
let out = s.execute("board.codeBlock", &json!({"x": 100, "y": 200})).unwrap();
assert_eq!(out["language"], json!("typescript"));
let (f, t) = (id(&out, "id"), id(&out, "text"));
let n = node(&s, f);
assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Typescript }));
assert!(n.is_board_atom());
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.x1, r.y1), (100.0, 200.0, 676.0, 328.0));
assert_eq!(n.fills, solid((0x1E, 0x1E, 0x1E)));
assert_eq!(n.corners.radii, [10.0; 4]);
assert_eq!(n.effects.iter().filter(|e| matches!(e.kind, EffectKind::DropShadow(_))).count(), 1);
let l = n.layout.clone().unwrap();
assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [16.0, 16.0, 16.0, 64.0]));
assert_eq!(n.child_layout.sizing_v, Sizing::Hug);
assert_eq!((n.child_layout.min_h, n.child_layout.min_w), (Some(128.0), Some(210.0)));
assert_eq!(n.children, vec![t]);
let tr = bx(&s, t);
assert_eq!((tr.x0, tr.y0, tr.width()), (164.0, 216.0, 496.0));
let d = td(&s, f);
assert_eq!(d.characters, "");
assert_eq!((d.style.font_family.as_str(), d.style.font_style.as_str(), d.style.font_size), (CODE_FONT, "Regular", 16.0));
assert_eq!(d.style.line_height, LineHeight::Percent(150.0));
assert_eq!((d.auto_resize, d.align_h), (TextAutoResize::Height, TextAlignH::Left));
assert_eq!(node(&s, t).fills, solid((0xE3, 0xE1, 0xDD)));
assert_eq!((d.features.get("liga"), d.features.get("calt")), (Some(&false), Some(&false)));
assert!(d.runs.is_empty());
assert_eq!(d.list, ListStyle::None);
assert_eq!(s.selection(), vec![f]);
assert_eq!(s.undo_depth().0, depth + 1);
undo(&mut s);
assert_eq!(s.doc().unwrap().ids().count(), before);
}
#[test]
fn a_block_without_a_place_is_centred_and_edit_asks_for_typing() {
let mut s = board();
// Centred on the view without a place.
let (vx, vy) = {
let v = &s.ds().unwrap().view;
(v.cx, v.cy)
};
let (f, _) = block(&mut s, json!({}));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0));
// Typing starts in it on request.
let (f, _) = block(&mut s, json!({"x": 0, "y": 500, "edit": true}));
assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(f)));
}
#[test]
fn the_height_is_its_lines_24_each_and_never_under_four() {
let mut s = board();
let heights = [("a", 128.0), ("a\nb\nc\nd", 128.0), ("a\nb\nc\nd\ne", 152.0)];
for (text, h) in heights {
let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "text": text}));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, h), "{text:?}");
}
let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)}));
assert_eq!(bx(&s, f).height(), 248.0);
assert_eq!(bx(&s, t).height(), 216.0);
s.execute("text.set", &json!({"id": t, "characters": "a\nb"})).unwrap();
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.height()), (100.0, 200.0, 128.0));
}
#[test]
fn long_lines_wrap_and_each_visual_line_adds_24() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)}));
let n = lines(&s, t);
assert!(n >= 3, "{n}");
assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * n as f64);
assert_eq!(bx(&s, t).width(), 496.0);
if figcraft_text::has_family(CODE_FONT) {
let (f, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(93)}));
assert_eq!(bx(&s, f).height(), 128.0);
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": "x".repeat(94)}));
assert_eq!(lines(&s, t), 2);
assert_eq!(bx(&s, f).height(), 128.0);
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "text": format!("{}\na\nb\nc", "x".repeat(94))}));
assert_eq!(lines(&s, t), 5);
assert_eq!(bx(&s, f).height(), 152.0);
}
}
#[test]
fn only_the_width_is_the_users() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 100, "y": 200, "text": ten(9)}));
assert_eq!(bx(&s, f).height(), 248.0);
s.execute("node.set", &json!({"id": f, "props": {"height": 400}})).unwrap();
assert_eq!(bx(&s, f).height(), 248.0);
assert_eq!(node(&s, f).child_layout.sizing_v, Sizing::Hug);
s.execute("transform.resize", &json!({"ids": [f], "width": 300, "height": 500})).unwrap();
let r = bx(&s, f);
assert_eq!((r.width(), r.height(), bx(&s, t).width()), (300.0, 248.0, 220.0));
s.execute("node.set", &json!({"id": f, "props": {"width": 100}})).unwrap();
assert_eq!((bx(&s, f).width(), bx(&s, t).width()), (210.0, 130.0));
// A pointer drag of the bottom-right handle.
let mut s = board();
let (f, _) = block(&mut s, json!({"x": 100, "y": 200}));
let depth = s.undo_depth().0;
drag(&mut s, (676.0, 328.0), (876.0, 628.0));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0, r.width(), r.height()), (100.0, 200.0, 776.0, 128.0));
assert_eq!(s.undo_depth().0, depth + 1);
undo(&mut s);
let r = bx(&s, f);
assert_eq!((r.width(), r.height()), (576.0, 128.0));
// A narrower block wraps into more lines and grows.
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "ab ".repeat(400)}));
let was = lines(&s, t);
s.execute("node.set", &json!({"id": f, "props": {"width": 300}})).unwrap();
let now = lines(&s, t);
assert!(now > was, "{now} > {was}");
assert_eq!(bx(&s, f).height(), 32.0 + 24.0 * now as f64);
}
/// A block settled after `how` made it incoherent: still 5 lines tall, 576 wide, hugging, with
/// its layout, and a second pass changes nothing.
fn settled_after(how: impl Fn(&mut Session, NodeId)) {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(4)}));
how(&mut s, f);
s.execute("text.set", &json!({"id": t, "characters": ten(5)})).unwrap();
let n = node(&s, f);
assert!(n.layout.is_some(), "the layout is restored");
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
assert_eq!((bx(&s, f).width(), bx(&s, f).height()), (576.0, 152.0));
assert_eq!(node(&s, t).child_layout.sizing_h, Sizing::Fill);
let doc = s.doc().unwrap().clone();
let mut again = doc.clone();
again.mark_dirty(doc.ids().collect::<Vec<_>>());
crate::normalize(&mut again, &doc);
assert_eq!(again, doc, "a second pass changes nothing");
}
#[test]
fn the_pass_keeps_a_blocks_layout_and_width_sizing() {
settled_after(|s, f| {
s.execute("layout.remove", &json!({"ids": [f]})).unwrap();
});
settled_after(|s, f| {
s.execute("node.set", &json!({"id": f, "props": {"layout": null}})).unwrap();
});
settled_after(|s, f| {
s.execute("node.set", &json!({"id": f, "props": {"sizingH": "hug"}})).unwrap();
});
}
#[test]
fn a_block_in_a_section_without_a_place_is_centred_on_the_view_too() {
let mut s = board();
let (vx, vy) = {
let v = &s.ds().unwrap().view;
(v.cx, v.cy)
};
let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 1000, "y": 500, "width": 4000, "height": 4000})).unwrap(), "id");
let (f, _) = block(&mut s, json!({"parent": sec}));
assert_eq!(node(&s, f).parent, Some(sec));
let r = bx(&s, f);
assert_eq!((r.x0, r.y0), (vx - 288.0, vy - 64.0), "on the page, where a block on the page would be");
}
#[test]
fn a_block_in_a_turned_frame_without_a_place_is_centred_on_the_view_and_a_given_place_is_the_frames() {
let mut s = board();
let (vx, vy) = {
let v = &s.ds().unwrap().view;
(v.cx, v.cy)
};
let fr = id(&s.execute("node.create", &json!({"type": "frame", "x": 300, "y": -200, "width": 3000, "height": 3000})).unwrap(), "id");
s.execute("node.set", &json!({"id": fr, "props": {"rotation": 30}})).unwrap();
// Left out: the block's middle (a four-line block) is on the view's centre, in the page.
let (f, _) = block(&mut s, json!({"parent": fr}));
let c = bx(&s, f).center();
assert!((c.x - vx).abs() < 1e-6 && (c.y - vy).abs() < 1e-6, "{c:?} vs ({vx}, {vy})");
// Given: `x`/`y` stay the frame's own coordinates.
let (g, _) = block(&mut s, json!({"parent": fr, "x": 10, "y": 20}));
let t = node(&s, g).transform.translation();
assert_eq!((t.x, t.y), (10.0, 20.0));
}
#[test]
fn a_default_position_is_within_a_billion_too() {
let mut s = board();
s.execute("view.set", &json!({"cx": 1e300})).unwrap();
match s.execute("board.codeBlock", &json!({})) {
Err(EngineError::BadParams { .. }) => {}
Err(other) => panic!("not a named refusal: {other:?}"),
Ok(out) => panic!("placed at {out}"),
}
}
#[test]
fn the_next_block_is_128_to_the_right_as_wide_and_in_the_same_language() {
let mut s = board();
let (a, _) = block(&mut s, json!({"x": 0, "y": 0, "width": 976, "language": "rust", "text": "fn main() {}"}));
let connectors = |s: &Session| s.doc().unwrap().nodes().filter(|n| matches!(n.board, Some(BoardItem::Connector(_)))).count();
let depth = s.undo_depth().0;
let out = s.execute("board.nextSticky", &json!({"id": a})).unwrap();
let b = id(&out, "id");
let r = bx(&s, b);
assert_eq!((r.x0, r.y0, r.width(), r.height()), (1104.0, 0.0, 976.0, 128.0));
assert_eq!(node(&s, b).board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust }));
assert_eq!(td(&s, b).characters, "");
assert_eq!(connectors(&s), 0);
assert_eq!(s.selection(), vec![b]);
assert_eq!(s.undo_depth().0, depth + 1);
undo(&mut s);
assert!(s.doc().unwrap().node(b).is_none());
// While typing in the source, with no id, and asking for the next one to be typed in.
let t = text_of(s.doc().unwrap(), a).unwrap();
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
let out = s.execute("board.nextSticky", &json!({"edit": true})).unwrap();
let c = id(&out, "id");
assert_eq!(bx(&s, c).x0, 1104.0);
assert!(s.ds().unwrap().text_edit.is_none(), "the edit has ended");
assert!(s.ui_requests.iter().any(|q| q.kind == "board.editText" && q.data["id"] == json!(c)));
let out = s.execute("board.nextSticky", &json!({"id": a, "side": "below"})).unwrap();
let r = bx(&s, id(&out, "id"));
assert_eq!((r.x0, r.y0), (0.0, 256.0));
assert!(s.execute("board.nextSticky", &json!({"id": a, "side": "up"})).is_err());
}
#[test]
fn a_block_is_in_one_of_sixteen_languages() {
let mut s = board();
let (f, _) = block(&mut s, json!({"x": 0, "y": 0}));
let lang = |s: &Session| node(s, f).board;
s.execute("board.setLanguage", &json!({"id": f, "language": "python"})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Python }));
for name in ["C++", "CPP"] {
s.execute("board.setLanguage", &json!({"id": f, "language": name})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Cpp }));
}
for l in CodeLanguage::ALL {
s.execute("board.setLanguage", &json!({"id": f, "language": l.id()})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: l }));
}
s.execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap();
let e = s.execute("board.setLanguage", &json!({"id": f, "language": "klingon"})).unwrap_err().to_string();
assert!(e.contains("typescript") && e.contains("plainText"), "{e}");
let sticky = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "id");
assert!(s.execute("board.setLanguage", &json!({"id": sticky, "language": "go"})).is_err());
s.execute("select.none", &json!({})).unwrap();
assert!(matches!(s.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..))));
// While typing in it, the text is the selection and the edit goes on.
let t = text_of(s.doc().unwrap(), f).unwrap();
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
s.execute("board.setLanguage", &json!({"language": "ruby"})).unwrap();
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Ruby }));
assert!(s.ds().unwrap().text_edit.is_some());
s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap();
undo(&mut s);
assert_eq!(lang(&s), Some(BoardItem::CodeBlock { language: CodeLanguage::Go }));
// The creating command refuses what it cannot make.
assert!(s.execute("board.codeBlock", &json!({"language": "nope"})).is_err());
assert!(s.execute("board.codeBlock", &json!({"width": 5})).is_err());
assert!(s.execute("board.codeBlock", &json!({"text": "x".repeat(CODE_MAX_CHARS + 1)})).is_err());
}
fn insert(s: &mut Session, text: &str) {
s.execute("text.edit.insert", &json!({"text": text})).unwrap();
}
fn key(s: &mut Session, key: &str, shift: bool) {
s.execute("text.edit.key", &json!({"key": key, "shift": shift})).unwrap();
}
fn characters(s: &Session, t: NodeId) -> String {
match node(s, t).kind {
NodeKind::Text(td) => td.characters,
other => panic!("not text: {other:?}"),
}
}
#[test]
fn typing_in_a_block_is_literal() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0}));
assert!(is_code_text(s.doc().unwrap(), t));
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
insert(&mut s, "-");
insert(&mut s, " ");
assert_eq!(characters(&s, t), "- ");
assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None) && td(&s, f).list == ListStyle::None);
insert(&mut s, "\n1.");
insert(&mut s, " ");
assert_eq!(characters(&s, t), "- \n1. ");
assert!(td(&s, f).paragraphs.iter().all(|p| p.list == ListStyle::None));
// Tab types two spaces.
s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap();
key(&mut s, "Tab", false);
assert_eq!(characters(&s, t), " ");
key(&mut s, "Tab", true);
assert_eq!(characters(&s, t), " ", "Shift+Tab does nothing");
// Enter keeps the line's indent, and nothing more after a brace.
insert(&mut s, "foo");
key(&mut s, "Enter", false);
assert_eq!(characters(&s, t), " foo\n ");
s.execute("text.set", &json!({"id": t, "characters": "foo"})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 3})).unwrap();
key(&mut s, "Enter", false);
assert_eq!(characters(&s, t), "foo\n");
s.execute("text.set", &json!({"id": t, "characters": "{"})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 1})).unwrap();
key(&mut s, "Enter", false);
assert_eq!(characters(&s, t), "{\n");
// Nothing is made smart.
s.execute("text.set", &json!({"id": t, "characters": ""})).unwrap();
s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap();
let raw = "\"a\" -- 'b' ... -> != fi";
insert(&mut s, raw);
let got = characters(&s, t);
assert_eq!(got, raw);
assert!(!got.chars().any(|c| matches!(c, '\u{201C}' | '\u{2019}' | '\u{2014}' | '\u{2026}')));
// In a sticky the same keys still make a list.
let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0})).unwrap(), "text");
s.execute("text.edit.begin", &json!({"id": note})).unwrap();
insert(&mut s, "-");
insert(&mut s, " ");
match node(&s, note).kind {
NodeKind::Text(d) => assert!(d.list == ListStyle::Bulleted || d.paragraphs.iter().any(|p| p.list == ListStyle::Bulleted)),
other => panic!("not text: {other:?}"),
}
}
#[test]
fn lists_links_and_styled_ranges_do_not_stick() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "one\ntwo"}));
let plain = |s: &Session| {
let d = td(s, f);
assert_eq!(d.list, ListStyle::None);
assert!(d.paragraphs.iter().all(|p| p.list == ListStyle::None));
assert_eq!(d.style.link, None);
assert_eq!((d.style.decoration, d.style.case), (TextDecoration::None, TextCase::Original));
assert!(d.runs.is_empty());
assert_eq!(d.characters, "one\ntwo");
assert_eq!(d.auto_resize, TextAutoResize::Height);
};
for (cmd, p) in [
("text.bulletList", json!({"ids": [t]})),
("text.link", json!({"url": "https://example.com", "ids": [t]})),
("text.underline", json!({"ids": [t]})),
("text.caseUpper", json!({"ids": [t]})),
] {
// Done or refused by name, and the block is plain either way.
match s.execute(cmd, &p) {
Ok(_) | Err(EngineError::BadParams { .. } | EngineError::Disabled(..)) => {}
Err(other) => panic!("{cmd}: {other:?}"),
}
plain(&s);
}
s.execute("text.edit.begin", &json!({"id": t, "caret": 0})).unwrap();
for _ in 0..3 {
key(&mut s, "ArrowRight", true);
}
s.execute("text.bold", &json!({})).unwrap();
s.execute("text.edit.key", &json!({"key": "Escape"})).unwrap();
plain(&s);
assert_eq!(td(&s, f).style.font_style, "Regular");
s.execute("node.set", &json!({"id": t, "props": {"textAutoResize": "widthAndHeight"}})).unwrap();
plain(&s);
// A sticky's note keeps its link (the guard).
let note = id(&s.execute("board.sticky", &json!({"x": 900, "y": 0, "text": "hi"})).unwrap(), "text");
s.execute("text.link", &json!({"url": "https://example.com", "ids": [note]})).unwrap();
match node(&s, note).kind {
NodeKind::Text(d) => assert_eq!(d.style.link.as_deref(), Some("https://example.com")),
other => panic!("not text: {other:?}"),
}
}
#[test]
fn saved_files_live_sessions_and_a_second_pass() {
let mut s = board();
let (f, _) = block(&mut s, json!({"x": 100, "y": 200, "width": 400, "language": "rust", "text": "a\nb"}));
let doc = s.doc().unwrap();
let (back, _) = figcraft_format::from_json(&figcraft_format::to_json(doc).unwrap().to_string()).unwrap();
let n = back.node(f).unwrap();
assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Rust }));
assert_eq!((n.width, n.height), (400.0, 128.0));
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0}));
let mut room = Room::new(s.doc().unwrap().clone(), 2, 7);
room.s(0).execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap();
room.s(1).execute("board.setLanguage", &json!({"id": f, "language": "go"})).unwrap();
room.settle();
room.check();
let server = room.server.document();
let n = server.node(f).unwrap();
assert_eq!(n.height, 176.0);
assert_eq!(n.board, Some(BoardItem::CodeBlock { language: CodeLanguage::Go }));
// A second pass over a settled document changes nothing.
let doc = s.doc().unwrap().clone();
let mut again = doc.clone();
again.mark_dirty(doc.ids().collect::<Vec<_>>());
crate::normalize(&mut again, &doc);
assert_eq!(again, doc);
// Not on design files.
let mut d = Session::new();
assert_eq!(d.doc().unwrap().kind, FileKind::Design);
assert!(matches!(d.execute("board.codeBlock", &json!({})), Err(EngineError::Disabled(..))));
assert!(matches!(d.execute("board.setLanguage", &json!({"language": "go"})), Err(EngineError::Disabled(..))));
}
#[test]
fn code_blocks_survive_junk_commands() {
let junk = [
json!({}),
json!(null),
json!({"language": 7, "id": "x", "ids": [1], "side": 3, "text": [1]}),
json!({"language": "nope", "id": 99_999, "side": "up", "width": 1e308, "x": "NaN"}),
];
let ids: Vec<&str> = crate::cmd::all_commands()
.iter()
.map(|c| c.id)
.filter(|i| {
i.starts_with("text.") && *i != "text.rescanFonts" || i.starts_with("layout.") || matches!(*i, "board.nextSticky" | "board.setLanguage")
})
.collect();
assert!(ids.len() > 20, "{ids:?}");
for editing in [false, true] {
for cmd in &ids {
for j in &junk {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": "a\nb"}));
if editing {
s.execute("text.edit.begin", &json!({"id": t})).unwrap();
} else {
s.set_selection(vec![f]);
}
if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) {
panic!("{cmd} panicked on {j} (editing {editing}): {msg}");
}
}
}
}
}
#[test]
fn a_structured_text_is_refused_and_no_block_is_made() {
for text in [json!({"a": 1}), json!([1]), json!(7), json!(true)] {
let mut s = board();
let before = s.doc().unwrap().ids().count();
let err = s.execute("board.codeBlock", &json!({"x": 0, "y": 0, "text": text}));
assert!(matches!(err, Err(EngineError::BadParams { .. })), "{text}: {err:?}");
assert_eq!(s.doc().unwrap().ids().count(), before, "{text}");
}
}
#[test]
fn the_pass_restores_padding_and_the_minimums() {
let mut s = board();
let (f, t) = block(&mut s, json!({"x": 0, "y": 0, "text": ten(6)}));
assert_eq!(bx(&s, f).height(), 176.0);
s.execute("node.set", &json!({"id": f, "props": {"padding": 0}})).unwrap();
s.execute("text.set", &json!({"id": t, "characters": ten(6)})).unwrap();
assert_eq!(node(&s, f).layout.unwrap().padding, [16.0, 16.0, 16.0, 64.0]);
assert_eq!(bx(&s, f).height(), 176.0);
let (f, t) = block(&mut s, json!({"x": 0, "y": 500}));
s.execute("node.set", &json!({"id": f, "props": {"minHeight": null}})).unwrap();
s.execute("text.set", &json!({"id": t, "characters": "a"})).unwrap();
assert_eq!(node(&s, f).child_layout.min_h, Some(128.0));
assert_eq!(bx(&s, f).height(), 128.0);
}
+3
View File
@@ -465,6 +465,7 @@ fn board_commands_survive_junk() {
json!({"end": "from", "target": {"x": 1e308, "y": -1e308}, "side": "inside", "style": "curved"}),
json!({"id": 99_999, "end": 7, "target": [1], "style": "wavy"}),
json!({"id": 99_999, "relation": 7, "children": "x", "text": [1], "x": "NaN", "y": 1e308}),
json!({"id": 99_999, "language": 7, "text": [1], "width": "wide", "x": "NaN", "y": 1e308, "side": 3}),
];
let ids: Vec<&str> = crate::cmd::all_commands()
.iter()
@@ -482,6 +483,7 @@ fn board_commands_survive_junk() {
let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone();
let b = s.execute("board.shape", &json!({"x": 300, "y": 0})).unwrap()["id"].clone();
let _ = s.execute("board.connector", &json!({"from": a, "to": b, "label": "x"}));
let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"}));
if let Err(EngineError::Internal { cmd, msg }) = s.execute(cmd, j) {
panic!("{cmd} panicked on {j}: {msg}");
}
@@ -497,6 +499,7 @@ fn board_commands_survive_junk() {
let a = s.execute("board.sticky", &json!({"x": 0, "y": 0})).unwrap()["id"].clone();
let b = s.execute("board.stamp", &json!({"x": 300, "y": 0})).unwrap()["id"].clone();
let _ = s.execute("board.connector", &json!({"from": a, "to": b}));
let _ = s.execute("board.codeBlock", &json!({"x": 0, "y": 300, "text": "a\nb"}));
if let Err(EngineError::Internal { cmd, msg }) = s.execute(spec.id, j) {
panic!("{cmd} panicked on {j}: {msg}");
}
+17 -1
View File
@@ -21,6 +21,7 @@ use crate::params::{boolean, color_of, get, id, id_of, num, num_or, opt_id, req_
use crate::tools::{Gesture, PointerEvent, ToolId};
use crate::{EngineError, Result, Session, bad, spec, textedit};
mod code;
mod connectors;
mod derived;
mod edit;
@@ -29,6 +30,7 @@ mod mindmap;
mod reshape;
mod tools;
pub use code::is_code_text;
pub(crate) use connectors::end_handle_at;
pub use connectors::{END_HANDLE_PX, selected_connector_ends};
use connectors::{connector_cmd, reattach};
@@ -144,7 +146,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"board.nextSticky",
"Next sticky note",
"{id? (a sticky or shape; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected",
"{id? (a sticky, shape or code block; default the selected or edited one), side?: right|below|left|above (default right), edit? (start typing in it; default false)} → {id, text, connector?} a sticky of the same colour beside a sticky; after a shape, the next shape joined to it by a connector, as board.addConnected; after a code block, the next code block beside it (128 away), as wide and in the same language, not joined",
true,
next_sticky
),
@@ -197,6 +199,20 @@ pub fn specs() -> Vec<CommandSpec> {
true,
mindmap::mind_map_add
),
spec!(
"board.codeBlock",
"Code block",
"{x?, y? (its top-left in the parent; default a four-line block centred in the view), language? (bash|cpp|css|go|graphql|html|javascript|json|kotlin|plainText|python|ruby|rust|sql|swift|typescript; default typescript), text?, width? (210 to 100000; default 576), parent?, edit? (start typing in it; default false)} → {id, text, language} a dark panel holding monospace text: as wide as it is made, as tall as its lines (four at least)",
true,
code::code_block_cmd
),
spec!(
"board.setLanguage",
"Code language",
"{id? | ids? (code blocks; default the selected ones, or the one being typed in), language} → {ids}",
true,
code::set_language
),
spec!("board.label", "Connector label", "{id (a connector; default the selection), text (empty removes it)} → {id, label}", true, label_cmd),
spec!(
"board.stamp",
+260
View File
@@ -0,0 +1,260 @@
//! Code blocks (#2237): a frame hugging one monospace text ([`BoardItem::CodeBlock`]), as wide as
//! it was made and as tall as its lines. The commands only make the block; [`settle_code`] keeps
//! it that way in the normalize pass (the height is the lines', the text is plain code), so every
//! entry point (a drag, `node.set`, a styled paste, a live session's edit) ends the same.
use std::collections::BTreeSet;
use figcraft_color::Paint;
use figcraft_doc::{
AutoLayout, BoardItem, CODE_FONT, CODE_FONT_SIZE, CODE_GAP, CODE_MAX_CHARS, CODE_MAX_W, CODE_MIN_H, CODE_MIN_W, CODE_PAD, CODE_PANEL,
CODE_RADIUS, CODE_TEXT, CODE_WIDTH, CodeLanguage, Document, LayoutMode, LineHeight, ListStyle, NodeId, NodeKind, ParaList, Sizing, TextAlignH,
TextAutoResize, TextCase, TextData, TextDecoration,
};
use serde_json::{Value, json};
use super::items::{add, add_text, owner_of_text, soft_shadow, text_of};
use super::{Result, Session, bad, boolean, get, num, parent_of, req_string, req_targets, require, string, textedit};
/// How far from the page's middle a block may be put.
const CODE_MAX_COORD: f64 = 1.0e9;
/// Whether `text` is the text of a code block: what the text editor asks before it converts what
/// is typed (a list from `- `, and any smart punctuation or link to come).
pub fn is_code_text(doc: &Document, text: NodeId) -> bool {
owner_of_text(doc, text).and_then(|o| doc.node(o)).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. })))
}
/// The auto layout every code block has: its text stacked inside the padding.
fn block_layout() -> AutoLayout {
AutoLayout { mode: LayoutMode::Vertical, gap: 0.0, padding: CODE_PAD, ..AutoLayout::default() }
}
/// A code block's frame and its text: `width` wide at `at` in `parent`, holding `text`.
fn make_code_block(doc: &mut Document, parent: NodeId, at: (f64, f64), width: f64, language: CodeLanguage, text: &str) -> Result<(NodeId, NodeId)> {
let frame = add(doc, parent, NodeKind::Frame, "Code block", at, (width, CODE_MIN_H), |n| {
n.fills = vec![Paint::solid(CODE_PANEL)];
n.corners.radii = [CODE_RADIUS; 4];
n.effects = vec![soft_shadow()];
n.clip = false;
n.layout = Some(block_layout());
n.child_layout.sizing_v = Sizing::Hug;
n.child_layout.min_h = Some(CODE_MIN_H);
n.child_layout.min_w = Some(CODE_MIN_W);
n.board = Some(BoardItem::CodeBlock { language });
})?;
let inner = width - CODE_PAD[1] - CODE_PAD[3];
let label = add_text(doc, frame, text, CODE_FONT_SIZE, CODE_TEXT, TextAlignH::Left, inner)?;
if let Some(NodeKind::Text(td)) = doc.node_mut(label).map(|n| &mut n.kind) {
td.style.font_family = CODE_FONT.into();
td.style.line_height = LineHeight::Percent(150.0);
td.features.insert("liga".into(), false);
td.features.insert("calt".into(), false);
}
Ok((frame, label))
}
/// A language from its id or name, or an error listing the ids.
fn language_of(cmd: &str, v: &str) -> Result<CodeLanguage> {
CodeLanguage::from_id(v).ok_or_else(|| {
let known: Vec<&str> = CodeLanguage::ALL.iter().map(|l| l.id()).collect();
bad(cmd, format!("unknown language `{v}` ({})", known.join("|")))
})
}
/// A coordinate from the params: given, it is a finite number within a billion of the origin.
fn coord(cmd: &str, p: &Value, key: &str, default: f64) -> Result<f64> {
let v = if get(p, key).is_none_or(Value::is_null) { Some(default) } else { num(p, key) };
v.filter(|v| v.is_finite() && v.abs() <= CODE_MAX_COORD).ok_or_else(|| bad(cmd, format!("`{key}` is a position within a billion of the origin")))
}
pub(super) fn code_block_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.codeBlock";
require(s, cmd)?;
let parent = parent_of(cmd, s, p)?;
let width = if get(p, "width").is_none_or(Value::is_null) {
CODE_WIDTH
} else {
num(p, "width")
.filter(|w| w.is_finite() && (CODE_MIN_W..=CODE_MAX_W).contains(w))
.ok_or_else(|| bad(cmd, format!("`width` is a size from {CODE_MIN_W} to {CODE_MAX_W}")))?
};
// The view's centre is on the page, and `x`/`y` are in the parent: a block in a section or
// frame takes the centre in that parent's coordinates (a parent that can't be inverted gives a
// non-finite centre, which `coord` refuses).
let (vx, vy) = {
let ds = s.ds()?;
let c = ds.doc.world_transform(parent).inverse() * figcraft_geom::Point::new(ds.view.cx, ds.view.cy);
(c.x, c.y)
};
let x = coord(cmd, p, "x", vx - width / 2.0)?;
let y = coord(cmd, p, "y", vy - CODE_MIN_H / 2.0)?;
let language = match string(p, "language") {
Some(v) => language_of(cmd, &v)?,
None if get(p, "language").is_none_or(Value::is_null) => CodeLanguage::default(),
None => return Err(bad(cmd, "`language` is a language id")),
};
let text = match get(p, "text") {
None | Some(Value::Null) => String::new(),
Some(Value::String(t)) => t.clone(),
Some(_) => return Err(bad(cmd, "`text` is a string")),
};
if text.chars().count() > CODE_MAX_CHARS {
return Err(bad(cmd, format!("`text` is at most {CODE_MAX_CHARS} characters")));
}
let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, &text)?;
s.set_selection(vec![frame]);
if boolean(p, "edit") == Some(true) {
s.request_ui("board.editText", json!({"id": frame}));
}
Ok(json!({"id": frame, "text": label, "language": language.id()}))
}
pub(super) fn set_language(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.setLanguage";
require(s, cmd)?;
let language = language_of(cmd, &req_string(cmd, p, "language")?)?;
let targets = req_targets(cmd, s, p)?;
let doc = s.doc()?;
let blocks: BTreeSet<NodeId> = targets
.into_iter()
.map(|i| owner_of_text(doc, i).unwrap_or(i))
.filter(|i| doc.node(*i).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. }))))
.collect();
if blocks.is_empty() {
return Err(bad(cmd, "select a code block"));
}
let doc = s.doc_mut()?;
for &b in &blocks {
if doc.node(b).is_some_and(|n| n.board != Some(BoardItem::CodeBlock { language })) {
doc.get_mut(b)?.board = Some(BoardItem::CodeBlock { language });
}
}
Ok(json!({"ids": blocks.into_iter().collect::<Vec<_>>()}))
}
/// `board.nextSticky` on code block `from`: the next one beside it, as wide and in the same
/// language, with no connector.
pub(super) fn next_block(s: &mut Session, from: NodeId, language: CodeLanguage, p: &Value) -> Result<Value> {
let cmd = "board.nextSticky";
let editing = s.ds()?.text_edit.is_some();
let doc = s.doc()?;
let n = doc.get(from)?;
let parent = n.parent.ok_or_else(|| bad(cmd, "that code block has no parent"))?;
let at = n.transform.translation();
let (w, h) = (n.width, n.height);
let (x, y) = match string(p, "side").as_deref().unwrap_or("right") {
"right" => (at.x + w + CODE_GAP, at.y),
"left" => (at.x - CODE_GAP - w, at.y),
"below" => (at.x, at.y + h + CODE_GAP),
"above" => (at.x, at.y - CODE_GAP - CODE_MIN_H),
other => return Err(bad(cmd, format!("`side` is right, below, left or above, not `{other}`"))),
};
if !(x.is_finite() && y.is_finite() && w.is_finite()) {
return Err(bad(cmd, "the next block can't be placed there"));
}
let width = w.clamp(CODE_MIN_W, CODE_MAX_W);
if editing {
textedit::end(s)?;
}
let (frame, label) = make_code_block(s.doc_mut()?, parent, (x, y), width, language, "")?;
s.set_selection(vec![frame]);
if boolean(p, "edit") == Some(true) {
s.request_ui("board.editText", json!({"id": frame}));
}
Ok(json!({"id": frame, "text": label, "language": language.id()}))
}
/// Whether `td` is already plain code: no list, indent, spacing, link, decoration, case change or
/// hand-made run, and a height that follows its lines.
fn is_plain(td: &TextData) -> bool {
td.auto_resize == TextAutoResize::Height
&& td.list == ListStyle::None
&& td.paragraphs == plain_paragraphs(&td.paragraphs)
&& td.paragraph_indent == 0.0
&& td.paragraph_spacing == 0.0
&& td.list_spacing == 0.0
&& td.style.link.is_none()
&& td.style.decoration == TextDecoration::None
&& td.style.decoration_look.is_none()
&& td.style.case == TextCase::Original
&& td.runs.is_empty()
}
/// `paragraphs` with no list, level or counting offset (the direction stays); empty when that
/// leaves every paragraph at its default.
fn plain_paragraphs(paragraphs: &[ParaList]) -> Vec<ParaList> {
let v: Vec<ParaList> = paragraphs.iter().map(|p| ParaList { direction: p.direction, ..ParaList::default() }).collect();
if v.iter().all(|p| *p == ParaList::default()) { Vec::new() } else { v }
}
fn make_plain(td: &mut TextData) {
td.auto_resize = TextAutoResize::Height;
td.list = ListStyle::None;
td.paragraphs = plain_paragraphs(&td.paragraphs);
td.paragraph_indent = 0.0;
td.paragraph_spacing = 0.0;
td.list_spacing = 0.0;
td.style.link = None;
td.style.decoration = TextDecoration::None;
td.style.decoration_look = None;
td.style.case = TextCase::Original;
td.runs.clear();
}
/// In the normalize pass, before text is measured and layout runs: every code block an edit
/// touched (or whose text it touched) is as tall as its lines again and holds plain code. Nothing
/// is written for a block already in that form, so a second pass changes nothing.
pub(crate) fn settle_code(doc: &mut Document, touched: &BTreeSet<NodeId>) {
let is_block = |doc: &Document, id: NodeId| doc.node(id).is_some_and(|n| matches!(n.board, Some(BoardItem::CodeBlock { .. })));
let mut blocks = BTreeSet::new();
for &id in touched {
if is_block(doc, id) {
blocks.insert(id);
} else if let Some(p) = doc.node(id).and_then(|n| n.parent).filter(|p| is_block(doc, *p)) {
blocks.insert(p);
}
}
for b in blocks {
// The frame's form is complete first: its layout and minimums (or it cannot hug) and a width that
// is not Hug (or its text cannot fill), else normalize puts them back every pass.
if let Some(n) = doc.node_mut(b) {
if n.layout.as_ref() != Some(&block_layout()) {
n.layout = Some(block_layout());
}
if n.child_layout.min_h != Some(CODE_MIN_H) {
n.child_layout.min_h = Some(CODE_MIN_H);
}
if n.child_layout.min_w != Some(CODE_MIN_W) {
n.child_layout.min_w = Some(CODE_MIN_W);
}
if n.child_layout.sizing_h == Sizing::Hug {
n.child_layout.sizing_h = Sizing::Fixed;
}
}
// A fixed height is not kept: the layout pass sizes the block to its lines again.
if doc.node(b).is_some_and(|n| n.child_layout.sizing_v != Sizing::Hug)
&& let Some(n) = doc.node_mut(b)
{
n.child_layout.sizing_v = Sizing::Hug;
}
let Some(t) = text_of(doc, b) else { continue };
let Some(node) = doc.node(t) else { continue };
let off = match &node.kind {
NodeKind::Text(td) => !is_plain(td),
_ => continue,
};
let fill_off = node.child_layout.sizing_h != Sizing::Fill;
if !(off || fill_off) {
continue;
}
if let Some(n) = doc.node_mut(t) {
if fill_off {
n.child_layout.sizing_h = Sizing::Fill;
}
if off && let NodeKind::Text(td) = &mut n.kind {
make_plain(td);
}
}
}
}
@@ -15,6 +15,7 @@ pub(crate) fn settle_text(doc: &mut Document, before: &Document, touched: &BTree
return;
}
crate::board_table::settle_resize(doc, before, touched);
super::code::settle_code(doc, touched);
for &id in touched {
let Some(n) = doc.node(id) else { continue };
if let Some(BoardItem::Shape { shape }) = n.board
+1 -1
View File
@@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result<Value> {
n.strokes = vec![Paint::solid(line_shade(color))];
}
BoardItem::Connector(_) | BoardItem::Ink => doc.get_mut(id)?.strokes = vec![Paint::solid(line_shade(color))],
BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode => continue,
BoardItem::Label { .. } | BoardItem::Stamp { .. } | BoardItem::Table | BoardItem::MindNode | BoardItem::CodeBlock { .. } => continue,
}
changed.push(id);
}
+6 -3
View File
@@ -26,7 +26,7 @@ pub(super) fn add(
}
/// A soft shadow under stickies and stamps.
fn soft_shadow() -> Effect {
pub(super) fn soft_shadow() -> Effect {
Effect {
kind: EffectKind::DropShadow(Shadow { color: Color::new(0.0, 0.0, 0.0, 0.16), offset: (0.0, 2.0), radius: 6.0, ..Shadow::default() }),
visible: true,
@@ -142,14 +142,17 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result<Value> {
let from = id(p, "id")
.or_else(|| editing.and_then(|t| owner_of_text(doc, t)))
.or_else(|| s.selection().first().copied().map(|i| owner_of_text(doc, i).unwrap_or(i)))
.ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky or a shape first".into()))?;
.ok_or_else(|| EngineError::Disabled(cmd.into(), "select a sticky, a shape or a code block first".into()))?;
let n = doc.get(from)?;
if let Some(BoardItem::CodeBlock { language }) = n.board {
return super::code::next_block(s, from, language, p);
}
if matches!(n.board, Some(BoardItem::Shape { .. })) {
// A shape gets the next one joined to it, as the "+" beside it makes (#1597).
return add_connected(s, p);
}
if !matches!(n.board, Some(BoardItem::Sticky { .. })) {
return Err(bad(cmd, "that isn't a sticky or a shape"));
return Err(bad(cmd, "that isn't a sticky, a shape or a code block"));
}
let color = n.fills.iter().find_map(Paint::solid_color).unwrap_or(s.tool.board.sticky);
let parent = n.parent.ok_or_else(|| bad(cmd, "that sticky has no parent"))?;
+19 -1
View File
@@ -87,6 +87,12 @@ fn text_of(s: &Session, id: NodeId) -> Result<TextData> {
}
}
/// Whether the text being edited is a code block's.
fn in_code(s: &Session) -> bool {
let Some(te) = s.ds().ok().and_then(|d| d.text_edit.as_ref()) else { return false };
s.doc().is_ok_and(|d| crate::board::is_code_text(d, te.id))
}
/// Start editing text node `id` with the caret at `caret` (None = select all).
pub fn begin(s: &mut Session, id: NodeId, caret: Option<usize>, created: bool) -> Result<()> {
let t = text_of(s, id)?;
@@ -282,13 +288,15 @@ fn insert_model(s: &mut Session, text: &str, ime_commit: bool) -> Result<ImeInse
// A commit the editor had to transform is an application edit, not a plain insertion.
let mut outcome = if normalized == text { ImeInsertion::Plain } else { ImeInsertion::Transformed };
let text = normalized;
// Code is typed as it is: no list from "- " (and no smart punctuation or link to come).
let code = in_code(s);
edit(s, |t, te| {
let (a, b) = range(te);
// "- ", "* ", "<number>. " or "1) " typed at the start of a plain paragraph starts a list
// (the creation characters of Create bulleted and numbered lists). As measured in Figma
// (2026-11-11), a typed "5. " starts the numbered list at 5 (there is no start-number
// field). "0. " and a bracket after a number other than 1 are not measured: plain text.
if text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
if !code && text == " " && a == b && t.para_list(t.para_of(a)).list == ListStyle::None {
let chars: Vec<char> = t.characters.chars().collect();
let start = line_start(&chars, a);
let typed: String = chars.get(start..a).unwrap_or(&[]).iter().collect();
@@ -463,6 +471,16 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
if matches!(key, "Tab" | "Backspace" | "Delete" | "Enter") && !word && !line && list_key(s, key, shift)? {
return Ok(());
}
// In a code block Tab types two spaces and Enter keeps the line's indent.
if matches!(key, "Tab" | "Enter") && !word && !line && in_code(s) {
if key == "Tab" {
return if shift { Ok(()) } else { insert(s, figcraft_doc::CODE_TAB) };
}
let (a, _) = range(&te);
let start = line_start(&chars, a);
let indent: String = chars.get(start..a).unwrap_or(&[]).iter().take(256).take_while(|c| matches!(c, ' ' | '\t')).collect();
return insert(s, &format!("\n{indent}"));
}
match key {
"Escape" => return end(s),
"Enter" => return insert(s, "\n"),
+39 -2
View File
@@ -431,6 +431,9 @@ pub(crate) enum Gesture {
additive: bool,
base: Vec<NodeId>,
within: Option<NodeId>,
/// A click stepping out of a selected descendant picks its frame. Wait for a real drag
/// before replacing that selection with the marquee's contents.
pending_click: bool,
},
Move {
start: Point,
@@ -441,8 +444,8 @@ pub(crate) enum Gesture {
/// A Shift-press on this selected layer: it leaves the selection on release, unless the
/// press became a drag.
deselect: Option<NodeId>,
/// A press on one layer of a multi-selection that keeps the selection to drag it all: a
/// release without a drag selects just this layer.
/// A press on one layer of a multi-selection, or on a layer inside a selected one, that
/// keeps the selection to drag it all: a release without a drag selects just this layer.
keep: Option<NodeId>,
},
Resize {
@@ -541,6 +544,27 @@ fn at_45_degrees(last: Point, p: Point) -> Point {
last + Vec2::from_angle(ang) * v.hypot()
}
/// Add where the pointer is to a Pencil (Marker, Highlighter) stroke: a sample once it has moved
/// half a screen pixel, or with Shift one straight segment from where the stroke started, at the
/// nearest 45° step, as the Line tool and the Pen keep theirs (#2447).
fn pencil_add(points: &mut Vec<Point>, pressure: &mut Vec<Option<f32>>, ev: &PointerEvent) {
let min = 0.5 / ev.zoom.max(1e-6);
if ev.shift
&& let (Some(&start), Some(&first)) = (points.first(), pressure.first())
{
let end = at_45_degrees(start, ev.p());
points.truncate(1);
pressure.truncate(1);
if (end - start).hypot() > min {
points.push(end);
pressure.push(ev.pressure.or(first));
}
} else if points.last().is_none_or(|l| (*l - ev.p()).hypot() > min) {
points.push(ev.p());
pressure.push(ev.pressure);
}
}
/// The handles a pen path shows while it is drawn ([`Overlay::pen_handles`]): the last anchor's in
/// and out handles and the one before's out handle, those that aren't zero.
fn pen_handles(points: &[(Point, Vec2, Vec2)]) -> Vec<[f64; 4]> {
@@ -620,4 +644,17 @@ impl ToolState {
pub fn busy(&self) -> bool {
!matches!(self.gesture, Gesture::None)
}
/// Whether the gesture under way pans the canvas when the pointer holds near the viewport's
/// edge (#2015): moving layers once past the drag slop, the selection box once it has grown
/// past it, and drawing a shape once it exists. Resizing, rotating, panning, text and vector
/// edits don't. `zoom`: screen px per page unit.
pub fn autopans(&self, zoom: f64) -> bool {
match &self.gesture {
Gesture::Move { moved, .. } => *moved,
Gesture::Marquee { .. } => self.overlay.marquee.is_some_and(|[x0, y0, x1, y1]| ((x1 - x0).hypot(y1 - y0) * zoom) >= DRAG_SLOP_PX),
Gesture::Draw { id, .. } => id.is_some(),
_ => false,
}
}
}
+45 -20
View File
@@ -4,8 +4,8 @@ use super::handles::{
};
use super::{
Affine, ArcHandle, ArcHint, Cursor, Document, Gesture, Guide, Handle, ImageScaleMode, LayoutMode, NodeId, NodeKind, PaintKind, Point,
PointerEvent, Rect, ResizeStart, Result, ScaleHint, Session, Sizing, Targets, TextAutoResize, ToolId, Vec2, move_world, roots, select_target,
textedit, within_slop,
PointerEvent, Rect, ResizeStart, Result, ScaleHint, Session, Sizing, Targets, TextAutoResize, ToolId, Vec2, move_world, pencil_add, roots,
select_target, textedit, within_slop,
};
impl Session {
@@ -77,8 +77,8 @@ impl Session {
}
// A frame's name label picks the frame itself. The background of a top-level frame with
// layers in it is like the canvas (a press starts a marquee inside it) unless the frame is
// selected; an empty frame (or a widget, or a board object such as a sticky) is picked and
// dragged.
// selected; stepping out from a selected descendant is handled by the marquee below.
// An empty frame (or a widget, or a board object such as a sticky) is picked and dragged.
let board_background = |leaf: NodeId| {
!sel.contains(&leaf)
&& doc.node(leaf).is_some_and(|n| {
@@ -86,17 +86,20 @@ impl Session {
})
};
let label = label_at(&doc, page, &self.tool.labels, ev.p());
let target = label.or_else(|| {
self.hit(&doc, page, ev.p(), ev.tol() * 2.0)
.filter(|leaf| ev.cmd || !board_background(*leaf))
.map(|leaf| select_target(&doc, leaf, &sel, ev.cmd))
});
let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0));
let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
// A press inside the selection's box that reaches nothing above it (an unfilled shape's
// inside, the frame or canvas behind it, or a layer stacked below the selected layer the
// press is in) drags the selection. In a gap between selected layers, what's there is hit.
let in_own_box = |s: NodeId| selection_box(&doc, &[s]).is_some_and(|q| in_quad(&q, ev.p()));
// A press on a layer inside a selected one (a child of a selected frame) drags the
// selection too, and a click selects that layer; Cmd/Ctrl keeps the deep pick.
let in_selected = |t: NodeId| sel.iter().any(|s| *s != t && doc.is_ancestor(*s, t));
let behind_sel = |t: Option<NodeId>| {
t.is_none_or(|t| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s)))))
t.is_none_or(|t| {
(!ev.cmd && in_selected(t))
|| sel.iter().any(|s| *s != t && (doc.is_ancestor(t, *s) || (in_own_box(*s) && paints_below(&doc, t, *s))))
})
};
// What the press hit (a label or a painted layer): a click that doesn't become a drag
// selects just it. A press that reaches nothing above the selection uses the selection as
@@ -119,8 +122,12 @@ impl Session {
let without_target = || sel.iter().copied().filter(|x| *x != target).collect::<Vec<_>>();
// A release without a drag narrows the selection to the layer the press hit. A
// selected frame's name label sits outside the selection bounds, so it counts too.
let keep = clicked
.filter(|c| (label.is_some() || in_sel_box) && !ev.cmd && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c))));
// A layer inside a selected one counts as well: the press drags the selection, and
// a click selects that layer.
let keep = clicked.filter(|c| {
!ev.cmd
&& (((label.is_some() || in_sel_box) && (sel.contains(c) || sel.iter().any(|s| doc.is_ancestor(*s, *c)))) || in_selected(*c))
});
let new_sel = if keep.is_some() {
sel.clone()
} else if ev.shift && deselect.is_none() {
@@ -138,7 +145,7 @@ impl Session {
if !edits {
if deselect.is_some() {
self.set_selection(without_target());
} else if let Some(k) = keep.filter(|_| sel.len() > 1) {
} else if let Some(k) = keep.filter(|k| sel.as_slice() != [*k]) {
self.set_selection(vec![k]);
}
return Ok(());
@@ -172,10 +179,22 @@ impl Session {
}
None => {
let within = self.marquee_within(ev.p())?;
if !ev.shift {
// Clicking the background of the frame containing the current selection steps
// out to that frame. Keep the marquee gesture (without a Move interaction), so
// dragging here still selects its contents and cannot leave a stale snapshot.
let parent = hit.filter(|f| !ev.shift && !ev.cmd && within == Some(*f) && sel.iter().any(|s| doc.is_ancestor(*f, *s)));
if let Some(f) = parent {
self.set_selection(vec![f]);
} else if !ev.shift {
self.set_selection(vec![]);
}
self.tool.gesture = Gesture::Marquee { start: ev.p(), additive: ev.shift, base: if ev.shift { sel } else { vec![] }, within };
self.tool.gesture = Gesture::Marquee {
start: ev.p(),
additive: ev.shift,
base: if ev.shift { sel } else { vec![] },
within,
pending_click: parent.is_some(),
};
}
}
Ok(())
@@ -196,9 +215,18 @@ impl Session {
it.label = if ev.alt { "Duplicate" } else { "Move" }.into();
}
}
if let Gesture::Marquee { start, pending_click, .. } = &mut g
&& *pending_click
{
if within_slop(ev, *start) {
self.tool.gesture = g;
return Ok(());
}
*pending_click = false;
}
let res = match &g {
Gesture::None => return self.hover(ev),
Gesture::Marquee { start, additive, base, within } => {
Gesture::Marquee { start, additive, base, within, .. } => {
let r = Rect::from_points(*start, ev.p());
self.tool.overlay.marquee = Some([r.x0, r.y0, r.x1, r.y1]);
// Cmd/Ctrl: the nested layers it touches.
@@ -416,10 +444,7 @@ impl Session {
}
Gesture::Pencil { points, pressure } => {
let (mut pts, mut pressure) = (points.clone(), pressure.clone());
if pts.last().is_none_or(|l| (*l - ev.p()).hypot() > 0.5 / ev.zoom.max(1e-6)) {
pts.push(ev.p());
pressure.push(ev.pressure);
}
pencil_add(&mut pts, &mut pressure, ev);
self.tool.overlay.pen = pts.iter().map(|p| [p.x, p.y]).collect();
self.tool.gesture = Gesture::Pencil { points: pts, pressure };
if let Ok(ds) = self.ds_mut() {
+6 -7
View File
@@ -1,7 +1,8 @@
use super::handles::SNAP_PX;
use super::pen::take_enclosed;
use super::{
Affine, Cursor, Gesture, Node, NodeId, NodeKind, Point, PointerEvent, Rect, Result, Session, StrokeCap, Targets, ToolId, Vec2, frame_at, textedit,
Affine, Cursor, Gesture, Node, NodeId, NodeKind, Point, PointerEvent, Rect, Result, Session, StrokeCap, Targets, ToolId, Vec2, frame_at,
pencil_add, textedit,
};
impl Session {
@@ -176,10 +177,11 @@ impl Session {
let sel = self.selection().into_iter().filter(|x| *x != d).collect();
self.set_selection(sel);
} else if let Some(k) = keep {
// A click (not a drag) on one layer of a multi-selection selects just it.
// A click (not a drag) on one layer of a multi-selection, or on a layer
// inside a selected one, selects just it.
let doc = self.doc()?.clone();
let sel = self.selection();
if sel.len() > 1 && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) {
if sel.as_slice() != [k] && (sel.contains(&k) || sel.iter().any(|s| doc.is_ancestor(*s, k))) {
self.set_selection(vec![k]);
}
}
@@ -239,10 +241,7 @@ impl Session {
self.tool.overlay.pen.clear();
self.tool.overlay.pen_color = None;
// The stroke ends where the button came up, even without a move to get there.
if points.last().is_none_or(|l| (*l - ev.p()).hypot() > 0.5 / ev.zoom.max(1e-6)) {
points.push(ev.p());
pressure.push(ev.pressure);
}
pencil_add(&mut points, &mut pressure, ev);
self.pencil_finish(&points, &pressure)?;
}
Gesture::Connect { from, start } => self.connect_up(ev, from, start)?,
+2
View File
@@ -7,6 +7,8 @@
//! the transform box around several points (in one layer or several) in [`transform`], point snapping in `point_snap.rs` and
//! hovering, hatching and selecting filled regions in [`regions`].
#[cfg(test)]
mod align_tests;
pub mod ops;
pub(crate) mod point_snap;
mod pointer;
@@ -0,0 +1,261 @@
//! Align and distribute the selected points in vector edit mode.
use serde_json::json;
use super::tests::{ex, net, pt, ve};
use super::*;
/// The measured path: points at (330, 480), (480, 430), (560, 560), (380, 620), in edit mode.
fn path(s: &mut Session) -> NodeId {
let r = ex(s, "vector.create", json!({"points": [[330, 480], [480, 430], [560, 560], [380, 620]], "closed": false}));
let id = crate::params::id_of(&r["id"]).unwrap();
ex(s, "vector.edit.begin", json!({"id": id}));
id
}
fn page(s: &Session, id: NodeId) -> Vec<Point> {
let w = s.doc().unwrap().world_transform(id);
net(s, id).vertices.iter().map(|v| w * v.point()).collect()
}
fn page_of(s: &Session, id: NodeId, p: Point) -> Point {
s.doc().unwrap().world_transform(id) * p
}
fn select(s: &mut Session, v: &[usize]) {
ex(s, "vector.edit.select", json!({"vertices": v}));
}
fn near(a: Point, b: Point) -> bool {
(a - b).hypot() < 1e-6
}
#[test]
fn each_alignment_moves_the_points_along_one_axis_to_their_box() {
// Points 0 and 1: box x 330..480, y 430..480.
let cases = [
("align.left", [pt(330.0, 480.0), pt(330.0, 430.0)]),
("align.hcenter", [pt(405.0, 480.0), pt(405.0, 430.0)]),
("align.right", [pt(480.0, 480.0), pt(480.0, 430.0)]),
("align.top", [pt(330.0, 430.0), pt(480.0, 430.0)]),
("align.vcenter", [pt(330.0, 455.0), pt(480.0, 455.0)]),
("align.bottom", [pt(330.0, 480.0), pt(480.0, 480.0)]),
];
for (cmd, want) in cases {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[0, 1]);
ex(&mut s, cmd, json!({}));
let after = page(&s, id);
assert!(near(after[0], want[0]) && near(after[1], want[1]), "{cmd}: {after:?}");
assert!(near(after[2], before[2]) && near(after[3], before[3]), "{cmd} left the others");
}
}
#[test]
fn one_point_does_not_move() {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[1]);
for c in ["align.left", "align.bottom", "distribute.horizontal"] {
ex(&mut s, c, json!({}));
}
assert_eq!(page(&s, id), before);
}
#[test]
fn two_points_do_not_distribute() {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[0, 1]);
for c in ["distribute.horizontal", "distribute.vertical"] {
ex(&mut s, c, json!({}));
}
assert_eq!(page(&s, id), before);
}
/// A vector inside a frame at (100, 100), its left (150) well inside the frame.
fn framed(s: &mut Session) -> (NodeId, NodeId) {
let f = crate::params::id_of(&ex(s, "frame.create", json!({"x": 100, "y": 100, "width": 400, "height": 400}))["id"]).unwrap();
let r = ex(s, "vector.create", json!({"points": [[50, 100], [150, 50], [200, 200]], "closed": false, "parent": f}));
(f, crate::params::id_of(&r["id"]).unwrap())
}
const ALIGNS: [&str; 6] = ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"];
#[test]
fn no_points_selected_moves_nothing_and_not_the_layer() {
let mut s = Session::new();
let (frame, v) = framed(&mut s);
ex(&mut s, "vector.edit.begin", json!({"id": v}));
ex(&mut s, "vector.edit.select", json!({"vertices": []}));
assert_eq!(transform::edit_point_count(s.doc().unwrap(), &ve(&s)), 0);
let (points, bounds, local) = (page(&s, v), s.doc().unwrap().world_bounds(v), net(&s, v).vertices);
assert!(bounds.unwrap().x0 > s.doc().unwrap().world_bounds(frame).unwrap().x0 + 10.0, "starts well inside the frame");
for c in ALIGNS.into_iter().chain(["distribute.horizontal", "distribute.vertical"]) {
ex(&mut s, c, json!({}));
assert_eq!(page(&s, v), points, "{c}");
assert_eq!(s.doc().unwrap().world_bounds(v), bounds, "{c} moved the layer");
assert_eq!(net(&s, v).vertices, local, "{c}");
}
}
#[test]
fn points_of_several_layers_align_and_one_undo_restores_all() {
let mut s = Session::new();
let mut line = |p: serde_json::Value| crate::params::id_of(&ex(&mut s, "vector.create", json!({"points": p, "closed": false}))["id"]).unwrap();
let (a, b) = (line(json!([[0, 100], [100, 150]])), line(json!([[300, 40], [400, 90]])));
ex(&mut s, "vector.edit.begin", json!({"ids": [a, b]}));
ex(&mut s, "vector.edit.select", json!({"id": a, "vertices": [0]}));
ex(&mut s, "vector.edit.select", json!({"id": b, "vertices": [1], "add": true}));
let (pa, pb) = (page(&s, a), page(&s, b));
ex(&mut s, "align.top", json!({}));
let (na, nb) = (page(&s, a), page(&s, b));
let top = pa[0].y.min(pb[1].y);
assert!(near(na[0], pt(pa[0].x, top)) && near(nb[1], pt(pb[1].x, top)), "{na:?} {nb:?}");
assert!(near(na[1], pa[1]) && near(nb[0], pb[0]), "unselected points stay");
s.undo().unwrap();
let (ua, ub) = (page(&s, a), page(&s, b));
assert!(pa.iter().zip(&ua).chain(pb.iter().zip(&ub)).all(|(x, y)| near(*x, *y)), "{ua:?} {ub:?}");
}
#[test]
fn a_rotated_layer_aligns_in_the_boxs_own_frame() {
let mut s = Session::new();
let id = path(&mut s);
ex(&mut s, "node.set", json!({"id": id, "props": {"rotation": 30}}));
select(&mut s, &[0, 1]);
let b = transform::point_box(s.doc().unwrap(), &ve(&s)).unwrap();
let inv = b.frame.inverse();
let before: Vec<Point> = page(&s, id).iter().map(|p| inv * *p).collect();
assert!((before[0].x - before[1].x).abs() > 1.0, "the points differ in box x");
ex(&mut s, "align.left", json!({}));
let after: Vec<Point> = page(&s, id).iter().map(|p| inv * *p).collect();
for i in 0..2 {
assert!(after[i].x.abs() < 1e-6, "box x is the box's left: {after:?}");
assert!((after[i].y - before[i].y).abs() < 1e-6, "box y unchanged: {after:?}");
}
}
#[test]
fn id_in_edit_mode_moves_the_layer_not_the_points() {
let mut s = Session::new();
let (frame, v) = framed(&mut s);
ex(&mut s, "vector.edit.begin", json!({"id": v}));
select(&mut s, &[0, 1]);
let local = net(&s, v).vertices;
ex(&mut s, "align.left", json!({"id": v}));
let d = s.doc().unwrap();
assert!((d.world_bounds(v).unwrap().x0 - d.world_bounds(frame).unwrap().x0).abs() < 1e-6, "layer at the frame's left");
assert_eq!(net(&s, v).vertices, local, "points were not aligned to each other");
}
#[test]
fn ids_distribute_layers_and_leave_the_edited_layers_points() {
let mut s = Session::new();
let mut rect = |x: f64| crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50}))["id"]).unwrap();
let (r1, r2, r3) = (rect(0.0), rect(60.0), rect(400.0));
ex(&mut s, "vector.edit.begin", json!({"id": r2}));
select(&mut s, &[0, 1]);
let local = net(&s, r2).vertices;
ex(&mut s, "distribute.horizontal", json!({"ids": [r1, r2, r3]}));
let x0 = s.doc().unwrap().world_bounds(r2).unwrap().x0;
assert!((x0 - 200.0).abs() < 1e-6, "middle layer centred between the outer two: {x0}");
assert_eq!(net(&s, r2).vertices, local);
}
#[test]
fn distribute_spaces_the_points_evenly_between_the_outermost() {
let mut s = Session::new();
let id = path(&mut s);
select(&mut s, &[0, 1, 2, 3]);
ex(&mut s, "distribute.horizontal", json!({}));
let p = page(&s, id);
let want_x = [330.0, 483.0 + 1.0 / 3.0, 560.0, 380.0 + 80.0 / 3.0];
for (q, x) in p.iter().zip(want_x) {
assert!((q.x - x).abs() < 1e-6, "{p:?}");
}
let want_y = [480.0, 430.0, 560.0, 620.0];
assert!(p.iter().zip(want_y).all(|(q, y)| (q.y - y).abs() < 1e-6), "y unchanged: {p:?}");
ex(&mut s, "distribute.vertical", json!({}));
let p = page(&s, id);
// y sorted 430, 480, 560, 620 spread over 430..620.
let step = 190.0 / 3.0;
let want_y = [430.0 + step, 430.0, 430.0 + 2.0 * step, 620.0];
assert!(p.iter().zip(want_y).all(|(q, y)| (q.y - y).abs() < 1e-6), "{p:?}");
}
#[test]
fn a_curved_points_handles_move_with_it() {
let mut s = Session::new();
let r = ex(&mut s, "vector.create", json!({"path": "M 0 0 C 0 50 50 100 100 100 L 200 0", "x": 0, "y": 0}));
let id = crate::params::id_of(&r["id"]).unwrap();
ex(&mut s, "vector.edit.begin", json!({"id": id}));
let before = net(&s, id);
let page_before = page(&s, id);
let handle = |s: &Session, n: &VectorNetwork, v: usize, t: (f64, f64)| page_of(s, id, n.vertices[v].point() + Vec2::new(t.0, t.1));
let (h1_before, h0_before) = (handle(&s, &before, 1, before.segments[0].tb), handle(&s, &before, 0, before.segments[0].ta));
select(&mut s, &[0, 1]);
ex(&mut s, "align.left", json!({}));
let after = net(&s, id);
let moved: Vec<usize> = (0..2).filter(|i| !near(page(&s, id)[*i], page_before[*i])).collect();
assert!(!moved.is_empty(), "something moved");
let p = page(&s, id);
assert!(near(p[0], pt(0.0, 0.0)) && near(p[1], pt(0.0, 100.0)), "{p:?}");
assert!(near(p[2], page_before[2]), "vertex 2 stays");
// Handles: vertex 1's incoming one (vertex + segment 0's `tb`) moves with it by (-100, 0).
let a0 = &after.segments[0];
assert!(near(h1_before, pt(50.0, 100.0)) && near(handle(&s, &after, 1, a0.tb), pt(-50.0, 100.0)), "vertex 1's handle moved by (-100, 0)");
assert!(near(h0_before, handle(&s, &after, 0, a0.ta)), "vertex 0's handle stays");
assert_eq!(before.segments.len(), after.segments.len());
for (a, b) in before.segments.iter().zip(&after.segments) {
assert_eq!((a.ta, a.tb), (b.ta, b.tb), "handle offsets travel with their vertex");
}
}
#[test]
fn one_undo_restores_the_points() {
let mut s = Session::new();
let id = path(&mut s);
let before = page(&s, id);
select(&mut s, &[0, 1, 2, 3]);
ex(&mut s, "align.right", json!({}));
assert_ne!(page(&s, id), before);
s.undo().unwrap();
let after = page(&s, id);
assert!(before.iter().zip(&after).all(|(a, b)| near(*a, *b)), "{after:?}");
}
#[test]
fn ids_in_edit_mode_still_align_layers() {
let mut s = Session::new();
let mut square = |x: f64| crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50}))["id"]).unwrap();
let (a, b) = (square(0.0), square(200.0));
ex(&mut s, "vector.edit.begin", json!({"id": a}));
select(&mut s, &[0, 1]);
let local = net(&s, a).vertices;
ex(&mut s, "align.left", json!({"ids": [a, b]}));
let x = |id| s.doc().unwrap().world_bounds(id).unwrap().x0;
assert!((x(a) - x(b)).abs() < 1e-6, "layers aligned");
assert_eq!(net(&s, a).vertices, local, "the selected points kept their local positions");
}
#[test]
fn a_segment_selected_in_another_edited_layer_counts_both_its_ends() {
// `a`'s segment (two ends) and `b`'s first point: three points, so the panel offers
// Distribute and the command spaces all three.
let mut s = Session::new();
let mut line = |p: serde_json::Value| crate::params::id_of(&ex(&mut s, "vector.create", json!({"points": p, "closed": false}))["id"]).unwrap();
let (a, b) = (line(json!([[0, 0], [100, 50]])), line(json!([[300, 200], [400, 260]])));
ex(&mut s, "vector.edit.begin", json!({"ids": [a, b]}));
ex(&mut s, "vector.edit.select", json!({"id": a, "segments": [0]}));
ex(&mut s, "vector.edit.select", json!({"id": b, "vertices": [0], "add": true}));
assert_eq!(transform::edit_point_count(s.doc().unwrap(), &ve(&s)), 3);
ex(&mut s, "distribute.horizontal", json!({}));
let xs: Vec<f64> = page(&s, a).iter().chain(page(&s, b).first()).map(|p| p.x).collect();
assert!(xs.iter().zip([0.0, 150.0, 300.0]).all(|(x, w)| (x - w).abs() < 1e-6), "{xs:?}");
}
@@ -172,6 +172,126 @@ pub fn transform_in_edit_mode(s: &mut Session, p: &Value, f: impl FnOnce(&PointB
Some(s.doc_mut().and_then(|doc| transform_points(doc, ve.id, &b.points, m)).map(|()| json!({"ok": true})))
}
/// Which edge or centre line of the selected points' box each point goes to.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PointAlign {
Left,
HCenter,
Right,
Top,
VCenter,
Bottom,
}
/// Every selected point of `b` in every layer as (layer, vertex, page position).
fn page_points(doc: &Document, b: &PointBox, id: NodeId) -> Vec<(NodeId, usize, Point)> {
let layers = std::iter::once((id, &b.points)).chain(b.others.iter().map(|(o, v)| (*o, v)));
layers
.flat_map(|(l, verts)| {
let w = doc.world_transform(l);
let net = network(doc, l);
verts.iter().filter_map(move |v| net.and_then(|n| n.vertices.get(*v)).map(|vx| (l, *v, w * vx.point()))).collect::<Vec<_>>()
})
.collect()
}
/// The box to align or distribute in: all edited layers' points when several are selected.
fn edit_box(doc: &Document, ve: &VectorEdit) -> Option<PointBox> {
let b = if ve.others_selected() { layers_box(doc, ve) } else { point_box(doc, ve) };
b.filter(|b| b.point_count() > 0)
}
/// How many points align and distribute act on: the selected points and selected segments' ends
/// of every edited layer.
pub fn edit_point_count(doc: &Document, ve: &VectorEdit) -> usize {
edit_box(doc, ve).map_or(0, |b| b.point_count())
}
/// Move each point by its own page delta, one vertex at a time (handles go with their vertex).
fn move_each(doc: &mut Document, moves: &[(NodeId, usize, Point)]) -> Result<()> {
for (l, v, d) in moves {
if d.x.is_finite() && d.y.is_finite() && (d.x != 0.0 || d.y != 0.0) {
transform_points(doc, *l, &[*v], Affine::translate((d.x, d.y)))?;
}
}
Ok(())
}
/// The page delta of moving by `(dx, dy)` along the box's axes.
fn along(frame: Affine, dx: f64, dy: f64) -> Point {
let [a, b, c, d, _, _] = frame.as_coeffs();
Point::new(a * dx + c * dy, b * dx + d * dy)
}
/// Align the selected points to their box's edge or centre line (`None` when edit mode is off or
/// the command names layers; with no points selected in edit mode nothing moves, and the edited
/// layer is not aligned to its parent). Each point moves along one axis of the box only; fewer than
/// two points stay put.
pub fn align_points_in_edit_mode(s: &mut Session, p: &Value, how: PointAlign) -> Option<Result<Value>> {
if get(p, "ids").is_some() || get(p, "id").is_some() {
return None;
}
let ve = editing(s).ok()?;
let Some(b) = edit_box(s.doc().ok()?, &ve) else {
return Some(Ok(json!({"ok": true})));
};
let pts = page_points(s.doc().ok()?, &b, ve.id);
let inv = b.frame.inverse();
let moves: Vec<(NodeId, usize, Point)> = if b.point_count() < 2 {
vec![]
} else {
pts.iter()
.map(|(l, v, pg)| {
let q = inv * *pg;
let (dx, dy) = match how {
PointAlign::Left => (-q.x, 0.0),
PointAlign::HCenter => (b.width / 2.0 - q.x, 0.0),
PointAlign::Right => (b.width - q.x, 0.0),
PointAlign::Top => (0.0, -q.y),
PointAlign::VCenter => (0.0, b.height / 2.0 - q.y),
PointAlign::Bottom => (0.0, b.height - q.y),
};
(*l, *v, along(b.frame, dx, dy))
})
.collect()
};
Some(s.doc_mut().and_then(|doc| move_each(doc, &moves)).map(|()| json!({"ok": true})))
}
/// Space the selected points evenly along the box's x (or y) axis between the outermost two, in
/// order along it (`None` when edit mode is off or the command names layers; with no points
/// selected in edit mode nothing moves). Fewer than three points stay put.
pub fn distribute_points_in_edit_mode(s: &mut Session, p: &Value, horizontal: bool) -> Option<Result<Value>> {
if get(p, "ids").is_some() || get(p, "id").is_some() {
return None;
}
let ve = editing(s).ok()?;
let Some(b) = edit_box(s.doc().ok()?, &ve) else {
return Some(Ok(json!({"ok": true})));
};
let pts = page_points(s.doc().ok()?, &b, ve.id);
let inv = b.frame.inverse();
let mut items: Vec<(NodeId, usize, Point)> = pts.iter().map(|(l, v, pg)| (*l, *v, inv * *pg)).collect();
let axis = |q: &Point| if horizontal { q.x } else { q.y };
items.sort_by(|a, c| axis(&a.2).total_cmp(&axis(&c.2)));
let n = items.len();
let moves: Vec<(NodeId, usize, Point)> = if n < 3 {
vec![]
} else {
let (lo, hi) = (0.0, if horizontal { b.width } else { b.height });
items
.iter()
.enumerate()
.map(|(k, (l, v, q))| {
let target = lo + (hi - lo) * k as f64 / (n - 1) as f64;
let d = target - axis(q);
(*l, *v, if horizontal { along(b.frame, d, 0.0) } else { along(b.frame, 0.0, d) })
})
.collect()
};
Some(s.doc_mut().and_then(|doc| move_each(doc, &moves)).map(|()| json!({"ok": true})))
}
/// The selected points' box, or an error naming `cmd`.
fn selected_box(s: &Session, cmd: &str) -> Result<(VectorEdit, PointBox)> {
let ve = editing(s)?;
@@ -315,9 +315,23 @@ fn edit_mode_transform_commands_survive_junk() {
json!({"width": -1e308, "height": "x", "center": "maybe", "angle": 1e308, "cx": "NaN", "matrix": [1, 2, 3, "a", 5, 6]}),
json!({"matrix": [0, 0, 0, 0, 0, 0], "vertices": [1e12, -1], "width": 1e308, "height": 0}),
];
for c in
["object.flipH", "object.flipV", "object.rotate180", "object.rotateLeft", "object.rotateRight", "vector.edit.resize", "vector.edit.rotate"]
{
for c in [
"object.flipH",
"object.flipV",
"object.rotate180",
"object.rotateLeft",
"object.rotateRight",
"vector.edit.resize",
"vector.edit.rotate",
"align.left",
"align.hcenter",
"align.right",
"align.top",
"align.vcenter",
"align.bottom",
"distribute.horizontal",
"distribute.vertical",
] {
for j in &junk {
let mut s = Session::new();
let id = rect(&mut s);
+1
View File
@@ -100,6 +100,7 @@ fn registry() -> &'static Registry {
list.extend(crate::shapebuilder::specs());
list.extend(crate::codegen::specs());
list.extend(crate::devinspect::specs());
list.extend(crate::design_context::specs());
list.extend(crate::component_codegen::specs());
list.extend(crate::playground::specs());
list.extend(crate::code_connect::specs());
+71 -8
View File
@@ -11,14 +11,62 @@ use crate::{Result, Session, bad, spec};
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!("align.left", "Align left", "{ids?}", true, |s, p| align(s, p, Al::Left)),
spec!("align.hcenter", "Align horizontal centers", "{ids?}", true, |s, p| align(s, p, Al::HCenter)),
spec!("align.right", "Align right", "{ids?}", true, |s, p| align(s, p, Al::Right)),
spec!("align.top", "Align top", "{ids?}", true, |s, p| align(s, p, Al::Top)),
spec!("align.vcenter", "Align vertical centers", "{ids?}", true, |s, p| align(s, p, Al::VCenter)),
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!(
"align.left",
"Align left",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Left)
),
spec!(
"align.hcenter",
"Align horizontal centers",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::HCenter)
),
spec!(
"align.right",
"Align right",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Right)
),
spec!(
"align.top",
"Align top",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Top)
),
spec!(
"align.vcenter",
"Align vertical centers",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::VCenter)
),
spec!(
"align.bottom",
"Align bottom",
"{ids?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| align(s, p, Al::Bottom)
),
spec!(
"distribute.horizontal",
"Distribute horizontal spacing",
"{ids?, spacing?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| distribute(s, p, true)
),
spec!(
"distribute.vertical",
"Distribute vertical spacing",
"{ids?, spacing?} (in vector edit mode without ids: the selected points, and nothing moves with none selected)",
true,
|s, p| distribute(s, p, false)
),
spec!(
"arrange.spacing",
"Spacing",
@@ -192,6 +240,18 @@ fn align_target(doc: &Document, roots: &[NodeId]) -> Option<Rect> {
}
fn align(s: &mut Session, p: &Value, a: Al) -> Result<Value> {
use crate::vectoredit::transform::PointAlign;
let how = match a {
Al::Left => PointAlign::Left,
Al::HCenter => PointAlign::HCenter,
Al::Right => PointAlign::Right,
Al::Top => PointAlign::Top,
Al::VCenter => PointAlign::VCenter,
Al::Bottom => PointAlign::Bottom,
};
if let Some(r) = crate::vectoredit::transform::align_points_in_edit_mode(s, p, how) {
return r;
}
let ids = req_targets("align", s, p)?;
let doc = s.doc_mut()?;
let ids = roots(doc, &ids);
@@ -212,6 +272,9 @@ fn align(s: &mut Session, p: &Value, a: Al) -> Result<Value> {
}
fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
if let Some(r) = crate::vectoredit::transform::distribute_points_in_edit_mode(s, p, horizontal) {
return r;
}
let ids = req_targets("distribute", s, p)?;
let doc = s.doc_mut()?;
let ids = roots(doc, &ids);
+40 -7
View File
@@ -312,9 +312,12 @@ fn own(cmd: &str, m: &Message, who: &str, what: &str) -> crate::Result<()> {
}
/// A node to pin to: a node id on `page`, `true` for the innermost frame under the point, else none.
fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>) -> Option<NodeId> {
fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>, within: Option<NodeId>) -> Option<NodeId> {
match v {
Some(Value::Bool(true)) => frame_at(doc, page, x, y),
Some(Value::Bool(true)) => match within.filter(|w| *w != page && doc.page_of(*w) == Some(page) && contains(doc, *w, x, y)) {
Some(w) => frame_in(doc, w, x, y, Some(w)),
None => frame_at(doc, page, x, y),
},
Some(v) => id_of(v).filter(|a| *a != page && doc.page_of(*a) == Some(page)),
None => None,
}
@@ -670,7 +673,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"comment.add",
"Add comment",
"{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point)}",
"{x, y, text, page?, author?, anchor? (node id to pin to; true = innermost frame under the point), within? (with anchor true: search only inside this frame on the page, which is the anchor when no child holds the point)}",
true,
|s, p| {
let x = req_num("comment.add", p, "x")?;
@@ -682,7 +685,7 @@ pub fn specs() -> Vec<CommandSpec> {
if !doc.pages.contains(&page) {
return Err(bad("comment.add", format!("{page} is not a page")));
}
let anchor = anchor_at(doc, page, x, y, get(p, "anchor"));
let anchor = anchor_at(doc, page, x, y, get(p, "anchor"), id(p, "within"));
let (lx, ly) = local(doc, anchor, x, y);
let mut c = Comment {
id: s.doc_mut()?.new_comment_id(),
@@ -772,7 +775,7 @@ pub fn specs() -> Vec<CommandSpec> {
let (x, y) = (req_num("comment.move", p, "x")?, req_num("comment.move", p, "y")?);
let doc = s.doc()?;
let page = doc.comment(id).map(|c| c.page).ok_or_else(|| bad("comment.move", "no comment"))?;
let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))));
let anchor = anchor_at(doc, page, x, y, Some(get(p, "anchor").unwrap_or(&Value::Bool(true))), None);
let (lx, ly) = local(doc, anchor, x, y);
if let Some(c) = s.doc_mut()?.comment_mut(id) {
(c.x, c.y, c.anchor) = (lx, ly, anchor);
@@ -974,9 +977,20 @@ pub fn specs() -> Vec<CommandSpec> {
/// Innermost frame (or component/instance/section) under a page point, for anchoring.
fn frame_at(doc: &Document, page: NodeId, x: f64, y: f64) -> Option<NodeId> {
frame_in(doc, page, x, y, None)
}
/// Whether the page point lies inside node `n`'s box.
fn contains(doc: &Document, n: NodeId, x: f64, y: f64) -> bool {
let Some(node) = doc.node(n) else { return false };
let l = doc.world_transform(n).inverse() * geom::Point::new(x, y);
l.x >= 0.0 && l.y >= 0.0 && l.x <= node.width && l.y <= node.height
}
/// The innermost frame-like or section under the point, searching from `root` (with `found` as the fallback).
fn frame_in(doc: &Document, root: NodeId, x: f64, y: f64, mut found: Option<NodeId>) -> Option<NodeId> {
let pt = geom::Point::new(x, y);
let mut found = None;
let mut stack = vec![page];
let mut stack = vec![root];
while let Some(parent) = stack.pop() {
let Some(n) = doc.node(parent) else { continue };
for c in n.children.iter().rev() {
@@ -1012,6 +1026,25 @@ mod tests {
assert_eq!(super::parse_link("figcraft://comment/5/"), Some(5));
}
#[test]
fn comment_add_within_anchors_to_the_presented_frame() {
let mut s = Session::new();
let mk = |s: &mut Session, params: serde_json::Value| crate::params::id_of(&s.execute("node.create", &params).unwrap()["id"]).unwrap();
let a = mk(&mut s, json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 200}));
let b = mk(&mut s, json!({"type": "frame", "x": 100, "y": 0, "width": 200, "height": 200}));
let anchor = |s: &mut Session, params: serde_json::Value| {
let c = s.execute("comment.add", &params).unwrap();
let id = c["id"].as_u64().unwrap();
s.doc().unwrap().comment(id).unwrap().anchor
};
assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true})), Some(b));
assert_eq!(anchor(&mut s, json!({"x": 150, "y": 50, "text": "t", "anchor": true, "within": a})), Some(a));
let c = mk(&mut s, json!({"type": "frame", "x": 120, "y": 20, "width": 50, "height": 50, "parent": a}));
assert_eq!(anchor(&mut s, json!({"x": 130, "y": 30, "text": "t", "anchor": true, "within": a})), Some(c));
// A point outside `within` ignores it.
assert_eq!(anchor(&mut s, json!({"x": 250, "y": 50, "text": "t", "anchor": true, "within": a})), Some(b));
}
#[test]
fn comment_thread_lifecycle_and_anchoring() {
let mut s = Session::new();
+44 -14
View File
@@ -218,6 +218,49 @@ fn set_prop_defs(doc: &mut Document, c: NodeId, rename: Option<(&str, &str)>, f:
Ok(())
}
/// Give each of components `comps` that lacks it property `name` (`def`), and their existing
/// instances its default.
fn give_prop(doc: &mut Document, comps: &[NodeId], name: &str, def: &PropDef) -> Result<()> {
for c in comps {
if prop_defs(doc, *c).contains_key(name) {
continue;
}
set_prop_defs(doc, *c, None, |m| {
m.insert(name.to_string(), def.clone());
})?;
if !takes_value(def) {
continue;
}
for inst in instances_of(doc, *c) {
if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind {
props.entry(name.to_string()).or_insert_with(|| prop_default_value(def));
}
}
}
Ok(())
}
/// Give every one of components `comps` (the variants of a set) the properties any of them has:
/// a set's properties belong to all its variants, as `component.addProperty` gives them, so one
/// made on a component before it was combined stays on an instance switched to another variant.
/// A variant that has a property of that name keeps its own.
pub(super) fn share_props(doc: &mut Document, comps: &[NodeId]) -> Result<()> {
let mut all: Vec<(String, PropDef)> = Vec::new();
for c in comps {
if let Some(NodeKind::Component { props, prop_order, .. }) = doc.node(*c).map(|n| &n.kind) {
for (k, d) in ordered_props(props, prop_order) {
if !all.iter().any(|(n, _)| n == k) {
all.push((k.clone(), d.clone()));
}
}
}
}
for (name, def) in &all {
give_prop(doc, comps, name, def)?;
}
Ok(())
}
fn valid_prop_name(cmd: &str, name: &str) -> Result<String> {
let name = name.trim();
if name.is_empty() || name.contains([',', '=']) || name.chars().count() > 200 {
@@ -295,20 +338,7 @@ pub(super) fn add_prop_for(cmd: &str, s: &mut Session, p: &Value) -> Result<Valu
}
_ => return Err(bad(cmd, "type: boolean|text|instanceSwap|variant|slot")),
};
for c in &comps {
set_prop_defs(doc, *c, None, |m| {
m.insert(name.clone(), def.clone());
})?;
// Existing instances get the default.
if !takes_value(&def) {
continue;
}
for inst in instances_of(doc, *c) {
if let NodeKind::Instance { props, .. } = &mut doc.get_mut(inst)?.kind {
props.entry(name.clone()).or_insert_with(|| prop_default_value(&def));
}
}
}
give_prop(doc, &comps, &name, &def)?;
if let Some(l) = layer {
bind(cmd, doc, l, Some(&name), None)?;
}
+3 -1
View File
@@ -68,7 +68,8 @@ pub fn can_add_variant(doc: &Document, id: NodeId) -> bool {
}
/// Wrap `ids` (z-sorted main components) in a new component set, naming them "Property 1=Default",
/// "Property 1=VariantN" unless already in prop=value form. Returns the set.
/// "Property 1=VariantN" unless already in prop=value form, each with the component properties
/// any of them has. Returns the set.
fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result<NodeId> {
let set = wrap_in_set(cmd, doc, ids)?;
for (k, i) in ids.iter().enumerate() {
@@ -77,6 +78,7 @@ fn make_variant_set(cmd: &str, doc: &mut Document, ids: &[NodeId]) -> Result<Nod
node.name = format!("Property 1={}", if k == 0 { "Default".to_string() } else { format!("Variant{}", k + 1) });
}
}
super::props::share_props(doc, ids)?;
Ok(set)
}
+2
View File
@@ -20,6 +20,8 @@ mod select;
mod vector_clipboard;
pub use vector_clipboard::clipboard_svg;
#[cfg(test)]
mod nudge_rotated_parent_tests;
#[cfg(test)]
mod vector_clipboard_tests;
pub(crate) use clipboard::apply_copied_props;
+36 -8
View File
@@ -295,6 +295,9 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
})
.filter(|i| !copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, *i)))
});
// One layer selected that isn't a frame target: the copy joins its parent, just above it (#2355).
let sibling_of = if target.is_none() && id(p, "parent").is_none() { sibling_anchor(s, &sel, copy_local) } else { None };
let target = target.or_else(|| sibling_of.and_then(|i| doc.node(i).and_then(|n| n.parent)));
let parent = target.unwrap_or(page);
let at = match (num(p, "x"), num(p, "y")) {
(Some(x), Some(y)) => Some((x, y)),
@@ -321,10 +324,42 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let ids = paste_into(s, parent, at)?;
if let Some(sel) = sibling_of {
let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1);
move_above(s, &ids, parent, above)?;
}
s.set_selection(ids.clone());
Ok(json!({"ids": ids}))
}
/// The one selected layer a plain paste goes next to: not a page-level layer, not inside an instance
/// (its children are fixed), not a board atom, a component set (a variant's parent) or inside a copied
/// component. Else the page, as before.
fn sibling_anchor(s: &Session, sel: &[NodeId], copy_local: bool) -> Option<NodeId> {
let [only] = sel else { return None };
let doc = s.doc().ok()?;
let parent = doc.node(*only)?.parent?;
let pn = doc.node(parent)?;
let ok = !pn.is_page()
&& pn.kind.is_frame_like()
&& !pn.is_board_atom()
&& !crate::components::inside_instance(doc, *only)
&& !matches!(pn.kind, NodeKind::Instance { .. } | NodeKind::ComponentSet { .. })
&& (!copy_local || !s.clipboard.copied_components.iter().any(|root| doc.is_ancestor(*root, parent)));
ok.then_some(*only)
}
/// Move the pasted copies that landed in `parent` to `above` and after, in the copied order.
fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option<usize>) -> Result<()> {
let Some(above) = above else { return Ok(()) };
let doc = s.doc_mut()?;
for (k, i) in ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::<Vec<_>>().into_iter().enumerate()
{
doc.reorder(i, above + k)?;
}
Ok(())
}
pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
let sel = s.selection();
let page = s.page()?;
@@ -337,14 +372,7 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
None => (page, None, None),
};
let ids = paste_into(s, parent, at)?;
if let Some(above) = above {
let doc = s.doc_mut()?;
for (k, i) in
ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::<Vec<_>>().into_iter().enumerate()
{
doc.reorder(i, above + k)?;
}
}
move_above(s, &ids, parent, above)?;
s.set_selection(ids.clone());
Ok(json!({"ids": ids}))
}
@@ -0,0 +1,92 @@
//! The arrow keys move a layer along the canvas axes whatever its parent's rotation (#2372).
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use figcraft_doc::NodeId;
fn frame(s: &mut Session, parent: Option<NodeId>, w: f64, h: f64, rotation: f64) -> NodeId {
let mut p = json!({"x": 10, "y": 20, "width": w, "height": h});
if let (Some(par), Some(o)) = (parent, p.as_object_mut()) {
o.insert("parent".into(), json!(par));
}
let r = s.execute("frame.create", &p).unwrap();
let id = id_of(&r["id"]).unwrap();
if rotation != 0.0 {
s.execute("node.set", &json!({"id": id, "props": {"rotation": rotation}})).unwrap();
}
id
}
fn world(s: &Session, id: NodeId) -> (f64, f64) {
let c = s.doc().unwrap().world_transform(id).as_coeffs();
(c[4], c[5])
}
fn nudge(s: &mut Session, id: NodeId, params: Value) {
let mut p = params;
if let Some(o) = p.as_object_mut() {
o.insert("ids".into(), json!([id]));
}
s.execute("transform.nudge", &p).unwrap();
}
fn moved_by(s: &mut Session, id: NodeId, params: Value) -> (f64, f64) {
let before = world(s, id);
nudge(s, id, params);
let after = world(s, id);
(after.0 - before.0, after.1 - before.1)
}
fn near(got: (f64, f64), want: (f64, f64)) {
assert!((got.0 - want.0).abs() < 1e-6 && (got.1 - want.1).abs() < 1e-6, "moved by {got:?}, wanted {want:?}");
}
fn in_rotated(rotation: f64) -> (Session, NodeId) {
let mut s = Session::new();
let outer = frame(&mut s, None, 400.0, 300.0, rotation);
let child = frame(&mut s, Some(outer), 100.0, 80.0, 0.0);
(s, child)
}
#[test]
fn down_moves_a_child_of_a_frame_rotated_90_down_the_canvas() {
let (mut s, child) = in_rotated(90.0);
let k = s.prefs.nudge_small;
near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k));
}
#[test]
fn right_moves_it_right_on_the_canvas() {
let (mut s, child) = in_rotated(90.0);
let k = s.prefs.nudge_small;
near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0));
}
#[test]
fn a_big_nudge_in_a_rotated_parent_follows_the_canvas_too() {
let (mut s, child) = in_rotated(90.0);
let k = s.prefs.nudge_big;
near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0, "big": true})), (k, 0.0));
}
#[test]
fn a_child_of_an_unrotated_frame_moves_as_before() {
let (mut s, child) = in_rotated(0.0);
let k = s.prefs.nudge_small;
let local_before = s.doc().unwrap().node(child).unwrap().transform.as_coeffs();
near(moved_by(&mut s, child, json!({"dx": 1, "dy": 0})), (k, 0.0));
let local_after = s.doc().unwrap().node(child).unwrap().transform.as_coeffs();
assert!((local_after[4] - local_before[4] - k).abs() < 1e-6 && (local_after[5] - local_before[5]).abs() < 1e-6);
}
#[test]
fn a_layer_two_rotated_frames_deep_moves_along_the_canvas() {
let mut s = Session::new();
let outer = frame(&mut s, None, 500.0, 400.0, 45.0);
let inner = frame(&mut s, Some(outer), 300.0, 200.0, 30.0);
let child = frame(&mut s, Some(inner), 100.0, 80.0, 0.0);
let k = s.prefs.nudge_small;
near(moved_by(&mut s, child, json!({"dx": 0, "dy": 1})), (0.0, k));
}
+17
View File
@@ -163,6 +163,9 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
names.join(", ")
));
}
let mut hugging = crate::cmd::props::hugging_parents(&s.ds()?.doc, &ids, &props);
let filling = crate::cmd::props::filling_children(&s.ds()?.doc, &ids, &props);
let targets = ids.clone();
let doc = s.doc_mut()?;
let before = crate::cmd::styles::bound_before(doc, &ids);
let mut ids = ids;
@@ -182,6 +185,20 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// A child that filled a hugging parent along its flow turned the parent Fixed: say so.
// A frame set to Hug turns the children that filled it along its flow Fixed. That is the
// coherence pass `normalize` runs once the command returns; run it here for those frames
// (idempotent) so the notice sees the demotion.
if !filling.is_empty() {
let doc = s.doc_mut()?;
for f in &targets {
figcraft_layout::coherent_sizing(doc, *f);
}
hugging.extend(filling);
}
if let Some(notice) = crate::cmd::props::fixed_notice(&s.ds()?.doc, &hugging) {
s.message = Some(notice);
}
if warnings.is_empty() { ok() } else { Ok(json!({"ok": true, "warnings": warnings})) }
}
+12 -1
View File
@@ -184,8 +184,19 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
// Children in an auto layout flow move one place instead (see `al_keys`).
for i in &ids {
if crate::al_keys::flowing_parent(doc, *i).is_none() && (dx, dy) != (0.0, 0.0) {
// The step is along the canvas axes; the layer's transform is in its parent's space.
let (lx, ly) = match doc.node(*i).and_then(|n| n.parent) {
Some(par) => {
let inv = doc.world_transform(par).inverse();
let o = inv * figcraft_geom::Point::new(0.0, 0.0);
let q = inv * figcraft_geom::Point::new(dx, dy);
let (lx, ly) = (q.x - o.x, q.y - o.y);
if lx.is_finite() && ly.is_finite() { (lx, ly) } else { (dx, dy) }
}
None => (dx, dy),
};
let n = doc.get_mut(*i)?;
n.transform = Affine::translate((dx, dy)) * n.transform;
n.transform = Affine::translate((lx, ly)) * n.transform;
changed = true;
}
}
+29 -1
View File
@@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator<Item = (NodeId, Vec<ExportSetting>)>, d
if out.len() >= MAX_EXPORT_FILES {
return out;
}
let stem = format!("{base}{}", safe_file_name(&e.file_suffix()));
let stem = crate::file_access::escape_device_names(&format!("{base}{}", safe_file_name(&e.file_suffix())));
let ext = e.format.ext();
let file =
(1..).map(|k| if k == 1 { format!("{stem}.{ext}") } else { format!("{stem} {k}.{ext}") }).find(|f| used.insert(f.to_lowercase()));
@@ -439,3 +439,31 @@ pub(super) fn export_frames_pdf(s: &mut Session, p: &Value) -> Result<Value> {
None => Ok(json!({"format": "pdf", "pages": pages, "data": base64::engine::general_purpose::STANDARD.encode(&bytes)})),
}
}
#[cfg(test)]
mod filename_tests {
use super::*;
#[test]
fn export_jobs_escape_device_names_after_suffixes_and_before_numbering() {
let mut doc = Document::new("Export names");
let page = doc.first_page().unwrap();
let cases = [
("C", "ON", "_CON.png"),
("_con", "", "_con 2.png"),
("CON/icon", "", "_CON/icon.png"),
("Home", "CON", "HomeCON.png"),
("COM", "1", "_COM1.png"),
("COM1", "@2x", "COM1@2x.png"),
];
let items: Vec<_> = cases
.iter()
.map(|(name, suffix, _)| {
let id = doc.create(page, NodeKind::Frame, name, 0.0, 0.0, 10.0, 10.0).unwrap();
(id, vec![ExportSetting { suffix: (*suffix).into(), ..Default::default() }])
})
.collect();
let files: Vec<_> = jobs_for(items, &doc).into_iter().map(|job| job.file).collect();
assert_eq!(files, cases.map(|(_, _, expected)| expected));
}
}
+39 -5
View File
@@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Err(EngineError::Waiting) => return Err(EngineError::Waiting),
_ => None,
};
let asset_weeks = asset_week_rows(s, &link, since)?;
let asset_actions = asset_period(asset_weeks.as_deref().unwrap_or_default());
let m = &lib.manifest;
// Component → (instances, files using it, instances detached).
let mut per: std::collections::BTreeMap<NodeId, (u64, u64, u64)> = std::collections::BTreeMap::new();
@@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result<Value> {
"files": rows,
"components": components,
"assetsKnown": assets.is_some(),
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), |id| {
"assetActionsKnown": asset_weeks.is_some(),
"styles": asset_rows(assets.iter().flatten().map(|a| &a.styles), &asset_actions, |id| {
m.style(id).map(|x| json!({"name": x.name, "type": x.kind}))
}),
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), |id| {
"variables": asset_rows(assets.iter().flatten().map(|a| &a.variables), &asset_actions, |id| {
let v = m.variable(id)?;
Some(json!({"name": v.name, "collection": m.collection(&v.collection).map(|c| c.name.clone())}))
}),
}))
}
/// The style or variable reports' totals, the most used first: each one's `id`, `layers` and
/// `files`, with what `describe` says of it (nothing for one no longer published).
fn asset_rows<'a>(reports: impl Iterator<Item = &'a Vec<(String, u32)>>, describe: impl Fn(&str) -> Option<Value>) -> Vec<Value> {
/// The styles' and variables' weeks overlapping a period from `since`; `None` from a server from
/// before them.
fn asset_week_rows(s: &mut Session, link: &str, since: u64) -> Result<Option<Vec<WeekActions<String>>>> {
match s.library_request(link, LibraryReq::AssetActions) {
Ok(LibraryReply::AssetActions(w)) => Ok(Some(w.into_iter().filter(|w| w.week.saturating_add(7 * 86_400) > since).collect())),
Err(EngineError::Waiting) => Err(EngineError::Waiting),
_ => Ok(None),
}
}
/// Each style's or variable's insertions and detachments in `weeks`.
fn asset_period(weeks: &[WeekActions<String>]) -> std::collections::BTreeMap<&str, (u64, u64)> {
let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new();
for w in weeks {
let e = per.entry(&w.component).or_default();
e.0 += u64::from(w.insertions);
e.1 += u64::from(w.detachments);
}
per
}
/// The style or variable reports' totals, the most used first: each one's `id`, `layers`, `files`,
/// `insertions` and `detachments` in the period, with what `describe` says of it (nothing for one
/// no longer published). One only inserted or detached is listed too, when it's of this kind.
fn asset_rows<'a>(
reports: impl Iterator<Item = &'a Vec<(String, u32)>>,
actions: &std::collections::BTreeMap<&str, (u64, u64)>,
describe: impl Fn(&str) -> Option<Value>,
) -> Vec<Value> {
let mut per = std::collections::BTreeMap::<&str, (u64, u64)>::new();
for (id, n) in reports.flatten() {
let e = per.entry(id).or_default();
e.0 += u64::from(*n);
e.1 += 1;
}
for id in actions.keys().filter(|id| describe(id).is_some()) {
per.entry(id).or_default();
}
let mut rows: Vec<_> = per.into_iter().collect();
rows.sort_by_key(|r| std::cmp::Reverse(r.1.0));
let row = |(id, (layers, files)): (&str, (u64, u64))| {
let mut r = describe(id).unwrap_or_else(|| json!({}));
let (insertions, detachments) = actions.get(id).copied().unwrap_or_default();
(r["id"], r["layers"], r["files"]) = (json!(id), json!(layers), json!(files));
(r["insertions"], r["detachments"]) = (json!(insertions), json!(detachments));
r
};
rows.into_iter().map(row).collect()
+2 -4
View File
@@ -53,9 +53,8 @@ pub fn specs() -> Vec<CommandSpec> {
return Ok(json!({"id": id, "divider": true}));
}
let ds = s.ds_mut()?;
ds.page = id;
ds.open_page(id);
ds.selection.clear();
ds.zoom_to_fit();
Ok(json!({"id": id}))
}),
spec!("page.select", "Go to page", "{id | index}", false, |s, p| {
@@ -74,10 +73,9 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad("page.select", "a divider isn't a page to open"));
}
let ds = s.ds_mut()?;
ds.page = id;
ds.open_page(id);
ds.selection.clear();
ds.text_edit = None;
ds.zoom_to_fit();
ok()
}),
spec!("page.rename", "Rename page", "{id?, name} (an empty page named with a leading hyphen becomes a divider)", true, |s, p| {
+91 -12
View File
@@ -1234,14 +1234,16 @@ pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map<String, Valu
if !unknown.is_empty() {
return Err(bad(cmd, format!("unknown properties: {} (known: {KEYS})", unknown.join(", "))));
}
// Inside an instance, record which property groups were overridden (an instance's own
// resizing, export settings and interactions are its own, not overrides).
// Inside an instance, record which property groups were overridden (an instance's own export
// settings and interactions are its own, not overrides). Its resizing is recorded like any
// layer's: the sync takes the main's Hug / Fixed unless it is overridden, and Reset instance
// clears it. Inferred: Figma was measured only with a typed width (kept); a resizing chosen
// from the dropdown is taken as an override the same way, as every property set on an
// instance in Figma is one.
let own_root = matches!(doc.get(id)?.kind, NodeKind::Instance { .. }) && !crate::components::inside_instance(doc, id);
let n = doc.get_mut(id)?;
if n.source.is_some() {
for g in
props.keys().map(|k| override_group(k)).filter(|g| *g != "other" && !(own_root && matches!(*g, "resizing" | "exports" | "interactions")))
{
for g in props.keys().map(|k| override_group(k)).filter(|g| *g != "other" && !(own_root && matches!(*g, "exports" | "interactions"))) {
n.overrides.insert(g.to_string());
}
}
@@ -1485,16 +1487,39 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal:
}
_ => {}
}
// A child can't fill an axis its parent hugs: the parent becomes fixed at its current size.
// (The other way round, a parent that starts to hug fixes the children that filled it: see
// `figcraft_layout::coherent_sizing`, applied after every edit.)
// A child can't fill the axis its parent hugs along the flow: the parent becomes fixed at its
// current size. Across the flow the parent keeps hugging and the child takes the line's size
// (the largest sibling that doesn't fill); the parent becomes fixed only when no such sibling
// is left. (The other way round, a parent that starts to hug fixes the children that filled it
// along the flow: see `figcraft_layout::coherent_sizing`, applied after every edit.)
if s == Sizing::Fill
&& let Some(p) = parent
{
let cl = &mut doc.get_mut(p)?.child_layout;
let ps = if horizontal { &mut cl.sizing_h } else { &mut cl.sizing_v };
if *ps == Sizing::Hug {
*ps = Sizing::Fixed;
let pn = doc.get(p)?;
if figcraft_layout::wrapping_row_hugs_across(pn, horizontal) {
return Err(bad(cmd, "Fill container across a wrapping row is not offered"));
}
let along = match pn.layout.as_ref().map(|al| al.mode) {
Some(LayoutMode::Horizontal) => horizontal,
Some(LayoutMode::Vertical) => !horizontal,
_ => true,
};
let others_fill = figcraft_layout::flow_children(doc, p)
.into_iter()
.filter(|c| *c != id)
.all(|c| doc.node(c).is_some_and(|c| (if horizontal { c.child_layout.sizing_h } else { c.child_layout.sizing_v }) == Sizing::Fill));
if along || others_fill {
let cl = &mut doc.get_mut(p)?.child_layout;
let ps = if horizontal { &mut cl.sizing_h } else { &mut cl.sizing_v };
if *ps == Sizing::Hug {
*ps = Sizing::Fixed;
// An instance's own root, or a layer inside one, turned Fixed by this edit: that
// is its resizing now, an override, or the next rebuild from the main would take
// the main's Hug back and the child would stop filling.
if doc.get(p)?.source.is_some() {
doc.get_mut(p)?.overrides.insert("resizing".to_string());
}
}
}
}
// Start from the sizing the layer has in effect (an auto-width text hugs both axes), so the
@@ -1517,6 +1542,60 @@ fn set_sizing(cmd: &str, doc: &mut Document, id: NodeId, s: Sizing, horizontal:
Ok(())
}
/// The hugging parents that `props` setting Fill on `ids` may turn Fixed, as (parent, horizontal):
/// taken before the edit, for [`fixed_notice`].
pub(crate) fn hugging_parents(doc: &Document, ids: &[NodeId], props: &Map<String, Value>) -> Vec<(NodeId, bool)> {
let mut out = Vec::new();
for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] {
if !keys.iter().any(|k| props.get(*k).and_then(sizing) == Some(Sizing::Fill)) {
continue;
}
for p in ids.iter().filter_map(|i| doc.node(*i)).filter_map(|n| n.parent) {
let hugs = doc
.node(p)
.is_some_and(|p| p.layout.is_some() && (if horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v }) == Sizing::Hug);
if hugs && !out.contains(&(p, horizontal)) {
out.push((p, horizontal));
}
}
}
out
}
/// The children, as (child, horizontal), that fill an axis of a frame in `ids` which `props` sets
/// to Hug: taken before the edit, for [`fixed_notice`] (the coherence pass turns them Fixed).
pub(crate) fn filling_children(doc: &Document, ids: &[NodeId], props: &Map<String, Value>) -> Vec<(NodeId, bool)> {
let mut out = Vec::new();
for (horizontal, keys) in [(true, ["sizingH", "layoutSizingHorizontal"]), (false, ["sizingV", "layoutSizingVertical"])] {
if !keys.iter().any(|k| props.get(*k).and_then(sizing) == Some(Sizing::Hug)) {
continue;
}
for f in ids.iter().filter_map(|i| doc.node(*i)).filter(|n| n.layout.is_some() && n.kind.is_frame_like()) {
for c in f.children.iter().filter_map(|c| doc.node(*c)) {
let fills = (if horizontal { c.child_layout.sizing_h } else { c.child_layout.sizing_v }) == Sizing::Fill;
if fills && !out.contains(&(c.id, horizontal)) {
out.push((c.id, horizontal));
}
}
}
}
out
}
/// The notice for the layers of [`hugging_parents`] or [`filling_children`] that the edit turned
/// Fixed ("Height set to Fixed for Frame 1"), `None` when every one kept its sizing.
pub(crate) fn fixed_notice(doc: &Document, before: &[(NodeId, bool)]) -> Option<String> {
let notes: Vec<String> = before
.iter()
.filter_map(|(p, horizontal)| {
let p = doc.node(*p)?;
let now = if *horizontal { p.child_layout.sizing_h } else { p.child_layout.sizing_v };
(now == Sizing::Fixed).then(|| format!("{} set to Fixed for {}", if *horizontal { "Width" } else { "Height" }, p.name))
})
.collect();
(!notes.is_empty()).then(|| notes.join("; "))
}
/// Resize a node's box from its top-left, applying constraints / group scaling to children.
/// The page transforms of `id`'s children, to put back with [`restore_worlds`] once a container
/// whose contents stay where they are on the page (a section; a frame resized with Cmd/Ctrl held)
+15
View File
@@ -577,6 +577,21 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result<Value> {
let doc = s.doc_mut()?;
let n = doc.get(i)?.clone();
if !n.has_visible_stroke() {
// A text without a stroke outlines its glyphs (#2405): flattened in place, filled as it was.
if matches!(n.kind, NodeKind::Text(_)) {
match flatten(s, &json!({"ids": [i]})) {
Ok(r) => {
if let Some(v) = id_of(&r["id"]) {
let o = s.doc_mut()?.get_mut(v)?;
(o.styles.fill, o.styles.effect) = (n.styles.fill, n.styles.effect);
(o.constraints, o.child_layout, o.visible, o.locked) = (n.constraints, n.child_layout, n.visible, n.locked);
out.push(v);
}
}
Err(EngineError::Disabled(..)) => {} // no glyphs (empty, or no font): nothing to outline
Err(e) => return Err(e),
}
}
continue;
}
let closed = figcraft_doc::geometry::is_closed(&n);
+12
View File
@@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option<Paragra
}
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, true, |s| detach_style(s, p))
}
fn detach_style(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "style.detach";
let which = req_string(cmd, p, "which")?;
if which == "text" {
@@ -458,6 +462,10 @@ pub fn apply_style_ref(doc: &mut Document, id: NodeId, field: &str, sid: Option<
}
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, false, |s| apply_style(s, p))
}
fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "style.apply";
let st = req_string(cmd, p, "style")?;
let style = s.doc()?.style(&st).cloned().ok_or_else(|| bad(cmd, format!("no style `{st}`")))?;
@@ -846,6 +854,10 @@ pub fn sync_list_styles(doc: &mut Document, before: &Document, ids: &[NodeId]) {
/// `variable.bind`: bind (or with no variable, unbind) `field` of the targets.
pub fn bind(s: &mut Session, p: &Value) -> Result<Value> {
crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p))
}
fn bind_field(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "variable.bind";
let field = req_string(cmd, p, "field")?;
let var = string(p, "variable");
+1 -1
View File
@@ -642,7 +642,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"text.edit.key",
"Text key",
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out",
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent",
true,
|s, p| {
let k = req_string("text.edit.key", p, "key")?;
+1 -2
View File
@@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result<Value> {
}
};
let ds = s.ds_mut()?;
ds.page = pg;
ds.open_page(pg);
ds.selection.clear();
ds.zoom_to_fit();
Ok(json!({"page": pg}))
}
@@ -1002,6 +1002,180 @@ fn deleting_a_layer_inside_an_instance_hides_it_instead() {
assert!(s.doc().unwrap().node(k.inst).is_none());
}
/// Issue 2090 item 2: after a main's child is set to fill, the instance's copy must match the main's
/// child (sizing, size) and the copy's parent must match the main's parent sizing. Relative, not
/// absolute, so it holds whatever the cross-axis rule is.
fn fill_matches_main(horizontal: bool, axis: &str) {
let hug_axis = if horizontal { "sizingV" } else { "sizingH" };
fill_matches_main_hugging(horizontal, axis, hug_axis);
}
/// As `fill_matches_main`, with the axis the main root hugs given explicitly.
fn fill_matches_main_hugging(horizontal: bool, axis: &str, hug_axis: &str) {
let mut s = Session::new();
let mode = if horizontal { "horizontal" } else { "vertical" };
let comp = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "name": "Note"})));
let bar = idv(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 20, "parent": comp, "props": {"name": "Bar"}})));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 40, "parent": comp, "props": {"name": "Body"}}));
ex(&mut s, "node.set", json!({"id": comp, "props": {"layout": mode, "gap": 12, "padding": 10, hug_axis: "hug"}}));
let comp = idv(&ex(&mut s, "component.create", json!({"ids": [comp]})));
let inst = idv(&ex(&mut s, "instance.create", json!({"component": comp, "x": 400, "y": 0})));
let bar = if node(&s, bar).parent.is_some() { bar } else { kids(&s, comp)[0] };
ex(&mut s, "node.set", json!({"id": bar, "props": {axis: "fill"}}));
let ibar = copy_of(&s, inst, bar);
let (m, c) = (node(&s, bar), node(&s, ibar));
let (mp, cp) = (node(&s, comp), node(&s, inst));
eprintln!(
"{axis}: main bar {}x{} sizing {:?}/{:?}; copy {}x{} sizing {:?}/{:?}; main parent {}x{} {:?}/{:?}; inst {}x{} {:?}/{:?}",
m.width,
m.height,
m.child_layout.sizing_h,
m.child_layout.sizing_v,
c.width,
c.height,
c.child_layout.sizing_h,
c.child_layout.sizing_v,
mp.width,
mp.height,
mp.child_layout.sizing_h,
mp.child_layout.sizing_v,
cp.width,
cp.height,
cp.child_layout.sizing_h,
cp.child_layout.sizing_v
);
assert_eq!((c.child_layout.sizing_h, c.child_layout.sizing_v), (m.child_layout.sizing_h, m.child_layout.sizing_v), "copy sizing");
assert_eq!((c.width, c.height), (m.width, m.height), "copy size matches main child");
assert_eq!(
(cp.child_layout.sizing_h, cp.child_layout.sizing_v),
(mp.child_layout.sizing_h, mp.child_layout.sizing_v),
"parent sizing matches main parent"
);
}
#[test]
fn instance_follows_main_child_fill_on_the_cross_axis() {
fill_matches_main(true, "sizingV");
}
#[test]
fn instance_follows_main_child_fill_on_the_main_axis() {
fill_matches_main(true, "sizingH");
}
#[test]
fn instance_follows_main_child_fill_along_a_hugging_main_axis() {
fill_matches_main_hugging(true, "sizingH", "sizingH");
}
/// A horizontal auto layout main hugging its width, with a "Bar" and a "Body" child, and an instance.
fn hugging_note(s: &mut Session) -> (NodeId, NodeId, NodeId) {
let comp = idv(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "name": "Note"})));
let bar = idv(&ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 20, "parent": comp, "props": {"name": "Bar"}})));
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 40, "parent": comp, "props": {"name": "Body"}}));
ex(s, "node.set", json!({"id": comp, "props": {"layout": "horizontal", "gap": 12, "padding": 10, "sizingH": "hug"}}));
let comp = idv(&ex(s, "component.create", json!({"ids": [comp]})));
let inst = idv(&ex(s, "instance.create", json!({"component": comp, "x": 400, "y": 0})));
let bar = if node(s, bar).parent.is_some() { bar } else { kids(s, comp)[0] };
(comp, inst, bar)
}
fn sizing_h(s: &Session, id: NodeId) -> Sizing {
node(s, id).child_layout.sizing_h
}
/// Measured in Figma: the main's root turning Fixed (set directly) reaches a plain instance, and
/// the main going back to Hug brings it back.
#[test]
fn a_plain_instances_resizing_follows_the_mains_root_both_ways() {
let mut s = Session::new();
let (comp, inst, _) = hugging_note(&mut s);
assert_eq!(sizing_h(&s, inst), Sizing::Hug);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Fixed);
assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "the instance turns Fixed with its main");
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Hug, "and back to Hug with it");
}
/// Measured in Figma: a child set to Fill along the hugging axis turns the main Fixed; the plain
/// instance follows it, and follows it back to Hug.
#[test]
fn a_plain_instance_goes_fixed_and_back_to_hug_with_its_main() {
let mut s = Session::new();
let (comp, inst, bar) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Fixed);
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Hug);
}
/// Measured in Figma: an instance whose width was typed keeps that Fixed width through both
/// changes, while its height kept hugging its content. Figma keeps one size override for both
/// axes, as FigCraft does: with the width typed, a change to a fixed main's height does not reach
/// the instance, and the only size reset is "Reset size" (measured 2026-11-09).
#[test]
fn an_instance_with_a_typed_width_keeps_it_when_the_main_turns_fixed_and_back() {
let mut s = Session::new();
let (comp, inst, bar) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": inst, "props": {"width": 200}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
assert_eq!(node(&s, inst).width, 200.0);
ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
assert_eq!(node(&s, inst).width, 200.0, "the typed width stays");
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "still Fixed after the main hugs again");
assert_eq!(node(&s, inst).width, 200.0);
}
/// An instance placed in an auto layout frame and set to Fill there keeps Fill when its main changes.
#[test]
fn an_instance_filling_its_auto_layout_parent_keeps_fill_when_the_main_changes() {
let mut s = Session::new();
let (comp, inst, bar) = hugging_note(&mut s);
let row = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 500, "height": 100, "name": "Row"})));
ex(&mut s, "node.set", json!({"id": row, "props": {"layout": "horizontal"}}));
ex(&mut s, "node.reparent", json!({"ids": [inst], "parent": row}));
ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fill);
ex(&mut s, "node.set", json!({"id": bar, "props": {"sizingH": "fill"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Fixed);
assert_eq!(sizing_h(&s, inst), Sizing::Fill, "its own Fill in the row is kept");
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fill);
}
/// Inferred (Figma was measured only with a typed width): a Fixed set directly on an instance's
/// root, with no width typed, is an override the sync keeps when the main's root turns Hug, Fixed
/// and Hug again.
#[test]
fn an_instance_root_set_to_fixed_keeps_it_through_the_mains_resizing_changes() {
let mut s = Session::new();
let (comp, inst, _) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
assert!(node(&s, inst).overrides.contains("resizing"), "{:?}", node(&s, inst).overrides);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
ex(&mut s, "node.set", json!({"id": comp, "props": {"sizingH": "hug"}}));
assert_eq!(sizing_h(&s, comp), Sizing::Hug);
assert_eq!(sizing_h(&s, inst), Sizing::Fixed, "its own Fixed stays after the main hugs again");
}
/// Resetting that instance brings its resizing back to the main's.
#[test]
fn resetting_an_instance_brings_its_own_resizing_back_to_the_mains() {
let mut s = Session::new();
let (_, inst, _) = hugging_note(&mut s);
ex(&mut s, "node.set", json!({"id": inst, "props": {"sizingH": "fixed"}}));
assert_eq!(sizing_h(&s, inst), Sizing::Fixed);
ex(&mut s, "component.resetInstance", json!({"ids": [inst]}));
assert!(!node(&s, inst).overrides.contains("resizing"));
assert_eq!(sizing_h(&s, inst), Sizing::Hug, "the main hugs");
}
/// Create multiple components (#2088): each selected layer becomes its own component in place,
/// keeping its name and position; all stay selected and one undo reverts them all.
#[test]
+409
View File
@@ -0,0 +1,409 @@
//! `inspect.designContext` against documents built with real commands.
use serde_json::{Value, json};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s
}
fn id(v: &Value) -> u64 {
v["id"].as_u64().unwrap()
}
fn node(s: &mut Session, params: Value) -> u64 {
id(&s.execute("node.create", &params).unwrap())
}
fn context(s: &mut Session, params: Value) -> Value {
s.execute("inspect.designContext", &params).unwrap()
}
/// A hugging auto layout card holding a fixed title and a filling line.
fn card(s: &mut Session) -> (u64, u64, u64) {
let f = node(s, json!({"type": "frame", "name": "Card", "x": 40, "y": 30, "width": 300, "height": 200, "props": {"fill": "#FFFFFF"}}));
s.execute("node.set", &json!({"ids": [f], "props": {"layout": {"mode": "vertical"}, "gap": 12, "padding": [16, 16, 16, 16], "sizingV": "hug"}}))
.unwrap();
let title = node(s, json!({"type": "text", "parent": f, "name": "Title", "text": "Pro plan", "props": {"fontSize": 24}}));
let line = node(s, json!({"type": "rectangle", "parent": f, "name": "Rule", "width": 100, "height": 2, "props": {"sizingH": "fill"}}));
(f, title, line)
}
fn only(v: &Value) -> &Value {
let nodes = v["nodes"].as_array().unwrap();
assert_eq!(nodes.len(), 1, "{v}");
&nodes[0]
}
#[test]
fn the_selection_is_what_is_read() {
let mut s = session();
let (f, title, _) = card(&mut s);
let other = node(&mut s, json!({"type": "rectangle", "name": "Elsewhere", "width": 10, "height": 10}));
s.execute("select.set", &json!({"ids": [f]})).unwrap();
let v = context(&mut s, json!({}));
assert_eq!(v["target"]["source"], "selection");
assert_eq!(only(&v)["id"], f);
assert_eq!(only(&v)["children"][0]["id"], title);
assert_eq!(v["target"]["layers"], 3);
assert!(!v.to_string().contains("Elsewhere"), "the rest of the page stays out");
let _ = other;
}
#[test]
fn several_selected_layers_each_come_back() {
let mut s = session();
let a = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10}));
let b = node(&mut s, json!({"type": "ellipse", "width": 10, "height": 10}));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
assert_eq!(context(&mut s, json!({}))["nodes"].as_array().unwrap().len(), 2);
}
#[test]
fn ids_and_scopes_choose_the_target() {
let mut s = session();
let (f, _, _) = card(&mut s);
let other = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10}));
s.execute("select.set", &json!({"ids": [other]})).unwrap();
assert_eq!(context(&mut s, json!({"ids": [f]}))["target"]["source"], "ids");
assert_eq!(context(&mut s, json!({"scope": "page"}))["nodes"].as_array().unwrap().len(), 2);
s.execute("page.add", &json!({"name": "Second"})).unwrap();
assert_eq!(context(&mut s, json!({"scope": "document"}))["target"]["source"], "document");
assert!(s.execute("inspect.designContext", &json!({"ids": [999_999]})).is_err());
assert!(s.execute("inspect.designContext", &json!({"scope": "everything"})).is_err());
}
#[test]
fn nothing_selected_reads_the_page() {
let mut s = session();
card(&mut s);
s.execute("select.none", &json!({})).unwrap();
assert_eq!(context(&mut s, json!({}))["target"]["source"], "page");
}
#[test]
fn what_layout_decides_is_derived_and_what_the_designer_set_is_explicit() {
let mut s = session();
let (f, _, _) = card(&mut s);
let v = context(&mut s, json!({"ids": [f]}));
let frame = only(&v);
assert_eq!(frame["explicit"]["width"], 300.0, "a fixed width is the designer's");
assert_eq!(frame["explicit"]["x"], 40.0);
assert!(frame["explicit"].get("height").is_none(), "a hug height isn't");
assert!(frame["derived"]["height"].is_number());
assert!(frame["derived"]["absoluteBounds"].is_object());
assert_eq!(frame["explicit"]["layout"]["gap"], 12.0);
let (title, rule) = (&frame["children"][0], &frame["children"][1]);
assert!(title["derived"].get("x").is_some(), "its place comes from the flow: {title}");
assert!(title["explicit"].get("x").is_none());
assert!(title["derived"].get("width").is_some(), "auto-width text: {title}");
assert!(rule["derived"].get("width").is_some(), "fill: {rule}");
assert_eq!(rule["explicit"]["height"], 2.0);
}
#[test]
fn the_values_are_the_documents() {
let mut s = session();
let (f, title, _) = card(&mut s);
let v = context(&mut s, json!({"ids": [f]}));
let got = &only(&v)["children"][0]["explicit"];
let inspected = s.execute("node.get", &json!({"id": title})).unwrap();
for key in ["characters", "fontFamily", "fontSize", "lineHeight", "letterSpacing", "textAlign", "fontStyle"] {
assert_eq!(got[key], inspected[key], "{key}");
}
assert_eq!(got["characters"], "Pro plan");
}
#[test]
fn tokens_are_joined_with_every_modes_value() {
let mut s = session();
let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap();
let collection = c["id"].clone();
let var = s
.execute(
"variable.create",
&json!({"collection": collection, "name": "surface", "type": "color", "values": {"Light": "#FFFFFF", "Dark": "#101010"}}),
)
.unwrap();
let var_id = var["id"].as_str().unwrap().to_string();
s.execute("variable.update", &json!({"variable": var_id, "codeSyntax": {"WEB": "var(--surface)"}})).unwrap();
let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": {"$var": var_id}}}));
let v = context(&mut s, json!({"ids": [r]}));
let bound = only(&v)["tokens"].as_object().unwrap().values().next().unwrap().clone();
assert_eq!((bound["variable"].as_str(), bound["name"].as_str()), (Some(var_id.as_str()), Some("surface")));
let entry = &v["variables"][var_id.as_str()];
assert_eq!((entry["name"].as_str(), entry["collection"].as_str()), (Some("surface"), Some("Theme")));
assert_eq!(entry["codeSyntax"]["WEB"], "var(--surface)");
assert_eq!(entry["modes"][0]["mode"], "Light");
assert_eq!(entry["modes"][1]["resolved"], "#101010");
}
#[test]
fn a_shared_style_is_named_and_defined_once() {
let mut s = session();
let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": "#FF0000"}}));
let st = s.execute("style.create", &json!({"type": "paint", "name": "Brand/Red", "from": r})).unwrap();
s.execute("style.apply", &json!({"style": st["id"], "ids": [r]})).unwrap();
let v = context(&mut s, json!({"ids": [r]}));
assert_eq!(only(&v)["tokens"]["style.fill"]["name"], "Brand/Red");
assert_eq!(v["styles"].as_object().unwrap().len(), 1);
assert_eq!(v["styles"][st["id"].as_str().unwrap()]["name"], "Brand/Red");
}
#[test]
fn a_connected_instance_gives_its_code_not_its_layers() {
let mut s = session();
let b = node(&mut s, json!({"type": "frame", "name": "Button", "width": 80, "height": 32}));
node(&mut s, json!({"type": "text", "parent": b, "text": "Buy"}));
let main = id(&s.execute("component.create", &json!({"ids": [b]})).unwrap());
let instance = id(&s.execute("instance.create", &json!({"component": main})).unwrap());
s.execute("codeConnect.set", &json!({"id": main, "language": "react", "importPath": "@/ui/button", "name": "Button", "template": "<Button />"}))
.unwrap();
let v = context(&mut s, json!({"ids": [instance]}));
let n = only(&v);
assert!(n["code"][0]["code"].as_str().unwrap().contains("<Button />"), "{n}");
assert_eq!(n["code"][0]["importPath"], "@/ui/button");
assert!(n.get("children").is_none(), "{n}");
assert_eq!(n["childCount"], 1);
assert_eq!(v["components"].as_object().unwrap().len(), 1);
assert_eq!(v["components"][main.to_string()]["codeLinks"][0]["name"], "Button");
}
#[test]
fn an_unconnected_instance_shows_its_layers_and_properties() {
let mut s = session();
let b = node(&mut s, json!({"type": "frame", "name": "Tag", "width": 80, "height": 32}));
node(&mut s, json!({"type": "text", "parent": b, "text": "New"}));
let main = id(&s.execute("component.create", &json!({"ids": [b]})).unwrap());
let inner = id(&s.execute("instance.create", &json!({"component": main})).unwrap());
let outer = node(&mut s, json!({"type": "frame", "name": "Row", "width": 200, "height": 60}));
s.execute("node.reparent", &json!({"ids": [inner], "parent": outer})).unwrap();
let v = context(&mut s, json!({"ids": [outer]}));
let i = &only(&v)["children"][0];
assert_eq!(i["explicit"]["mainComponentName"], "Tag");
assert_eq!(i["children"].as_array().unwrap().len(), 1, "nested layers: {i}");
assert!(v["components"].get(main.to_string()).is_some());
}
#[test]
fn what_css_cant_say_is_reported_and_kept() {
let mut s = session();
let r = node(
&mut s,
json!({"type": "rectangle", "width": 50, "height": 50, "props": {"cornerRadius": 12, "cornerSmoothing": 0.6, "strokes": ["#000000"], "strokeWeight": 2, "strokeAlign": "outside"}}),
);
let v = context(&mut s, json!({"ids": [r]}));
let n = only(&v);
let said: Vec<&str> = n["unsupported"].as_array().unwrap().iter().map(|u| u["property"].as_str().unwrap()).collect();
assert_eq!(said, ["cornerSmoothing", "strokeAlign"], "{n}");
assert_eq!(n["explicit"]["cornerSmoothing"], s.execute("node.get", &json!({"id": r})).unwrap()["cornerSmoothing"]);
}
#[test]
fn a_plain_layer_claims_no_limits() {
let mut s = session();
let r = node(&mut s, json!({"type": "rectangle", "width": 50, "height": 50, "props": {"fill": "#123456", "cornerRadius": 4}}));
let v = context(&mut s, json!({"ids": [r]}));
assert!(only(&v).get("unsupported").is_none());
}
#[test]
fn hidden_layers_stay_in_the_tree_marked() {
let mut s = session();
let (f, title, _) = card(&mut s);
s.execute("node.set", &json!({"ids": [title], "props": {"visible": false}})).unwrap();
let v = context(&mut s, json!({"ids": [f]}));
assert_eq!(only(&v)["children"][0]["explicit"]["visible"], false);
}
#[test]
fn what_the_design_doesnt_say_is_missing_not_guessed() {
let mut s = session();
let (f, _, _) = card(&mut s);
let v = context(&mut s, json!({"ids": [f]}));
assert!(v["missing"].as_array().unwrap().iter().any(|m| m["what"] == "responsive behaviour"));
assert!(!v.to_string().contains("@media"));
}
#[test]
fn annotations_come_with_their_layer() {
let mut s = session();
let (f, _, _) = card(&mut s);
s.execute("annotation.add", &json!({"id": f, "label": "Cards stack on mobile"})).unwrap();
let v = context(&mut s, json!({"ids": [f]}));
assert_eq!(only(&v)["explicit"]["annotations"][0]["label"], "Cards stack on mobile");
}
#[test]
fn deep_trees_stop_at_depth_and_say_so() {
let mut s = session();
let mut parent = node(&mut s, json!({"type": "frame", "width": 100, "height": 100}));
let root = parent;
for _ in 0..6 {
parent = node(&mut s, json!({"type": "frame", "parent": parent, "width": 50, "height": 50}));
}
let v = context(&mut s, json!({"ids": [root], "depth": 2}));
assert_eq!(v["target"]["layers"], 3);
assert_eq!(v["truncated"]["depth"], true);
assert_eq!(only(&v)["children"][0]["children"][0]["childCount"], 1);
assert!(context(&mut s, json!({"ids": [root]})).get("truncated").is_none());
}
#[test]
fn a_large_selection_keeps_to_the_cap_and_counts_the_rest() {
let mut s = session();
let root = node(&mut s, json!({"type": "frame", "width": 1000, "height": 1000}));
for _ in 0..50 {
node(&mut s, json!({"type": "rectangle", "parent": root, "width": 5, "height": 5}));
}
let v = context(&mut s, json!({"ids": [root], "maxNodes": 10}));
assert_eq!(v["target"]["layers"], 10);
assert_eq!(v["truncated"]["layersLeftOut"], 41);
assert_eq!(only(&v)["childCount"], 50, "it says how many there are");
}
#[test]
fn reading_changes_nothing() {
let mut s = session();
let (f, _, _) = card(&mut s);
let before = s.execute("node.get", &json!({"id": f})).unwrap();
let undo = s.undo_depth();
context(&mut s, json!({"ids": [f]}));
assert_eq!(s.execute("node.get", &json!({"id": f})).unwrap(), before);
assert_eq!(s.undo_depth(), undo);
}
#[test]
fn junk_parameters_are_errors_not_panics() {
let mut s = session();
card(&mut s);
for p in [json!({"depth": "x"}), json!({"maxNodes": -1}), json!({"maxNodes": "many"}), json!({"depth": {}})] {
assert!(s.execute("inspect.designContext", &p).is_err(), "{p}");
}
assert!(s.execute("inspect.designContext", &json!({"ids": []})).is_ok());
assert!(s.execute("inspect.designContext", &json!({"maxNodes": 0})).is_ok());
}
/// A colour variable in collection Theme (Light, Dark): (collection id, variable id).
fn variable(s: &mut Session, name: &str, light: &str, dark: &str) -> (Value, String) {
let c = s.execute("variable.createCollection", &json!({"name": format!("{name} theme"), "modes": ["Light", "Dark"]})).unwrap()["id"].clone();
let v = s.execute("variable.create", &json!({"collection": c, "name": name, "type": "color", "values": {"Light": light, "Dark": dark}})).unwrap();
(c, v["id"].as_str().unwrap().to_string())
}
#[test]
fn a_variable_an_alias_reads_is_joined_too() {
let mut s = session();
let (c, brand) = variable(&mut s, "brand", "#3B5BDB", "#748FFC");
let button = s
.execute("variable.create", &json!({"collection": c, "name": "button", "type": "color", "values": {"Light": "#000000", "Dark": "#000000"}}))
.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
for mode in ["Light", "Dark"] {
s.execute("variable.set", &json!({"variable": button, "mode": mode, "value": {"alias": brand}})).unwrap();
}
let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": {"$var": button}}}));
let v = context(&mut s, json!({"ids": [r]}));
assert!(v["variables"].get(&button).is_some());
assert_eq!(v["variables"][&brand]["name"], "brand", "the aliased variable is defined as well: {}", v["variables"]);
}
#[test]
fn a_variable_a_shared_style_binds_is_joined() {
let mut s = session();
let (_, brand) = variable(&mut s, "brand", "#3B5BDB", "#748FFC");
let r = node(&mut s, json!({"type": "rectangle", "width": 10, "height": 10, "props": {"fill": "#FF0000"}}));
let st = s.execute("style.create", &json!({"type": "paint", "name": "Brand/Fill", "from": r})).unwrap()["id"].clone();
s.execute("style.bind", &json!({"style": st, "field": "fill", "variable": brand})).unwrap();
s.execute("style.apply", &json!({"style": st, "ids": [r]})).unwrap();
let v = context(&mut s, json!({"ids": [r]}));
assert_eq!(only(&v)["tokens"]["style.fill"]["name"], "Brand/Fill");
assert_eq!(v["variables"][&brand]["name"], "brand", "the style's variable is defined: {}", v["variables"]);
}
#[test]
fn every_returned_text_layer_has_its_font_listed() {
let mut s = session();
let title = node(&mut s, json!({"type": "text", "text": "Title", "props": {"fontFamily": "Serif Display Test"}}));
let busy = node(&mut s, json!({"type": "frame", "x": 300, "width": 200, "height": 200}));
for _ in 0..12 {
node(&mut s, json!({"type": "rectangle", "parent": busy, "width": 4, "height": 4}));
}
let v = context(&mut s, json!({"ids": [title, busy], "maxNodes": 2}));
assert_eq!(v["target"]["layers"], 2);
let families: Vec<&str> = v["fonts"].as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap()).collect();
assert_eq!(families, ["Serif Display Test"], "{}", v["fonts"]);
}
#[test]
fn a_malformed_target_is_refused_rather_than_read_as_the_selection() {
let mut s = session();
let (f, _, _) = card(&mut s);
s.execute("select.set", &json!({"ids": [f]})).unwrap();
for p in [json!({"id": "not-an-id"}), json!({"id": true}), json!({"ids": [f, "nope"]}), json!({"ids": "1"})] {
assert!(s.execute("inspect.designContext", &p).is_err(), "{p}");
}
assert_eq!(context(&mut s, json!({"ids": []}))["target"]["layers"], 0, "an empty list reads nothing");
}
#[test]
fn a_font_stored_with_outer_spaces_isnt_taken_for_installed() {
let mut s = session();
let t = node(&mut s, json!({"type": "text", "text": "Hi", "props": {"fontFamily": " Missing Display Test "}}));
let v = context(&mut s, json!({"ids": [t]}));
let font = &v["fonts"][0];
assert_eq!(font["family"], " Missing Display Test ", "the spelling stays as stored");
assert_eq!(font["installed"], false, "{font}");
}
#[test]
fn assets_follow_the_layers_returned_and_say_what_was_left_out() {
let mut s = session();
let frame = node(&mut s, json!({"type": "frame", "width": 400, "height": 400}));
for seed in 0..20u8 {
let img = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([x as u8, y as u8, seed]));
let mut bytes = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bytes);
s.execute("image.place", &json!({"data": data, "parent": frame})).unwrap();
}
let all = context(&mut s, json!({"ids": [frame]}));
assert_eq!(all["assets"].as_array().unwrap().len(), 20);
let few = context(&mut s, json!({"ids": [frame], "maxNodes": 5}));
let shown = few["assets"].as_array().unwrap().len();
assert_eq!(shown, 4, "only the images among the 5 layers returned");
assert_eq!(few["truncated"]["assetsLeftOut"], 16);
}
#[test]
fn a_join_stopped_at_its_budget_says_so() {
let mut s = session();
let (c, first) = variable(&mut s, "v0", "#000000", "#000000");
let mut prev = first.clone();
for k in 1..6 {
let next = s
.execute(
"variable.create",
&json!({"collection": c, "name": format!("v{k}"), "type": "color", "values": {"Light": "#111111", "Dark": "#111111"}}),
)
.unwrap()["id"]
.as_str()
.unwrap()
.to_string();
for mode in ["Light", "Dark"] {
s.execute("variable.set", &json!({"variable": prev, "mode": mode, "value": {"alias": next}})).unwrap();
}
prev = next;
}
let start = std::collections::BTreeSet::from([first]);
let none = std::collections::BTreeSet::new();
let (all, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 100);
assert_eq!((all.len(), complete), (6, true));
let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3);
assert_eq!((some.len(), complete), (3, false), "{some:?}");
}
+1
View File
@@ -2,6 +2,7 @@ pub mod annotations;
pub mod code_connect;
pub mod codegen;
pub mod component_codegen;
pub mod design_context;
pub mod dev_measurements;
pub mod dev_resources;
pub mod devcompare;
+11 -1
View File
@@ -162,6 +162,7 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
}
if matches!(n.kind, NodeKind::Text(_)) {
// Text: a solid is the ink (`color`), one per fill, so the last (top) one wins.
let top = n.fills.iter().rposition(|p| p.visible);
for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) {
match &p.kind {
PaintKind::Solid { color } => {
@@ -169,7 +170,16 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo
// A variable binds the first paint's colour.
put("color", if i == 0 { tok(doc, n, &["fill"], c, t) } else { c });
}
PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)),
PaintKind::Gradient(g) => {
put("background", css_gradient(g, n.width, n.height, p.opacity));
// A gradient on top fills the glyphs: clip the background to the text and clear the ink.
// Under a later paint it must not hide that paint's colour, so it stays a plain background.
if Some(i) == top {
put("-webkit-background-clip", "text".into());
put("background-clip", "text".into());
put("color", "transparent".into());
}
}
PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()),
PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()),
}
+473
View File
@@ -0,0 +1,473 @@
//! Design context: what an AI agent needs to build a design, in one read (`inspect.designContext`,
//! the MCP tool `design_context`). The selection by default, as a tree in which every layer keeps
//! apart what the designer set (`explicit`), what layout or the file worked out (`derived`) and
//! what has no direct CSS equivalent (`unsupported`, with the reason). The variables, styles and
//! components the tree uses are joined once at the top level, and a connected instance gives its
//! code instead of its layers. Values are the file's own: nothing is guessed or converted, and
//! `missing` says what the design doesn't specify.
use std::collections::{BTreeMap, BTreeSet};
use figcraft_color::{GradientKind, PaintKind};
use figcraft_doc::{Document, EffectKind, Node, NodeId, NodeKind, Sizing, StrokeAlign, TextAutoResize};
use serde_json::{Map, Value, json};
use crate::cmd::CommandSpec;
use crate::cmd::component::describe_props;
use crate::code_connect;
use crate::codegen::CodeLang;
use crate::inspect::{camel, node_json};
use crate::params::{get, num, string, targets};
use crate::{Result, Session, bad, spec};
/// The format's version: fields may be added without changing it.
const VERSION: u64 = 1;
/// How deep the tree goes by default.
const DEFAULT_DEPTH: usize = 32;
/// The deepest tree asked for.
const MAX_DEPTH: usize = 128;
/// How many layers it holds by default.
const DEFAULT_NODES: usize = 2_000;
/// The most layers asked for.
const MAX_NODES: usize = 20_000;
/// Worked out rather than set, whatever the layer.
const DERIVED: [&str; 3] = ["absoluteBounds", "rotation", "gridCell"];
/// What the tree used, to join at the top level.
#[derive(Default)]
struct Used {
variables: BTreeSet<String>,
styles: BTreeSet<String>,
components: BTreeSet<NodeId>,
/// Layers placed so far, and those left out for the cap.
nodes: usize,
left_out: usize,
/// Reached `depth` with children left.
cut_by_depth: bool,
/// The layers placed.
placed: BTreeSet<NodeId>,
/// Font families of the text layers placed, with their styles.
fonts: BTreeMap<String, BTreeSet<String>>,
}
/// `property` of a layer has no direct CSS equivalent, because `why`.
fn limit(out: &mut Vec<Value>, property: &str, why: &str) {
out.push(json!({"property": property, "why": why}));
}
/// What of `n` CSS can't say directly. The original values stay in `explicit`.
fn limits(n: &Node) -> Vec<Value> {
let mut out = Vec::new();
if matches!(n.blend, figcraft_color::BlendMode::PlusDarker) {
limit(&mut out, "blend", "only some browsers have the plus-darker blend mode");
}
if n.corners.smoothing > 0.0 {
limit(&mut out, "cornerSmoothing", "CSS border-radius has no corner smoothing");
}
if !n.strokes.is_empty() {
match n.stroke.align {
StrokeAlign::Inside => {}
StrokeAlign::Center => limit(&mut out, "strokeAlign", "a CSS border can't straddle the box edge"),
StrokeAlign::Outside => {
limit(&mut out, "strokeAlign", "a CSS border sits inside the box's border area: an outline or box-shadow comes closest")
}
}
if n.stroke.profile().is_some() {
limit(&mut out, "widthProfile", "CSS strokes have one width");
}
if n.stroke.brush.is_some() {
limit(&mut out, "brush", "CSS has no brush strokes");
}
}
for p in n.fills.iter().chain(&n.strokes) {
match &p.kind {
PaintKind::Gradient(g) if g.kind == GradientKind::Diamond => limit(&mut out, "fills", "CSS has no diamond gradient"),
PaintKind::Pattern(_) => limit(&mut out, "fills", "a pattern fill needs an image or an SVG pattern in CSS"),
_ => {}
}
}
for e in &n.effects {
match e.kind {
EffectKind::Noise(_) => limit(&mut out, "effects", "CSS has no noise effect"),
EffectKind::Texture(_) => limit(&mut out, "effects", "CSS has no roughened edge effect"),
EffectKind::Glass(_) => limit(&mut out, "effects", "CSS has no curved glass effect"),
_ => {}
}
}
if let NodeKind::Text(t) = &n.kind {
if t.path.is_some() {
limit(&mut out, "textPath", "text on a path needs SVG");
}
if t.leading_trim != figcraft_doc::LeadingTrim::None {
limit(&mut out, "leadingTrim", "CSS text-box-trim isn't in every browser");
}
if t.hanging_punctuation {
limit(&mut out, "hangingPunctuation", "CSS hanging-punctuation isn't in every browser");
}
}
out
}
/// Moves `key` of `explicit` to `derived`.
fn derive(explicit: &mut Map<String, Value>, derived: &mut Map<String, Value>, key: &str) {
if let Some(v) = explicit.remove(key) {
derived.insert(key.into(), v);
}
}
/// Splits a layer's properties: a size or a position that layout decides isn't the designer's.
fn split(doc: &Document, n: &Node, explicit: &mut Map<String, Value>) -> Map<String, Value> {
let mut derived = Map::new();
for key in DERIVED {
derive(explicit, &mut derived, key);
}
let in_flow = n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some()) && !n.child_layout.absolute;
if in_flow {
derive(explicit, &mut derived, "x");
derive(explicit, &mut derived, "y");
}
let (mut wide, mut tall) = (n.child_layout.sizing_h != Sizing::Fixed, n.child_layout.sizing_v != Sizing::Fixed);
if let NodeKind::Text(t) = &n.kind {
wide |= t.auto_resize == TextAutoResize::WidthAndHeight;
tall |= matches!(t.auto_resize, TextAutoResize::WidthAndHeight | TextAutoResize::Height);
}
if wide {
derive(explicit, &mut derived, "width");
}
if tall {
derive(explicit, &mut derived, "height");
}
derived
}
/// What a layer's tokens are called: bindings by field, shared styles by kind, as they would be
/// looked up in the top-level `variables` and `styles`.
fn tokens(doc: &Document, n: &Node, used: &mut Used) -> Map<String, Value> {
let mut out = Map::new();
for (field, id) in &n.bound {
used.variables.insert(id.clone());
let name = doc.variables.variables.iter().find(|v| v.id == *id).map(|v| v.name.clone());
out.insert(field.clone(), json!({"variable": id, "name": name}));
}
let refs = &n.styles;
let mut styles: Vec<(String, &String)> =
[("fill", &refs.fill), ("stroke", &refs.stroke), ("effect", &refs.effect), ("grid", &refs.grid), ("text", &refs.text)]
.into_iter()
.filter_map(|(k, s)| s.as_ref().map(|s| (format!("style.{k}"), s)))
.collect();
if let NodeKind::Text(t) = &n.kind {
let spans = t.spans();
styles.extend(spans.iter().filter_map(|(a, b, s)| s.style_id.as_ref().map(|i| (format!("style.text[{a}..{b}]"), i))));
}
for (key, id) in styles {
used.styles.insert(id.clone());
let name = doc.styles.iter().find(|s| s.id == *id).map(|s| s.name.clone());
out.insert(key, json!({"style": id, "name": name}));
}
out
}
/// The code component a component, set or instance is connected to, per language, with the
/// instance's own values in its snippet.
fn code(doc: &Document, id: NodeId) -> Vec<Value> {
let Some(owner) = code_connect::owner(doc, id).and_then(|o| doc.node(o)) else { return vec![] };
owner
.code_links
.iter()
.filter_map(|l| {
let lang = CodeLang::from_id(&l.language)?;
let snippet = code_connect::connected_code(doc, id, lang, l)?;
Some(json!({"language": l.language, "importPath": l.import_path, "name": l.name, "code": snippet}))
})
.collect()
}
/// Layer `id` and, to `depth`, what's under it, while the cap holds.
fn layer(doc: &Document, id: NodeId, depth: usize, cap: usize, used: &mut Used) -> Option<Value> {
let n = doc.node(id)?;
used.nodes += 1;
used.placed.insert(id);
if let NodeKind::Text(t) = &n.kind {
for (_, _, style) in t.spans() {
used.fonts.entry(style.font_family.clone()).or_default().insert(style.font_style.clone());
}
}
let Value::Object(mut explicit) = node_json(doc, id, 0) else { return None };
explicit.remove("childCount");
let mut out = Map::new();
for key in ["id", "name", "type"] {
if let Some(v) = explicit.remove(key) {
out.insert(key.into(), v);
}
}
let derived = split(doc, n, &mut explicit);
let tokens = tokens(doc, n, used);
let unsupported = limits(n);
out.insert("explicit".into(), Value::Object(explicit));
if !derived.is_empty() {
out.insert("derived".into(), Value::Object(derived));
}
if !tokens.is_empty() {
out.insert("tokens".into(), Value::Object(tokens));
}
if !unsupported.is_empty() {
out.insert("unsupported".into(), Value::Array(unsupported));
}
if let Some(owner) = code_connect::owner(doc, id) {
used.components.insert(owner);
}
let connected = code(doc, id);
// An instance built from a code component needs its call, not its layers.
let stop = matches!(n.kind, NodeKind::Instance { .. }) && !connected.is_empty();
if !connected.is_empty() {
out.insert("code".into(), Value::Array(connected));
}
if n.children.is_empty() {
return Some(Value::Object(out));
}
if stop {
out.insert("childCount".into(), json!(n.children.len()));
return Some(Value::Object(out));
}
if depth == 0 {
used.cut_by_depth = true;
out.insert("childCount".into(), json!(n.children.len()));
return Some(Value::Object(out));
}
let mut children = Vec::new();
for c in &n.children {
if used.nodes >= cap {
used.left_out += 1;
continue;
}
children.extend(layer(doc, *c, depth - 1, cap, used));
}
if children.len() < n.children.len() {
out.insert("childCount".into(), json!(n.children.len()));
}
out.insert("children".into(), Value::Array(children));
Some(Value::Object(out))
}
/// A value as the panels show it: colours in hex.
fn value_json(v: &figcraft_doc::VariableValue) -> Value {
match v {
figcraft_doc::VariableValue::Color(c) => json!(c.to_css_hex()),
figcraft_doc::VariableValue::Number(n) => json!(n),
figcraft_doc::VariableValue::String(s) => json!(s),
figcraft_doc::VariableValue::Boolean(b) => json!(b),
other => serde_json::to_value(other).unwrap_or(Value::Null),
}
}
/// `ids`' variables: every mode's stored and resolved value. A value that is an alias or a
/// calculation stays in `value`; the variables it reads are in `ids` too ([`referenced`]).
fn variables_json(doc: &Document, ids: &BTreeSet<String>, missing: &mut Vec<Value>) -> Value {
let store = &doc.variables;
let mut out = Map::new();
for id in ids {
let Some(var) = store.variables.iter().find(|v| v.id == *id) else {
missing.push(json!({"what": "variable", "id": id, "why": "a layer is bound to it, but it isn't in this file"}));
continue;
};
let collection = store.collection_by_id(&var.collection);
let modes: Vec<Value> = collection
.map(|c| c.modes.as_slice())
.unwrap_or_default()
.iter()
.map(|m| {
let chosen = BTreeMap::from([(var.collection.clone(), m.id.clone())]);
json!({
"mode": m.name,
"value": var.values.get(&m.id).map(value_json),
"resolved": store.resolve(id, &chosen).as_ref().map(value_json),
})
})
.collect();
let mut v = json!({"name": var.name, "collection": collection.map(|c| c.name.as_str()), "type": var.kind, "modes": modes});
if !var.code_syntax.is_empty() {
v["codeSyntax"] = json!(var.code_syntax);
}
if !var.description.is_empty() {
v["description"] = json!(var.description);
}
out.insert(id.clone(), v);
}
Value::Object(out)
}
/// Most variables followed through aliases.
const MAX_VARIABLES: usize = 10_000;
/// The variables a tree uses: those its layers bind (`bound`), those its shared `styles` bind, and
/// those any of them reads as an alias or in a colour calculation, however deep, up to `max`. The
/// flag is false when `max` stopped it with variables still to follow.
pub(crate) fn referenced(doc: &Document, bound: &BTreeSet<String>, styles: &BTreeSet<String>, max: usize) -> (BTreeSet<String>, bool) {
let mut out: BTreeSet<String> = BTreeSet::new();
let mut todo: Vec<String> = bound.iter().cloned().collect();
todo.extend(doc.styles.iter().filter(|st| styles.contains(&st.id)).flat_map(|st| st.bound.values().cloned()));
todo.reverse();
while let Some(id) = todo.pop() {
if out.contains(&id) {
continue;
}
if out.len() >= max {
return (out, false);
}
out.insert(id.clone());
let Some(var) = doc.variables.variables.iter().find(|v| v.id == id) else { continue };
for value in var.values.values() {
match value {
figcraft_doc::VariableValue::Alias(other) => todo.push(other.clone()),
figcraft_doc::VariableValue::ColorAlpha { variable, .. } => todo.push(variable.clone()),
figcraft_doc::VariableValue::ColorMix { from, to, .. } => todo.extend(from.variable().into_iter().chain(to.variable()).cloned()),
_ => {}
}
}
}
(out, true)
}
/// The shared styles the tree uses, with what each sets.
fn styles_json(doc: &Document, ids: &BTreeSet<String>, missing: &mut Vec<Value>) -> Value {
let mut out = Map::new();
for id in ids {
match doc.styles.iter().find(|s| s.id == *id) {
Some(st) => {
out.insert(id.clone(), camel(serde_json::to_value(st).unwrap_or(Value::Null)));
}
None => missing.push(json!({"what": "style", "id": id, "why": "a layer links to it, but it isn't in this file"})),
}
}
Value::Object(out)
}
/// The components and sets the tree uses: their properties, variants and code.
fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
let mut out = Map::new();
for id in ids {
let Some(n) = doc.node(*id) else { continue };
let mut v = json!({"name": n.name, "type": n.kind.type_name(), "properties": describe_props(doc, *id)["properties"]});
if let NodeKind::Component { description, .. } = &n.kind
&& !description.is_empty()
{
v["description"] = json!(description);
}
if !n.code_links.is_empty() {
v["codeLinks"] = camel(serde_json::to_value(&n.code_links).unwrap_or(Value::Null));
}
out.insert(id.to_string(), v);
}
Value::Object(out)
}
/// The font families the tree's text layers use, with their styles, and whether each is installed
/// (the family name trimmed, as the missing-fonts list reads it). The spelling stays as stored.
fn fonts(used: &BTreeMap<String, BTreeSet<String>>) -> Value {
Value::Array(
used.iter()
.map(|(family, styles)| json!({"family": family, "styles": styles, "installed": figcraft_text::has_family(family.trim())}))
.collect(),
)
}
/// What the request names: (where it came from, the layers).
fn roots(s: &Session, p: &Value) -> Result<(&'static str, Vec<NodeId>)> {
let cmd = "inspect.designContext";
let doc = s.doc()?;
let malformed = || bad(cmd, "ids: a list of layer ids (or id: one)");
match (get(p, "ids"), get(p, "id")) {
(Some(Value::Array(list)), _) if list.iter().all(|i| crate::params::id_of(i).is_some()) => {}
(Some(_), _) => return Err(malformed()),
(None, Some(one)) if crate::params::id_of(one).is_none() => return Err(malformed()),
_ => {}
}
if get(p, "ids").is_some() || get(p, "id").is_some() {
let ids: Vec<NodeId> = targets(s, p);
if let Some(gone) = ids.iter().find(|i| !doc.contains(**i)) {
return Err(bad(cmd, format!("no layer {gone}")));
}
return Ok(("ids", ids));
}
let page = |pg: NodeId| doc.node(pg).map(|n| n.children.clone()).unwrap_or_default();
match string(p, "scope").as_deref() {
None | Some("selection") => match s.selection() {
ids if ids.is_empty() => Ok(("page", page(s.page()?))),
ids => Ok(("selection", ids)),
},
Some("page") => Ok(("page", page(s.page()?))),
Some("document") => Ok(("document", doc.pages.iter().flat_map(|pg| page(*pg)).collect())),
Some(_) => Err(bad(cmd, "scope: selection|page|document")),
}
}
/// A whole-number parameter within `1..=max`.
fn limit_param(p: &Value, key: &str, default: usize, max: usize) -> Result<usize> {
match get(p, key) {
None | Some(Value::Null) => Ok(default),
Some(_) => match num(p, key).filter(|v| v.is_finite() && *v >= 0.0) {
Some(v) => Ok((v as usize).min(max)),
None => Err(bad("inspect.designContext", format!("{key}: a whole number"))),
},
}
}
fn design_context(s: &mut Session, p: &Value) -> Result<Value> {
let (source, ids) = roots(s, p)?;
let depth = limit_param(p, "depth", DEFAULT_DEPTH, MAX_DEPTH)?;
let cap = limit_param(p, "maxNodes", DEFAULT_NODES, MAX_NODES)?.max(1);
let doc = s.doc()?;
let mut used = Used::default();
let mut nodes = Vec::new();
for id in &ids {
if used.nodes >= cap {
used.left_out += 1;
continue;
}
nodes.extend(layer(doc, *id, depth, cap, &mut used));
}
let mut missing = vec![
json!({"what": "responsive behaviour", "why": "the file stores no breakpoints: sizes are as designed here, and constraints, sizing and annotations are all it says about other widths"}),
];
let (joined, complete) = referenced(doc, &used.variables, &used.styles, MAX_VARIABLES);
let variables = variables_json(doc, &joined, &mut missing);
let styles = styles_json(doc, &used.styles, &mut missing);
let components = components_json(doc, &used.components);
let fonts = fonts(&used.fonts);
let page = doc.node(s.page()?).map(|n| n.name.clone());
// The assets of the layers returned: a smaller tree means a smaller list.
let found = crate::devinspect::assets(doc, &ids);
let assets: Vec<&crate::devinspect::Asset> = found.iter().filter(|a| used.placed.contains(&a.id)).collect();
let assets_left_out = found.len() - assets.len();
let mut out = json!({
"version": VERSION,
"document": {"name": doc.name, "page": {"id": s.page()?, "name": page}, "colorProfile": doc.color_profile.id()},
"target": {"source": source, "ids": ids, "layers": used.nodes},
"nodes": nodes,
"variables": variables,
"styles": styles,
"components": components,
"fonts": fonts,
"assets": assets,
"missing": missing,
});
if used.left_out > 0 || used.cut_by_depth {
out["truncated"] = json!({"layersLeftOut": used.left_out, "assetsLeftOut": assets_left_out, "depth": used.cut_by_depth, "maxNodes": cap, "hint": "call again with the ids of the parts you need"});
}
if !complete {
out["truncated"]["variables"] =
json!({"maxVariables": MAX_VARIABLES, "why": "aliases go deeper than this: some variables they read aren't defined here"});
}
Ok(out)
}
pub fn specs() -> Vec<CommandSpec> {
vec![spec!(
"inspect.designContext",
"Design context",
"{ids? | id? (those layers), scope?: selection|page|document (default the selection, or the page with nothing selected), depth? (default 32), maxNodes? (default 2000)} everything needed to build them, in one read → {version, document, target {source, ids, layers}, nodes [{id, name, type, explicit, derived?, tokens?, unsupported? [{property, why}], code?, children?, childCount?}], variables, styles, components, fonts, assets, missing [{what, why}], truncated?}",
false,
design_context
)]
}
+3
View File
@@ -293,6 +293,9 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> {
// An image shorthand (`url(…) center / cover`) is a whole `background`, not a bg colour.
("background", v) if v.starts_with("url(") => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))),
("background", v) => one(util("bg", "color", v, "color:")),
("-webkit-background-clip", "text") => Vec::new(),
("background-clip", "text") => kw("bg-clip-text"),
("color", "transparent") => kw("text-transparent"),
("color", v) => one(util("text", "color", v, "color:")),
("border", v) => border("", v),
("border-top", v) => border("t", v),
+22 -1
View File
@@ -1,5 +1,7 @@
use super::view_state::ViewState;
use super::{Arc, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit};
use super::{
Arc, BTreeMap, BTreeSet, Deserialize, Document, NodeId, Serialize, cmd, components, file_access, guides, library, rotation_origin, vectoredit,
};
/// One undo step.
#[derive(Clone, Debug)]
@@ -114,6 +116,9 @@ pub struct DocState {
/// The file on disk as this tab last read or wrote it: a save refuses to replace what another
/// app (figcraft-cli, say) wrote to it since (#1330).
pub(crate) on_disk: Option<library::Stamp>,
/// Where each page's view was left in this session (its centre and zoom; see
/// [`Self::open_page`]; not saved).
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
}
/// A version shown on the canvas in place of the document: read-only until it's restored or the
@@ -178,6 +183,7 @@ impl DocState {
last_duplicate: None,
images_left_in_file: None,
on_disk: None,
page_views: BTreeMap::new(),
};
st.zoom_to_fit();
st
@@ -311,6 +317,21 @@ impl DocState {
}
/// Fit the current page's content (or centre on the origin when empty).
/// Show `page` at the view it was left at in this session, or one that fits its content the
/// first time; the page shown till now keeps its view for when it comes back. The page shown
/// already keeps its view.
pub fn open_page(&mut self, page: NodeId) {
if page == self.page {
return;
}
self.page_views.insert(self.page, (self.view.cx, self.view.cy, self.view.zoom));
self.page = page;
match self.page_views.get(&page) {
Some(&(cx, cy, zoom)) => (self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom),
None => self.zoom_to_fit(),
}
}
pub fn zoom_to_fit(&mut self) {
match self.doc.page_content_bounds(self.page) {
Some(b) => self.view.fit(b, 1.0),
+2
View File
@@ -43,6 +43,8 @@ impl EngineError {
match self {
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: format!("step {step}: {msg}") },
EngineError::Other(msg) => EngineError::Other(format!("step {step}: {msg}")),
EngineError::Disabled(cmd, msg) => EngineError::Disabled(cmd, format!("step {step}: {msg}")),
EngineError::Internal { cmd, msg } => EngineError::Internal { cmd, msg: format!("step {step}: {msg}") },
e => e,
}
}
@@ -355,3 +355,35 @@ fn rem_conversion_keeps_the_original_pixels() {
assert_eq!(f("padding: 3px;", 16.0), "padding: 0.1875rem;");
assert_eq!(f("gap: 0.5px;", 16.0), "gap: 0.03125rem;");
}
#[test]
fn text_gradient_fill_clips_to_the_glyphs() {
let mut s = Session::new();
let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}]);
let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}})));
let c = css(&mut s, t);
assert!(c.contains("background: linear-gradient("), "{c}");
assert!(c.contains("-webkit-background-clip: text;"), "{c}");
assert!(c.contains("\nbackground-clip: text;"), "{c}");
assert!(c.contains("color: transparent;"), "{c}");
let tw = code(&mut s, t, json!({"language": "tailwind"}));
assert!(tw.contains("bg-clip-text") && tw.contains("text-transparent"), "{tw}");
// A box keeps its gradient as a plain background.
let r = rect(&mut s, 0.0, 0.0, 50.0, 50.0, None);
let set = s.execute("node.set", &json!({"id": r, "props": {"fills": fills}}));
assert!(set.is_ok(), "{set:?}");
let box_css = css(&mut s, r);
assert!(box_css.contains("background: linear-gradient("), "{box_css}");
assert!(!box_css.contains("background-clip"), "{box_css}");
}
#[test]
fn text_gradient_under_a_solid_fill_keeps_the_solid_ink() {
let mut s = Session::new();
let fills = json!([{"type": "linearGradient", "stops": ["#D98200", "#FF6B4A"]}, {"type": "solid", "color": "#112233"}]);
let t = id(&ex(&mut s, "node.create", json!({"type": "text", "text": "Gradient", "props": {"fontSize": 48, "fills": fills}})));
let c = css(&mut s, t);
assert!(!c.contains("color: transparent;"), "{c}");
assert!(!c.contains("background-clip"), "{c}");
assert!(c.contains("color: #112233;"), "{c}");
}
+95
View File
@@ -505,3 +505,98 @@ fn node_get_uses_options_but_keeps_its_existing_depth_and_selection() {
assert_eq!(s.selection(), selection);
assert_eq!(s.undo_depth(), history);
}
/// Text and stroke settings a layer stores are reported, under the names `node.set` takes, so a
/// value read can be written back unchanged.
#[test]
fn stored_text_and_stroke_settings_are_read_back_as_set() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let text = s.execute("node.create", &json!({"type": "text", "text": "Hi", "width": 120})).unwrap()["id"].clone();
let line =
s.execute("node.create", &json!({"type": "line", "width": 80, "props": {"strokes": ["#000000"], "strokeWeight": 2}})).unwrap()["id"].clone();
let set = json!({
"textAlignVertical": "middle", "textCase": "upper", "paragraphSpacing": 8.0, "paragraphIndent": 12.0, "features": {"liga": false},
});
s.execute("node.set", &json!({"ids": [text.clone()], "props": set})).unwrap();
s.execute("node.set", &json!({"ids": [line.clone()], "props": {"startCap": "round", "endCap": "triangleArrow"}})).unwrap();
let got = s.execute("node.get", &json!({"id": text})).unwrap();
for (key, value) in set.as_object().unwrap() {
assert_eq!(&got[key], value, "{key}: {got}");
// Written back as read, it changes nothing.
s.execute("node.set", &json!({"ids": [text.clone()], "props": {key.as_str(): got[key].clone()}})).unwrap();
assert_eq!(s.execute("node.get", &json!({"id": text})).unwrap()[key], *value, "{key}");
}
let got = s.execute("node.get", &json!({"id": line})).unwrap();
assert_eq!((got["startCap"].as_str(), got["endCap"].as_str()), (Some("round"), Some("triangleArrow")), "{got}");
// Defaults stay out, as they do for other keys.
let plain = s.execute("node.create", &json!({"type": "text", "text": "x"})).unwrap()["id"].clone();
let got = s.execute("node.get", &json!({"id": plain})).unwrap();
for key in ["textAlignVertical", "textCase", "paragraphSpacing", "paragraphIndent", "features", "startCap", "endCap", "variableModes"] {
assert!(got.get(key).is_none(), "{key} at its default: {got}");
}
}
/// A frame's variable modes, a layer's component property bindings and an exposed nested instance
/// are reported.
#[test]
fn modes_property_bindings_and_exposed_instances_are_read() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let c = s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap();
let frame = s.execute("node.create", &json!({"type": "frame", "width": 100, "height": 100})).unwrap()["id"].clone();
s.execute("variable.setMode", &json!({"ids": [frame.clone()], "collection": c["id"], "mode": "Dark"})).unwrap();
let modes = s.execute("node.get", &json!({"id": frame})).unwrap()["variableModes"].clone();
assert_eq!(modes.as_object().map(|m| m.len()), Some(1), "{modes}");
let card = s.execute("node.create", &json!({"type": "frame", "name": "Card", "width": 100, "height": 50})).unwrap()["id"].clone();
let title = s.execute("node.create", &json!({"type": "text", "parent": card.clone(), "text": "Title"})).unwrap()["id"].clone();
let main = s.execute("component.create", &json!({"ids": [card]})).unwrap()["id"].clone();
s.execute("component.addProperty", &json!({"id": main.clone(), "name": "Label", "type": "text", "layer": title.clone()})).unwrap();
let refs = s.execute("node.get", &json!({"id": title})).unwrap()["propertyReferences"].clone();
assert!(refs.as_object().is_some_and(|r| r.values().any(|v| v.as_str().is_some_and(|p| p.starts_with("Label")))), "{refs}");
let tag = s.execute("node.create", &json!({"type": "frame", "name": "Tag", "x": 300, "width": 40, "height": 20})).unwrap()["id"].clone();
let tag_main = s.execute("component.create", &json!({"ids": [tag]})).unwrap()["id"].clone();
let nested = s.execute("instance.create", &json!({"component": tag_main})).unwrap()["id"].clone();
s.execute("node.reparent", &json!({"ids": [nested.clone()], "parent": main})).unwrap();
s.execute("component.exposeInstance", &json!({"id": nested.clone()})).unwrap();
assert_eq!(s.execute("node.get", &json!({"id": nested})).unwrap()["exposedInstance"], true);
}
/// Every key a layer's JSON can have is one `fields` accepts: a key missing from `NODE_KEYS` can be
/// read in full output but is refused when asked for by name (`dashCap` was).
#[test]
fn every_key_node_get_writes_can_be_asked_for() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let frame = s
.execute("node.create", &json!({"type": "frame", "width": 200, "height": 100, "props": {"layout": {"mode": "horizontal"}, "gap": 4}}))
.unwrap()["id"]
.clone();
let line = s
.execute(
"node.create",
&json!({"type": "line", "parent": frame, "width": 80, "props": {
"strokes": ["#000000"], "strokeWeight": 2, "dashes": [4, 2], "dashCap": "round", "strokeJoin": "round",
"opacity": 0.5, "visible": false, "locked": true}}),
)
.unwrap()["id"]
.clone();
s.execute("node.create", &json!({"type": "text", "parent": frame, "text": "Hi", "props": {"textDecoration": "underline"}})).unwrap();
s.execute("annotation.add", &json!({"id": line, "label": "Note"})).unwrap();
let mut keys = std::collections::BTreeSet::new();
fn walk(v: &Value, keys: &mut std::collections::BTreeSet<String>) {
if let Some(o) = v.as_object() {
keys.extend(o.keys().cloned());
for c in o.get("children").and_then(Value::as_array).into_iter().flatten() {
walk(c, keys);
}
}
}
walk(&node_json(s.doc().unwrap(), crate::params::id_of(&frame).unwrap(), 4), &mut keys);
assert!(keys.contains("dashCap"), "the test sets a dash cap: {keys:?}");
for key in keys {
assert!(crate::inspect::NODE_KEYS.contains(&key.as_str()), "`{key}` is written but `fields` refuses it");
let one = InspectOptions::parse(&json!({"fields": [key]}));
assert!(one.is_ok(), "{key}: {one:?}");
}
}
+31 -1
View File
@@ -77,6 +77,34 @@ fn a_layer_in_an_instance_fills_and_keeps_it_through_main_edits() {
healthy(&s);
}
/// A child set to Fill along a hugging instance root turns the root Fixed: that is the root's own
/// resizing now, recorded as an override, so a later rebuild from the main (an edit of the main's
/// resizing or structure) keeps it Fixed and the child keeps filling.
#[test]
fn a_child_filling_a_hugging_instance_root_keeps_the_root_fixed_through_a_rebuild() {
let mut s = Session::new();
let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 120, "height": 40, "name": "Row"})));
ex(&mut s, "node.set", json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"}}));
let atom = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": f, "name": "Atom"})));
ex(&mut s, "node.set", json!({"id": atom, "props": {"layout": "horizontal", "padding": 0, "gap": 0, "sizingH": "hug", "sizingV": "hug"}}));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": atom, "props": {"name": "Dot"}}));
let c = idv(&ex(&mut s, "component.create", json!({"ids": [f]})));
let i = idv(&ex(&mut s, "instance.create", json!({"component": c, "x": 0, "y": 100})));
let ia = copy_of(&s, i, atom);
assert_eq!((sizing_h(&s, i), sizing_h(&s, ia), node(&s, i).width), (Sizing::Hug, Sizing::Hug, 50.0));
ex(&mut s, "node.set", json!({"id": ia, "props": {"sizingH": "fill"}}));
assert_eq!((sizing_h(&s, i), sizing_h(&s, ia)), (Sizing::Fixed, Sizing::Fill), "the root turned Fixed, the child fills");
// The main's resizing changes, and its structure: both rebuild the instance.
ex(&mut s, "node.set", json!({"id": c, "props": {"minWidth": 60}}));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5, "parent": c}));
assert_eq!((sizing_h(&s, i), sizing_h(&s, ia)), (Sizing::Fixed, Sizing::Fill), "the root stays Fixed through the rebuild");
assert!(node(&s, i).overrides.contains("resizing"), "{:?}", node(&s, i).overrides);
// Reset instance gives the main's Hug back.
ex(&mut s, "component.resetInstance", json!({"ids": [i]}));
assert_eq!(sizing_h(&s, i), Sizing::Hug);
healthy(&s);
}
#[test]
fn size_and_resizing_overrides_undo_reset_and_detach() {
let mut s = Session::new();
@@ -123,8 +151,10 @@ fn layers_in_instances_resize_but_keep_their_place() {
for props in [json!({"x": 50}), json!({"rotation": 15}), json!({"constraints": {"horizontal": "right"}})] {
assert!(s.execute("node.set", &json!({"id": it, "props": props})).is_err(), "{props} is refused");
}
// The instance's own resizing is its own, not an override.
// The instance's own resizing is recorded as an override (inferred), which Reset instance clears.
ex(&mut s, "node.set", json!({"id": i, "props": {"minWidth": 100}}));
assert!(node(&s, i).overrides.contains("resizing"));
ex(&mut s, "component.resetInstance", json!({"ids": [i]}));
assert!(!node(&s, i).overrides.contains("resizing"));
healthy(&s);
}
+19
View File
@@ -65,6 +65,7 @@ pub use dev::annotations;
pub use dev::code_connect;
pub use dev::codegen;
pub use dev::component_codegen;
pub use dev::design_context;
pub use dev::dev_measurements;
pub use dev::dev_resources;
pub use dev::devcompare;
@@ -208,6 +209,8 @@ mod batch_undo_snapshot_tests;
#[cfg(test)]
mod binding_lists_tests;
#[cfg(test)]
mod board_code_tests;
#[cfg(test)]
mod board_connected_tests;
#[cfg(test)]
mod board_connector_tests;
@@ -284,6 +287,8 @@ mod datafill_tests;
#[cfg(test)]
mod default_props_tests;
#[cfg(test)]
mod design_context_tests;
#[cfg(test)]
mod design_paste_tests;
#[cfg(test)]
mod dev_measurements_tests;
@@ -404,12 +409,16 @@ mod keymap_tests;
#[cfg(test)]
mod layout_suggest_tests;
#[cfg(test)]
mod library_asset_counts_tests;
#[cfg(test)]
mod library_beacon_tests;
#[cfg(test)]
mod library_path_tests;
#[cfg(test)]
mod library_range_styles_tests;
#[cfg(test)]
mod library_style_hops_tests;
#[cfg(test)]
mod library_variables_tests;
#[cfg(test)]
mod line_endings_tests;
@@ -474,6 +483,8 @@ mod panels_behaviour_tests;
#[cfg(test)]
mod paste_missing_image_tests;
#[cfg(test)]
mod paste_sibling_tests;
#[cfg(test)]
mod path_read_caps_tests;
#[cfg(test)]
mod pdf_print_tests;
@@ -486,6 +497,8 @@ mod pen_undo_tests;
#[cfg(test)]
mod pen_vector_edit_tests;
#[cfg(test)]
mod pencil_shift_tests;
#[cfg(test)]
mod penpot_export_tests;
#[cfg(test)]
mod pixel_preview_tests;
@@ -634,6 +647,8 @@ mod variables_import_shapes_tests;
#[cfg(test)]
mod variables_io_tests;
#[cfg(test)]
mod variant_shared_props_tests;
#[cfg(test)]
mod variants_discovery_tests;
#[cfg(test)]
mod vector_behaviour_tests;
@@ -652,6 +667,8 @@ mod version_preview_tests;
#[cfg(test)]
mod version_tests;
#[cfg(test)]
mod view_autopan_tests;
#[cfg(test)]
mod view_behaviour_tests;
#[cfg(test)]
mod vote_history_tests;
@@ -668,6 +685,8 @@ mod widget_shapes_tests;
#[cfg(test)]
mod widgets_tests;
#[cfg(test)]
mod page_view_tests;
#[cfg(test)]
mod selection_reorder_tests;
#[cfg(test)]
@@ -0,0 +1,183 @@
//! What a file counts as inserting and detaching a library's styles and variables, as the help
//! center's library analytics page says: applying one, or copying or duplicating content that uses
//! it, inserts it; the Detach button detaches it. Content that is an instance counts as the
//! instance alone, and local styles and variables count nothing. An undo takes its count back.
use serde_json::{Value, json};
use crate::Session;
use crate::components::tests::{ex, idv};
use crate::library_server::{asset_action_reports, asset_actions};
use figcraft_collab::message::MAX_ASSET_USAGE;
use figcraft_doc::{AssetCount, Document, NodeId, NodeKind, PublishedLibrary};
/// A file with a published library holding a paint style, a colour variable and a Card, and a
/// second file that uses it: the second session, the library's id and its keys.
fn user() -> (Session, String, Value) {
let mut a = Session::new();
let r = idv(&ex(&mut a, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40})));
let style = ex(&mut a, "style.create", json!({"type": "paint", "name": "Brand", "from": r.0}));
let coll = ex(&mut a, "variable.createCollection", json!({"name": "Tokens"}));
ex(&mut a, "variable.create", json!({"name": "Accent", "type": "color", "collection": coll["id"], "value": "#0D99FF"}));
let card = idv(&ex(&mut a, "frame.create", json!({"x": 0, "y": 100, "width": 100, "height": 40, "name": "Card"})));
ex(&mut a, "style.apply", json!({"ids": [card.0], "style": style["id"]}));
ex(&mut a, "component.create", json!({"ids": [card.0]}));
ex(&mut a, "library.publish", json!({}));
let lib: PublishedLibrary = a.doc().unwrap().published.as_deref().unwrap().clone();
let path = std::env::temp_dir().join(format!("figcraft-asset-counts-{}-{:?}.figcraft", std::process::id(), std::thread::current().id()));
ex(&mut a, "file.save", json!({"path": path.to_string_lossy()}));
let mut b = Session::new();
let id = ex(&mut b, "library.add", json!({"path": path.to_string_lossy()}))["id"].as_str().unwrap().to_string();
assert_eq!(lib.manifest.id, id);
(b, id, json!({"style": "Brand", "variable": "Accent"}))
}
fn rect(s: &mut Session, x: i32) -> NodeId {
idv(&ex(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 40, "height": 40})))
}
/// (inserted, detached) of the style and of the variable, as `doc` keeps them.
fn counts(s: &Session) -> ((u32, u32), (u32, u32)) {
let of = |key: &str| {
s.doc().unwrap().libraries.asset_counts.iter().find(|c: &&AssetCount| c.key.starts_with(key)).map_or((0, 0), |c| (c.inserted, c.detached))
};
(of("S:"), of("VariableID:"))
}
#[test]
fn applying_counts_once_per_layer_that_takes_it() {
let (mut s, lib, _) = user();
let (one, two) = (rect(&mut s, 0), rect(&mut s, 100));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]}));
assert_eq!(counts(&s).0, (2, 0));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
assert_eq!(counts(&s).0, (2, 0), "a layer that has it already adds nothing");
let three = rect(&mut s, 200);
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [three.0], "field": "fill"}));
assert_eq!(counts(&s).1, (1, 0));
}
#[test]
fn duplicating_and_pasting_content_counts_what_it_uses() {
let (mut s, lib, _) = user();
let one = rect(&mut s, 0);
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
ex(&mut s, "select.set", json!({"ids": [one.0]}));
ex(&mut s, "edit.duplicate", json!({}));
assert_eq!(counts(&s).0, (2, 0), "the copy inserts it too");
ex(&mut s, "select.set", json!({"ids": [one.0]}));
ex(&mut s, "edit.copy", json!({}));
ex(&mut s, "edit.paste", json!({}));
assert_eq!(counts(&s).0, (3, 0));
}
#[test]
fn an_instance_counts_as_its_component_alone() {
let (mut s, lib, _) = user();
let i = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0})));
assert_eq!(counts(&s).0, (0, 0), "placing it");
ex(&mut s, "select.set", json!({"ids": [i.0]}));
ex(&mut s, "edit.duplicate", json!({}));
assert_eq!(counts(&s).0, (0, 0), "duplicating it");
assert_eq!(s.doc().unwrap().libraries.inserted[0].count, 2);
}
/// Applying and detaching a library style or variable on an instance, on a layer in it, or on a
/// layer of an instance nested in it counts nothing either: what an instance uses counts as it.
#[test]
fn applying_and_detaching_inside_an_instance_counts_nothing() {
let (mut s, lib, _) = user();
let placed = idv(&ex(&mut s, "library.place", json!({"library": lib, "component": "Card", "x": 0, "y": 0})));
// A Button holding a rectangle and an Icon instance (the Icon holds a dot), and a Button instance.
let icon = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 24, "height": 24, "name": "Icon"})));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 8, "height": 8, "parent": icon.0}));
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon.0]})));
let button = idv(&ex(&mut s, "frame.create", json!({"x": 100, "y": 200, "width": 80, "height": 40, "name": "Button"})));
ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 80, "height": 40, "parent": button.0}));
ex(&mut s, "instance.create", json!({"component": icon.0, "parent": button.0, "x": 4, "y": 4}));
let button = idv(&ex(&mut s, "component.create", json!({"ids": [button.0]})));
let i = idv(&ex(&mut s, "instance.create", json!({"component": button.0, "x": 300, "y": 200})));
let (layer, nested, deep) = {
let d = s.doc().unwrap();
let kids = |id: NodeId| d.node(id).unwrap().children.clone();
let nested = kids(i).into_iter().find(|k| matches!(d.node(*k).unwrap().kind, NodeKind::Instance { .. })).unwrap();
let layer = kids(i).into_iter().find(|k| *k != nested).unwrap();
(layer, nested, kids(nested)[0])
};
let targets = [placed.0, i.0, layer.0, nested.0, deep.0];
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": targets}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": targets, "field": "stroke"}));
let d = s.doc().unwrap();
assert!(d.node(deep).unwrap().styles.fill.is_some() && !d.node(deep).unwrap().bound.is_empty(), "the nested layer took both");
ex(&mut s, "style.detach", json!({"ids": targets, "which": "fill"}));
ex(&mut s, "variable.bind", json!({"ids": targets, "field": "stroke"}));
assert_eq!(counts(&s), ((0, 0), (0, 0)));
// The same on a plain layer counts.
let plain = rect(&mut s, 600);
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [plain.0]}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [plain.0], "field": "stroke"}));
ex(&mut s, "style.detach", json!({"ids": [plain.0], "which": "fill"}));
ex(&mut s, "variable.bind", json!({"ids": [plain.0], "field": "stroke"}));
assert_eq!(counts(&s), ((1, 1), (1, 1)));
}
#[test]
fn only_the_detach_buttons_detach() {
let (mut s, lib, _) = user();
let (one, two) = (rect(&mut s, 0), rect(&mut s, 100));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0, two.0]}));
ex(&mut s, "library.bindVariable", json!({"library": lib, "variable": "Accent", "ids": [two.0], "field": "stroke"}));
ex(&mut s, "style.detach", json!({"ids": [one.0, two.0], "which": "fill"}));
assert_eq!(counts(&s).0, (2, 2));
ex(&mut s, "variable.bind", json!({"ids": [two.0], "field": "stroke"}));
assert_eq!(counts(&s).1, (1, 1));
// Another style in its place isn't a detach of the first.
let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0}));
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]}));
assert_eq!(counts(&s).0, (3, 2));
}
#[test]
fn local_styles_count_nothing_and_undo_takes_a_count_back() {
let (mut s, lib, _) = user();
let one = rect(&mut s, 0);
let local = ex(&mut s, "style.create", json!({"type": "paint", "name": "Mine", "from": one.0}));
ex(&mut s, "style.apply", json!({"ids": [one.0], "style": local["id"]}));
ex(&mut s, "style.detach", json!({"ids": [one.0], "which": "fill"}));
assert!(s.doc().unwrap().libraries.asset_counts.is_empty());
assert!(asset_actions(s.doc().unwrap(), &lib).is_none());
ex(&mut s, "library.applyStyle", json!({"library": lib, "style": "Brand", "ids": [one.0]}));
let report = asset_actions(s.doc().unwrap(), &lib).unwrap();
assert_eq!((report.inserted.len(), report.detached.len()), (1, 0));
ex(&mut s, "edit.undo", json!({}));
assert_eq!(counts(&s).0, (0, 0));
}
#[test]
fn asset_action_reports_cover_every_count_past_the_message_cap() {
let mut doc = Document::new("File");
let n = MAX_ASSET_USAGE + 1;
let libraries = std::sync::Arc::make_mut(&mut doc.libraries);
for i in 0..n {
let key = format!("s{i}");
libraries.count_asset("Lib", &key, false, 1);
libraries.count_asset("Lib", &key, true, 2);
}
// Another library's counts do not belong in these reports.
libraries.count_asset("Other", "x", false, 9);
libraries.count_asset("Other", "x", true, 9);
let full = asset_actions(&doc, "Lib").unwrap();
assert_eq!(full.inserted.len(), n, "the document's counts are not truncated");
assert_eq!(full.detached.len(), n);
let reports = asset_action_reports(&doc, "Lib");
assert!(reports.len() >= 2, "one message cannot carry {n} counts");
assert!(reports.iter().all(|r| r.file == "File" && r.inserted.len() <= MAX_ASSET_USAGE && r.detached.len() <= MAX_ASSET_USAGE));
let inserted: Vec<_> = reports.iter().flat_map(|r| r.inserted.iter().cloned()).collect();
let detached: Vec<_> = reports.iter().flat_map(|r| r.detached.iter().cloned()).collect();
assert_eq!(inserted, full.inserted);
assert_eq!(detached, full.detached);
assert!(asset_action_reports(&doc, "Missing").is_empty());
}
@@ -0,0 +1,85 @@
//! Styles that reach a file through another library (#2414): a kit's style used by a component of
//! a second library is, in a file linking both, the kit's own bound copy, so a mode set on the kit's
//! collection colours it. Before, the file got a second, unbound copy frozen in the kit's default mode.
use figcraft_doc::*;
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
}
fn id(v: &Value) -> NodeId {
id_of(&v["id"]).unwrap()
}
/// The main component named `name` (a library copy or this file's own).
fn component(s: &Session, name: &str) -> NodeId {
s.doc().unwrap().nodes().find(|n| n.name == name && matches!(n.kind, NodeKind::Component { .. })).unwrap().id
}
/// Publish `s` and save it as `name`.figcraft in `dir`; returns (its path, its library id).
fn publish(s: &mut Session, dir: &std::path::Path, name: &str) -> (String, String) {
let lid = ex(s, "library.publish", json!({}))["id"].as_str().unwrap().to_string();
let path = dir.join(format!("{name}.figcraft")).to_string_lossy().into_owned();
ex(s, "file.saveAs", json!({"path": path}));
(path, lid)
}
#[test]
fn a_kit_style_through_another_library_is_the_kits_bound_copy() {
let dir = std::env::temp_dir().join(format!("figcraft-style-hops-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// kit: a Theme (Light/Brand) colour and a style bound to it, used by "kit-button".
let mut kit = Session::new();
ex(&mut kit, "variable.createCollection", json!({"name": "Theme", "modes": ["Light", "Brand"]}));
ex(
&mut kit,
"variable.create",
json!({"collection": "Theme", "name": "primary", "type": "color", "values": {"Light": "#7B1FA2", "Brand": "#1565C0"}}),
);
let src = id(&ex(&mut kit, "node.create", json!({"type": "rectangle", "x": 0, "y": 200, "width": 40, "height": 40})));
ex(&mut kit, "variable.bind", json!({"ids": [src], "field": "fill", "variable": "primary"}));
ex(&mut kit, "style.create", json!({"type": "paint", "name": "kit/primary", "from": src}));
let c = id(&ex(&mut kit, "node.create", json!({"type": "component", "width": 120, "height": 40, "name": "kit-button"})));
let bg = id(&ex(&mut kit, "node.create", json!({"type": "rectangle", "parent": c, "width": 120, "height": 40, "name": "bg"})));
ex(&mut kit, "style.apply", json!({"ids": [bg], "style": "kit/primary", "target": "fill"}));
let (kit_path, kit_id) = publish(&mut kit, &dir, "kit");
// auth: "auth-button" holds a kit-button.
let mut auth = Session::new();
ex(&mut auth, "library.add", json!({"path": kit_path}));
ex(&mut auth, "library.import", json!({"library": kit_id, "component": "kit-button"}));
let c = id(&ex(&mut auth, "node.create", json!({"type": "component", "width": 200, "height": 40, "name": "auth-button"})));
let main = component(&auth, "kit-button");
ex(&mut auth, "instance.create", json!({"component": main, "parent": c}));
let (auth_path, auth_id) = publish(&mut auth, &dir, "auth");
// app: links both, uses an auth-button in a frame set to the kit's Brand mode.
let mut app = Session::new();
ex(&mut app, "library.add", json!({"path": kit_path}));
ex(&mut app, "library.add", json!({"path": auth_path}));
ex(&mut app, "library.import", json!({"library": kit_id, "component": "kit-button"}));
ex(&mut app, "library.import", json!({"library": auth_id, "component": "auth-button"}));
let f = id(&ex(&mut app, "node.create", json!({"type": "frame", "width": 240, "height": 100, "name": "Brand"})));
ex(&mut app, "library.setVariableMode", json!({"library": kit_id, "collection": "Theme", "mode": "Brand", "ids": [f]}));
let main = component(&app, "auth-button");
ex(&mut app, "instance.create", json!({"component": main, "parent": f}));
let doc = app.doc().unwrap();
let kit_styles: Vec<&Style> = doc.styles.iter().filter(|s| s.name == "kit/primary").collect();
assert_eq!(kit_styles.len(), 1, "one copy of the kit's style: {:?}", kit_styles.iter().map(|s| &s.id).collect::<Vec<_>>());
let style = kit_styles[0];
assert!(doc.libraries.styles.iter().any(|r| r.local == style.id && r.library == kit_id), "it is the kit's copy: {}", style.id);
let var = style.bound.values().next().expect("the copy stays bound");
assert!(doc.libraries.variables.iter().any(|r| r.local == *var && r.library == kit_id), "to the kit's variable: {var}");
// The bg inside the placed auth-button uses it.
let placed: Vec<NodeId> = doc.subtree(f).into_iter().filter(|n| doc.node(*n).is_some_and(|n| n.name == "bg")).collect();
assert_eq!(placed.len(), 1);
assert_eq!(doc.node(placed[0]).unwrap().styles.fill.as_deref(), Some(style.id.as_str()));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -550,3 +550,55 @@ fn stored_variable_ids_keep_library_alias_dependencies() {
assert!(copy.values.values().all(|v| *v == VariableValue::Alias(map.variables[target].clone())));
assert!(dest.variables.collections.iter().any(|c| c.name == "Base"));
}
/// A library with collection `coll` (Main/Alt), a colour variable `var` and a paint style `var`
/// bound to it, published to `path`; returns (the library session, its id).
fn styled_library(path: &str, coll: &str, var: &str, main: &str, alt: &str) -> (Session, String) {
let mut lib = Session::new();
ex(&mut lib, "variable.createCollection", json!({"name": coll, "modes": ["Main", "Alt"]}));
let v = ex(&mut lib, "variable.create", json!({"collection": coll, "name": var, "type": "color", "values": {"Main": main, "Alt": alt}}))["id"]
.clone();
let style = ex(&mut lib, "style.create", json!({"type": "paint", "name": var, "value": main}))["id"].clone();
ex(&mut lib, "style.bind", json!({"style": style, "field": "fill", "variable": v}));
let lid = publish_to(&mut lib, path);
(lib, lid)
}
#[test]
fn accepting_updates_keeps_variables_only_library_styles_use() {
let d = dir("accept-style-vars");
let (pa, pb) = (path_str(&d.join("a.figcraft")), path_str(&d.join("b.figcraft")));
let (mut a, la) = styled_library(&pa, "TokensA", "accent", "#1565c0", "#2e7d32");
let (_b, lb) = styled_library(&pb, "TokensB", "primary", "#7b1fa2", "#00838f");
let mut s = Session::new();
let frame = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 200})));
let ra = idv(&ex(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20, "parent": frame})));
let rb = idv(&ex(&mut s, "shape.rectangle", json!({"x": 50, "y": 10, "width": 20, "height": 20, "parent": frame})));
ex(&mut s, "library.add", json!({"path": pa}));
ex(&mut s, "library.add", json!({"path": pb}));
ex(&mut s, "library.applyStyle", json!({"library": la, "style": "accent", "id": ra}));
ex(&mut s, "library.applyStyle", json!({"library": lb, "style": "primary", "id": rb}));
ex(&mut s, "library.setVariableMode", json!({"library": la, "collection": "TokensA", "mode": "Alt", "ids": [frame]}));
ex(&mut s, "library.setVariableMode", json!({"library": lb, "collection": "TokensB", "mode": "Alt", "ids": [frame]}));
assert_eq!(fill(&s, ra), "2E7D32");
assert_eq!(fill(&s, rb), "00838F");
healthy(&s);
ex(&mut a, "variable.set", json!({"variable": "accent", "mode": "Alt", "value": "#ef6c00"}));
republish(&mut a);
let r = ex(&mut s, "library.acceptUpdates", json!({}));
assert_eq!(r["variables"], 1, "{r}");
let doc = s.doc().unwrap();
for name in ["accent", "primary"] {
let v = doc.variables.variables.iter().find(|v| v.name == name && is_remote_variable(doc, &v.id));
assert!(v.is_some(), "library variable copy `{name}` was deleted");
let id = &v.unwrap().id;
assert!(doc.libraries.variables.iter().any(|r| &r.local == id), "record of `{name}` was deleted");
}
assert_eq!(fill(&s, ra), "EF6C00");
assert_eq!(fill(&s, rb), "00838F");
healthy(&s);
let _ = std::fs::remove_dir_all(&d);
}
+35
View File
@@ -0,0 +1,35 @@
//! Each page keeps its view in a session: going back to a page shows it where it was left, not
//! fitted again (a new page is still fitted); going to the page shown changes nothing.
use serde_json::{Value, json};
use crate::Session;
fn view(s: &mut Session) -> (f64, f64, f64) {
let v: Value = s.execute("view.get", &json!({})).unwrap();
(v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap(), v["zoom"].as_f64().unwrap())
}
#[test]
fn going_back_to_a_page_shows_it_where_it_was_left() {
let mut s = Session::new();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 400, "height": 300})).unwrap();
let first = s.page().unwrap();
s.execute("view.set", &json!({"zoom": 2.5, "cx": 1000, "cy": 500})).unwrap();
let second = crate::params::id_of(&s.execute("page.add", &json!({})).unwrap()["id"]).unwrap();
assert_ne!(view(&mut s), (1000.0, 500.0, 2.5), "a new page is fitted, not shown at the last page's view");
s.execute("shape.ellipse", &json!({"x": 5000, "y": 5000, "width": 100, "height": 100})).unwrap();
s.execute("view.set", &json!({"zoom": 0.5, "cx": -200, "cy": 40})).unwrap();
s.execute("page.select", &json!({"id": first})).unwrap();
assert_eq!(view(&mut s), (1000.0, 500.0, 2.5), "the first page as it was left");
s.execute("view.nextPage", &json!({})).unwrap();
assert_eq!(s.page().unwrap(), second);
assert_eq!(view(&mut s), (-200.0, 40.0, 0.5), "the second page as it was left");
// The page shown: nothing moves.
s.execute("view.set", &json!({"zoom": 3.0, "cx": 7, "cy": 8})).unwrap();
s.execute("page.select", &json!({"id": second})).unwrap();
assert_eq!(view(&mut s), (7.0, 8.0, 3.0));
s.execute("view.prevPage", &json!({})).unwrap();
assert_eq!(view(&mut s), (1000.0, 500.0, 2.5));
}
+122
View File
@@ -0,0 +1,122 @@
//! Cmd/Ctrl+V with one layer inside a frame selected pastes next to it, in its parent (#2355).
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use figcraft_doc::NodeId;
fn id(v: &Value) -> NodeId {
id_of(&v["id"]).unwrap()
}
fn sess() -> Session {
Session::new()
}
fn rect(s: &mut Session, parent: Option<NodeId>, x: f64, y: f64) -> NodeId {
let mut p = json!({"x": x, "y": y, "width": 40, "height": 20});
if let Some(parent) = parent {
p["parent"] = json!(parent);
}
id(&s.execute("shape.rectangle", &p).unwrap())
}
fn kids(s: &Session, parent: NodeId) -> Vec<NodeId> {
s.doc().unwrap().node(parent).unwrap().children.clone()
}
fn parent_of(s: &Session, n: NodeId) -> Option<NodeId> {
s.doc().unwrap().node(n).unwrap().parent
}
fn paste(s: &mut Session) -> Vec<NodeId> {
s.execute("edit.paste", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect()
}
#[test]
fn paste_with_a_layer_in_an_auto_layout_frame_selected_goes_right_after_it() {
let mut s = sess();
let a = rect(&mut s, None, 0.0, 0.0);
let b = rect(&mut s, None, 0.0, 30.0);
let r = s.execute("layout.add", &json!({"ids": [a, b], "direction": "vertical"})).unwrap();
let frame = id_of(&r["ids"][0]).unwrap();
s.execute("node.set", &json!({"id": frame, "props": {"gap": 10}})).unwrap();
let h0 = s.doc().unwrap().node(frame).unwrap().height;
assert_eq!(h0, 50.0);
assert_eq!(kids(&s, frame), vec![a, b]);
s.set_selection(vec![b]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(pasted.len(), 1);
assert_eq!(parent_of(&s, pasted[0]), Some(frame), "the copy joins the selected layer's frame");
assert_eq!(kids(&s, frame), vec![a, b, pasted[0]], "right after the selected layer in the flow");
assert_eq!(s.doc().unwrap().node(frame).unwrap().height, h0 + 20.0 + 10.0, "the frame grew by the copy's height plus the gap");
assert_eq!(s.selection(), pasted);
}
#[test]
fn paste_with_a_layer_in_a_plain_frame_selected_stays_in_the_frame_in_place() {
let mut s = sess();
let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap());
let a = rect(&mut s, Some(frame), 10.0, 10.0);
let b = rect(&mut s, Some(frame), 100.0, 100.0);
s.set_selection(vec![a]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(pasted.len(), 1);
assert_eq!(parent_of(&s, pasted[0]), Some(frame));
assert_eq!(kids(&s, frame), vec![a, pasted[0], b], "just above the selected layer");
let wb = s.doc().unwrap().world_bounds(pasted[0]).unwrap();
assert_eq!((wb.x0, wb.y0), (10.0, 10.0), "at the selected layer's position");
assert_eq!(s.selection(), pasted);
}
#[test]
fn paste_with_a_top_level_layer_selected_is_unchanged() {
let mut s = sess();
let a = rect(&mut s, None, 10.0, 10.0);
let page = parent_of(&s, a).unwrap();
let before = kids(&s, page);
s.set_selection(vec![a]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(parent_of(&s, pasted[0]), Some(page));
let mut want = before;
want.push(pasted[0]);
assert_eq!(kids(&s, page), want, "on the page, on top, as before");
}
#[test]
fn paste_with_two_layers_selected_is_unchanged() {
let mut s = sess();
let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap());
let a = rect(&mut s, Some(frame), 10.0, 10.0);
let b = rect(&mut s, Some(frame), 100.0, 100.0);
let page = parent_of(&s, frame).unwrap();
s.set_selection(vec![a, b]);
s.execute("edit.copy", &json!({})).unwrap();
let pasted = paste(&mut s);
assert_eq!(pasted.len(), 2);
assert!(pasted.iter().all(|p| parent_of(&s, *p) == Some(page)), "on the page, as before");
assert_eq!(kids(&s, frame), vec![a, b]);
}
#[test]
fn paste_with_a_layer_inside_an_instance_selected_is_unchanged() {
let mut s = sess();
let f = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Button"})).unwrap());
s.execute("text.create", &json!({"text": "OK", "x": 10, "y": 10, "parent": f})).unwrap();
let c = id(&s.execute("component.create", &json!({"ids": [f]})).unwrap());
let inst = id(&s.execute("instance.create", &json!({"component": c, "x": 200, "y": 0})).unwrap());
let page = parent_of(&s, inst).unwrap();
let inner = kids(&s, inst)[0];
let inner_kids = kids(&s, inst);
let other = rect(&mut s, None, 500.0, 500.0);
s.set_selection(vec![other]);
s.execute("edit.copy", &json!({})).unwrap();
s.set_selection(vec![inner]);
let pasted = paste(&mut s);
assert_eq!(parent_of(&s, pasted[0]), Some(page), "an instance's children are fixed: the copy goes to the page");
assert_eq!(kids(&s, inst), inner_kids);
}
+55
View File
@@ -0,0 +1,55 @@
//! Shift with the Pencil draws one straight segment from where the stroke started, at the nearest
//! 45° step, as the Line tool and the Pen keep theirs (#2447).
use serde_json::json;
use crate::Session;
use crate::tools::{PointerEvent, PointerKind};
use figcraft_doc::NodeKind;
fn ev(kind: PointerKind, x: f64, y: f64, shift: bool) -> PointerEvent {
PointerEvent { shift, ..PointerEvent::at(kind, x, y, 1.0) }
}
/// Draws a wobbly stroke from (0, 0) to `end`, Shift held throughout or not, and returns the
/// stroke's size.
fn stroke(shift: bool, end: (f64, f64)) -> (f64, f64) {
let mut s = Session::new();
s.execute("tool.set", &json!({"tool": "pencil"})).unwrap();
s.pointer(&ev(PointerKind::Down, 0.0, 0.0, shift)).unwrap();
for i in 1..=20 {
let t = f64::from(i) / 20.0;
s.pointer(&ev(PointerKind::Move, end.0 * t, end.1 * t + (t * 9.0).sin() * 6.0, shift)).unwrap();
}
if shift {
assert_eq!(s.tool.overlay.pen.len(), 2, "the preview is one segment: {:?}", s.tool.overlay.pen);
}
s.pointer(&ev(PointerKind::Up, end.0, end.1, shift)).unwrap();
let doc = s.doc().unwrap();
let n = doc.nodes().find(|n| matches!(n.kind, NodeKind::Vector { .. })).expect("a pencil stroke");
let b = doc.world_bounds(n.id).unwrap();
(b.width(), b.height())
}
#[test]
fn shift_keeps_a_pencil_stroke_straight_at_45_degree_steps() {
// Nearly level: level, as long as the pointer is far from the start.
let (w, h) = stroke(true, (100.0, 12.0));
assert!((w - 100.0_f64.hypot(12.0)).abs() < 0.5 && h < 0.5, "{w} x {h}");
// Nearly diagonal: at 45°.
let (w, h) = stroke(true, (80.0, 70.0));
assert!((w - h).abs() < 0.5 && (w.hypot(h) - 80.0_f64.hypot(70.0)).abs() < 0.5, "{w} x {h}");
// Without Shift the stroke follows the pointer.
let (_, h) = stroke(false, (100.0, 12.0));
assert!(h > 12.0, "{h}");
}
#[test]
fn a_shift_click_with_the_pencil_draws_nothing() {
let mut s = Session::new();
s.execute("tool.set", &json!({"tool": "pencil"})).unwrap();
let before = s.doc().unwrap().nodes().count();
s.pointer(&ev(PointerKind::Down, 10.0, 10.0, true)).unwrap();
s.pointer(&ev(PointerKind::Up, 10.0, 10.0, true)).unwrap();
assert_eq!(s.doc().unwrap().nodes().count(), before);
}
@@ -108,6 +108,42 @@ fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v
}
#[test]
fn clicking_a_device_background_after_its_nested_button_selects_the_device() {
let mut s = Session::new();
let device = id(&ex(&mut s, "frame.create", json!({"x": 132, "y": -148, "width": 440, "height": 956})));
let button = id(&ex(&mut s, "frame.create", json!({"parent": device, "x": 155, "y": 30, "width": 130, "height": 34})));
rect(&mut s, 10.0, 5.0, Some(button));
ex(&mut s, "layout.add", json!({"ids": [button], "direction": "horizontal"}));
ex(&mut s, "select.set", json!({"ids": [button]}));
let before = s.doc().unwrap().clone();
let history = s.undo_depth();
s.pointer(&ev(PointerKind::Down, 352.0, 330.0, NONE)).unwrap();
assert_eq!(s.selection(), vec![device], "the parent is selected on press");
// Small pointer jitter must not turn the click into a zero-sized marquee.
s.pointer(&ev(PointerKind::Move, 353.0, 330.0, NONE)).unwrap();
s.pointer(&ev(PointerKind::Up, 353.0, 330.0, NONE)).unwrap();
s.pointer(&ev(PointerKind::Hover, 353.0, 330.0, NONE)).unwrap();
assert_eq!(s.selection(), vec![device], "the parent stays selected after release and hover");
assert_eq!(*s.doc().unwrap(), before);
assert_eq!(s.undo_depth(), history, "selection adds no edit history");
}
#[test]
fn dragging_a_device_background_after_its_child_still_marquees_and_closes_cleanly() {
let mut s = Session::new();
let k = scene(&mut s);
ex(&mut s, "select.set", json!({"ids": [k.d]}));
drag(&mut s, (390.0, 290.0), (190.0, 10.0), NONE);
assert_eq!(s.selection(), vec![k.n], "a background drag selects the nested frame");
assert!(s.ds().unwrap().interaction.is_none(), "a marquee leaves no move snapshot behind");
ex(&mut s, "node.set", json!({"id": k.n, "props": {"opacity": 0.5}}));
click(&mut s, 30.0, 130.0, NONE);
assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 0.5, "the next click keeps the edit");
ex(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc().unwrap().node(k.n).unwrap().opacity, 1.0, "the edit retains its undo step");
}
#[test]
fn clicking_selects_by_the_documented_rules() {
let mut s = Session::new();
@@ -130,6 +166,9 @@ fn clicking_selects_by_the_documented_rules() {
((520.0, 120.0), NONE, vec![], vec![k.r2], "a locked layer can't be selected on the canvas: the click goes to what is under it"),
((520.0, 220.0), NONE, vec![k.r], vec![], "a hidden layer can't be selected on the canvas (empty canvas deselects)"),
((390.0, 290.0), NONE, vec![k.r], vec![], "the background of a top-level frame with layers is like the canvas: a click deselects"),
((390.0, 290.0), NONE, vec![k.c], vec![k.f], "clicking the containing frame's background steps out from its child"),
((390.0, 290.0), NONE, vec![k.d], vec![k.f], "stepping out works from a deeper descendant too"),
((390.0, 290.0), NONE, vec![], vec![], "without a selected descendant the background remains canvas-like"),
((390.0, 290.0), NONE, vec![k.f], vec![k.f], "a selected top-level frame stays selected when its background is clicked"),
((390.0, 290.0), CMD, vec![], vec![k.f], "silent: Cmd/Ctrl-click on a frame's background selects the frame (the deepest layer there)"),
((640.0, 40.0), NONE, vec![], vec![k.empty], "an empty top-level frame is selected by a click on it"),
@@ -523,3 +562,71 @@ fn shift_click_takes_a_layer_out_where_nothing_can_move() {
s.pointer(&ev(PointerKind::Up, 520.0, 20.0, SHIFT)).unwrap();
assert_eq!(s.selection(), vec![k.empty], "Shift-click still takes the layer out");
}
/// A top-level 300 x 300 frame with a filled 100 x 100 rectangle at (50, 50) and a nested 100 x 100
/// frame at (180, 180) holding a 40 x 40 rectangle at (200, 200).
fn frame_with_child(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
let f = id(&ex(s, "frame.create", json!({"x": 0, "y": 0, "width": 300, "height": 300})));
let c = id(&ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": f})));
let n = id(&ex(s, "frame.create", json!({"x": 180, "y": 180, "width": 100, "height": 100, "parent": f})));
let gc = id(&ex(s, "shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 40, "parent": n})));
(f, c, n, gc)
}
#[test]
fn a_drag_from_a_child_of_a_selected_frame_moves_the_frame() {
let mut s = Session::new();
let (f, c, _n, gc) = frame_with_child(&mut s);
let sib = id(&ex(&mut s, "shape.rectangle", json!({"x": 90, "y": 90, "width": 30, "height": 30})));
let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap().origin();
let local = |s: &Session, i: NodeId| {
let d = s.doc().unwrap();
let n = d.node(i).unwrap();
let c = n.transform.as_coeffs();
(c[4], c[5])
};
let c_local = local(&s, c);
// (selection before, press point, modifiers, selection after, the layers that move by (10, 10), derivation)
let rows: Vec<(Vec<NodeId>, (f64, f64), Mods, Vec<NodeId>, Vec<NodeId>, &str)> = vec![
(vec![f], (60.0, 60.0), NONE, vec![f], vec![f, c, gc], "a drag from a child of the selected frame moves the frame"),
(vec![f], (220.0, 220.0), NONE, vec![f], vec![f, c, gc], "a drag from a grandchild moves the top-level frame"),
(vec![], (60.0, 60.0), NONE, vec![c], vec![c], "with nothing selected the child is picked and moved"),
(vec![f], (60.0, 60.0), CMD, vec![c], vec![c], "Cmd picks the deepest layer and moves it"),
(vec![f], (100.0, 100.0), NONE, vec![sib], vec![sib], "a sibling painted above the frame takes the press"),
];
for (before, from, m, after, moved, why) in rows {
let all = [f, c, gc, sib];
let home: Vec<Point> = all.iter().map(|i| at(&s, *i)).collect();
ex(&mut s, "select.set", json!({"ids": before}));
drag(&mut s, from, (from.0 + 10.0, from.1 + 10.0), m);
assert_eq!(sorted(s.selection()), sorted(after), "{why}");
for (i, h) in all.iter().zip(&home) {
// The frame carries its children: they move in the world, not in their local space.
let d = if moved.contains(i) { 10.0 } else { 0.0 };
assert_eq!(at(&s, *i), Point::new(h.x + d, h.y + d), "{why}");
}
assert_eq!(local(&s, c), if moved == [c] { (c_local.0 + 10.0, c_local.1 + 10.0) } else { c_local }, "{why}: the child's local position");
assert!(s.undo().unwrap(), "{why}: one undo step");
for (i, h) in all.iter().zip(&home) {
assert_eq!(at(&s, *i), *h, "{why}: undo restores");
}
}
}
#[test]
fn a_click_on_a_child_of_a_selected_frame_selects_the_child() {
let mut s = Session::new();
let (f, c, n, gc) = frame_with_child(&mut s);
let home = s.doc().unwrap().world_bounds(c).unwrap().origin();
for (p, want) in [((60.0, 60.0), c), ((190.0, 190.0), n)] {
ex(&mut s, "select.set", json!({"ids": [f]}));
click(&mut s, p.0, p.1, NONE);
assert_eq!(s.selection(), vec![want], "a click selects the layer inside the selected frame");
}
assert_eq!(s.doc().unwrap().world_bounds(c).unwrap().origin(), home, "nothing moved");
let _ = gc;
s.tool.dev_mode = true;
ex(&mut s, "select.set", json!({"ids": [f]}));
click(&mut s, 60.0, 60.0, NONE);
assert_eq!(s.selection(), vec![c], "in Dev Mode too");
}
@@ -571,6 +571,42 @@ fn outline_stroke_outlines_every_selected_layer() {
}
}
#[test]
fn outline_stroke_outlines_a_text_without_a_stroke() {
// Fixed (#2405): a fill-only text was left as it was; its glyphs become a vector filled as the text was.
let mut s = Session::new();
let t = create(&mut s, "text.create", json!({"text": "OPEN", "x": 10, "y": 20}));
ex(&mut s, "style.create", json!({"type": "paint", "name": "Ink", "value": ["#112233"]}));
ex(&mut s, "style.apply", json!({"ids": [t], "style": "Ink"}));
let before = node(&s, t);
let page = s.page().unwrap();
let out = ex(&mut s, "vector.outlineStroke", json!({"ids": [t]}));
let ids: Vec<NodeId> = out["ids"].as_array().unwrap().iter().filter_map(id_of).collect();
// Without a font nothing lays out, so there is nothing to outline.
if !figcraft_text::layout_node(&before).is_some_and(|(l, _)| !l.glyphs.is_empty()) {
assert!(ids.is_empty() && matches!(node(&s, t).kind, NodeKind::Text(_)), "no glyphs: the text stays: {out}");
return;
}
assert_eq!(ids.len(), 1, "one outline: {out}");
let v = node(&s, ids[0]);
assert!(matches!(v.kind, NodeKind::Vector { .. }), "the glyphs become a vector");
assert_eq!((&v.fills, v.styles.fill), (&before.fills, before.styles.fill), "filled as the text was, colour style too");
assert_eq!(s.doc().unwrap().node(page).unwrap().children, ids, "the outline stands in for the text");
assert_eq!(s.selection(), ids, "the outline is selected");
s.undo().unwrap();
assert!(matches!(node(&s, t).kind, NodeKind::Text(_)), "undo brings the text back");
}
#[test]
fn outline_stroke_leaves_an_empty_text_as_it_is() {
// An empty text has no glyphs to outline: it stays, and nothing else changes.
let mut s = Session::new();
let t = create(&mut s, "text.create", json!({"text": "", "x": 10, "y": 20}));
let out = ex(&mut s, "vector.outlineStroke", json!({"ids": [t]}));
assert_eq!(out["ids"], json!([]), "nothing outlined: {out}");
assert!(matches!(node(&s, t).kind, NodeKind::Text(_)), "the text stays");
}
#[test]
fn node_set_non_numeric_miter_smoothing_paragraph_is_an_error() {
let mut s = Session::new();
@@ -98,10 +98,13 @@ fn library(w: &mut Wire, req: LibraryReq) -> LibraryReply {
LibraryReply::Published { version: 1 }
}
(LibraryReq::Usage, _) => LibraryReply::Usage(Vec::new()),
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_), _) => LibraryReply::Noted,
(LibraryReq::ReportDetached(_) | LibraryReq::ReportInserted(_) | LibraryReq::ReportAssets(_) | LibraryReq::ReportAssetActions(_), _) => {
LibraryReply::Noted
}
(LibraryReq::Detached, _) => LibraryReply::Detached(Vec::new()),
(LibraryReq::Actions, _) => LibraryReply::Actions(Vec::new()),
(LibraryReq::Assets, _) => LibraryReply::Assets(Vec::new()),
(LibraryReq::AssetActions, _) => LibraryReply::AssetActions(Vec::new()),
}
}
@@ -0,0 +1,58 @@
//! A set's component properties belong to all its variants, as `component.addProperty` on a set
//! gives them: one made on a component before it was combined goes to every variant, so another
//! variant's layer can be bound to it and an instance switched to that variant keeps its value.
use serde_json::{Value, json};
use crate::Session;
use crate::components::tests::{ex, healthy, idv};
use figcraft_doc::NodeId;
/// A main component named `name` at `x`, made from a 120×40 frame holding a "Button" text: the
/// component and the text.
fn component(s: &mut Session, name: &str, x: f64) -> (NodeId, NodeId) {
let f = idv(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 120, "height": 40, "name": name})));
let t = idv(&ex(s, "text.create", json!({"text": "Button", "x": 8, "y": 8, "parent": f})));
(idv(&ex(s, "component.create", json!({"ids": [f]}))), t)
}
/// `id`'s component property `name` as `component.properties` lists it.
fn property(s: &mut Session, id: NodeId, name: &str) -> Option<Value> {
let all = ex(s, "component.properties", json!({"id": id}));
all["properties"].as_array().and_then(|l| l.iter().find(|p| p["name"] == name).cloned())
}
#[test]
fn a_property_made_before_combining_goes_to_every_variant() {
let mut s = Session::new();
let (a, label) = component(&mut s, "State=Default", 0.0);
let (b, b_label) = component(&mut s, "State=Hover", 200.0);
ex(&mut s, "component.addProperty", json!({"id": a, "name": "Text", "type": "text", "layer": label}));
let of_b = idv(&ex(&mut s, "instance.create", json!({"component": b, "x": 0, "y": 300})));
ex(&mut s, "component.combineVariants", json!({"ids": [a, b]}));
healthy(&s);
let shared = property(&mut s, b, "Text").expect("the other variant has the property");
assert_eq!((shared["type"].clone(), shared["default"].clone()), (json!("text"), json!("Button")));
// The other variant's text can be bound to it, and its instance then shows the default.
ex(&mut s, "component.bindProperty", json!({"layer": b_label, "property": "Text"}));
assert_eq!(property(&mut s, of_b, "Text").map(|p| p["value"].clone()), Some(json!("Button")));
// An instance switched to the other variant keeps the value it was given.
let of_a = idv(&ex(&mut s, "instance.create", json!({"component": a, "x": 200, "y": 300})));
ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"Text": "Buy"}}));
ex(&mut s, "instance.setProperties", json!({"ids": [of_a], "properties": {"State": "Hover"}}));
assert_eq!(property(&mut s, of_a, "Text").map(|p| p["value"].clone()), Some(json!("Buy")));
healthy(&s);
}
#[test]
fn a_variant_keeps_its_own_property_of_the_same_name() {
let mut s = Session::new();
let (a, _) = component(&mut s, "State=Default", 0.0);
let (b, _) = component(&mut s, "State=Hover", 200.0);
ex(&mut s, "component.addProperty", json!({"id": a, "name": "Icon", "type": "text", "default": "Star"}));
ex(&mut s, "component.addProperty", json!({"id": b, "name": "Icon", "type": "boolean", "default": false}));
ex(&mut s, "component.combineVariants", json!({"ids": [a, b]}));
healthy(&s);
assert_eq!(property(&mut s, a, "Icon").map(|p| p["type"].clone()), Some(json!("text")));
assert_eq!(property(&mut s, b, "Icon").map(|p| p["type"].clone()), Some(json!("boolean")));
}
+50
View File
@@ -0,0 +1,50 @@
//! Canvas auto-pan (#2015): the speed a drag held near the viewport's edge pans the view at, as
//! measured in the incumbent at 100% (screen px per second, `40 x (15 - d)` clamped to 0..600,
//! `d` the pointer's distance inside the edge), and which gestures pan.
use crate::ViewState;
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn the_speed_grows_40_px_per_second_for_each_px_inside_the_zone_up_to_600() {
for (d, speed) in [(40.0, 0.0), (25.0, 0.0), (15.0, 0.0), (12.0, 120.0), (8.0, 280.0), (2.0, 520.0), (0.0, 600.0), (-30.0, 600.0)] {
assert!(near(ViewState::autopan_speed(d), speed), "{d} px inside: {} px/s, wanted {speed}", ViewState::autopan_speed(d));
}
assert_eq!(ViewState::autopan_speed(f64::NAN), 0.0);
assert!(near(ViewState::autopan_speed(f64::NEG_INFINITY), 600.0));
}
#[test]
fn the_velocity_points_toward_the_near_edge_on_each_axis() {
let (w, h) = (1000.0, 600.0);
let v = |x: f64, y: f64| ViewState::autopan_velocity(x, y, w, h);
assert_eq!(v(500.0, 300.0), (0.0, 0.0), "the middle");
assert_eq!(v(1000.0 - 2.0, 300.0), (520.0, 0.0), "right edge: right");
assert_eq!(v(2.0, 300.0), (-520.0, 0.0), "left edge: left");
assert_eq!(v(500.0, 600.0 - 8.0), (0.0, 280.0), "bottom edge: down");
assert_eq!(v(500.0, 12.0), (0.0, -120.0), "top edge: up");
assert_eq!(v(1000.0 - 40.0, 300.0), (0.0, 0.0), "40 px in: none");
assert_eq!(v(1000.0 - 15.0, 300.0), (0.0, 0.0), "15 px in: none");
// A corner pans on both axes, each by its own distance.
assert_eq!(v(1000.0 - 12.0, 600.0 - 2.0), (120.0, 520.0));
assert_eq!(v(8.0, 2.0), (-280.0, -520.0));
// Past the edge, or outside the viewport altogether: the cap.
assert_eq!(v(1030.0, 300.0), (600.0, 0.0));
assert_eq!(v(-500.0, 900.0), (-600.0, 600.0));
}
#[test]
fn panning_moves_the_view_by_the_velocity_in_screen_px_at_any_zoom() {
for zoom in [0.25, 1.0, 4.0] {
let mut v = ViewState { vw: 1000.0, vh: 600.0, zoom, cx: 50.0, cy: 70.0, ..Default::default() };
assert!(v.autopan(998.0, 300.0, 0.5), "in the zone");
assert!(near((v.cx - 50.0) * zoom, 260.0), "{zoom}: 520 px/s for half a second is 260 screen px");
assert_eq!(v.cy, 70.0);
assert!(!v.autopan(500.0, 300.0, 0.5), "out of the zone");
assert!(!v.autopan(998.0, 300.0, 0.0), "no time");
assert!(!v.autopan(998.0, 300.0, f64::NAN), "no time");
}
}
+38
View File
@@ -159,6 +159,44 @@ impl ViewState {
self.cx -= dx / z;
self.cy -= dy / z;
}
/// How near the viewport's edge a drag must hold the pointer to pan the canvas (screen px).
pub const AUTOPAN_ZONE_PX: f64 = 15.0;
/// Auto-pan speed gained for each pixel the pointer is closer to the edge (screen px/s).
pub const AUTOPAN_RATE: f64 = 40.0;
/// The fastest auto-pan, at the edge and beyond it (screen px/s).
pub const AUTOPAN_MAX: f64 = 600.0;
/// The speed (screen px/s) the canvas pans toward an edge while a drag holds the pointer
/// `d` px inside it (negative: outside), as measured in the incumbent: `40 x (15 - d)`
/// clamped to 0..600 (#2015). Constant while the pointer stays put, at every zoom.
pub fn autopan_speed(d: f64) -> f64 {
if d.is_nan() {
return 0.0;
}
(Self::AUTOPAN_RATE * (Self::AUTOPAN_ZONE_PX - d)).clamp(0.0, Self::AUTOPAN_MAX)
}
/// The velocity (screen px/s, positive: right and down) the canvas auto-pans at while a drag
/// holds the pointer at (`px`, `py`) in a viewport of `width` x `height` (both from its
/// top-left corner): toward each edge the pointer is near, each axis by its own distance, so a
/// corner pans both ways.
pub fn autopan_velocity(px: f64, py: f64, width: f64, height: f64) -> (f64, f64) {
let axis = |p: f64, len: f64| {
if p < len / 2.0 { -Self::autopan_speed(p) } else { Self::autopan_speed(len - p) }
};
(axis(px, width), axis(py, height))
}
/// Auto-pan for `dt` seconds with the pointer at (`px`, `py`) from the viewport's top-left
/// corner: moves the view by the velocity ([`Self::autopan_velocity`]) in screen px. True when
/// it moved.
pub fn autopan(&mut self, px: f64, py: f64, dt: f64) -> bool {
let (vx, vy) = Self::autopan_velocity(px, py, self.vw, self.vh);
if !(dt.is_finite() && dt > 0.0) || (vx == 0.0 && vy == 0.0) {
return false;
}
let z = self.zoom.max(1e-6);
self.cx += vx * dt / z;
self.cy += vy * dt / z;
true
}
pub fn page_to_screen(&self, x: f64, y: f64) -> (f64, f64) {
let (ox, oy) = self.origin();
((x - ox) * self.zoom, (y - oy) * self.zoom)
Loaded 100 of 232 files, more files were not shown because too many files have changed in this diff. Show more