diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..6917bde73 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,29 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ci.yml': [] + '.github/workflows/freebsd.yml': [] + '.github/workflows/house-rules.yml': [] + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nix.yml': [] + '.github/workflows/packaging-lint.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/release.yml': [] + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/windows-arm64.yml': [] +dependencies: + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 000000000..e630c9a8f --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 0a91cc050..f442059bb 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -30,10 +30,10 @@ jobs: runs-on: windows-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Install the pinned packaging toolchain diff --git a/AGENTS.md b/AGENTS.md index e63e92c7c..cc4ea91e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ inspection. It runs natively on macOS, Windows, Linux and FreeBSD, and in the br Siblings: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop-class), `../designcraft` (InDesign-class) and the other Crafting Apps; same conventions. -Repos don't share code. +Share reusable code through craft-libs; do not depend on sibling application crates. ## Start every session here 1. Read [`ROADMAP.md`](ROADMAP.md) (stage, headline numbers, estimates) and @@ -182,3 +182,7 @@ commit. Grade by behaviour against the incumbent, not by whether a menu item exi - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +## Shared Craft libraries + +Before adding or changing reusable file-format, codec, protocol or UI code, check [craft-libs](https://github.com/storytold/craft-libs) and existing contributor work; reuse its public APIs or extend the appropriate shared library instead of adding an app-local duplicate, keeping app-specific policy and model mapping local and preserving compatibility, security limits and regression coverage. diff --git a/Cargo.lock b/Cargo.lock index d6d010579..a2e846d04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 05aa2d393..95cfc2a23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/ROADMAP.md b/ROADMAP.md index fa01afc21..2286b0c6e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents) -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-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 | diff --git a/apps/figcraft-cli/src/args.rs b/apps/figcraft-cli/src/args.rs index 4696b8664..b8372ece4 100644 --- a/apps/figcraft-cli/src/args.rs +++ b/apps/figcraft-cli/src/args.rs @@ -316,7 +316,10 @@ fn whole_number(s: &str) -> Result { /// `mcp --attach`: `host:port` as given, or a bare port on 127.0.0.1. fn attach(s: &str) -> Result { - if s.contains(':') { + if let Some((host, port)) = s.rsplit_once(':') { + if host.is_empty() || port.parse::().is_err() { + return Err(ValueError::Attach); + } return Ok(s.to_owned()); } let port: u16 = s.parse().map_err(|_| ValueError::Attach)?; @@ -461,6 +464,12 @@ mod tests { assert_eq!(a.attach.as_deref(), Some("127.0.0.1:7979")); let Command::Mcp(a) = ok(&["mcp", "--attach=localhost:7979"]) else { panic!("mcp") }; assert_eq!(a.attach.as_deref(), Some("localhost:7979")); + for address in ["127.0.0.1:7979", "[::1]:7979", "[fe80::1%3]:7979", "localhost:0"] { + let Command::Mcp(a) = ok(&["mcp", "--attach", address]) else { panic!("mcp") }; + assert_eq!(a.attach.as_deref(), Some(address)); + } + let Command::Mcp(a) = ok(&["mcp", "--attach", "0"]) else { panic!("mcp") }; + assert_eq!(a.attach.as_deref(), Some("127.0.0.1:0")); let Command::Mcp(a) = ok(&["mcp", "--attach", "7979", "--timeout", "300"]) else { panic!("mcp") }; assert_eq!(a.timeout, Some(300)); let Command::Mcp(a) = ok(&["mcp", "--automation-read-root", "in", "--automation-write-root", "out"]) else { panic!("mcp") }; @@ -514,6 +523,11 @@ mod tests { (&["perf", "--layers", "10,x"], ValueValidation), (&["perf", "--layers", "10", "--layers", "20"], ArgumentConflict), (&["mcp", "--attach", "notaport"], ValueValidation), + (&["mcp", "--attach", ":7979"], ValueValidation), + (&["mcp", "--attach", "localhost:"], ValueValidation), + (&["mcp", "--attach", "localhost:notaport"], ValueValidation), + (&["mcp", "--attach", "localhost:65536"], ValueValidation), + (&["mcp", "--attach", "[::1]"], ValueValidation), (&["mcp", "--attach", "7979", "--timeout", "0"], ValueValidation), (&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation), (&["mcp", "--timeout", "300"], MissingRequiredArgument), @@ -543,6 +557,7 @@ mod tests { &["export", "x.figcraft", "-o", "out", "--help"], &["export", "-o", "--help"], &["mcp", "--attach", "notaport", "--help"], + &["mcp", "--attach", "localhost:notaport", "--help"], &["mcp", "--bogus", "-h"], &["--no-system-fonts", "plugin", "publish", "--bogus", "--help"], ] { diff --git a/apps/figcraft-cli/src/files.rs b/apps/figcraft-cli/src/files.rs index 165057086..5f4a006f4 100644 --- a/apps/figcraft-cli/src/files.rs +++ b/apps/figcraft-cli/src/files.rs @@ -12,7 +12,7 @@ use crate::{CliError, CliResult}; /// A document's or plugin's text as a terminal should show it: control characters escaped, and /// everything else (quotes, backslashes in paths) left as it is. -fn plain(text: &str) -> String { +pub(crate) fn plain(text: &str) -> String { text.chars().map(|c| if c.is_control() { c.escape_default().to_string() } else { c.to_string() }).collect() } @@ -242,7 +242,10 @@ pub fn info(path: &str, as_json: bool) -> CliResult { fn sanitize(name: &str) -> String { let s = figcraft_engine::cmd::file::safe_file_name(name); let s = s.trim_matches(|c: char| c == '.' || c.is_whitespace()); - if s.is_empty() { "layer".into() } else { s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect() } + let cap = |s: &str| s.char_indices().take(100).take_while(|(i, c)| i + c.len_utf8() <= 200).map(|(_, c)| c).collect::(); + // Truncation can expose a device name; its escape must still fit the limits. + let s = figcraft_engine::file_access::escape_device_names(&cap(s)); + if s.is_empty() { "layer".into() } else { cap(&s) } } /// What `export` exports and how. @@ -543,6 +546,10 @@ mod tests { assert_eq!(sanitize("Home / Hero"), "Home _ Hero"); assert_eq!(sanitize("../.."), "_"); assert_eq!(sanitize(""), "layer"); + assert_eq!(sanitize("CON"), "_CON"); + assert_eq!(sanitize(" .nul.txt. "), "_nul.txt"); + assert_eq!(sanitize("COM1"), "_COM1"); + assert_eq!(sanitize("HomeCON"), "HomeCON"); // The same characters the app's export keeps (#1154): only what file systems refuse goes. assert_eq!(sanitize("Homepage - desktop (live + verbeteringen)"), "Homepage - desktop (live + verbeteringen)"); assert_eq!(sanitize("Q&A, 50% #1 [v2] {x} ~é"), "Q&A, 50% #1 [v2] {x} ~é"); @@ -553,6 +560,16 @@ mod tests { assert_eq!(sanitize(&"\u{1F600}".repeat(100)), "\u{1F600}".repeat(50), "at most 200 bytes, whole characters"); } + #[test] + fn sanitizes_names_that_become_devices_at_the_character_limit() { + assert_eq!(sanitize(&format!("CON{}X", " ".repeat(97))), format!("_CON{}", " ".repeat(96))); + } + + #[test] + fn sanitizes_names_that_become_devices_at_the_byte_limit() { + assert_eq!(sanitize(&format!("NUL{} X", "\u{2003}".repeat(65))), format!("_NUL{} ", "\u{2003}".repeat(65))); + } + #[test] fn default_page_skips_leading_divider() { let mut doc = Document::new("divider"); diff --git a/apps/figcraft-cli/src/main.rs b/apps/figcraft-cli/src/main.rs index 2d3596bca..44bdd4520 100644 --- a/apps/figcraft-cli/src/main.rs +++ b/apps/figcraft-cli/src/main.rs @@ -38,14 +38,15 @@ fn main() -> ExitCode { return ExitCode::from(u8::try_from(e.exit_code()).unwrap_or(2)); } }; + // Paths and imported/plugin errors may carry terminal controls; keep diagnostics printable. match run(cli) { Ok(code) => code, Err(CliError::Usage(msg)) => { - eprintln!("error: {msg}\n\nFor more information, try '--help'."); + eprintln!("error: {}\n\nFor more information, try '--help'.", files::plain(&msg)); ExitCode::from(2) } Err(CliError::Failed(msg)) => { - eprintln!("error: {msg}"); + eprintln!("error: {}", files::plain(&msg)); ExitCode::from(1) } } diff --git a/apps/figcraft-cli/tests/it/cli.rs b/apps/figcraft-cli/tests/it/cli.rs index 77d816b60..efc1f0e29 100644 --- a/apps/figcraft-cli/tests/it/cli.rs +++ b/apps/figcraft-cli/tests/it/cli.rs @@ -106,6 +106,22 @@ fn bad_arguments_exit_2_without_panicking() { assert_eq!(out.status.code(), Some(1)); } +#[test] +fn post_parse_errors_escape_terminal_controls() { + let missing = format!("__figcraft_missing_diagnostic_{}_\u{1b}[31m\n.figcraft", std::process::id()); + let failed = ["info", missing.as_str()]; + let usage = ["connect", "publish", "invalid-\u{1b}[31m\n.txt"]; + for (args, expected) in [(&failed[..], 1), (&usage[..], 2)] { + let out = bin().arg("--no-system-fonts").args(args).output().unwrap(); + let error = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(expected), "{args:?}: {error:?}"); + assert!(error.starts_with("error: "), "{args:?}: {error:?}"); + assert!(!error.contains('\u{1b}'), "{args:?}: {error:?}"); + assert!(error.contains(r"\u{1b}[31m\n"), "{args:?}: {error:?}"); + assert!(out.stdout.is_empty(), "{args:?}"); + } +} + /// `--help` / `-h` after a subcommand prints that subcommand's help on stdout and exits 0, as it /// does first (#1155), whatever else is on the line; nothing runs. #[test] diff --git a/apps/figcraft-server/src/disk.rs b/apps/figcraft-server/src/disk.rs index 219bce324..19cbfc8d3 100644 --- a/apps/figcraft-server/src/disk.rs +++ b/apps/figcraft-server/src/disk.rs @@ -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"; diff --git a/apps/figcraft-server/src/library_assets_tests.rs b/apps/figcraft-server/src/library_assets_tests.rs index 4c9b8aaef..9cbf24e1d 100644 --- a/apps/figcraft-server/src/library_assets_tests.rs +++ b/apps/figcraft-server/src/library_assets_tests.rs @@ -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:?}"); +} diff --git a/apps/figcraft-server/src/store.rs b/apps/figcraft-server/src/store.rs index 2e713deb2..d75a24f1b 100644 --- a/apps/figcraft-server/src/store.rs +++ b/apps/figcraft-server/src/store.rs @@ -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, /// Insertions and detachments week by week, over every file (kept in `actions.json`). weeks: Vec, + /// The same for styles and variables (kept in `asset-actions.json`). + asset_weeks: Vec>, 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 { - 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); diff --git a/apps/figcraft-server/src/store/backend.rs b/apps/figcraft-server/src/store/backend.rs index 5d4a3bfe9..42900e6b8 100644 --- a/apps/figcraft-server/src/store/backend.rs +++ b/apps/figcraft-server/src/store/backend.rs @@ -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), } } diff --git a/apps/figcraft-server/src/store/library.rs b/apps/figcraft-server/src/store/library.rs index 322c906e8..42d284b04 100644 --- a/apps/figcraft-server/src/store/library.rs +++ b/apps/figcraft-server/src/store/library.rs @@ -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(path: &Path) -> Vec { 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(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, grown: &[(NodeId, u32)], kind: Count, t: u64) { +fn add_to_week(weeks: &mut Vec>, 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>, 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)); + } +} diff --git a/apps/figcraft-web/Cargo.toml b/apps/figcraft-web/Cargo.toml index c37663258..dae65ac55 100644 --- a/apps/figcraft-web/Cargo.toml +++ b/apps/figcraft-web/Cargo.toml @@ -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 } diff --git a/apps/figcraft/Cargo.toml b/apps/figcraft/Cargo.toml index 8e26ac161..cde76b6ef 100644 --- a/apps/figcraft/Cargo.toml +++ b/apps/figcraft/Cargo.toml @@ -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 } diff --git a/contributors/people.toml b/contributors/people.toml index 34f849ed7..4e238341a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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" diff --git a/crates/collab-net/src/driver.rs b/crates/collab-net/src/driver.rs index e55eba957..526cf0941 100644 --- a/crates/collab-net/src/driver.rs +++ b/crates/collab-net/src/driver.rs @@ -152,6 +152,12 @@ impl Driver { None => self.done = true, } } + exchange::Next::Tell(events, then) => { + for e in events { + self.inbox.push(e); + } + self.follow(*then, now); + } } } diff --git a/crates/collab-net/src/exchange.rs b/crates/collab-net/src/exchange.rs index b0d103ae1..5a75e382c 100644 --- a/crates/collab-net/src/exchange.rs +++ b/crates/collab-net/src/exchange.rs @@ -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, + requests: VecDeque, 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, pub(crate) replies: Vec, + /// The answer on a library or plugin directory connection. + pub(crate) library: Option, + pub(crate) plugins: Option, } /// What follows an exchange's answers (or why it failed). @@ -46,6 +55,8 @@ pub(crate) enum Next { Ask(Box, Then), /// Done: tell the UI these, then join the file this invite names (`None`: nothing to join). Done(Vec, Option), + /// Tell the UI these now, then go on with what follows. + Tell(Vec, Box), } 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) -> 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) -> Result { + 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) -> 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| { + 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 { 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 { 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, }) } diff --git a/crates/collab-net/src/exchange_tests.rs b/crates/collab-net/src/exchange_tests.rs index 85274e411..ecebdc8f7 100644 --- a/crates/collab-net/src/exchange_tests.rs +++ b/crates/collab-net/src/exchange_tests.rs @@ -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()); } diff --git a/crates/collab-net/src/lib.rs b/crates/collab-net/src/lib.rs index 3696dbc30..982d8a036 100644 --- a/crates/collab-net/src/lib.rs +++ b/crates/collab-net/src/lib.rs @@ -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)] diff --git a/crates/collab-net/src/link.rs b/crates/collab-net/src/link.rs index 30bc587c3..198022a09 100644 --- a/crates/collab-net/src/link.rs +++ b/crates/collab-net/src/link.rs @@ -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 }); diff --git a/crates/collab-net/src/manage.rs b/crates/collab-net/src/manage.rs index aa73a2ec5..96146f830 100644 --- a/crates/collab-net/src/manage.rs +++ b/crates/collab-net/src/manage.rs @@ -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; @@ -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))?; diff --git a/crates/collab-net/src/requests.rs b/crates/collab-net/src/requests.rs index a2c7f9439..cb5802d57 100644 --- a/crates/collab-net/src/requests.rs +++ b/crates/collab-net/src/requests.rs @@ -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()) diff --git a/crates/collab-net/src/web.rs b/crates/collab-net/src/web.rs index 8c54f6c23..602665dc6 100644 --- a/crates/collab-net/src/web.rs +++ b/crates/collab-net/src/web.rs @@ -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, /// Answers to requests sent in the background (outlives sessions). background: Inbox, + /// A check of the team libraries is out. + fetching: Arc, } 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)); diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 07adbb2af..1ba0896aa 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -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 { 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), Actions(Vec), Assets(Vec), + AssetActions(Vec>), } /// Opens a connection to a server's plugin directory (instead of [`Hello`]). Anyone who can reach diff --git a/crates/doc/src/board.rs b/crates/doc/src/board.rs index eb0594bab..999631aed 100644 --- a/crates/doc/src/board.rs +++ b/crates/doc/src/board.rs @@ -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", } } } diff --git a/crates/doc/src/board_code.rs b/crates/doc/src/board_code.rs new file mode 100644 index 000000000..bebce4c8b --- /dev/null +++ b/crates/doc/src/board_code.rs @@ -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 { + 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 +} diff --git a/crates/doc/src/board_code_tests.rs b/crates/doc/src/board_code_tests.rs new file mode 100644 index 000000000..4f8ec0bb9 --- /dev/null +++ b/crates/doc/src/board_code_tests.rs @@ -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 = 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::(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::(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)); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 174693079..170da1a25 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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) { #[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; diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs index 35279aae4..828e1605b 100644 --- a/crates/doc/src/library.rs +++ b/crates/doc/src/library.rs @@ -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, + /// 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, } /// 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, 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. diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index fd6d48072..768c2f6ee 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -145,6 +145,25 @@ struct Corner { cut2: f64, } +/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the +/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from +/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths. +struct Turn { + v: usize, + r: f64, + s1: usize, + a1: bool, + s2: usize, + a2: bool, + c1: CubicBez, + c2: CubicBez, + u1: Vec2, + u2: Vec2, + angle: f64, + l1: f64, + l2: f64, +} + /// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to /// those ends, and the point it ends at. struct CornerCurve { @@ -391,10 +410,11 @@ impl VectorNetwork { } /// The network with its rounded points drawn in: each sharp point with a corner radius becomes - /// an arc between its two segments (the radius shrinks so the arc fits in half of each - /// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps - /// the rest of its curve, the arc leaving along its direction there. `None` when no point is - /// rounded. + /// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other + /// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose + /// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where + /// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there. + /// `None` when no point is rounded. pub fn rounded(&self) -> Option { self.rounded_smoothed(0.0) } @@ -424,7 +444,9 @@ impl VectorNetwork { *x = true; } } - let corners: Vec = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect(); + let turns: Vec> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect(); + let rounds: Vec = turns.iter().map(Option::is_some).collect(); + let corners: Vec = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect(); let mut out = self.clone(); for v in &mut out.vertices { v.radius = 0.0; @@ -558,10 +580,9 @@ impl VectorNetwork { joining.next().is_none().then_some(first) } - /// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments - /// run on smoothly or fold back. With `smoothing`, a point between two straight segments that - /// are both `on_loop` gets a smoothed corner. - fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option { + /// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two + /// segments that neither run on smoothly nor fold back there. + fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option { let r = self.vertices.get(v)?.radius; let [(s1, a1), (s2, a2)] = *incident else { return None }; if !(r > 0.0 && r.is_finite()) || s1 == s2 { @@ -577,6 +598,23 @@ impl VectorNetwork { if !(l1 > 1e-9 && l2 > 1e-9) { return None; } + Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 }) + } + + /// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner + /// there may reach: all of it when the other end stays sharp, half when that end is rounded + /// too (`rounds`, by point) and takes the other half. + fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 { + let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a }); + if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l } + } + + /// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as + /// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point + /// between two straight segments that are both `on_loop` gets a smoothed corner. + fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option { + let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p; + let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds)); let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t }; let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false); if smoothing > 0.0 @@ -584,7 +622,7 @@ impl VectorNetwork { && is_line(&c2) && closed(s1) && closed(s2) - && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing) + && let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing) && let (Some(first), Some(last)) = (curves.first(), curves.last()) { let (a, b) = (first.p0, last.p3); @@ -595,7 +633,7 @@ impl VectorNetwork { let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2); return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) }); } - let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0); + let t = (r / (angle / 2.0).tan()).min(reach); let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2)); // A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between // them and ρ the radius of the circle through both ends (the corner radius between lines). diff --git a/crates/doc/src/vector_radius_tests.rs b/crates/doc/src/vector_radius_tests.rs new file mode 100644 index 000000000..b48414a76 --- /dev/null +++ b/crates/doc/src/vector_radius_tests.rs @@ -0,0 +1,118 @@ +//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the +//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single +//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other. + +use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg}; +use figcraft_geom::{BezPath, Point}; + +use crate::vector::VectorNetwork; + +/// A 100 × 100 square's points: top left, top right, bottom right, bottom left. +const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]; + +/// A network through `pts` (closed or open) whose points have radii `radii`. +fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork { + let mut n = VectorNetwork::from_points(pts, closed); + for (v, r) in n.vertices.iter_mut().zip(radii) { + v.radius = *r; + } + n +} + +/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight). +fn curves(path: &BezPath) -> Vec { + path.segments() + .filter_map(|s| match s { + PathSeg::Cubic(c) => Some(c), + _ => None, + }) + .collect() +} + +/// Whether `a` and `b` are the same point to within rounding. +fn near(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-9 +} + +/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc +/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the +/// circle's radius is `t`), and no other curve. +fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) { + let got = curves(path); + assert_eq!(got.len(), want.len(), "{why}: {got:?}"); + for &(corner, prev, next, t) in want { + let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t; + let (a, b) = (toward(prev), toward(next)); + let center = a + (b - corner); + let mid = center + (corner - center) / (corner - center).hypot() * t; + // Two arcs can share both ends (opposite corners of a square), so the middle picks one. + let ends = |c: &&CubicBez| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a)); + let passing: Vec = got.iter().filter(ends).map(|c| c.eval(0.5)).collect(); + assert!( + passing.iter().any(|&m| near(m, mid)), + "{why}: no arc at {corner:?} from {a:?} to {b:?} through {mid:?}; arcs between them pass {passing:?}" + ); + } +} + +#[test] +fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() { + let [tl, tr, br, bl] = SQUARE; + // (radii of [top left, top right, bottom right, bottom left], each arc as (point, its + // neighbours, how far it reaches along both), derivation) + #[allow(clippy::type_complexity)] + let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![ + ([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"), + ([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"), + ([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"), + ([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"), + ( + [0.0, 10.0, 100.0, 0.0], + vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)], + "the segment to the rounded top right is shared, half each, and the shorter room wins", + ), + ( + [100.0, 0.0, 100.0, 0.0], + vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)], + "opposite points share no segment: each reaches its sharp neighbours (a lens)", + ), + ( + [100.0; 4], + vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)], + "every point rounded: a circle, as before", + ), + ]; + for (radii, want, why) in rows { + let net = network(&SQUARE, true, &radii); + assert_arcs(&net.fill_path(), &want, why); + assert_arcs(&net.stroke_path(), &want, why); + // The stored radii stay as they were set. + assert_eq!(net.vertices.iter().map(|p| p.radius).collect::>(), radii.to_vec(), "{why}"); + } +} + +#[test] +fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() { + let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)]; + // (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no + // room from the middle point. + let rows: Vec<([f64; 3], &str)> = + vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")]; + for (radii, why) in rows { + let net = network(&pts, false, &radii); + assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why); + } +} + +#[test] +fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() { + // Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100 + // side (50) would cut smoothing down; the whole side next to sharp points leaves all of it. + let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]); + let path = net.rounded_smoothed(0.6).unwrap().fill_path(); + let ends: Vec = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect(); + for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] { + assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}"); + } + assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}"); +} diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index 49950de6d..2e1f01b4e 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -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 diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs index 513f4f7c8..b8c9bdf8d 100644 --- a/crates/engine/src/assets/components/sync.rs +++ b/crates/engine/src/assets/components/sync.rs @@ -336,6 +336,28 @@ fn index_old_layers(doc: &Document, inst: NodeId, spare: BTreeMap 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) -> 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(); diff --git a/crates/engine/src/assets/library.rs b/crates/engine/src/assets/library.rs index 2fb64a26d..c5b3c1ba0 100644 --- a/crates/engine/src/assets/library.rs +++ b/crates/engine/src/assets/library.rs @@ -83,14 +83,66 @@ pub fn asset_root(doc: &Document, id: NodeId) -> Option { 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 { + 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(s: &mut crate::Session, detach: bool, edit: impl FnOnce(&mut crate::Session) -> Result) -> Result { + 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::>(); + 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, update: bool) -> BTreeMap { - 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, 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( diff --git a/crates/engine/src/assets/library_server.rs b/crates/engine/src/assets/library_server.rs index 81889be5d..f8ddf0e50 100644 --- a/crates/engine/src/assets/library_server.rs +++ b/crates/engine/src/assets/library_server.rs @@ -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 { 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 { + 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 { + let Some(full) = asset_actions(doc, library) else { return Vec::new() }; + chunk_asset_actions(full) +} + +fn chunk_asset_actions(actions: AssetActions) -> Vec { + 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). diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 249d3483c..5eba5a506 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40; /// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute /// is refused as well, rather than left to what comes next. fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option { + // Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given. + if has_trimmed_name(path) { + return Some(Unresolved::Linked); + } // Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a // bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes // `..` by name, so `link\..\x` is `x` and never goes through the link. @@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool { /// the way is opened in turn while the path is resolved, and the device behind a name such as /// `LPT1` can be a printer on another computer. fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option { + // A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names. + if is_native_name(Path::new(p)) { + return Some(Refused::Device); + } match craft_docpath::resolve(p, None) { // With a root passed as the document path (what a link would be relative to), a path on // that root's share is allowed. @@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool { let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else { return false; }; - volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}') + let bytes = volume.as_bytes(); + bytes.len() == 44 + && volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) + && volume.ends_with('}') + && bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() }) } /// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`] @@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - Entry::Link(target) => target, }; let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true }; + // Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive, + // and Win32 trims a trailing period or space that the kernel follows as it is. + if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) { + return true; + } // A relative target is relative to the link's folder; an absolute one replaces it. let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path())); return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look); @@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - false } +/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link +/// may hold: no prefix for `std`, yet the system follows it to wherever it names. +fn is_native_name(path: &Path) -> bool { + let bytes = path.as_os_str().as_encoded_bytes(); + [&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| { + bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\')) + }) +} + +/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no +/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names. +fn is_rooted_without_drive(path: &Path) -> bool { + matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\')) +} + +/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up. +fn has_trimmed_name(path: &Path) -> bool { + path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' ')))) +} + /// `p` with its `.` and `..` taken by name, as Windows takes them. fn lexical(p: &Path) -> PathBuf { let mut out = PathBuf::new(); @@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool { matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f)) } +/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a +/// path that resolving would not be allowed to open (on another computer, or a device: see +/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the +/// callers guard against overwriting a file through another name for it, so it counts as the same: +/// the guard keeps asking (a path like that can't be written anyway). A local path outside the +/// roots is compared. pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { let (a, b) = (a.as_ref(), b.as_ref()); - a == b || same_file::is_same_file(a, b).unwrap_or(false) + if a == b { + return true; + } + if let Some(scope) = current() { + let roots = [scope.read.as_slice(), scope.write.as_slice()].concat(); + if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) { + return true; + } + } + same_file::is_same_file(a, b).unwrap_or(false) } /// `p` without Windows' `\\?\` prefix, for messages. @@ -345,6 +397,12 @@ fn device_name(n: &str) -> bool { && stem.chars().last().is_some_and(|c| c.is_ascii_digit() || matches!(c, '¹' | '²' | '³'))) } +/// Prefix Windows device-name components of a generated export path with `_`. +/// Apply after character filtering and suffix construction, so a safe suffix stays unchanged. +pub fn escape_device_names(path: &str) -> String { + path.split('/').map(|name| if device_name(name) { format!("_{name}") } else { name.to_string() }).collect::>().join("/") +} + thread_local! { static ROOTS: RefCell>> = const { RefCell::new(None) }; } diff --git a/crates/engine/src/automation/file_access/tests.rs b/crates/engine/src/automation/file_access/tests.rs index d642befb1..ed8449fb7 100644 --- a/crates/engine/src/automation/file_access/tests.rs +++ b/crates/engine/src/automation/file_access/tests.rs @@ -9,6 +9,27 @@ use serde_json::json; use super::{Access, Roots, allow, confined, current}; use crate::Session; +#[test] +fn generated_export_paths_escape_device_components_and_preserve_other_names() { + for (path, expected) in [ + ("CON", "_CON"), + ("CoN.txt", "_CoN.txt"), + ("nul.txt", "_nul.txt"), + ("PRN/icon", "_PRN/icon"), + ("folder/COM1", "folder/_COM1"), + ("LPT9.png", "_LPT9.png"), + ("COM¹", "_COM¹"), + ("LPT²/icon", "_LPT²/icon"), + ("CONIN$", "_CONIN$"), + ("HomeCON", "HomeCON"), + ("COM10", "COM10"), + ("CON@2x", "CON@2x"), + ("folder/.NUL", "folder/.NUL"), + ] { + assert_eq!(super::escape_device_names(path), expected, "{path}"); + } +} + /// A fresh folder for one test: `/figcraft-roots--`, holding `root/`, `root2/` /// (a sibling whose name starts like the root's) and `outside/`. struct Fixture(PathBuf); @@ -229,6 +250,8 @@ fn spellings_of_other_computers_and_devices_are_refused() { r"C:\work\LPT³\x.png", r"C:\work\conout$", r"C:\work\aux:stream", + // A volume name that is not a GUID could be an alias of anything. + r"\\?\Volume{remote}\x.png", // After a name `craft_docpath` refuses for another reason. r"C:\work\a:b\prn.png", ]; @@ -402,6 +425,34 @@ fn a_parent_after_a_link_is_taken_by_name() { assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root"); } +/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the +/// same file as one inside, even when it is another name for it (a hard link outside the roots). +#[test] +fn same_file_does_not_open_a_path_outside_the_roots() { + let f = Fixture::new("same-file"); + let inside = f.p("root/in.txt"); + let outside = f.p("outside/linked.txt"); + if std::fs::hard_link(&inside, &outside).is_err() { + eprintln!("skipped: hard links can't be made here"); + return; + } + assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file"); + let roots = Arc::new(f.rw()); + confined(Some(&roots), || { + assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file"); + if cfg!(windows) { + assert!( + super::same_file(&inside, r"\\192.0.2.1\share\x"), + "a path on another computer is never opened, and counts as the same so that the guard keeps asking" + ); + } + assert!(super::same_file(&inside, &inside), "a path is the same file as itself"); + let other = f.p("root/sub/other.txt"); + std::fs::write(&other, b"other").unwrap(); + assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ"); + }); +} + /// A path on another computer and a device path are refused before anything is opened: resolving /// them made Windows contact the server, which may send it the signed-in user's credentials /// (#1094). Each is refused with a message that only the check before resolving gives: had the @@ -468,6 +519,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() { assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok()); } +/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the +/// rest of the path after it, reaches `\Device\Mup\...`. +#[test] +fn native_names_are_told_with_or_without_the_closing_separator() { + for p in + [r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"] + { + assert!(super::is_native_name(Path::new(p)), "{p}"); + } + for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] { + assert!(!super::is_native_name(Path::new(p)), "{p}"); + } +} + +/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the +/// link's drive, whichever directory it names. +#[test] +fn rooted_link_targets_without_a_drive_are_refused() { + for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] { + assert!(super::is_rooted_without_drive(Path::new(p)), "{p}"); + } + for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] { + assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}"); + } +} + +/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a +/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the +/// others where it looks a name up but not where the kernel follows a link. +#[test] +#[cfg(windows)] +fn native_names_and_names_windows_trims_are_refused_as_written() { + let f = Fixture::new("native-trimmed"); + let r = f.rw(); + if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native")) + || !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed")) + { + eprintln!("skipped: this system doesn't let tests make symbolic links"); + return; + } + let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be"); + // However the system stores the native name, the link is refused. + let native = f.p("root/native/x.png"); + assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}"); + let p = f.p("root/trimmed/x.png"); + let e = r.check(Path::new(&p), Access::Read).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + let p = f.p("root/remote /x.png"); + let e = r.check(Path::new(&p), Access::Write).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device)); +} + #[test] fn a_scope_confines_the_thread_and_ends_with_it() { let f = Fixture::new("scope"); diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index c74829961..359c58bb4 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -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, 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, 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, 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)); } diff --git a/crates/engine/src/batch_step_ref_tests.rs b/crates/engine/src/batch_step_ref_tests.rs index 17d9fc725..e50824edb 100644 --- a/crates/engine/src/batch_step_ref_tests.rs +++ b/crates/engine/src/batch_step_ref_tests.rs @@ -652,3 +652,60 @@ fn a_continue_batch_reports_runtime_errors_and_runs_later_steps() { assert_eq!(results[6]["ok"], true); assert_eq!(s.doc().unwrap().node(s.page().unwrap()).unwrap().name, "Done"); } + +#[test] +fn a_refused_step_names_its_step_and_keeps_its_kind() { + let mut s = Session::new(); + let comp = id(&s.execute("node.create", &json!({"type": "component", "name": "Button", "width": 100, "height": 40})).unwrap()); + let inst = id(&s.execute("instance.create", &json!({"component": comp})).unwrap()); + let before = s.doc().unwrap().clone(); + let undo = s.undo_depth(); + let result = s.execute( + "command.batch", + &json!({"commands": [ + {"command": "node.create", "params": {"type": "rectangle", "parent": inst, "width": 10, "height": 10}} + ]}), + ); + match result { + Err(EngineError::Disabled(cmd, msg)) => { + assert_eq!(cmd, "node.create"); + assert!(msg.starts_with("step 0: "), "{msg}"); + assert!(msg.contains("can't be added"), "{msg}"); + } + other => panic!("expected Disabled, got {other:?}"), + } + assert_eq!(s.doc().unwrap(), &before, "the batch rolled back"); + assert_eq!(s.undo_depth(), undo, "no undo step for the refused batch"); + // Outside a batch the same refusal keeps its kind and says no step. + match s.execute("node.create", &json!({"type": "rectangle", "parent": inst, "width": 10, "height": 10})) { + Err(EngineError::Disabled(_, msg)) => assert!(!msg.contains("step "), "{msg}"), + other => panic!("expected Disabled, got {other:?}"), + } +} + +#[test] +fn an_internal_step_says_which_step_without_changing_kind() { + use crate::derived; + let mut s = Session::new(); + let r = id(&s.execute("node.create", &json!({"type": "rectangle", "width": 10, "height": 10})).unwrap()); + let before = s.doc().unwrap().clone(); + derived::PANIC.with(|p| p.set(true)); + let result = s.execute( + "command.batch", + &json!({"commands": [ + {"command": "node.set", "params": {"ids": [r], "props": {"name": "Renamed"}}} + ]}), + ); + derived::PANIC.with(|p| p.set(false)); + match result { + Err(EngineError::Internal { cmd, msg }) => { + assert_eq!(cmd, "node.set"); + assert!(msg.starts_with("step 0: "), "{msg}"); + } + other => panic!("expected Internal, got {other:?}"), + } + assert_eq!(s.doc().unwrap(), &before, "the panicking step is rolled back"); + // Kinds without a message are left as they are. + assert!(matches!(EngineError::NoNode(figcraft_doc::NodeId(7)).at_step(2), EngineError::NoNode(_))); + assert!(matches!(EngineError::Waiting.at_step(2), EngineError::Waiting)); +} diff --git a/crates/engine/src/board_code_tests.rs b/crates/engine/src/board_code_tests.rs new file mode 100644 index 000000000..97fc6bfdc --- /dev/null +++ b/crates/engine/src/board_code_tests.rs @@ -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 { + 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::>()); + 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::>()); + 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); +} diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index dfcb28d32..83b353f96 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -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}"); } diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index ddee2d823..a320ee6f5 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -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 { 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 { 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", diff --git a/crates/engine/src/boards/board/code.rs b/crates/engine/src/boards/board/code.rs new file mode 100644 index 000000000..226f51bd4 --- /dev/null +++ b/crates/engine/src/boards/board/code.rs @@ -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::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 { + 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 { + 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 { + 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 = 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::>()})) +} + +/// `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 { + 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 { + let v: Vec = 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) { + 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); + } + } + } +} diff --git a/crates/engine/src/boards/board/derived.rs b/crates/engine/src/boards/board/derived.rs index a6461fb85..e62d41973 100644 --- a/crates/engine/src/boards/board/derived.rs +++ b/crates/engine/src/boards/board/derived.rs @@ -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 diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 61a3c5659..6df2fa397 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -84,7 +84,7 @@ pub(super) fn set_color(s: &mut Session, p: &Value) -> Result { 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); } diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index 431a27cf9..481f0ebed 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -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 { 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"))?; diff --git a/crates/engine/src/canvas/textedit.rs b/crates/engine/src/canvas/textedit.rs index 51a1640f7..6c8c15071 100644 --- a/crates/engine/src/canvas/textedit.rs +++ b/crates/engine/src/canvas/textedit.rs @@ -87,6 +87,12 @@ fn text_of(s: &Session, id: NodeId) -> Result { } } +/// 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, 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. " 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 = 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"), diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index f876885ef..acf77e32d 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -431,6 +431,9 @@ pub(crate) enum Gesture { additive: bool, base: Vec, within: Option, + /// 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, - /// 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, }, 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, pressure: &mut Vec>, 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, + } + } } diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index 2208f74ee..84ca02ba4 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -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| { - 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::>(); // 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() { diff --git a/crates/engine/src/canvas/tools/draw.rs b/crates/engine/src/canvas/tools/draw.rs index 43110681c..b29768afe 100644 --- a/crates/engine/src/canvas/tools/draw.rs +++ b/crates/engine/src/canvas/tools/draw.rs @@ -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)?, diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs index ab9fcb79f..ff8af30a4 100644 --- a/crates/engine/src/canvas/vectoredit.rs +++ b/crates/engine/src/canvas/vectoredit.rs @@ -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; diff --git a/crates/engine/src/canvas/vectoredit/align_tests.rs b/crates/engine/src/canvas/vectoredit/align_tests.rs new file mode 100644 index 000000000..323929563 --- /dev/null +++ b/crates/engine/src/canvas/vectoredit/align_tests.rs @@ -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 { + 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 = 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 = 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 = (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 = 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:?}"); +} diff --git a/crates/engine/src/canvas/vectoredit/transform.rs b/crates/engine/src/canvas/vectoredit/transform.rs index 0f87a0bd5..0eaacb185 100644 --- a/crates/engine/src/canvas/vectoredit/transform.rs +++ b/crates/engine/src/canvas/vectoredit/transform.rs @@ -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::>() + }) + .collect() +} + +/// The box to align or distribute in: all edited layers' points when several are selected. +fn edit_box(doc: &Document, ve: &VectorEdit) -> Option { + 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> { + 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> { + 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)?; diff --git a/crates/engine/src/canvas/vectoredit/transform_tests.rs b/crates/engine/src/canvas/vectoredit/transform_tests.rs index eb2f96f5e..7d6206ea7 100644 --- a/crates/engine/src/canvas/vectoredit/transform_tests.rs +++ b/crates/engine/src/canvas/vectoredit/transform_tests.rs @@ -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); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0e90dc198..b90204504 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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()); diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index d32064271..ea7a8830e 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -11,14 +11,62 @@ use crate::{Result, Session, bad, spec}; pub fn specs() -> Vec { 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 { } fn align(s: &mut Session, p: &Value, a: Al) -> Result { + 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 { } fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result { + 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); diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 388d56d88..35ea38901 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -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 { +fn anchor_at(doc: &Document, page: NodeId, x: f64, y: f64, v: Option<&Value>, within: Option) -> Option { 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 { 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 { 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 { 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 { /// Innermost frame (or component/instance/section) under a page point, for anchoring. fn frame_at(doc: &Document, page: NodeId, x: f64, y: f64) -> Option { + 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) -> Option { 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", ¶ms).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", ¶ms).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(); diff --git a/crates/engine/src/cmd/component/props.rs b/crates/engine/src/cmd/component/props.rs index 97bef3ce2..8ef066d37 100644 --- a/crates/engine/src/cmd/component/props.rs +++ b/crates/engine/src/cmd/component/props.rs @@ -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 { 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 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)?; } diff --git a/crates/engine/src/cmd/component/variants.rs b/crates/engine/src/cmd/component/variants.rs index 96de6ba3a..be43bced0 100644 --- a/crates/engine/src/cmd/component/variants.rs +++ b/crates/engine/src/cmd/component/variants.rs @@ -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 { 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 Result { }) .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 { } }; 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 { + 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) -> 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::>().into_iter().enumerate() + { + doc.reorder(i, above + k)?; + } + Ok(()) +} + pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { let sel = s.selection(); let page = s.page()?; @@ -337,14 +372,7 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result { 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::>().into_iter().enumerate() - { - doc.reorder(i, above + k)?; - } - } + move_above(s, &ids, parent, above)?; s.set_selection(ids.clone()); Ok(json!({"ids": ids})) } diff --git a/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs b/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs new file mode 100644 index 000000000..f1ab3ba48 --- /dev/null +++ b/crates/engine/src/cmd/edit/nudge_rotated_parent_tests.rs @@ -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, 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)); +} diff --git a/crates/engine/src/cmd/edit/props.rs b/crates/engine/src/cmd/edit/props.rs index c39f8abe2..5bd6710af 100644 --- a/crates/engine/src/cmd/edit/props.rs +++ b/crates/engine/src/cmd/edit/props.rs @@ -163,6 +163,9 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result { 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 { } } } + // 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})) } } diff --git a/crates/engine/src/cmd/edit/select.rs b/crates/engine/src/cmd/edit/select.rs index 17f80af6b..9d8fa822e 100644 --- a/crates/engine/src/cmd/edit/select.rs +++ b/crates/engine/src/cmd/edit/select.rs @@ -184,8 +184,19 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { // 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; } } diff --git a/crates/engine/src/cmd/file/export.rs b/crates/engine/src/cmd/file/export.rs index bbc52e1b5..ac8353c30 100644 --- a/crates/engine/src/cmd/file/export.rs +++ b/crates/engine/src/cmd/file/export.rs @@ -295,7 +295,7 @@ pub fn jobs_for(items: impl IntoIterator)>, d if out.len() >= MAX_EXPORT_FILES { return out; } - let stem = format!("{base}{}", safe_file_name(&e.file_suffix())); + let stem = crate::file_access::escape_device_names(&format!("{base}{}", safe_file_name(&e.file_suffix()))); let ext = e.format.ext(); let file = (1..).map(|k| if k == 1 { format!("{stem}.{ext}") } else { format!("{stem} {k}.{ext}") }).find(|f| used.insert(f.to_lowercase())); @@ -439,3 +439,31 @@ pub(super) fn export_frames_pdf(s: &mut Session, p: &Value) -> Result { None => Ok(json!({"format": "pdf", "pages": pages, "data": base64::engine::general_purpose::STANDARD.encode(&bytes)})), } } + +#[cfg(test)] +mod filename_tests { + use super::*; + + #[test] + fn export_jobs_escape_device_names_after_suffixes_and_before_numbering() { + let mut doc = Document::new("Export names"); + let page = doc.first_page().unwrap(); + let cases = [ + ("C", "ON", "_CON.png"), + ("_con", "", "_con 2.png"), + ("CON/icon", "", "_CON/icon.png"), + ("Home", "CON", "HomeCON.png"), + ("COM", "1", "_COM1.png"), + ("COM1", "@2x", "COM1@2x.png"), + ]; + let items: Vec<_> = cases + .iter() + .map(|(name, suffix, _)| { + let id = doc.create(page, NodeKind::Frame, name, 0.0, 0.0, 10.0, 10.0).unwrap(); + (id, vec![ExportSetting { suffix: (*suffix).into(), ..Default::default() }]) + }) + .collect(); + let files: Vec<_> = jobs_for(items, &doc).into_iter().map(|job| job.file).collect(); + assert_eq!(files, cases.map(|(_, _, expected)| expected)); + } +} diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index d8e2e6893..e562b142b 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -436,6 +436,8 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { 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 = std::collections::BTreeMap::new(); @@ -481,30 +483,62 @@ fn usage_cmd(s: &mut Session, p: &Value) -> Result { "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>, describe: impl Fn(&str) -> Option) -> Vec { +/// 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>>> { + 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]) -> 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>, + actions: &std::collections::BTreeMap<&str, (u64, u64)>, + describe: impl Fn(&str) -> Option, +) -> Vec { 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() diff --git a/crates/engine/src/cmd/page.rs b/crates/engine/src/cmd/page.rs index 0648dedd2..3883c3f39 100644 --- a/crates/engine/src/cmd/page.rs +++ b/crates/engine/src/cmd/page.rs @@ -53,9 +53,8 @@ pub fn specs() -> Vec { return Ok(json!({"id": id, "divider": true})); } let ds = s.ds_mut()?; - ds.page = id; + ds.open_page(id); ds.selection.clear(); - ds.zoom_to_fit(); Ok(json!({"id": id})) }), spec!("page.select", "Go to page", "{id | index}", false, |s, p| { @@ -74,10 +73,9 @@ pub fn specs() -> Vec { return Err(bad("page.select", "a divider isn't a page to open")); } let ds = s.ds_mut()?; - ds.page = id; + ds.open_page(id); ds.selection.clear(); ds.text_edit = None; - ds.zoom_to_fit(); ok() }), spec!("page.rename", "Rename page", "{id?, name} (an empty page named with a leading hyphen becomes a divider)", true, |s, p| { diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 75889bb53..94b681381 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1234,14 +1234,16 @@ pub fn apply(cmd: &str, doc: &mut Document, id: NodeId, props: &Map {} } - // 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) -> 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) -> 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 { + let notes: Vec = 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) diff --git a/crates/engine/src/cmd/structure.rs b/crates/engine/src/cmd/structure.rs index c73ef8b21..bf1c92d2f 100644 --- a/crates/engine/src/cmd/structure.rs +++ b/crates/engine/src/cmd/structure.rs @@ -577,6 +577,21 @@ fn outline_stroke(s: &mut Session, p: &Value) -> Result { 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); diff --git a/crates/engine/src/cmd/styles.rs b/crates/engine/src/cmd/styles.rs index 710eec76e..f5a0dd6a0 100644 --- a/crates/engine/src/cmd/styles.rs +++ b/crates/engine/src/cmd/styles.rs @@ -302,6 +302,10 @@ fn paragraph_style_of(n: &Node, range: Option<(usize, usize)>) -> Option Result { + crate::library::counting_links(s, true, |s| detach_style(s, p)) +} + +fn detach_style(s: &mut Session, p: &Value) -> Result { 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 { + crate::library::counting_links(s, false, |s| apply_style(s, p)) +} + +fn apply_style(s: &mut Session, p: &Value) -> Result { 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 { + crate::library::counting_links(s, string(p, "variable").is_none(), |s| bind_field(s, p)) +} + +fn bind_field(s: &mut Session, p: &Value) -> Result { let cmd = "variable.bind"; let field = req_string(cmd, p, "field")?; let var = string(p, "variable"); diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index c865924c5..177155a8a 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -642,7 +642,7 @@ pub fn specs() -> Vec { 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")?; diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 56f4aff27..7edf1372a 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -187,9 +187,8 @@ fn page_step(s: &mut Session, dir: i64) -> Result { } }; let ds = s.ds_mut()?; - ds.page = pg; + ds.open_page(pg); ds.selection.clear(); - ds.zoom_to_fit(); Ok(json!({"page": pg})) } diff --git a/crates/engine/src/components_behaviour_tests.rs b/crates/engine/src/components_behaviour_tests.rs index 3565a3165..e8dda9e95 100644 --- a/crates/engine/src/components_behaviour_tests.rs +++ b/crates/engine/src/components_behaviour_tests.rs @@ -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] diff --git a/crates/engine/src/design_context_tests.rs b/crates/engine/src/design_context_tests.rs new file mode 100644 index 000000000..5d6f51304 --- /dev/null +++ b/crates/engine/src/design_context_tests.rs @@ -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", ¶ms).unwrap()) +} + +fn context(s: &mut Session, params: Value) -> Value { + s.execute("inspect.designContext", ¶ms).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": "