Merge main into feat/corner-marks

This commit is contained in:
dotCooCoo committed 2026-11-29 16:16:11 -08:00
commit e969d29387
158 files changed
+3932 -1092

No files matched your search

+27 -7
View File
@@ -7,9 +7,26 @@ on:
- "apps/vectorcraft/Cargo.toml"
- "apps/vectorcraft/src/printing.rs"
- "apps/vectorcraft/src/printing/**"
- "crates/ui-egui/Cargo.toml"
- "crates/ui-egui/src/print.rs"
- "crates/ui-egui/src/tests/printps.rs"
- ".github/workflows/print.yml"
# A push to main saves the Windows cache entry that pull requests restore.
push:
branches: [main]
paths:
- "Cargo.toml"
- "Cargo.lock"
- "apps/vectorcraft/Cargo.toml"
- "apps/vectorcraft/src/printing.rs"
- "apps/vectorcraft/src/printing/**"
- "crates/ui-egui/Cargo.toml"
- "crates/ui-egui/src/print.rs"
- "crates/ui-egui/src/tests/printps.rs"
- ".github/workflows/print.yml"
# A weekly run on main saves a fresh entry after a new stable Rust changes the cache key.
schedule:
- cron: "23 6 * * 1"
workflow_dispatch:
permissions:
contents: read
@@ -18,15 +35,14 @@ concurrency:
group: print-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
# but never save one; a manual run on main saves the cache they restore.
# Desktop printing on Windows, through the suite's shared gate. Pushes to main, the weekly run and
# manual runs on main save the cache; pull requests restore it and never save one.
windows:
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-2022"]'
# A change to Cargo.lock finds no cache (only main saves one) and builds everything cold:
# about 55 minutes for `-p vectorcraft` alone, then the UI crate's tests.
# A run that finds no cache builds everything cold, which took 76 to 126 minutes.
timeout-minutes: 150
# As in ci.yml: test binaries without debug info or symbols, and workspace crates without
# line tables. A panic still names its file and line.
@@ -36,10 +52,14 @@ jobs:
craft-fonts-ref: ""
tools: ""
targets: ""
# A filter that matches nothing still passes, so the printps run fails unless some test ran.
# Both test runs select the same two packages, so Cargo resolves features once and the
# second run reuses the first run's dependencies. The first runs every test of the app
# (`--bin vectorcraft --test it`), the second the UI crate's `tests::printps` tests. A filter
# that matches nothing still passes, so the printps run fails unless some test ran.
command: |
set -o pipefail
cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
cargo test --locked -p vectorcraft
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --bin vectorcraft --test it
log="$RUNNER_TEMP/printps.log"
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
+1
View File
@@ -42,6 +42,7 @@ jobs:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: vectorcraft
app-title: VectorCraft
macos-runner: macos-15
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
+1 -1
View File
@@ -11,7 +11,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
Generated
+158 -172
View File
File diff suppressed because it is too large. Load diff
+50 -54
View File
@@ -4,53 +4,55 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.24.1"
version = "0.25.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] }
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
# the members it imports.
craft = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -86,7 +88,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
peniko = "0.6"
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
@@ -156,10 +157,8 @@ egui = "0.37"
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
eframe = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
arboard = { version = "3.6", default-features = false }
clipboard-win = "5.4"
webbrowser = "1"
[workspace.lints.rust]
unsafe_code = "deny"
@@ -193,25 +192,22 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+1
View File
@@ -164,6 +164,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
+3
View File
@@ -211,6 +211,9 @@ fn main() -> ExitCode {
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
// The Language packs installed in the shared font store; `proof.installPack` returns once
// installed.
prefs_dir::use_language_packs();
let mut args: Vec<String> = std::env::args().skip(1).collect();
// Before any subcommand attaches the plug-in folder.
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
+3 -2
View File
@@ -20,14 +20,15 @@ vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] }
egui = { workspace = true }
egui_extras = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# Image loaders for `src/web.rs`, which builds only for wasm32.
egui_extras = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+4
View File
@@ -5,6 +5,10 @@ dist = "../../dist/web"
public_url = "./"
filehash = true
[tools]
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
wasm_opt = "version_133"
[serve]
addresses = ["127.0.0.1"]
port = 8766
-2
View File
@@ -129,5 +129,3 @@ winresource = "0.1"
[dev-dependencies]
tempfile = "3"
# Bound socket buffers in real loopback transport deadline regressions.
socket2 = { workspace = true }
+4
View File
@@ -571,6 +571,10 @@ fn main() -> std::process::ExitCode {
mac_fonts::install();
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
prefs_dir::install_fonts();
// Language packs: installs and index fetches run on their own threads, so the window keeps
// working while a pack downloads.
prefs_dir::use_language_packs();
vectorcraft_engine::packs::run_in_background(true);
// The log file lives in the settings directory, next to the preferences; opened after the
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
// first. Runs without preferences (agents' test runs) log to standard error only, so they
+8
View File
@@ -24,6 +24,14 @@ pub fn install_fonts() {
}
}
/// Have spelling and hyphenation read the Language packs installed in the Craft apps' shared font
/// store (`proof.installPack`, or another Craft app), and install new ones there (#4936). Like the
/// Fonts folder, whether or not `VECTORCRAFT_NO_PREFS` is set: the packs are the store's, not
/// VectorCraft's preferences.
pub fn use_language_packs() {
vectorcraft_engine::packs::use_font_store();
}
/// The folder `name` next to the settings, for what the user keeps: none in a run without
/// preferences (`VECTORCRAFT_NO_PREFS`), which keeps nothing.
fn store_dir(name: &str) -> Option<PathBuf> {
+79 -8
View File
@@ -446,6 +446,66 @@ impl Drop for InMask {
}
}
thread_local! {
/// While an [`InteriorProbe`] lives, whether a leaf tested without
/// [`HitOptions::unfilled_interiors`] would have been hit inside an unfilled closed path with
/// it; `None` outside a probe.
static INTERIOR_SEEN: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
/// While a guard lives, the leaves tested without [`HitOptions::unfilled_interiors`] note whether
/// they would be hit inside an unfilled closed path with it ([`unfilled_inside`]). A walk that hits
/// nothing then looks inside the unfilled closed paths with a second walk only when one of them
/// holds the point.
struct InteriorProbe {
was: Option<bool>,
}
impl InteriorProbe {
/// A probe when `wanted`, the walk that follows a miss looking inside unfilled closed paths.
/// Otherwise the guard leaves things as they are, and no leaf measures an interior for it.
fn open(wanted: bool) -> Self {
Self { was: if wanted { INTERIOR_SEEN.replace(Some(false)) } else { INTERIOR_SEEN.get() } }
}
/// Did a leaf tested since [`Self::open`] have an unfilled closed path holding the point?
fn seen(&self) -> bool {
INTERIOR_SEEN.get() == Some(true)
}
}
impl Drop for InteriorProbe {
fn drop(&mut self) {
// A probe opened inside another passes what it saw on to it.
let seen = INTERIOR_SEEN.get() == Some(true);
INTERIOR_SEEN.set(self.was.map(|was| was || seen));
}
}
/// The hit inside path or compound path `n`'s closed subpaths, which have no visible fill, when
/// `n` takes one there ([`takes_interior`]) and `contains` says they hold the point. Without
/// [`HitOptions::unfilled_interiors`], under an [`InteriorProbe`], notes whether `n` would take
/// one with it, and hits nothing.
fn unfilled_inside(n: &Node, opt: HitOptions, contains: impl FnOnce() -> bool) -> Option<HitKind> {
if takes_interior(n, opt) {
return contains().then_some(HitKind::Fill);
}
if INTERIOR_SEEN.get() == Some(false) && takes_interior(n, HitOptions { unfilled_interiors: true, ..opt }) {
#[cfg(test)]
INTERIORS_PROBED.with(|c| c.set(c.get() + 1));
if contains() {
INTERIOR_SEEN.set(Some(true));
}
}
None
}
#[cfg(test)]
thread_local! {
/// How many interiors [`unfilled_inside`] measured for an [`InteriorProbe`] on this thread.
static INTERIORS_PROBED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
/// the region it clips to. It is also under an [`InMask`] guard.
@@ -667,10 +727,15 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
// an unfilled closed path ([`HitOptions::unfilled_interiors`]), when the first pass passes one
// holding `p` ([`InteriorProbe`]).
let painted = HitOptions { unfilled_interiors: false, ..opt };
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
let mut probe = Some(InteriorProbe::open(interiors));
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
if pass.unfilled_interiors && !probe.take().is_some_and(|probe| probe.seen()) {
break;
}
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
@@ -1017,12 +1082,15 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
/// only when the first, without it, hits nothing.
/// only when the first, without it, hits nothing and passes an unfilled closed path holding `p`
/// ([`InteriorProbe`]).
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !opt.outline);
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline || !probe.seen() {
return painted;
}
drop(probe);
hit_test_walk(doc, p, opt, skip, editable_only)
}
@@ -1672,8 +1740,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
match &n.kind {
NodeKind::Path { path, rule, .. } => {
let has_fill = n.appearance.has_visible_fill();
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed);
let inside = || interior.then(|| unfilled_inside(n, opt, || fill_contains(&closed_subpaths_at([path], p), *rule, p))).flatten();
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
@@ -1740,7 +1808,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
}
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
unfilled_inside(n, opt, || fill_contains(&closed(), *rule, p))
}
// The type path lies within the bounds: they rule out the rest before it is measured.
NodeKind::Text(t) if opt.type_path_only => {
@@ -2121,11 +2189,14 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
find.find(&art.art, &mut path, None, outline).map(|_| path)
};
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit, and only
// when the first walk passes one holding `p` ([`InteriorProbe`]).
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !outline);
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
if !opt.unfilled_interiors || opt.path_only || outline {
if !opt.unfilled_interiors || opt.path_only || outline || !probe.seen() {
return None;
}
drop(probe);
walk.restart();
pick(opt)
})
+105
View File
@@ -200,6 +200,88 @@ fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
}
/// An open path with a black stroke and no fill, from (`o`, 0) to (100, `o`) to (100, 100): its box
/// holds (50, 50), and it is drawn nowhere near that point.
fn open_corner(d: &mut Document, o: f64) -> Node {
let pts = [Point::new(o, 0.0), Point::new(100.0, o), Point::new(100.0, 100.0)];
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false));
Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
}
/// How many leaves [`hit_leaf`] tested while `f` ran, with its result.
fn leaves_tested<R>(f: impl FnOnce() -> R) -> (R, usize) {
LEAVES_TESTED.with(|c| c.set(0));
let r = f();
(r, LEAVES_TESTED.with(std::cell::Cell::get))
}
/// A selection click that hits nothing, where no unfilled closed path holds the point, walks the
/// document once: looking inside unfilled closed paths tests no more leaves than a click without
/// it. An unfilled closed path that holds the point is still hit inside.
#[test]
fn a_selection_click_that_hits_nothing_walks_the_document_once() {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
for i in 0..10 {
let corner = open_corner(&mut d, f64::from(i));
d.insert(Some(l), 99, corner).unwrap();
}
let p = Point::new(50.0, 50.0);
let (hit, without) = leaves_tested(|| hit_test(&d, p, SELECTING));
assert_eq!(hit, None);
assert_eq!(without, 10);
let (hit, with) = leaves_tested(|| hit_test(&d, p, INTERIORS));
assert_eq!(hit, None);
assert_eq!(with, without, "hit_test");
let (tops, with) = leaves_tested(|| objects_at(&d, p, INTERIORS, None));
assert!(tops.is_empty());
assert_eq!(with, without, "objects_at");
// An unfilled frame below them that holds the point: the second walk finds it.
let frame = d.alloc_id();
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(Some(l), 0, Node::path(frame, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap();
assert_eq!(hit_test(&d, p, INTERIORS).map(|h| h.leaf), Some(frame));
assert_eq!(objects_at(&d, p, INTERIORS, None), vec![frame]);
}
/// A hit test that does not look inside unfilled closed paths measures none of their interiors.
#[test]
fn a_hit_test_without_unfilled_interiors_measures_no_interior() {
let mut d = Document::new(200.0, 200.0);
stroked(&mut d, &FRAME, true);
let p = Point::new(50.0, 50.0);
let probed = |f: &dyn Fn()| {
INTERIORS_PROBED.with(|c| c.set(0));
f();
INTERIORS_PROBED.with(std::cell::Cell::get)
};
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, SELECTING), None)), 0, "hit_test");
assert_eq!(probed(&|| assert!(objects_at(&d, p, SELECTING, None).is_empty())), 0, "objects_at");
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, HitOptions { path_only: true, ..INTERIORS }), None)), 0, "by path only");
assert_eq!(probed(&|| assert!(hit_test(&d, p, INTERIORS).is_some())), 1, "looking inside");
}
/// Direct Selection on a dynamic symbol's instance that picks no part of its art, where no
/// unfilled closed path of the art holds the point, walks the art once.
#[test]
fn a_symbol_part_pick_that_hits_nothing_walks_the_art_once() {
let mut d = Document::new(200.0, 200.0);
let corners: Vec<Arc<Node>> = (0..10).map(|i| Arc::new(open_corner(&mut d, f64::from(i)))).collect();
let root = Node::group(d.alloc_id(), corners);
d.symbols.push(crate::Symbol { dynamic: true, name: "Corners".into(), art: Arc::new(root) });
let l = d.layers[0].id;
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corners".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
let n = d.node(inst).unwrap();
let p = Point::new(50.0, 50.0);
let (part, without) = leaves_tested(|| symbol_part_at(&d, n, p, SELECTING));
assert_eq!(part, None);
assert!(without >= 10, "{without} leaves tested");
let (part, with) = leaves_tested(|| symbol_part_at(&d, n, p, INTERIORS));
assert_eq!(part, None);
assert_eq!(with, without);
}
#[test]
fn long_plain_stroke_hits_its_middle_and_curved_end() {
let mut d = Document::new(200.0, 200.0);
@@ -3569,3 +3651,26 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
}
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
#[test]
fn hovers_past_many_paths_read_their_anchors_once() {
use vectorcraft_geom::anchors::measured_control_anchors;
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
for i in 0..100 {
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
d.insert(Some(l), 0, n).unwrap();
}
let empty = Point::new(900.0, 900.0);
let before = measured_control_anchors();
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = measured_control_anchors() - before;
assert!(first >= 400, "the first hover reads every square's anchors: {first}");
for _ in 0..3 {
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
}
assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor");
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
}
+4
View File
@@ -89,6 +89,10 @@ windows-native-keyring-store = "1.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
rayon = { version = "1.12", optional = true }
# Language packs (packs.rs): the shared font store installs them and finds its folder. Already in
# Cargo.lock (craft-font-manager), so this adds no new crate.
craft-font-store = { workspace = true }
craft-font-catalog = { workspace = true }
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
# Linux. All MIT OR Apache-2.0.
+5
View File
@@ -65,6 +65,8 @@ pub(crate) mod objects_on_path;
mod opacitymask;
mod overprint;
pub mod package;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
mod paint;
mod panelcmds;
pub mod params;
@@ -382,6 +384,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(tags::specs());
v.extend(interactivity::specs());
v.extend(spelling::specs());
// Language packs need a font store, which the web build has none of.
#[cfg(not(target_arch = "wasm32"))]
v.extend(packs::specs());
v.extend(svgfilter::specs());
v.extend(newart::specs());
v.extend(colortheme::specs());
+48 -2
View File
@@ -1,5 +1,6 @@
//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects
//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two;
//! out in rows and columns, a row or a column; Offset Objects chains them one after another in a
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
@@ -19,7 +20,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::recolor::Rng;
use vectorcraft_doc::{Node, NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
@@ -54,6 +55,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
grid
),
cmd!(
"addon.arrange.offset",
"Offset Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}",
has_multi,
offset
),
cmd!(
"addon.arrange.swap",
"Swap Objects",
@@ -233,6 +243,42 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "count": n }))
}
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.offset";
let row = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
let gap = number_in(p, "gap", 10.0, (-LIMIT, LIMIT), C)?;
let by_position = choice(p, C, "order", &["stacking", "position"])?.unwrap_or("stacking") == "position";
let reverse = switch_or(p, "reverse", false, C)?;
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
// The objects in stacking order from the back, each with its leading and trailing edge along the direction.
let mut items: Vec<(NodeId, f64, f64)> = roots
.iter()
.filter_map(|id| {
let b = effects::preview::bounds_of(d, &[*id], true)?;
Some(if row { (*id, b.x0, b.x1) } else { (*id, b.y0, b.y1) })
})
.collect();
if by_position {
items.sort_by(|a, b| a.1.total_cmp(&b.1));
}
if reverse {
items.reverse();
}
// The first stays; each later one starts `gap` past where the one before it now ends.
let mut end: Option<f64> = None;
let xfs: Vec<(NodeId, Affine)> = items
.iter()
.map(|&(id, start, finish)| {
let shift = end.map_or(0.0, |e| e + gap - start);
end = Some(finish + shift);
(id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }))
})
.collect();
transform_each(s, "Offset Objects", false, &xfs)?;
Ok(json!({ "count": items.len() }))
}
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.swap";
let size = switch_or(p, "size", false, C)?;
@@ -106,6 +106,134 @@ fn grid_measures_visual_bounds() {
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
}
#[test]
fn offset_chains_a_row_in_stacking_order_from_the_first_in_place() {
let mut s = session();
let a = rect(&mut s, 100.0, 50.0, 20.0, 10.0);
let b = rect(&mut s, 0.0, 200.0, 40.0, 30.0);
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[c, a, b]);
let n = steps(&s);
let r = s.execute("addon.arrange.offset", &json!({"gap": 5})).unwrap();
assert_eq!(r["count"], json!(3));
assert_eq!(steps(&s), n + 1, "one undo step");
// From the back: a stays, b starts 5 past a's right edge, c 5 past b's; each keeps its y.
assert!(near(bounds(&s, a), (100.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (125.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (170.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(bounds(&s, b), (0.0, 200.0, 40.0, 30.0)));
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)));
// Reversed: c stays, then b, then a. The gap defaults to 10.
s.execute("addon.arrange.offset", &json!({"reverse": true})).unwrap();
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (320.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, a), (370.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
}
#[test]
fn offset_chains_a_column_by_position_either_way_and_overlaps_with_a_negative_gap() {
let mut s = session();
let a = rect(&mut s, 0.0, 100.0, 10.0, 20.0);
let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0);
let c = rect(&mut s, 100.0, 40.0, 10.0, 30.0);
select(&mut s, &[a, b, c]);
// Top to bottom: b, c, a; each 5 into the one before it, keeping its x.
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "gap": -5})).unwrap();
assert!(near(bounds(&s, b), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (100.0, 5.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, a), (0.0, 30.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
s.execute("edit.undo", &json!({})).unwrap();
// Bottom to top: a stays, then c, then b.
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "reverse": true, "gap": 0})).unwrap();
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, c), (100.0, 120.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
assert!(near(bounds(&s, b), (50.0, 150.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
s.execute("edit.undo", &json!({})).unwrap();
// Left to right in a row: a, b, c.
s.execute("addon.arrange.offset", &json!({"order": "position", "gap": 1})).unwrap();
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
assert!(near(bounds(&s, b), (11.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (22.0, 40.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
// Visual boxes 24 wide, touching.
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
// A 200 wide object clipped to a 30 wide mask at x 100.
let clipped = rect(&mut s, 50.0, 50.0, 200.0, 10.0);
let mask = rect(&mut s, 100.0, 40.0, 30.0, 30.0);
select(&mut s, &[clipped, mask]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0];
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
select(&mut s, &[a, group, c]);
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
// The mask starts at a's right edge, and c at the mask's.
assert!(near(bounds(&s, mask), (20.0, 40.0, 30.0, 30.0)), "{:?}", bounds(&s, mask));
assert!(near(bounds(&s, clipped), (-30.0, 50.0, 200.0, 10.0)), "{:?}", bounds(&s, clipped));
assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 30.0, 50.0, 20.0, 20.0);
select(&mut s, &[a]);
assert!(!enabled(&s, "addon.arrange.offset"), "off with one object");
select(&mut s, &[a, b]);
assert!(enabled(&s, "addon.arrange.offset"));
// Already 10 apart in a row.
let n = steps(&s);
s.execute("addon.arrange.offset", &json!({})).unwrap();
assert_eq!(steps(&s), n, "no step when nothing moves");
// Two objects in one group are one object: nothing to chain.
s.execute("object.group", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
assert!(!enabled(&s, "addon.arrange.offset"), "off with one group");
refuses(&mut s, "addon.arrange.offset", &[json!({"gap": 50})]);
s.execute("edit.undo", &json!({})).unwrap();
let c = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
select(&mut s, &[b]);
s.execute("object.lock", &json!({})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
assert!(near(bounds(&s, b), (30.0, 50.0, 20.0, 20.0)), "the locked object stays, {:?}", bounds(&s, b));
assert!(near(bounds(&s, c), (20.0, 200.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
}
#[test]
fn offset_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0);
select(&mut s, &[a, b]);
refuses(
&mut s,
"addon.arrange.offset",
&[
json!({"direction": "diagonal"}),
json!({"direction": 1}),
json!({"gap": 1e7}),
json!({"gap": -1e7}),
json!({"gap": "10"}),
json!({"order": "size"}),
json!({"reverse": "yes"}),
],
);
}
#[test]
fn swap_trades_places_and_optionally_sizes() {
let mut s = session();
+2 -2
View File
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); values the symbol already has, newName included, change nothing and add no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_doc,
symbol_options
),
@@ -289,7 +289,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Symbol",
[],
None,
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}",
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them; when every instance already shows the symbol, nothing changes and no undo step is recorded) → {ids}",
has_selection,
symbol_replace
),
+8 -11
View File
@@ -347,13 +347,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
let dynamic = type_param(p, C)?;
let pixel = pixel_grid_param(p, C)?;
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
match pixel {
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
Some(_) => {}
}
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() && pixel.is_none() {
return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid"));
}
if let Some(ref n) = new_name
&& n != &name
@@ -362,7 +357,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("a symbol named `{n}` already exists")));
}
let final_name = new_name.clone().unwrap_or_else(|| name.clone());
s.edit("Symbol Options", |d, _| {
// Values the symbol already has leave the document as it is, and no undo step is added.
crate::cmd::colorcmds::edit_if_changed(s, "Symbol Options", |before, d| {
if let Some(ref n) = new_name
&& n != &name
{
@@ -439,7 +435,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(on) = pixel {
d.set_symbol_pixel_aligned(&final_name, on);
}
Ok(())
Ok(((), before != &*d))
})?;
Ok(options_json(&s.doc()?.doc, &final_name))
}
@@ -859,7 +855,8 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(EngineError::Other("no symbol instances selected".into()));
}
s.edit("Replace Symbol", |d, _| {
// Instances that already show the symbol leave the document as it is, and no undo step is added.
crate::cmd::colorcmds::edit_if_changed(s, "Replace Symbol", |before, d| {
let new = natural_size(d, &name);
for id in &ids {
let (old, other) = match d.node(*id).map(|n| &n.kind) {
@@ -877,7 +874,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
}
}
fit_overrides(d, &ids);
Ok(())
Ok(((), ids.iter().any(|id| before.node(*id) != d.node(*id))))
})?;
Ok(json!({ "ids": ids_json(&ids) }))
}
+55 -10
View File
@@ -194,6 +194,51 @@ impl Options {
/// Outlines with their layer colours ([`highlights`]).
pub type Outlines = Vec<(BezPath, [u8; 3])>;
/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
/// allocation back until the outlines are found again.
#[derive(Debug, Default, PartialEq)]
pub struct Highlights {
/// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
/// it stroked for these outlines while the number stays the same.
pub revision: u64,
/// The outlines in each layer color, the colors in the order of their first outline.
pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
}
/// The [`Highlights::revision`] the next set of outlines takes.
static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
static NO_HIGHLIGHTS: std::sync::LazyLock<std::sync::Arc<Highlights>> = std::sync::LazyLock::new(Default::default);
impl Highlights {
/// `outlines` grouped by color, under a new revision.
fn new(outlines: Outlines) -> std::sync::Arc<Self> {
if outlines.is_empty() {
return NO_HIGHLIGHTS.clone();
}
let mut groups: Vec<([u8; 3], Vec<BezPath>)> = vec![];
for (path, color) in outlines {
match groups.iter_mut().find(|(c, _)| *c == color) {
Some((_, paths)) => paths.push(path),
None => groups.push((color, vec![path])),
}
}
let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
}
/// How many outlines there are, in every color.
pub fn len(&self) -> usize {
self.groups.iter().map(|(_, paths)| paths.len()).sum()
}
/// Whether there is no outline.
pub fn is_empty(&self) -> bool {
self.groups.iter().all(|(_, paths)| paths.is_empty())
}
}
/// A Global Edit in progress (per document; not saved, not an undo step).
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalEdit {
@@ -202,7 +247,7 @@ pub struct GlobalEdit {
/// outline onto its own.
pub members: Vec<(NodeId, Affine)>,
/// [`highlights`] as of a document revision: the canvas asks every frame.
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
outlines: std::cell::RefCell<Option<(u64, std::sync::Arc<Highlights>)>>,
}
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
@@ -1017,31 +1062,31 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
/// ([`similar`]).
pub fn highlights(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
let Some(ge) = &st.global_edit else { return similar(s) };
if let Some((rev, out)) = &*ge.outlines.borrow()
&& *rev == st.revision
{
return out.clone();
}
let out = outlines(st, &ge.members);
let out = Highlights::new(outlines(st, &ge.members));
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
out
}
/// [`similar`]'s outlines as of a document revision and the options they were found with.
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>;
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
/// Before Global Edit starts: with one supported object selected, the outlines of the other
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
/// progress, or when fewer than two objects would be taken. Kept per document revision and
/// options, as finding them walks the whole document.
pub fn similar(s: &Session) -> Outlines {
let Some(st) = s.active() else { return vec![] };
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
return vec![];
return NO_HIGHLIGHTS.clone();
}
let o = &s.global_edit_options;
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
@@ -1050,10 +1095,10 @@ pub fn similar(s: &Session) -> Outlines {
{
return out.clone();
}
let out = match matches(s, o) {
let out = Highlights::new(match matches(s, o) {
Ok(m) if m.len() >= 2 => outlines(st, &m),
_ => vec![],
};
});
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
out
}
+11 -5
View File
@@ -105,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transparency Info",
[],
None,
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none); editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none). Without ids or id, with an object of a dynamic symbol instance selected by Direct Selection, opacity and blend are that object's for this instance, as transparency.set changes them; editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
has_doc,
info
),
@@ -489,10 +489,16 @@ impl Session {
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let ids = transparency_targets(s, p)?;
// The points `transparency.set` with the same `ids` (or none) fades.
let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) };
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
// Without `ids` or `id`, the values `transparency.set` without them edits: those of the panel,
// whose picked mesh points and selected dynamic symbol part take the opacity (and the part the
// blend mode).
let i = if p.get("ids").is_none() && p.get("id").is_none() {
s.transparency_info()
} else {
let ids = transparency_targets(s, p)?;
let points = super::paint::picked_mesh_points_of(s, &ids);
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
};
Ok(json!({
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
"opacity": i.opacity,
+117
View File
@@ -0,0 +1,117 @@
//! Language packs as commands (#4936): list, install and remove the packs that spell-check and
//! hyphenate languages other than English ([`crate::packs`]). They open nothing and never turn
//! downloading on: an install needs the Craft apps' shared download setting, which only the person
//! using an app turns on.
use serde_json::{Value, json};
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
use crate::packs::{self, Outcome};
/// The Language pack commands.
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "proof.packs",
"Language Packs",
[],
None,
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}",
always,
list
),
cmd!(
query "proof.installPack",
"Install Language Pack",
[],
None,
"{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}",
always,
install
),
cmd!(
query "proof.removePack",
"Remove Language Pack",
[],
None,
"{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}",
always,
remove
),
]
}
fn locale_param(p: &Value, command: &str) -> Result<String> {
let raw = text_param(p, "locale", command)?.ok_or_else(|| bad(command, "`locale` (a language tag like nl) is required"))?;
packs::parse_locale(raw).map_err(|e| bad(command, e))
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "proof.packs";
match p.get("refresh") {
None | Some(Value::Null) | Some(Value::Bool(false)) => {}
Some(Value::Bool(true)) => {
not_confined(C)?;
packs::refresh().map_err(EngineError::Other)?;
}
Some(_) => return Err(bad(C, "`refresh` must be true or false")),
}
// The jobs before the installed packs: an install makes craft-proof read its pack before it
// leaves the jobs, so one that ends between the two reads is in one list or the other.
let packs::Status { installing, refreshing, errors } = packs::status();
let installed = craft_proof::packs::installed();
let backend = packs::backend();
let rows: Vec<Value> = packs::available()
.iter()
.map(|p| {
json!({
"locale": p.locale, "name": p.name, "size": p.size, "licence": p.licence, "class": p.class,
"spelling": p.spelling, "hyphenation": p.hyphenation,
"installed": installed.iter().any(|i| i.locale == p.locale),
})
})
.collect();
// An install that ended since the last frame shows in every document's layout.
s.poll_language_packs();
Ok(json!({
"packs": rows,
"installed": installed.iter().map(|i| json!({"locale": i.locale, "name": i.name, "licence": i.licence})).collect::<Vec<_>>(),
"installing": installing.iter().map(|(l, done, total)| json!({"locale": l, "done": done, "total": total})).collect::<Vec<_>>(),
"refreshing": refreshing,
"errors": errors,
"downloads": backend.as_ref().is_some_and(|b| b.downloads_on()),
"indexOverride": backend.as_ref().and_then(|b| b.index_override()),
"available": backend.is_some(),
}))
}
/// Refuses `command` for a caller confined to automation roots: the packs are written into the font
/// store the Craft apps share, which is outside them.
fn not_confined(command: &str) -> Result<()> {
if crate::file_access::current().is_some() {
return Err(EngineError::Other(format!(
"automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots"
)));
}
Ok(())
}
fn install(s: &mut Session, p: &Value) -> Result<Value> {
let locale = locale_param(p, "proof.installPack")?;
not_confined("proof.installPack")?;
match packs::install(&locale).map_err(EngineError::Other)? {
Outcome::Started => Ok(json!({"locale": locale, "started": true})),
Outcome::Done => {
s.poll_language_packs();
Ok(json!({"locale": locale, "installed": true}))
}
}
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let locale = locale_param(p, "proof.removePack")?;
not_confined("proof.removePack")?;
packs::remove(&locale).map_err(EngineError::Other)?;
s.poll_language_packs();
Ok(json!({"locale": locale, "installed": false}))
}
+3
View File
@@ -1914,6 +1914,9 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
/// record one for another module → its report; saves the disabled list when loading changed it.
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
// Only native builds load modules, so only they save the disabled list.
#[cfg(target_arch = "wasm32")]
let _ = (s, turn);
let (report, retry) = match load.load.take() {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(modules)) => {
+2
View File
@@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[
"text.rescanFonts",
"text.fontList",
"text.spelling.",
// Language packs: downloads into, and removals from, the font store the Craft apps share.
"proof.",
"colorTheme.",
"magicWand.",
"eyedropper.",
@@ -7,6 +7,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.arrange.grid",
"addon.arrange.groupOverlapping",
"addon.arrange.markBounds",
"addon.arrange.offset",
"addon.arrange.randomizeOpacity",
"addon.arrange.replace",
"addon.arrange.size",
+4 -3
View File
@@ -325,10 +325,11 @@ pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize
/// not, since a save takes in the words another window saved), and a dictionary file attached.
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
/// out of date (Auto Spell Check checks the type again).
/// The dictionaries' generation: what [`misspellings`] found before it last changed may be out of
/// date (Auto Spell Check checks the type again). It moves on with the custom dictionary and with
/// craft-proof's own dictionaries, which change when a Language pack is installed or removed.
pub fn dictionary_generation() -> u64 {
DICTIONARY_GENERATION.load(Ordering::Relaxed)
DICTIONARY_GENERATION.load(Ordering::Relaxed).wrapping_add(craft_proof::dictionary_generation())
}
fn dictionary_changed() {
+5
View File
@@ -12,6 +12,8 @@ pub mod guard;
pub mod inspect;
pub mod journal;
pub mod link_watch;
#[cfg(not(target_arch = "wasm32"))]
pub mod packs;
pub mod schemas;
pub mod steps;
pub mod store;
@@ -220,6 +222,9 @@ pub struct Session {
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
/// that starts them ([`Session::load_plugins_in_background`]).
plugin_loads_in_background: bool,
/// The Language packs' generation the documents were last laid out for
/// ([`Session::poll_language_packs`]).
packs_seen: u64,
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
+389
View File
@@ -0,0 +1,389 @@
//! Language packs (#4936, RFC-0011): the spelling dictionary, hyphenation patterns and licence
//! texts of a language other than English, published by storytold/craft-i18n and installed into the
//! Craft apps' shared font store (craft-libs `craft-font-store`, item kind `language-pack`), where
//! craft-proof reads them (`craft_proof::packs`). A pack installed by another Craft app is used
//! here too, since the apps share the store.
//!
//! The store downloads only while its download setting is on, which only the person using an app
//! turns on, with their own click. Nothing here turns it on: [`use_font_store`] opens the store as
//! an agent's, so `proof.installPack` from the CLI, MCP or a script installs only after the person
//! allowed downloads.
//!
//! The packs state is the process's, like craft-proof's: one backend ([`set_backend`]), one list of
//! installs running and one error per locale. In the desktop app installs run on a thread of their
//! own ([`run_in_background`]) and [`crate::Session::poll_language_packs`] lays out the documents
//! again when one ends; elsewhere they return once installed.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
pub use craft_font_store::Cancel;
/// One pack the pack index lists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pack {
/// Lowercase BCP 47 tag (`nl`, `pt-br`), also the installed pack's folder name.
pub locale: String,
/// The language's own name (`Nederlands`).
pub name: String,
/// The download's size in bytes.
pub size: u64,
/// SPDX licence expression of the pack's data.
pub licence: String,
/// The licence class: `Embeddable` or `Download-only`.
pub class: String,
/// Whether it has a spelling dictionary.
pub spelling: bool,
/// Whether it has hyphenation patterns.
pub hyphenation: bool,
}
/// Where packs come from and go to: the font store ([`use_font_store`]), or a stand-in in tests.
pub trait Backend: Send + Sync {
/// The installed-packs folder craft-proof reads.
fn packs_dir(&self) -> PathBuf;
/// Whether the person allowed downloads.
fn downloads_on(&self) -> bool;
/// The packs of the index fetched last, with no request; empty before the first fetch.
fn cached_index(&self) -> Vec<Pack>;
/// Fetches the pinned pack index (needs downloads on).
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String>;
/// Downloads, checks and installs the pack for `locale`, which the index lists (needs downloads
/// on), calling `progress(done, total)` in bytes.
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String>;
/// Removes the installed pack for `locale`.
fn remove(&self, locale: &str) -> Result<(), String>;
/// The test index used instead of the pinned one (`CRAFT_LANGUAGE_PACK_INDEX`), if any.
fn index_override(&self) -> Option<String> {
None
}
}
/// An install running.
struct Job {
done: u64,
total: u64,
cancel: Cancel,
}
#[derive(Default)]
struct Jobs {
installing: BTreeMap<String, Job>,
/// A fetch of the index running.
refreshing: Option<Cancel>,
/// The last failure of each locale's install or removal, and of the index fetch (key `""`).
errors: BTreeMap<String, String>,
}
static BACKEND: RwLock<Option<Arc<dyn Backend>>> = RwLock::new(None);
static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refreshing: None, errors: BTreeMap::new() });
static BACKGROUND: AtomicBool = AtomicBool::new(false);
/// Goes up each time the installed packs change.
static GENERATION: AtomicU64 = AtomicU64::new(0);
fn jobs() -> MutexGuard<'static, Jobs> {
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Use `backend` for packs (`None`: none), and have craft-proof read its installed packs.
pub fn set_backend(backend: Option<Arc<dyn Backend>>) {
let dir = backend.as_ref().map(|b| b.packs_dir());
*BACKEND.write().unwrap_or_else(PoisonError::into_inner) = backend;
craft_proof::packs::set_packs_dir(dir);
changed();
}
/// The backend [`set_backend`] set.
pub fn backend() -> Option<Arc<dyn Backend>> {
BACKEND.read().unwrap_or_else(PoisonError::into_inner).clone()
}
/// Use the Craft apps' shared font store for packs, as an agent's store (it can't turn downloads
/// on): the desktop app and `vectorcraft-cli` call it at startup. Without a per-user folder there
/// are no packs.
pub fn use_font_store() {
let env = craft_font_catalog::FontEnv::from_process();
set_backend(craft_font_store::FontStore::for_agent(&env).map(|store| Arc::new(FontStoreBackend::new(store)) as Arc<dyn Backend>));
}
/// Run installs and index fetches on a thread of their own (the desktop app, so its window keeps
/// working) instead of returning once they are done.
pub fn run_in_background(on: bool) {
BACKGROUND.store(on, Ordering::Relaxed);
}
/// Goes up each time the installed packs change ([`crate::Session::poll_language_packs`]).
pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
/// Read the packs folder again: spelling and hyphenation in its languages change.
fn changed() {
craft_proof::packs::reload();
GENERATION.fetch_add(1, Ordering::Relaxed);
}
/// Whether an install or an index fetch is running.
pub fn busy() -> bool {
let j = jobs();
!j.installing.is_empty() || j.refreshing.is_some()
}
/// `raw` as a pack locale: trimmed, lower case, `_` read as `-` (`pt_BR` is `pt-br`); a language
/// tag of letters and digits, at most 35 bytes, in parts of at most 8.
pub fn parse_locale(raw: &str) -> Result<String, String> {
let l = raw.trim().to_ascii_lowercase().replace('_', "-");
let ok = !l.is_empty()
&& l.len() <= 35
&& l.split('-').all(|p| !p.is_empty() && p.len() <= 8 && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
if ok { Ok(l) } else { Err(format!("{:?} is not a language tag like nl or pt-br", raw.chars().take(40).collect::<String>())) }
}
fn no_backend() -> String {
"Language packs aren't available: there is no font store folder for this user".into()
}
fn downloads_off() -> String {
"downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into()
}
/// The packs the index fetched last lists.
pub fn available() -> Vec<Pack> {
backend().map(|b| b.cached_index()).unwrap_or_default()
}
/// What `proof.packs` reports about the jobs.
pub struct Status {
/// The installs running, as (locale, bytes done, bytes in all).
pub installing: Vec<(String, u64, u64)>,
/// Whether the index is being fetched.
pub refreshing: bool,
/// The last error of each locale (`""`: the index fetch).
pub errors: BTreeMap<String, String>,
}
/// The jobs running and the last errors.
pub fn status() -> Status {
let j = jobs();
Status {
installing: j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(),
refreshing: j.refreshing.is_some(),
errors: j.errors.clone(),
}
}
/// What an install or a fetch did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
/// Done.
Done,
/// Running in the background ([`run_in_background`]).
Started,
}
/// Runs `job` on a thread of its own in the background, else here and gives its own result (never
/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its
/// thread can't start.
fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result<Outcome, String> {
if !BACKGROUND.load(Ordering::Relaxed) {
return job().map(|()| Outcome::Done);
}
match std::thread::Builder::new().name("language-pack".into()).spawn(move || {
// The result is kept in the shared errors for `proof.packs`.
let _ = job();
}) {
Ok(_) => Ok(Outcome::Started),
Err(e) => {
undo();
Err(format!("couldn't start the download: {e}"))
}
}
}
/// Fetches the pinned pack index again. Needs downloads on.
pub fn refresh() -> Result<Outcome, String> {
let b = backend().ok_or_else(no_backend)?;
if !b.downloads_on() {
return Err(downloads_off());
}
let cancel = {
let mut j = jobs();
if j.refreshing.is_some() {
return Ok(Outcome::Started);
}
let cancel = Cancel::new();
j.refreshing = Some(cancel.clone());
j.errors.remove("");
cancel
};
run(
move || {
let r = b.fetch_index(&cancel).map(|_| ());
let mut j = jobs();
j.refreshing = None;
if let Err(e) = &r {
j.errors.insert(String::new(), e.clone());
}
r
},
|| jobs().refreshing = None,
)
}
/// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs
/// downloads on. Spelling and hyphenation in that language use it once it is installed.
pub fn install(locale: &str) -> Result<Outcome, String> {
let b = backend().ok_or_else(no_backend)?;
if !b.downloads_on() {
return Err(downloads_off());
}
let locale = locale.to_string();
let cancel = {
let mut j = jobs();
if j.installing.contains_key(&locale) {
return Ok(Outcome::Started);
}
let cancel = Cancel::new();
j.installing.insert(locale.clone(), Job { done: 0, total: 0, cancel: cancel.clone() });
j.errors.remove(&locale);
cancel
};
let l = locale.clone();
run(
move || {
let r = install_now(&*b, &l, &cancel);
// craft-proof reads the new pack before the job ends, so a caller that sees no
// install running sees the pack installed (`proof.packs`, `busy`).
if r.is_ok() {
changed();
}
let mut j = jobs();
j.installing.remove(&l);
if let Err(e) = &r {
j.errors.insert(l, e.clone());
}
r
},
|| {
jobs().installing.remove(&locale);
},
)
}
fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> {
let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale);
if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) {
return Err(format!("there is no Language pack for {locale}"));
}
b.install(locale, cancel, &mut |done, total| {
if let Some(job) = jobs().installing.get_mut(locale) {
(job.done, job.total) = (done, total);
}
})
}
/// Stops the install of `locale` (or the index fetch, for `""`) if one is running.
pub fn cancel(locale: &str) {
let j = jobs();
let c = if locale.is_empty() { j.refreshing.as_ref() } else { j.installing.get(locale).map(|job| &job.cancel) };
if let Some(c) = c {
c.cancel();
}
}
/// Removes the installed pack for `locale`; not while it is installing.
pub fn remove(locale: &str) -> Result<(), String> {
let b = backend().ok_or_else(no_backend)?;
if jobs().installing.contains_key(locale) {
return Err(format!("the {locale} pack is still installing"));
}
let r = b.remove(locale);
changed();
let mut j = jobs();
match &r {
Ok(()) => j.errors.remove(locale),
Err(e) => j.errors.insert(locale.to_string(), e.clone()),
};
r
}
/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75
/// packs), pinned by the sha256 of its `index.json`. The font store reads
/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only).
pub const PACK_INDEX: craft_font_store::PackIndexPin = craft_font_store::PackIndexPin {
url: "https://github.com/storytold/craft-i18n/releases/download/language-packs-2/index.json",
sha256: "b35c7aef0591177f18233b551da16035dcd615549ff874e169ffd19f16fea74b",
};
/// The font store as the packs [`Backend`].
struct FontStoreBackend {
store: craft_font_store::FontStore,
/// The index read or fetched last: an install takes its entry (URL, size, sha256) from it.
index: Mutex<Option<craft_font_store::PackIndex>>,
}
impl FontStoreBackend {
fn new(store: craft_font_store::FontStore) -> Self {
Self { store, index: Mutex::new(None) }
}
fn keep(&self, index: craft_font_store::PackIndex) -> Vec<Pack> {
let packs = index
.packs
.iter()
.map(|e| Pack {
locale: e.locale.clone(),
name: e.name.clone(),
size: e.size,
licence: e.licence.clone(),
class: e.class.clone(),
spelling: e.spelling,
hyphenation: e.hyphenation,
})
.collect();
*self.index.lock().unwrap_or_else(PoisonError::into_inner) = Some(index);
packs
}
}
impl Backend for FontStoreBackend {
fn packs_dir(&self) -> PathBuf {
self.store.language_packs_dir()
}
fn downloads_on(&self) -> bool {
self.store.network() == craft_font_store::Network::On
}
fn cached_index(&self) -> Vec<Pack> {
self.store.cached_language_pack_index(&PACK_INDEX).map(|i| self.keep(i)).unwrap_or_default()
}
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String> {
let index = self.store.fetch_language_pack_index(&PACK_INDEX, cancel).map_err(|e| e.to_string())?;
Ok(self.keep(index))
}
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
let held = self.index.lock().unwrap_or_else(PoisonError::into_inner).clone();
let index = held.or_else(|| self.store.cached_language_pack_index(&PACK_INDEX)).ok_or("the list of Language packs hasn't been fetched")?;
let entry = index.pack(locale).ok_or_else(|| format!("there is no Language pack for {locale}"))?.clone();
self.store.install_language_pack(&index, &entry, cancel, &mut |p| progress(p.done, p.total)).map(|_| ()).map_err(|e| e.to_string())
}
fn remove(&self, locale: &str) -> Result<(), String> {
self.store.remove_language_pack(locale).map_err(|e| e.to_string())
}
fn index_override(&self) -> Option<String> {
craft_font_store::language_pack_index_overridden()
}
}
/// The font store backend in `dir`, for tests that need the real store without a request.
#[cfg(test)]
pub(crate) fn font_store_in(dir: PathBuf) -> Arc<dyn Backend> {
Arc::new(FontStoreBackend::new(craft_font_store::FontStore::new(dir, craft_font_store::Caller::Agent)))
}
+12 -6
View File
@@ -2140,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let name = &text_arg(arg(a, 1), "name")?;
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
@@ -2158,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
/// or a Boolean becomes the text `String(value)` gives.
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let note = &text_arg(arg(a, 1), "note")?;
if note.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the note is too long".into()));
}
let item = this_item(h, a)?;
let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim()));
if !same {
edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?;
@@ -2196,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let hidden = boolean(arg(a, 1), "hidden")?;
refuse_protected_edit(h, this_item(h, a)?)?;
refuse_protected_edit(h, item)?;
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
}
@@ -2206,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let locked = boolean(arg(a, 1), "locked")?;
refuse_protected_edit(h, this_item(h, a)?)?;
refuse_protected_edit(h, item)?;
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
@@ -2216,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer {
}
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let v = number(arg(a, 1), "opacity")?;
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
@@ -2225,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
// replaces the one the graph keeps for its series or kind.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let item = this_item(h, a)?;
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
@@ -2271,12 +2274,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
/// would still replace the blend mode a graph keeps for the item's series or kind.
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let mode = match arg(a, 1) {
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
_ => None,
};
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
let item = this_item(h, a)?;
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
@@ -2403,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
}
fn item_set_position(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let p = point(arg(a, 1), "position")?;
move_to(h, a, Some(p[0]), Some(p[1]))
}
fn item_set_left(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let x = coordinate(arg(a, 1), "left")?;
move_to(h, a, Some(x), None)
}
fn item_set_top(h: &Host, a: &[Data]) -> Answer {
this_item(h, a)?;
let y = coordinate(arg(a, 1), "top")?;
move_to(h, a, None, Some(y))
}
@@ -2421,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer {
/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated
/// objects included.
fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
let item = this_item(h, a)?;
let what = if width { "width" } else { "height" };
let size = number(arg(a, 1), what)?;
if size <= 0.0 || size > MAX_SIZE {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
}
let item = this_item(h, a)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
+98 -21
View File
@@ -1225,7 +1225,26 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer {
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
path_at(h, *run, *uid, *high, *low)
let item = path_at(h, *run, *uid, *high, *low)?;
flush_other(h, item)?;
Ok(item)
}
/// Writes the waiting point changes of another path in the same Objects on Path group as `item`.
fn flush_other(h: &super::Host, item: Item) -> std::result::Result<(), HostError> {
let waiting = h.dom.pending.borrow().as_ref().map(|(w, _)| *w);
let other = waiting.is_some_and(|w| {
w.doc.uid == item.doc.uid
&& w.id != item.id
&& with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let read = d.ancestry(item.id).unwrap_or_default();
d.ancestry(w.id).is_some_and(|a| {
a.iter().any(|g| read.contains(g) && d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))
})
})
});
if other { flush(h) } else { Ok(()) }
}
/// `typename` of the points of a path that is still in its document.
@@ -1322,7 +1341,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid. A document that is the one the run last looked
/// at is skipped, as are its paths. While the object model writes one path's points
/// ([`super::State`]'s `one_path`), only that path is looked at in its document.
/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing
/// Objects on Path group are looked at in its document.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
let seen = h.dom.point_nodes.borrow();
@@ -1335,9 +1355,24 @@ pub(super) fn see_all_points(h: &super::Host) {
let mut keys = Vec::new();
// The documents that changed since the last look, kept as they are now.
for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) {
// Editing a path in an Objects on Path group can move other paths in the group.
let mut moved = Vec::new();
match s.documents().iter().find(|d| d.uid == *uid) {
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue,
Some(st) => {
if let Some(item) = one.filter(|i| i.doc.uid == *uid) {
let d = &st.doc;
let group = d.ancestry(item.id).and_then(|a| {
a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g))
});
if let Some(g) = group {
g.walk(&mut |n: &crate::doc::Node| {
if n.id != item.id && paths.contains_key(&n.id.0) {
moved.push((*uid, n.id.0));
}
});
}
}
docs.insert(*uid, st.doc.clone());
}
None => {
@@ -1345,7 +1380,10 @@ pub(super) fn see_all_points(h: &super::Host) {
}
}
match one {
Some(item) if item.doc.uid == *uid => keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))),
Some(item) if item.doc.uid == *uid => {
keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0)));
keys.append(&mut moved);
}
_ => keys.extend(paths.keys().map(|id| (*uid, *id))),
}
}
@@ -1432,6 +1470,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
flush_other(h, item)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
}
@@ -1664,38 +1703,69 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer {
let sel = &st.selection;
(sel.anchors.contains_key(&item.id) || sel.segments.contains_key(&item.id)).then(|| sel.clone())
};
// Writing the points can prune the selection, and selecting loads the selected paths' paint
// into new art, so new art's paint, the defaults a script set included, is put back.
keeping_paint(h, || remove_point(h, item, i, selected))?;
cut_points(h, item);
Ok(Data::Undefined)
}
/// Removes point `i` of the path of `item` for [`pt_remove`], and renumbers `selected`, the
/// direct selection of the path's points before the removal.
fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::doc::Selection>) -> std::result::Result<(), HostError> {
let removed = edit_points(h, item, |subs| {
let (s, j) = locate(subs, i)?;
let sp = subs.get_mut(s)?;
// The segment that closes a closed subpath ends at its first anchor.
let closing = (sp.closed && j == 0).then(|| sp.anchors.len() - 1);
// The segment that closes a closed subpath runs from its last anchor to its first.
let last = sp.closed.then(|| sp.anchors.len() - 1);
sp.anchors.remove(j);
let gone = sp.anchors.is_empty();
if gone {
subs.remove(s);
}
Some((s, j, gone, closing))
Some((s, j, gone, last))
})?;
if let (Some((s, j, gone, closing)), Some(mut sel)) = (removed, selected) {
// The points are written first, and the selection is then set with selection commands,
// which the journal records with the edit.
flush(h)?;
renumber_selected(&mut sel, item.id, s, j, gone, closing);
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
})?;
if let (Some((s, j, gone, last)), Some(before)) = (removed, selected) {
let mut sel = before.clone();
renumber_selected(&mut sel, item.id, s, j, gone, last);
// A selection the removal leaves as it was waits with the points, so that removals in a
// row are written together, unless its anchors are now all of the path's, which selects
// the path whole, or the path is in an Objects on Path group, which places it again.
let wait = sel == before && {
let valid = read_points(h, item, |subs| {
sel.anchors.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| *k < sp.anchors.len())))
&& sel.segments.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| sp.has_segment(*k, true))))
})?;
let total = points_of(h, item)?;
let all = sel.anchors.get(&item.id).is_some_and(|a| a.len() >= total) && !sel.segments.contains_key(&item.id);
let on_path = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
d.ancestry(item.id).is_some_and(|a| a.iter().any(|g| d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)))
});
valid && !all && !on_path
};
if !wait {
// The points are written first, and the selection is then set with selection
// commands, which the journal records with the edit.
flush(h)?;
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
})?;
}
}
cut_points(h, item);
Ok(Data::Undefined)
Ok(())
}
/// Updates the direct selection `sel` of the path `id` after the anchor `j` of its subpath `s` was
/// removed, and the subpath with it when `gone`: the anchor, the segments it ended and their other
/// ends leave the selection, unless a segment still selected ends there, and the anchors, segments
/// and subpaths after it keep the points they selected. `closing` is the segment that closed the
/// subpath at the removed anchor, when it did.
fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, closing: Option<usize>) {
/// and subpaths after it keep the points they selected. `last` is the index of the subpath's last
/// anchor before the removal when the subpath is closed: its closing segment runs from that anchor
/// to anchor 0.
fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, last: Option<usize>) {
// The closing segment ends at the removed anchor when the removed anchor is the first one.
let closing = last.filter(|_| j == 0);
// An anchor (or a segment, by its first anchor) after the removed one moves down one place.
let shift = |(p, k): (usize, usize), segment: bool| -> Option<(usize, usize)> {
match p.cmp(&s) {
@@ -1713,7 +1783,14 @@ fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: u
let cut: Vec<(usize, usize)> = segments.iter().copied().filter(|g| shift(*g, true).is_none() && g.0 == s && !gone).collect();
for (p, k) in cut {
// Segment k runs from anchor k to anchor k + 1; one of the two is the removed one.
let other = if k == j { k + 1 } else { k };
// The closing segment of a closed subpath ends at anchor 0.
let other = if k != j {
k
} else if last == Some(k) {
0
} else {
k + 1
};
// The closing segment's other end is its first anchor, the old last one.
let other = if closing == Some(k) { k } else { other };
ends.extend(shift((p, other), false));
+1
View File
@@ -163,6 +163,7 @@ pub fn refused_to_scripts(id: &str) -> bool {
"edit.undoGroup.",
"file.recovery.",
"stroke.widthProfile.",
"proof.",
];
const IDS: &[&str] = &[
"text.addFontFiles",
+2 -1
View File
@@ -111,6 +111,7 @@ impl Session {
plugin_dir: None,
plugin_loads: Default::default(),
plugin_loads_in_background: false,
packs_seen: 0,
scripts_dir: None,
startup_scripts_dir: None,
script_listing_clock: Default::default(),
@@ -359,7 +360,7 @@ impl Session {
/// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved
/// document stays saved, and its undo history keeps its documents as they are. The document is
/// left as it is when `stale` picks nothing.
fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
pub(crate) fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
let Some(st) = self.docs.get_mut(index) else { return };
if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) {
return;
+38
View File
@@ -1093,6 +1093,44 @@ impl Session {
self.plugin_loads_in_background = on;
}
/// Lays every document out again when the installed Language packs changed since the last
/// call (an install in the background ended, or a pack was removed), since spelling and
/// hyphenation in their languages change → whether an install or index fetch is still running,
/// so the app looks again. The app calls it as its frames go by.
pub fn poll_language_packs(&mut self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
// Busy first: an install moves the generation on before it ends, so when none is
// running any more its change is read below.
let busy = crate::packs::busy();
let now = crate::packs::generation();
if now != self.packs_seen {
self.packs_seen = now;
for index in 0..self.docs.len() {
// A document in the back is measured in its own composite fonts, lent for the
// measuring, as `measure_back_document` does: the front document's are the
// ones registered, and one of the same name may differ.
let back_fonts = (self.active != Some(index)).then(|| self.docs.get(index).map(|st| st.doc.composite_fonts.clone())).flatten();
let lent = back_fonts.as_ref().map(|fonts| vectorcraft_text::FontDb::global().lend_document_composite_fonts(fonts));
// Type in a language of its own may break its lines elsewhere now: it is
// measured again (not an edit), so its selection box and hits follow.
self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some()));
drop(lent);
if let Some(st) = self.docs.get_mut(index) {
st.revision += 1;
}
}
}
busy
}
// The web build has no packs.
#[cfg(target_arch = "wasm32")]
{
let _ = self.packs_seen;
false
}
}
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
/// load's file-name order, up to the first module still loading, without waiting → whether
/// some are still loading. A load starts once the loads before it are done. When another
+2
View File
@@ -128,6 +128,8 @@ mod outlineobject;
pub(super) mod outlinestroke;
mod overprint;
mod package;
#[cfg(not(target_arch = "wasm32"))]
mod packs;
mod paintopacity;
mod paintproxy;
mod panelcmds;
+55
View File
@@ -3048,6 +3048,61 @@ fn symbol_export_type_defaults_to_movie_clip_and_round_trips() {
assert!(s.execute("symbol.options", &json!({"name": "Renamed"})).is_err());
}
/// `symbol.options` whose values are the ones the symbol already has changes neither the document
/// nor its revision, and records no undo step.
#[test]
fn symbol_options_that_change_nothing_record_no_undo_step() {
let mut s = session();
make_symbol(&mut s);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let unchanged = [
json!({"name": "Box", "newName": "Box"}),
json!({"name": "Box", "newName": " Box "}),
json!({"name": "Box", "registration": 4}),
json!({"name": "Box", "exportType": "movieClip"}),
json!({"name": "Box", "nineSlice": false}),
json!({"name": "Box", "type": "static"}),
json!({"name": "Box", "alignToPixelGrid": false}),
json!({"name": "Box", "newName": "Box", "registration": 4, "exportType": "movieClip", "type": "static", "alignToPixelGrid": false}),
];
let before = state(&s);
for p in &unchanged {
assert_eq!(s.execute("symbol.options", p).unwrap()["name"], "Box");
assert_eq!(state(&s), before, "{p} changes nothing");
}
s.execute("symbol.options", &json!({"name": "Box", "registration": 0, "exportType": "graphic", "type": "dynamic"})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "changed options are one undo step");
let before = state(&s);
let r = s.execute("symbol.options", &json!({"name": "Box", "registration": 0, "exportType": "graphic", "type": "dynamic"})).unwrap();
assert_eq!((r["registration"].clone(), r["exportType"].clone(), r["type"].clone()), (json!(0), json!("graphic"), json!("dynamic")));
assert_eq!(state(&s), before, "setting the options again changes nothing");
s.execute("symbol.options", &json!({"name": "Box", "newName": "Logo"})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step");
}
/// `symbol.replace` with the symbol the instances already show changes neither the document nor
/// its revision, and records no undo step.
#[test]
fn symbol_replace_with_the_same_symbol_records_no_undo_step() {
let mut s = session();
let (inst, _, _) = make_symbol(&mut s);
rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("symbol.new", &json!({"name": "Small"})).unwrap();
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let before = state(&s);
assert_eq!(s.execute("symbol.replace", &json!({"name": "Box", "ids": [inst.0]})).unwrap()["ids"], json!([inst.0]));
assert_eq!(state(&s), before, "replacing an instance with its own symbol changes nothing");
s.execute("symbol.replace", &json!({"name": "Small", "ids": [inst.0]})).unwrap();
assert!(matches!(&node(&s, inst).kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Small"));
assert_eq!(undo_steps(&s), before.2 + 1, "replacing it with another symbol is one undo step");
}
#[test]
fn sprayer_command_creates_a_symbol_set_and_alt_removes() {
let mut s = session();
@@ -1184,6 +1184,28 @@ fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6);
}
#[test]
fn transparency_info_reports_the_picked_object_that_transparency_set_edits() {
let mut s = session();
let inst = pair(&mut s, "dynamic");
s.execute("transparency.set", &json!({"ids": [inst.0], "opacity": 75, "blend": "screen", "isolate": true, "knockout": "on"})).unwrap();
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap();
let shown = |v: &Value| (v["ids"].clone(), v["opacity"].as_f64(), v["blend"].clone(), v["isolate"].clone(), v["knockout"].clone());
// Without ids, the picked object's opacity and blend mode, and the instance's isolate and knockout.
let info = s.execute("transparency.info", &json!({})).unwrap();
assert_eq!(shown(&info), (json!([inst.0]), Some(50.0), json!("Multiply"), json!(true), json!("on")));
let panel = s.transparency_info();
assert_eq!((panel.opacity, panel.blend.map(vectorcraft_color::BlendMode::label)), (Some(50.0), Some("Multiply")));
// The other object of the art draws as the symbol does.
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [0]})).unwrap();
let info = s.execute("transparency.info", &json!({})).unwrap();
assert_eq!(shown(&info), (json!([inst.0]), Some(100.0), json!("Normal"), json!(true), json!("on")));
// With the instance's id, the instance itself, as transparency.set with that id edits it.
let info = s.execute("transparency.info", &json!({"id": inst.0})).unwrap();
assert_eq!(shown(&info), (json!([inst.0]), Some(75.0), json!("Screen"), json!(true), json!("on")));
}
#[test]
fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
let mut s = session();
+38 -4
View File
@@ -150,7 +150,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
let moved = node(&s, copies[1]).stroke_path().unwrap();
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
assert!(shown.groups.iter().flat_map(|(_, paths)| paths.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
@@ -162,9 +162,7 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
let [a, b, ..] = squares(&mut s);
let outline = node(&s, b).stroke_path().unwrap();
let shown = |s: &mut Session| {
s.overlays(ViewInfo::default())
.iter()
.any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0))
s.overlays(ViewInfo::default()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Outlines { paths, .. } if paths.contains(&outline)))
};
sel(&mut s, &[a]);
s.select_tool("selection", ViewInfo::default()).unwrap();
@@ -175,6 +173,42 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
assert!(shown(&mut s), "while Global Edit is on, with any tool");
}
/// Each frame hands the canvas the kept outlines, one overlay per layer color sharing them, with no copy of a path; the
/// revision changes when the outlines are found again.
#[test]
fn every_frame_shares_the_kept_outlines_instead_of_copying_each_one() {
use std::sync::Arc;
use vectorcraft_tools::Overlay;
let outlines = |s: &mut Session| -> Vec<(Arc<[vectorcraft_geom::BezPath]>, u64)> {
s.overlays(ViewInfo::default())
.into_iter()
.filter_map(|o| if let Overlay::Outlines { paths, revision, .. } = o { Some((paths, revision)) } else { None })
.collect()
};
let mut s = session();
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
for i in 1..200 {
rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0);
}
sel(&mut s, &[key]);
s.select_tool("selection", ViewInfo::default()).unwrap();
let first = outlines(&mut s);
let [(paths, revision)] = &first[..] else { panic!("one overlay for the one layer color, not one per object: {}", first.len()) };
assert_eq!(paths.len(), 199);
let second = outlines(&mut s);
let [(again, same)] = &second[..] else { panic!("{}", second.len()) };
assert!(Arc::ptr_eq(paths, again), "the next frame gets the same outlines, not a copy");
assert_eq!(same, revision);
s.execute("select.globalEdit", &json!({})).unwrap();
let on = outlines(&mut s);
let [(members, started)] = &on[..] else { panic!("{}", on.len()) };
assert_eq!(members.len(), 199);
assert_ne!(started, revision, "outlines found again take a new revision");
let next = outlines(&mut s);
let [(kept, still)] = &next[..] else { panic!("{}", next.len()) };
assert!(Arc::ptr_eq(members, kept) && still == started, "and are kept from frame to frame while Global Edit is on");
}
#[test]
fn size_and_appearance_options_narrow_the_match() {
let mut s = session();
+267
View File
@@ -0,0 +1,267 @@
//! Language packs (`proof.packs`, `proof.installPack`, `proof.removePack`, #4936): an installed pack
//! spell-checks its language in the documents, an install needs downloads on, and a pack installed
//! in the background reaches the documents once it ends.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use serde_json::{Value, json};
use crate::packs::{self, Backend, Cancel, Pack};
use crate::*;
/// Tests that set the process-wide packs backend take turns.
fn packs_lock() -> MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Puts the process back to no packs and no background installs when dropped, also when the test
/// panicked: the jobs still running are cancelled and waited for, so none outlives its test. Then
/// it deletes the test's folder.
struct Reset(PathBuf);
impl Drop for Reset {
fn drop(&mut self) {
while packs::busy() {
for (locale, _, _) in packs::status().installing {
packs::cancel(&locale);
}
packs::cancel("");
std::thread::yield_now();
}
packs::run_in_background(false);
packs::set_backend(None);
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A new folder for one test.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-packs-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
/// Writes a small Dutch pack into `packs/nl`, laid out as the font store unpacks one.
fn write_dutch_pack(packs: &Path) {
let dir = packs.join("nl");
std::fs::create_dir_all(dir.join("LICENCES")).unwrap();
std::fs::write(dir.join("pack.toml"), "locale = \"nl\"\nname = \"Nederlands (test)\"\nlicence = \"MIT\"\n").unwrap();
std::fs::write(dir.join("LICENCES").join("COPYING"), "Test licence text.").unwrap();
std::fs::write(dir.join("spelling.aff"), "SET UTF-8\nTRY esianrtolducgmphbykfvwjzxq\n").unwrap();
std::fs::write(dir.join("spelling.dic"), "5\nhet\nhuis\nen\nde\nfiets\n").unwrap();
}
/// A session with a new document holding Dutch point type with one misspelt word, `fietz`.
fn dutch_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Het huis en de fietz"})).unwrap()["id"].clone();
s.execute("text.setFormat", &json!({"ids": [id], "language": "Dutch"})).unwrap();
s
}
/// The unknown words a check lists, as (word, lang).
fn unknown(s: &mut Session) -> Vec<(String, String)> {
let r = s.execute("text.spelling.check", &json!({})).unwrap();
r["words"].as_array().unwrap().iter().map(|w| (w["word"].as_str().unwrap().into(), w["lang"].as_str().unwrap().into())).collect()
}
fn installed_locales(s: &mut Session) -> Vec<String> {
let r = s.execute("proof.packs", &json!({})).unwrap();
r["installed"].as_array().unwrap().iter().map(|p| p["locale"].as_str().unwrap().to_string()).collect()
}
#[test]
fn a_pack_in_the_font_store_checks_its_language_until_it_is_removed() {
let _turn = packs_lock();
let root = folder("store");
let _reset = Reset(root.clone());
let mut s = dutch_session();
let without = unknown(&mut s);
// A pack another Craft app installed into the shared store.
let store = packs::font_store_in(root.clone());
write_dutch_pack(&store.packs_dir());
packs::set_backend(Some(store));
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())], "checked in Dutch by the pack");
assert_eq!(installed_locales(&mut s), ["nl"]);
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!((listed["available"].clone(), listed["downloads"].clone()), (json!(true), json!(false)), "downloads stay off");
let before = s.doc().unwrap().revision;
assert_eq!(s.execute("proof.removePack", &json!({"locale": "NL"})).unwrap()["installed"], false);
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), without, "checked as before the pack");
assert!(installed_locales(&mut s).is_empty());
assert!(s.execute("proof.removePack", &json!({"locale": "nl"})).is_err(), "no longer installed");
}
/// A stand-in for the font store: it lists a Dutch pack and installs it by writing its files.
struct Fake {
dir: PathBuf,
downloads: bool,
/// While set, an install waits until it is cleared.
hold: AtomicBool,
}
impl Backend for Fake {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
self.downloads
}
fn cached_index(&self) -> Vec<Pack> {
let nl = Pack {
locale: "nl".into(),
name: "Nederlands".into(),
size: 2,
licence: "MIT".into(),
class: "Embeddable".into(),
spelling: true,
hyphenation: false,
};
vec![nl]
}
fn fetch_index(&self, _: &Cancel) -> std::result::Result<Vec<Pack>, String> {
Ok(self.cached_index())
}
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> {
progress(1, 2);
while self.hold.load(Ordering::Relaxed) {
if cancel.is_cancelled() {
return Err("cancelled".into());
}
std::thread::yield_now();
}
// The index lists only Dutch, which `packs::install` checks first.
if locale != "nl" {
return Err(format!("asked to install {locale}"));
}
write_dutch_pack(&self.dir);
Ok(())
}
fn remove(&self, locale: &str) -> std::result::Result<(), String> {
std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string())
}
}
fn error(s: &mut Session, id: &str, p: Value) -> String {
s.execute(id, &p).unwrap_err().to_string()
}
#[test]
fn an_install_needs_downloads_on_and_a_pack_the_index_lists() {
let _turn = packs_lock();
let root = folder("fake");
let _reset = Reset(root.clone());
let mut s = dutch_session();
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("aren't available"), "no store, no packs");
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: false, hold: AtomicBool::new(false) })));
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("downloading is turned off"));
assert!(error(&mut s, "proof.packs", json!({"refresh": true})).contains("downloading is turned off"));
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
for bad in [json!({}), json!({"locale": ""}), json!({"locale": "../nl"}), json!({"locale": 5})] {
assert!(s.execute("proof.installPack", &bad).is_err(), "{bad} is refused");
}
assert!(!root.exists(), "a refused locale writes nothing");
assert!(error(&mut s, "proof.installPack", json!({"locale": "fy"})).contains("no Language pack for fy"));
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["fy"].is_string(), "the failure is reported");
let before = s.doc().unwrap().revision;
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl_NL"})).contains("no Language pack for nl-nl"), "nl_NL reads as nl-nl");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true);
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!(listed["packs"][0]["installed"], true);
}
#[test]
fn an_install_in_the_background_reaches_the_documents_when_it_ends() {
let _turn = packs_lock();
let root = folder("background");
let _reset = Reset(root.clone());
let mut s = dutch_session();
let without = unknown(&mut s);
let fake = Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) });
packs::set_backend(Some(fake.clone()));
packs::run_in_background(true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true, "asked again, it is the same install");
let listed = s.execute("proof.packs", &json!({})).unwrap();
assert_eq!(listed["installing"][0]["locale"], "nl");
assert!(error(&mut s, "proof.removePack", json!({"locale": "nl"})).contains("still installing"));
assert_eq!(unknown(&mut s), without, "not used before it is installed");
let before = s.doc().unwrap().revision;
fake.hold.store(false, Ordering::Relaxed);
while s.poll_language_packs() {
std::thread::yield_now();
}
s.poll_language_packs();
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
}
#[test]
fn a_cancelled_background_install_installs_nothing() {
let _turn = packs_lock();
let root = folder("cancel");
let _reset = Reset(root.clone());
let mut s = dutch_session();
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) })));
packs::run_in_background(true);
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
packs::cancel("nl");
while packs::busy() {
std::thread::yield_now();
}
assert!(installed_locales(&mut s).is_empty());
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled"));
}
/// A caller confined to automation roots lists the packs but can't fetch, install or remove them:
/// the store they are written into is outside its roots.
#[test]
fn a_confined_caller_lists_packs_but_cannot_change_them() {
let _turn = packs_lock();
let root = folder("confined");
let _reset = Reset(root.clone());
let roots_dir = folder("confined-roots");
std::fs::create_dir_all(&roots_dir).unwrap();
let mut s = dutch_session();
write_dutch_pack(&root);
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
let roots = crate::file_access::AutomationRoots::new(&[roots_dir.as_path()], &[roots_dir.as_path()]).unwrap();
let mut confined = |cmd: &str, p: Value| crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string());
for (cmd, p) in
[("proof.installPack", json!({"locale": "nl"})), ("proof.removePack", json!({"locale": "nl"})), ("proof.packs", json!({"refresh": true}))]
{
let e = confined(cmd, p).unwrap_err();
assert!(e.contains("automation path rejected"), "{cmd}: {e}");
}
assert_eq!(confined("proof.packs", json!({})).unwrap()["installed"][0]["locale"], "nl", "listing is allowed");
assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there");
let _ = std::fs::remove_dir_all(&roots_dir);
}
/// A script's rollback cannot put back what an install writes into the shared font store, so a
/// script cannot run the pack commands.
#[test]
fn a_script_cannot_install_a_pack() {
let _turn = packs_lock();
let root = folder("script");
let _reset = Reset(root.clone());
let mut s = dutch_session();
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
let e = error(&mut s, "script.run", json!({"source": "vc.run('proof.installPack', {locale: 'nl'});", "name": "t.js"}));
assert!(e.contains("a script cannot run `proof.installPack`"), "{e}");
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true, "outside a script it installs");
}
+23
View File
@@ -1702,6 +1702,29 @@ fn wrappers_go_stale_after_delete_and_undo() {
assert!(e.contains("Stale page item"), "{e}");
}
/// A setter on a removed item reports the stale item before it checks the value it was given.
#[test]
fn setters_on_a_stale_item_report_it_before_a_bad_value() {
let (mut s, _, _) = doc();
for set in [
"name = {}",
"note = {}",
"hidden = 'x'",
"locked = 'x'",
"opacity = 500",
"blendingMode = 'x'",
"selected = 'x'",
"position = 'x'",
"left = 'x'",
"top = 'x'",
"width = -1",
"height = -1",
] {
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0].duplicate(); i.remove(); i.{set};"));
assert!(e.contains("Stale page item"), "{set}: {e}");
}
}
/// File › Revert loads objects with the ids they were saved with: an object or a layer read before
/// the revert does not name the loaded one.
#[test]
+215
View File
@@ -809,6 +809,221 @@ fn removing_a_point_keeps_the_direct_selection_on_the_same_anchors() {
assert!(!s.active().unwrap().selection.objects.contains(&a));
}
/// Removing the last anchor of a closed path with only its closing segment selected takes the
/// segment's other end, the first anchor, out of the selection too.
#[test]
fn removing_the_last_point_deselects_the_closing_segment_and_its_first_anchor() {
let (mut s, a, _) = doc();
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 3]], "mode": "set"})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();");
assert_eq!(selected_anchors(&s, a), None, "the first anchor is not selected");
assert!(!s.active().unwrap().selection.objects.contains(&a));
}
/// Removing a point that renumbers the selected anchors keeps the new-art stroke width a script
/// set, so the next path it draws gets it.
#[test]
fn removing_a_point_keeps_the_default_stroke_width_a_script_set() {
let (mut s, a, _) = doc();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument; d.defaultStrokeWidth = 7; d.pathItems[0].pathPoints[0].remove();\
vc.log(d.pathItems.rectangle(10, 10, 5, 5).strokeWidth);",
);
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)]));
assert_eq!(out, [json!(7)]);
}
/// Removals that leave the direct selection as it was are written together, with one
/// `path.setAnchors`.
#[test]
fn removals_that_keep_the_selection_are_written_together() {
let (mut s, a, _) = doc();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap();
let start = s.journal.len();
log(&mut s, "var q = app.activeDocument.pathItems[0].pathPoints; q[3].remove(); q[2].remove();");
let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count();
assert_eq!(writes, 1);
assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors.len(), 2);
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)]));
}
#[test]
fn removing_a_replacement_point_clears_selection_of_a_missing_subpath() {
for segments in [false, true] {
let (mut s, a, _) = doc();
let anchors: Vec<Value> = (0..3).map(|x| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false})).collect();
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": [{"anchors": anchors, "closed": false}, {"anchors": anchors, "closed": false}]}))
.unwrap();
if segments {
s.execute("select.segments", &json!({"id": a.0, "segments": [[1, 0]], "mode": "set"})).unwrap();
} else {
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[1, 0]]}], "mode": "set"})).unwrap();
}
let out = log(
&mut s,
"var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [20, 0], [30, 0]]);\
p.pathPoints[3].remove(); vc.log(p.selected); vc.log(p.selectedPathPoints.length);",
);
assert_eq!(out, [json!(false), json!(0)], "segments: {segments}");
let path = node(&s, a);
let subs = &path.path_data().unwrap().subpaths;
assert_eq!(subs.len(), 1);
assert_eq!(subs[0].anchors.len(), 3);
assert_eq!(selected_anchors(&s, a), None);
let sel = &s.active().unwrap().selection;
assert!(!sel.segments.contains_key(&a));
assert!(!sel.objects.contains(&a));
}
}
#[test]
fn reading_an_unrelated_path_keeps_point_edits_written_together() {
let (mut s, a, b) = doc();
let before = node(&s, b);
let start = s.journal.len();
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, p = P[0].pathPoints, q = P[1].pathPoints;\
p[0].anchor = [20, 30]; vc.log(q.length); vc.log(q[0].anchor); p[1].anchor = [50, 30];",
);
let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count();
assert_eq!(writes, 1);
assert_eq!(out, [json!(4), json!([100, 200])]);
assert_eq!(node(&s, b), before);
let edited = node(&s, a);
let anchors = &edited.path_data().unwrap().subpaths[0].anchors;
assert_eq!(anchors[0].p, vectorcraft_geom::Point::new(20.0, 270.0));
assert_eq!(anchors[1].p, vectorcraft_geom::Point::new(50.0, 270.0));
}
/// Removing the one point that was not direct-selected leaves every point selected, which
/// selects the path whole.
#[test]
fn removing_the_only_unselected_point_selects_the_path_whole() {
let (mut s, a, _) = doc();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]}], "mode": "set"})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();");
assert_eq!(selected_anchors(&s, a), None);
assert!(s.active().unwrap().selection.objects.contains(&a));
}
/// Removing a point of a direct-selected member of an Objects on Path group writes it at once, so
/// its points read where the group places it.
#[test]
fn removing_a_point_of_a_selected_member_reads_where_the_group_places_it() {
let (mut s, b) = doc_on_path();
s.execute("select.anchorsMany", &json!({"items": [{"id": b.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap();
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, m = P.getByName('m');\
m.pathPoints[3].remove(); m.pathPoints[2].remove(); vc.log(m.pathPoints[0].anchor);\
P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor);",
);
assert_eq!(out[0], out[1], "the member read where it is after the run");
}
/// [`doc`] with path `drive`, the path of an Objects on Path group that holds `b`, named `m`.
fn doc_on_path() -> (Session, NodeId) {
let (mut s, _, b) = doc();
let c = rect(&mut s, 200.0, 50.0, 100.0, 100.0);
log(&mut s, "var p = app.activeDocument.pathItems; p[0].name = 'drive'; p[2].name = 'm';");
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("object.objectsOnPath.attach", &json!({"path": c.0, "ids": [b.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
(s, b)
}
/// Reading the points of a path writes the waiting point changes of another path first, so a
/// member of an Objects on Path group reads where the group's edited path moved it.
#[test]
fn reading_a_member_point_after_editing_its_group_path_reads_where_it_moved() {
let (mut s, _) = doc_on_path();
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\
var x = m.pathPoints[0].anchor[0];\
for (var i = 0; i < g.pathPoints.length; i++) { var q = g.pathPoints[i]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; }\
vc.log(m.pathPoints[0].anchor[0] - x);\
P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor[0] - x);",
);
assert_ne!(out[1], json!(0), "the member moved");
assert_eq!(out[0], out[1], "the member read where it is after the run");
}
/// A member point read before the group's path is edited is stale afterwards, as the engine moved
/// the member, even when an undo puts the member back.
#[test]
fn a_member_point_read_before_its_group_path_changes_is_stale() {
let (mut s, _) = doc_on_path();
let e = failure(
&mut s,
"var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\
var mp = m.pathPoints[0]; mp.anchor;\
var q = g.pathPoints[0]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; app.undo();\
mp.anchor;",
);
assert!(e.contains("Stale path point"), "{e}");
}
#[test]
fn a_point_in_a_nested_member_is_stale_after_another_path_changes_and_undoes() {
let (mut s, a, b) = doc();
log(&mut s, "var P = app.activeDocument.pathItems; P[0].name = 'edit'; P[1].name = 'm';");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.active().unwrap().doc.parent_of(a).unwrap();
let drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0);
s.execute("object.objectsOnPath.attach", &json!({"path": drive.0, "ids": [group.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = art(&s);
let e = failure(
&mut s,
"var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\
var mp = m.pathPoints[0]; mp.anchor;\
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\
mp.anchor;",
);
assert!(e.contains("Stale path point"), "{e}");
assert_eq!(art(&s), before);
}
#[test]
fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_changes_and_undoes() {
let (mut s, a, b) = doc();
log(&mut s, "app.activeDocument.pathItems[0].name = 'drive';");
s.execute("object.objectsOnPath.attach", &json!({"path": a.0, "ids": [b.0]})).unwrap();
let inner = s.active().unwrap().doc.parent_of(a).unwrap();
let sibling = rect(&mut s, 100.0, 200.0, 50.0, 50.0);
s.execute("object.setProps", &json!({"ids": [sibling.0], "name": "m"})).unwrap();
s.execute("select.set", &json!({"ids": [inner.0, sibling.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.active().unwrap().doc.parent_of(inner).unwrap();
let outer_drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0);
s.execute("object.objectsOnPath.attach", &json!({"path": outer_drive.0, "ids": [group.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = art(&s);
let out = log(
&mut s,
"var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\
vc.log(m.pathPoints[0].anchor);\
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]];\
vc.log(m.pathPoints[0].anchor); app.undo();",
);
assert_ne!(out[0], out[1], "the sibling outside the inner group moved");
assert_eq!(art(&s), before);
let e = failure(
&mut s,
"var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\
var mp = m.pathPoints[0]; mp.anchor;\
var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\
mp.anchor;",
);
assert!(e.contains("Stale path point"), "{e}");
assert_eq!(art(&s), before);
}
/// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke.
fn doc_with_paints() -> (Session, NodeId) {
let (mut s, a, _) = doc();
+6 -3
View File
@@ -1478,9 +1478,12 @@ impl Session {
// Global Edit: the objects edited with the selected one are highlighted; before it starts,
// with the Selection tool, the objects it would take.
let ge_on = self.active().is_some_and(|d| d.global_edit.is_some());
let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] };
for (path, color) in shown {
v.push(Overlay::Path { path, color, width: 1.0, dashed: false });
// One overlay per layer color, sharing the kept outlines.
if ge_on || self.tool.id() == "selection" {
let shown = crate::cmd::globaledit::highlights(self);
for (color, paths) in &shown.groups {
v.push(Overlay::Outlines { paths: paths.clone(), color: *color, revision: shown.revision });
}
}
if let Some((cmd, p)) = deferred_preview {
v.extend(self.deferred_preview_overlays_from_command(&cmd, &p));
+2
View File
@@ -995,6 +995,8 @@ fn structured_junk() {
("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})),
("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})),
("addon.arrange.grid", json!({"layout": "column", "gapX": -1e6})),
("addon.arrange.offset", json!({"direction": "column", "gap": -1e6, "order": "position", "reverse": true})),
("addon.arrange.offset", json!({"direction": "diagonal", "gap": f64::MAX, "order": 3, "reverse": "x"})),
("addon.arrange.swap", json!({"size": true, "scaleStrokes": true})),
("addon.arrange.replace", json!({"fit": "proportional", "keep": true})),
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
+108 -3
View File
@@ -8,12 +8,16 @@
//! in and rebuilds the table, which has one entry per chunk.
//!
//! The list reads and writes as one flat sequence of anchors, as a `Vec<Anchor>` does.
//!
//! The list also keeps the box round its anchors' points and handles ([`Anchors::control_bounds`])
//! once it has been measured, until the list changes.
use std::borrow::Cow;
use std::fmt;
use std::ops::{Index, IndexMut, RangeBounds};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use kurbo::Rect;
use serde::{Deserialize, Serialize};
use crate::path::Anchor;
@@ -40,12 +44,49 @@ pub struct Anchors {
ends: Vec<usize>,
/// The number of anchors.
len: usize,
/// The box round every anchor's point and handles, once measured; emptied by every change.
control: OnceLock<Rect>,
}
thread_local! {
/// [`measured_control_anchors`] of this thread.
static MEASURED_CONTROL_ANCHORS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many anchors [`Anchors::control_bounds`] has read on this thread.
pub fn measured_control_anchors() -> u64 {
MEASURED_CONTROL_ANCHORS.get()
}
impl Anchors {
/// An empty list.
pub const fn new() -> Self {
Self { chunks: Vec::new(), ends: Vec::new(), len: 0 }
Self { chunks: Vec::new(), ends: Vec::new(), len: 0, control: OnceLock::new() }
}
/// The box round every anchor's point and handles, or `None` when the list is empty. The list
/// reads its anchors for it once, and again only after it has changed.
pub fn control_bounds(&self) -> Option<Rect> {
if self.len == 0 {
return None;
}
Some(*self.control.get_or_init(|| {
MEASURED_CONTROL_ANCHORS.set(MEASURED_CONTROL_ANCHORS.get().saturating_add(self.len as u64));
let mut r: Option<Rect> = None;
for c in &self.chunks {
for a in c.iter() {
for p in [a.p, a.h_in, a.h_out] {
r = Some(r.map_or(Rect::from_points(p, p), |r| r.union_pt(p)));
}
}
}
r.unwrap_or_default()
}))
}
/// Forget the measured [`Self::control_bounds`]: every change calls it.
fn changed(&mut self) {
self.control.take();
}
/// The number of anchors.
@@ -85,6 +126,7 @@ impl Anchors {
if i >= self.len {
return None;
}
self.changed();
let (c, o) = self.locate(i);
Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o)
}
@@ -101,11 +143,13 @@ impl Anchors {
/// The first anchor to change.
pub fn first_mut(&mut self) -> Option<&mut Anchor> {
self.changed();
Arc::make_mut(self.chunks.first_mut()?).first_mut()
}
/// The last anchor to change.
pub fn last_mut(&mut self) -> Option<&mut Anchor> {
self.changed();
Arc::make_mut(self.chunks.last_mut()?).last_mut()
}
@@ -118,6 +162,7 @@ impl Anchors {
/// The anchors in order, to change. Each chunk is copied, when another list shares it, as the
/// iterator reaches it.
pub fn iter_mut(&mut self) -> IterMut<'_> {
self.changed();
let chunk: fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut();
self.chunks.iter_mut().flat_map(chunk)
}
@@ -177,6 +222,7 @@ impl Anchors {
/// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks.
fn reindex(&mut self) {
self.changed();
self.chunks.retain(|c| !c.is_empty());
self.len = self.chunks.iter().map(|c| c.len()).sum();
let n = self.chunks.len();
@@ -193,6 +239,7 @@ impl Anchors {
/// Add `a` at the end.
pub fn push(&mut self, a: Anchor) {
self.changed();
match self.chunks.last_mut() {
Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a),
_ => {
@@ -210,6 +257,7 @@ impl Anchors {
/// Remove the last anchor.
pub fn pop(&mut self) -> Option<Anchor> {
self.changed();
let last = self.chunks.last_mut()?;
let a = Arc::make_mut(last).pop();
if last.is_empty() {
@@ -489,6 +537,7 @@ impl Index<usize> for Anchors {
impl IndexMut<usize> for Anchors {
/// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does.
fn index_mut(&mut self, i: usize) -> &mut Anchor {
self.changed();
let (c, o) = self.locate(i);
&mut Arc::make_mut(&mut self.chunks[c])[o]
}
@@ -501,7 +550,7 @@ impl From<Vec<Anchor>> for Anchors {
}
let len = v.len();
let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() };
Self { chunks, ends: Vec::new(), len }
Self { chunks, ends: Vec::new(), len, control: OnceLock::new() }
}
}
@@ -725,6 +774,8 @@ mod tests {
}
}
assert_eq!(a.len(), v.len(), "step {step}");
// The box kept from the step before is measured again after the edit.
assert_eq!(a.control_bounds(), Anchors::from(v.clone()).control_bounds(), "step {step}");
if step % 50 == 0 {
assert_eq!(a, v, "step {step}");
for i in 0..v.len() {
@@ -737,6 +788,60 @@ mod tests {
assert_eq!(a.get(v.len()), None);
}
/// The box of every anchor of `v` with its handles, measured anchor by anchor.
fn box_of(v: &[Anchor]) -> Option<Rect> {
let mut it = v.iter().flat_map(|a| [a.p, a.h_in, a.h_out]);
let first = it.next()?;
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
}
#[test]
fn control_bounds_read_the_anchors_once_until_they_change() {
let n = 1000;
let mut a = Anchors::from(line(n));
let read = measured_control_anchors;
let before = read();
assert_eq!(a.control_bounds(), box_of(&line(n)));
assert_eq!(read() - before, n as u64, "the first call reads every anchor");
let copy = a.clone();
for _ in 0..5 {
assert_eq!(a.control_bounds(), box_of(&line(n)));
assert_eq!(copy.control_bounds(), box_of(&line(n)));
}
assert_eq!(read() - before, n as u64, "later calls, and a copy's, read no anchor");
// Every change measures again, and only the list that changed.
let far = Point::new(-50.0, 900.0);
type Edit = fn(&mut Anchors, Point);
let edits: [(&str, Edit); 11] = [
("get_mut", |a, p| a.get_mut(3).into_iter().for_each(|x| x.h_out = p)),
("index_mut", |a, p| a[4].h_in = p),
("first_mut", |a, p| a.first_mut().into_iter().for_each(|x| x.p = p)),
("last_mut", |a, p| a.last_mut().into_iter().for_each(|x| x.p = p)),
("iter_mut", |a, p| a.iter_mut().take(1).for_each(|x| x.p = p)),
("push", |a, p| a.push(Anchor::corner(p))),
("insert", |a, p| a.insert(1, Anchor::corner(p))),
("pop", |a, _| {
let _ = a.pop();
}),
("remove", |a, _| {
let _ = a.try_remove(0);
}),
("truncate", |a, _| a.truncate(10)),
("reverse", |a, _| a.reverse()),
];
for (k, (what, edit)) in edits.iter().enumerate() {
let p = Point::new(far.x - k as f64, far.y + k as f64);
assert!(a.control_bounds().is_some());
edit(&mut a, p);
let r = read();
assert_eq!(a.control_bounds(), box_of(&a.to_vec()), "after {what}");
assert_eq!(read() - r, a.len() as u64, "after {what}: measured again");
}
assert_eq!(copy.control_bounds(), box_of(&line(n)), "the copy keeps its box");
a.clear();
assert_eq!(a.control_bounds(), None);
}
#[test]
fn iterators_skip_and_count_as_a_slice_does() {
let v = line(1000);
+3 -4
View File
@@ -745,11 +745,10 @@ impl PathData {
}
bbox
}
/// Bounds including control handles (used for quick culling).
/// Bounds including control handles (used for quick culling). Each subpath keeps its own box
/// ([`Anchors::control_bounds`]) until its anchors change.
pub fn control_bounds(&self) -> Option<Rect> {
let mut it = self.subpaths.iter().flat_map(|s| s.anchors.iter()).flat_map(|a| [a.p, a.h_in, a.h_out]);
let first = it.next()?;
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
self.subpaths.iter().filter_map(|s| s.anchors.control_bounds()).reduce(|a, b| a.union(b))
}
pub fn transform(&mut self, a: Affine) {
for sp in &mut self.subpaths {
+3 -2
View File
@@ -25,8 +25,9 @@ use crate::{Action, Overlay, PointerEvent, ToolContext};
pub const DIALOG: &str = "corners";
/// Widgets sit at least this far inside their corner along each side of a right angle (screen px;
/// √2 times it along the bisector, at any angle), further in once the radius is.
const MIN_INSET_PX: f64 = 10.0;
/// √2 times it along the bisector, at any angle), further in once the radius is. The canvas draws the
/// widgets at the framework's `CornerWidgets::INSET`, which the UI's tests hold equal to this value.
pub const MIN_INSET_PX: f64 = 10.0;
/// Corners with a side shorter than this on screen (px) hide their widgets.
const MIN_SIDE_PX: f64 = 3.0 * MIN_INSET_PX;
+5
View File
@@ -88,6 +88,11 @@ pub enum Overlay {
/// the dash pattern: the pieces of one line, each starting where the one before it ends, dash
/// as the whole line does.
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32, dash: Option<f64> },
/// Thin solid outlines of many objects in one color (the objects Global Edit takes). Later calls
/// return the same `paths` with the same `revision` for as long as the outlines do not change, and
/// a new `revision` when they do. The host strokes them again only when `revision` or the view
/// changes.
Outlines { paths: std::sync::Arc<[BezPath]>, color: [u8; 3], revision: u64 },
/// A line segment (smart guide, handle line).
Line { a: Point, b: Point, color: [u8; 3], dashed: bool },
/// An anchor square: filled = selected.
+26 -5
View File
@@ -1,7 +1,7 @@
//! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of
//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity, Sort Objects and
//! Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping
//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity, Sort Objects
//! and Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command on OK;
//! Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection.
use std::borrow::Cow;
@@ -22,14 +22,16 @@ use crate::menus::{Sep, c, cp};
/// Zoom to Selection: a view command, since the view is the interface's.
pub const ZOOM: &str = "addon.arrange.zoomSelection";
const GRID: &str = "addon.arrange.grid";
const OFFSET: &str = "addon.arrange.offset";
const REPLACE: &str = "addon.arrange.replace";
const SIZE: &str = "addon.arrange.size";
const OPACITY: &str = "addon.arrange.randomizeOpacity";
const SORT: &str = "addon.arrange.sort";
const MARKS: &str = "addon.arrange.markBounds";
/// Each dialog's command and heading.
const DIALOGS: [(&str, &str); 6] = [
const DIALOGS: [(&str, &str); 7] = [
(GRID, "Arrange in Grid"),
(OFFSET, "Offset Objects"),
(REPLACE, "Replace with Top Object"),
(SIZE, "Set Size of Each"),
(OPACITY, "Randomize Opacity"),
@@ -39,7 +41,7 @@ const DIALOGS: [(&str, &str); 6] = [
/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights.
const MARK_LENGTHS: std::ops::RangeInclusive<f64> = 0.001..=1e6;
const WEIGHTS: std::ops::RangeInclusive<f64> = 0.01..=1000.0;
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes.
/// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid and Offset Objects take.
const SIZES: std::ops::RangeInclusive<f64> = 0.001..=1e6;
const GAPS: std::ops::RangeInclusive<f64> = -1e6..=1e6;
/// The seeds the Randomize Opacity dialog offers.
@@ -61,6 +63,7 @@ const ATTRIBUTES: [(&str, &str); 7] = [
pub fn menu() -> Vec<Node> {
vec![
c("Arrange in Grid…", GRID),
c("Offset Objects…", OFFSET),
cp("Swap Objects", "addon.arrange.swap", json!({})),
cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })),
c("Replace with Top Object…", REPLACE),
@@ -75,6 +78,7 @@ pub fn menu() -> Vec<Node> {
}
static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None };
static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None };
static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None };
static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None };
static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None };
@@ -123,6 +127,17 @@ fn grid_rows(lengths: LengthUnits) -> Vec<Param> {
]
}
fn offset_rows(lengths: LengthUnits) -> Vec<Param> {
let directions = [("row", "Row (Left to Right)"), ("column", "Column (Top to Bottom)")];
let orders = [("stacking", "Stacking Order"), ("position", "Position")];
vec![
choice("direction", "Direction:", &directions, "row"),
length("gap", "Gap:", 10.0, GAPS, lengths),
choice("order", "Order:", &orders, "stacking"),
check("reverse", "Reverse Order", false),
]
}
fn replace_rows() -> Vec<Param> {
let fits = [("keep", "Actual Size"), ("bounds", "Bounds"), ("proportional", "Bounds (Fit Proportionally)")];
vec![choice("fit", "Size:", &fits, "keep"), check("keep", "Keep Original", false), scale_strokes()]
@@ -179,6 +194,10 @@ fn grid_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&grid_rows(POINTS), fields))
}
fn offset_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&offset_rows(POINTS), fields))
}
fn replace_params(fields: &DialogFields) -> Value {
Value::Object(form::json_of(&replace_rows(), fields))
}
@@ -219,6 +238,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
"gapX": 10, "gapY": 10, "centerOnArtboard": false,
}),
),
OFFSET => (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })),
REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })),
// A new seed each time the document has changed, so running it again varies the result.
OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })),
@@ -247,6 +267,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
let fields = form::fields_of(&rows, opening.as_object()?);
let opened = match command {
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))),
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))),
OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| {
let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0));
+107
View File
@@ -1,3 +1,4 @@
use craft::ui::contract::Role;
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
@@ -61,6 +62,60 @@ fn real_grid_edits_reach_the_preview_and_confirmed_geometry() {
assert!(!app.any_dialog_open());
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
#[test]
fn real_offset_edits_reach_the_preview_and_ok_applies_them_as_one_step() {
let (app, a, b) = app();
let n = steps(&app);
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Offset Objects…");
type_number(&mut panel, "Gap", "3");
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.number("gap")), Some(3.0));
{
// From the back: a stays and b starts 3 past its right edge, keeping its y.
let app = panel.app();
assert_eq!((bounds(&app, a).x0, bounds(&app, a).y0), (0.0, 0.0));
assert_eq!((bounds(&app, b).x0, bounds(&app, b).y0), (23.0, 100.0));
}
panel.focus("Reverse Order");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
panel.frame();
let preview = {
// Reversed: b stays and a starts 3 past b's right edge, keeping its y.
let app = panel.app();
assert_eq!((bounds(&app, b).x0, bounds(&app, b).y0), (100.0, 100.0));
assert_eq!((bounds(&app, a).x0, bounds(&app, a).y0), (143.0, 0.0));
(bounds(&app, a), bounds(&app, b))
};
panel.click("OK");
panel.frame();
let app = panel.app();
assert_eq!((bounds(&app, a), bounds(&app, b)), preview);
assert_eq!(steps(&app), n + 1, "one undo step");
assert!(!app.any_dialog_open());
}
#[test]
fn real_offset_cancel_puts_the_objects_back() {
let (app, a, b) = app();
let n = steps(&app);
let before = (bounds(&app, a), bounds(&app, b));
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Offset Objects…");
type_number(&mut panel, "Gap", "50");
assert_eq!(bounds(&panel.app(), b).x0, 70.0, "the preview moves b");
panel.click("Cancel");
panel.frame();
let app = panel.app();
assert_eq!((bounds(&app, a), bounds(&app, b)), before);
assert_eq!(steps(&app), n);
assert!(!app.any_dialog_open());
}
#[test]
fn real_size_keyboard_edits_keep_unticked_sides_unchanged() {
let (app, a, b) = app();
@@ -109,6 +164,58 @@ fn real_opacity_edits_drive_validation_confirmation_and_cancel() {
assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6);
}
/// The objects of the first layer, from the back.
fn stacking(panel: &Harness) -> Vec<NodeId> {
panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn real_replace_edits_reach_the_preview_and_confirmed_copies() {
let (app, a, b) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Replace with Top Object…");
panel.frame();
panel.click_role("Size", Role::COMBO_BOX);
panel.click("Bounds");
panel.click_role("Keep Original", Role::CHECK_BOX);
panel.frame();
let id = host::dialog_id(&panel.app());
let fields = host::read(&panel.app(), id, |f| (f.text("fit").map(str::to_owned), f.bool("keep")));
assert_eq!(fields, (Some("bounds".to_owned()), Some(true)));
// The copies of the top object: every object other than the two rectangles, with its bounds.
let copies = |panel: &Harness| {
let ids: Vec<NodeId> = stacking(panel).into_iter().filter(|id| ![a, b].contains(id)).collect();
let app = panel.app();
ids.into_iter().map(|id| bounds(&app, id)).collect::<Vec<_>>()
};
let preview = copies(&panel);
assert_eq!(preview, vec![bounds(&panel.app(), a)], "one copy, fitted to the kept original's bounds");
panel.click("OK");
panel.frame();
assert_eq!(copies(&panel), preview);
assert_eq!(stacking(&panel).len(), 3, "Keep Original leaves the original in place");
assert!(!panel.app().any_dialog_open());
}
#[test]
fn real_sort_edits_reach_the_preview_and_confirmed_stacking() {
let (app, a, b) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Sort Objects…");
panel.frame();
assert_eq!(stacking(&panel), vec![a, b], "the smaller area is already at the back");
panel.click_role("Order", Role::COMBO_BOX);
panel.click("Large to Small");
panel.frame();
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.text("order").map(str::to_owned)), Some("descending".to_owned()));
assert_eq!(stacking(&panel), vec![b, a], "the preview puts the larger area at the back");
panel.click("OK");
panel.frame();
assert_eq!(stacking(&panel), vec![b, a]);
assert!(!panel.app().any_dialog_open());
}
#[test]
fn set_size_of_each_sets_the_sides_ticked() {
let (mut app, a, b) = app();
@@ -80,11 +80,14 @@ pub(crate) fn rows() -> Vec<PanelRow> {
}
/// Dims the Select row of each status no image or placed document has ([`enabled`]), in the states of
/// the commands the Links panel's menu shows.
/// the commands the Links panel's menu shows, and names each row and its Shift alternate for its status: the
/// catalog's label for the command is Select by Link Status's.
pub(crate) fn states(app: &VectorcraftApp, states: &mut CommandStates) {
for &(status, ..) in &STATUSES {
for &(status, label, _) in &STATUSES {
let params = json!({ "status": status });
states.set(CommandRef::with_params(COMMAND, params.clone()), CommandState::new().enabled(enabled(app, &params)));
let state = CommandState::new().enabled(enabled(app, &params)).title(crate::i18n::t(label));
states.set(CommandRef::with_params(COMMAND, with_shift(params.clone())), state.clone());
states.set(CommandRef::with_params(COMMAND, params), state);
}
}
@@ -178,14 +178,20 @@ fn menu_items_are_on_for_the_statuses_present_and_shift_adds() {
{
assert_eq!(item(label).enabled, on, "{label}");
}
// The Links panel's rows follow the statuses present, per status.
let enabled_of = |app: &VectorcraftApp| {
// The Links panel's rows follow the statuses present, per status, and each row and its Shift alternate is named
// for its status.
let enabled_of = |app: &VectorcraftApp, shift: bool| {
let mut all = CommandStates::new();
states(app, &mut all);
STATUSES.map(|(status, ..)| all.get(&CommandRef::with_params(COMMAND, json!({ "status": status }))).cloned())
STATUSES.map(|(status, ..)| {
let p = json!({ "status": status });
all.get(&CommandRef::with_params(COMMAND, if shift { with_shift(p) } else { p })).cloned()
})
};
let on = Some(CommandState::new().enabled(true));
assert_eq!(enabled_of(&app), [on.clone(), on.clone(), on.clone(), Some(CommandState::new().enabled(false))]);
let named = |on: bool, label: &str| Some(CommandState::new().enabled(on).title(label));
let want = [named(true, "Select Linked"), named(true, "Select Embedded"), named(true, "Select Missing"), named(false, "Select Modified")];
assert_eq!(enabled_of(&app, false), want);
assert_eq!(enabled_of(&app, true), want, "the Shift alternates");
// The item's params run as the menu runs them: Shift's alternate is `with_shift` of them.
let run = |app: &mut VectorcraftApp, status: &str, shift: bool| {
let p = json!({ "status": status });
@@ -207,9 +213,9 @@ fn menu_items_are_on_for_the_statuses_present_and_shift_adds() {
app.run("select.set", json!({"ids": [harbour]})).unwrap();
app.run("edit.clear", json!({})).unwrap();
refresh(&mut app, 1.0);
let after = enabled_of(&app);
assert_eq!(after[2], Some(CommandState::new().enabled(false)), "no missing image is left");
assert_eq!(after[1], on, "the embedded one stays");
let after = enabled_of(&app, false);
assert_eq!(after[2], named(false, "Select Missing"), "no missing image is left");
assert_eq!(after[1], named(true, "Select Embedded"), "the embedded one stays");
}
/// A missing link kept only in a symbol's art can't be selected: Select Missing stays off and
+7 -3
View File
@@ -246,7 +246,6 @@ impl VectorcraftApp {
three_d_dialog: None,
three_d: Default::default(),
export_dialogs: Default::default(),
slice_dialogs: Default::default(),
package_document: None,
web_export: Default::default(),
flattener_preview: Default::default(),
@@ -554,6 +553,11 @@ impl VectorcraftApp {
// what waits for them. They install after the control requests are drained, so the frame
// after the last one opens the files held for them (the desktop app does that before this
// pass) before a control request waiting for them runs.
// A Language pack installed or removed lays the documents out again; while one downloads
// the host keeps coming back to look.
if self.session.poll_language_packs() {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
if self.session.plugins_loading() {
if self.session.poll_plugin_loads() {
ctx.request_repaint_after(std::time::Duration::from_millis(50));
@@ -810,8 +814,8 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
root.values.set(TabCloseLook::Glyph);
// A collapsed panel column's icon groups stand apart by a hairline, as production drew them.
root.values.set(IconGroupSeparator::Rule);
// New Document's preset cards show blank paper on a flat card, as production drew them.
root.values.set(PresetCardLook::Page);
// New Document's preset cards show blank paper on a card that rests on a tile, as production drew them.
root.values.set(PresetCardLook::PageTile);
// A bare Tab on the canvas, or with nothing focused, toggles the panels (`window.dock`) instead of moving focus.
root.tab_toggles_chrome = true;
// Escape in a text field gives up its focus, reverting any typing, so the next keys are the window's.
+2 -5
View File
@@ -405,15 +405,12 @@ fn compass(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option<Can
})
}
/// `rect` without the strip the vertical scroll bar takes along its right edge (the bar's thickness and its margin,
/// the sizes `CanvasScrollbars` draws with), in the screen modes that show the scroll bars.
/// `rect` without the strips the scroll bars take, in the screen modes that show them ([`scroll_bars`]).
fn clear_of_scroll_bars(app: &VectorcraftApp, ui: &Ui, rect: egui::Rect) -> egui::Rect {
if app.ui.screen_mode >= 2 {
return rect;
}
let env = Env::of(ui);
let strip = env.tokens.size.icon.md + env.tokens.space.gap.tight;
egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - strip).max(rect.left()), rect.bottom()))
CanvasScrollbars::clear_of(ui, rect, false, false)
}
/// The scroll bars along the right and bottom edges (Normal and Full Screen with Menu Bar): the view
+8 -2
View File
@@ -48,7 +48,7 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
});
}
/// The framework control `o` stands for, if it is one: a marquee, a settled outline or a distance.
/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance.
fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
match o {
Overlay::Marquee(r) => {
@@ -65,6 +65,11 @@ fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
let outline = if dash.is_some() { SelectionOutline::dashed(Label::Empty, paths) } else { SelectionOutline::solid(Label::Empty, paths) };
outline.color(data(*color)).revision(revision).show_at(ui, rect);
}
Overlay::Outlines { paths, color, revision } => {
// The overlay's revision changes whenever its paths do, so the lines are stroked again only then or when
// the view changes.
SelectionOutline::solid(Label::Empty, paths).color(data(*color)).revision(*revision).show_at(ui, rect);
}
Overlay::Distance { .. } => {
if let Some((measure, color)) = distance_measure(o) {
SmartGuides::new(&[], std::slice::from_ref(&measure)).color(color).show_at(ui, rect);
@@ -180,7 +185,7 @@ impl Component for ToolMarks<'_> {
}
}
/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths and distances are controls
/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths, outlines and distances are controls
/// of their own and paint nothing here.
// PLAN: contract cv.S14 gives `paint(draw, view, overlays, options)`; the pill, ink and ring colours come from the theme, so the style goes too.
fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &PathOptionsSettings, style: &ToolMarksStyle) {
@@ -244,6 +249,7 @@ fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &Pat
Overlay::Marquee(_)
| Overlay::SelectionMarquee { .. }
| Overlay::SharedPath { .. }
| Overlay::Outlines { .. }
| Overlay::Distance { .. }
| Overlay::HoverText { .. } => {}
}
+8 -20
View File
@@ -38,20 +38,12 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>
/// [`frame`] on a window `size` points large.
fn frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, size: egui::Vec2) -> Vec<Shape> {
fn flat(s: Shape, out: &mut Vec<Shape>) {
match s {
Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)),
s => out.push(s),
}
}
let raw =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)), max_texture_side: Some(8192), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| app.canvas_area(ui));
// A pane's picture is uploaded once, maybe in this frame: [`wait_ready`] finds it later.
note_uploads(&mut out.textures_delta);
let mut shapes = vec![];
out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes));
shapes
crate::tests_labels::flat_painted_shapes(&out.shapes)
}
/// A texture's picture: its pixels and size.
@@ -627,15 +619,10 @@ fn art_carried_through_a_tab_drops_into_a_third_documents_pane() {
// A tab's title starts with its document's name (an inactive tab shows the name alone).
let names: Vec<String> = app.session.documents().iter().map(|d| d.title()).collect();
let titles = |out: egui::FullOutput| -> Vec<egui::Rect> {
let mut t: Vec<_> = out
.shapes
.iter()
.filter_map(|s| match &s.shape {
Shape::Text(t) if names.iter().any(|n| t.galley.text().starts_with(n.as_str())) => {
Some(egui::Rect::from_min_size(t.pos, t.galley.size()))
}
_ => None,
})
let mut t: Vec<_> = crate::tests_labels::text_shapes(&out)
.into_iter()
.filter(|(t, _)| names.iter().any(|n| t.galley.text().starts_with(n.as_str())))
.map(|(t, transform)| transform * egui::Rect::from_min_size(t.pos, t.galley.size()))
.collect();
t.sort_by(|a, b| a.left().total_cmp(&b.left()));
t
@@ -1002,14 +989,15 @@ fn other_panes_draw_through_their_documents_profiles() {
let fills = |out: &egui::FullOutput, rgb: [u8; 3]| {
fn any(s: &Shape, f: &dyn Fn(Color32) -> bool) -> bool {
match s {
Shape::Vec(v) => v.iter().any(|s| any(s, f)),
Shape::Path(p) => f(p.fill),
Shape::Rect(r) => f(r.fill),
Shape::Mesh(m) if m.texture_id == egui::TextureId::default() => m.vertices.iter().any(|v| f(v.color)),
_ => false,
}
}
out.shapes.iter().any(|c| any(&c.shape, &|c: Color32| c.a() == 255 && near([c.r(), c.g(), c.b()], rgb)))
crate::tests_labels::painted_shapes(&out.shapes)
.into_iter()
.any(|(s, ..)| any(s, &|c: Color32| c.a() == 255 && near([c.r(), c.g(), c.b()], rgb)))
};
let ctx = crate::testing::ui_context();
let raw = || egui::RawInput {
+4 -2
View File
@@ -464,10 +464,12 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpac
.show(ui, space.view.rect, |ui, _| {
for (label, icon, cmd, params) in &offer.actions {
if *cmd == TASK_BAR_FIDELITY {
// The Smooth tool's Fidelity, labeled, sets the tool's option as it is typed or stepped.
// The Smooth tool's Fidelity, labeled, sets the tool's option once a typed or stepped value is
// committed; Escape leaves the option as it was.
if let Some(v) = offer.fidelity {
Text::new(*label).show(ui);
if let Some(x) = crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth").filter(|x| *x != v) {
let events = crate::dialogs::freehand::fidelity_field(ui, "task-bar-fidelity", v, "smooth");
if let Some(x) = events.committed().and_then(|typed| typed.to_owned()).filter(|x| *x != v) {
run = Some(("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": x}})));
}
}
+27 -10
View File
@@ -333,6 +333,30 @@ fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
assert!(moved >= 4, "the drag moves the object: {moved} frames");
}
/// With one rectangle selected, the canvas outlines its copies, which Start Global Edit would take, at their corners.
#[test]
fn the_canvas_outlines_the_objects_global_edit_would_take() {
let mut app = drag_app();
let rect = |app: &mut VectorcraftApp, x: f64| {
app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap()
};
let key = rect(&mut app, 20.0);
let copies = [rect(&mut app, 120.0), rect(&mut app, 220.0)];
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [key]})).unwrap();
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
let xf = app.canvas_view().unwrap();
let points = painted_points(&mut app, &ctx, vec![]);
for id in copies {
let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y1)] {
let at = xf.to_screen(corner);
assert!(points.iter().any(|p| p.distance(at) < 1.0), "copy {id} is outlined at {at:?}");
}
}
}
/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and
/// none at the pointer of the frame before.
#[test]
@@ -956,17 +980,10 @@ fn shapes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Shape> {
shapes
}
/// The shapes of a frame's output, `Shape::Vec`s flattened: the canvas's picture slot holds the art's.
/// The shapes of a frame's output, `Shape::Vec`s and retained paint chunks flattened: the canvas's
/// picture slot holds the art's.
fn flat_shapes(clipped: Vec<egui::epaint::ClippedShape>) -> Vec<Shape> {
fn flat(s: Shape, out: &mut Vec<Shape>) {
match s {
Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)),
s => out.push(s),
}
}
let mut v = vec![];
clipped.into_iter().for_each(|c| flat(c.shape, &mut v));
v
crate::tests_labels::flat_painted_shapes(&clipped)
}
/// One headless canvas frame → the shapes drawn ([`flat_shapes`]) and the textures uploaded by it
@@ -101,6 +101,12 @@ fn corner_widgets_hide_above_the_preference_angle() {
assert!(corners(&app, app.session.tool_id(), app.view_info().zoom).is_none());
}
/// The tools hit-test corner widgets at the inset the canvas draws them at.
#[test]
fn corner_widgets_are_hit_tested_at_the_inset_they_are_drawn_at() {
assert_eq!(vectorcraft_tools::corners::MIN_INSET_PX, f64::from(CornerWidgets::INSET));
}
/// #1232: the pointer within 5 screen points of a corner widget gives the cut of the corner it controls, in the
/// layer colour, with Direct Selection, the Selection tool and the Rectangle tool. It gives none with a mouse button
/// down (a press on the widget or a pan), during a drag from the widget, off the canvas, away from the widgets, or
+105 -46
View File
@@ -1,5 +1,5 @@
use super::{ROTATE_VIEW_ANGLES, Ui, VectorcraftApp, json};
use craft::behavior::kurbo::Size;
use craft::behavior::kurbo::{Point, Size};
use craft::behavior::{CanvasView, IconId};
use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress};
use craft::ui::buttons::{Button, IconButton};
@@ -31,7 +31,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
let view = app.view();
let rotation = view.map_or(0.0, |v| v.rotation);
let lang = crate::i18n::current();
let canvas_view = app.canvas_view();
let canvas_zoom = app.canvas_view().map(|v| v.zoom);
// PLAN: assumed Artboard::rect has `width()` and `height()`.
let document = st.and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height()));
let scaling = app.ui_scaling();
@@ -92,21 +92,10 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
};
// PLAN: assumed VectorcraftApp::canvas_view() -> Option<CanvasView> (cv.S4) and the label msgid "Status Bar".
Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |ui, _| {
let navigation = Navigation {
view: canvas_view,
document,
scaling,
print,
shown_zoom,
has_view: view.is_some(),
turned,
degrees,
cur,
revision,
artboards,
lang,
picked: Outbox::new(&mut picks),
};
let zoom =
ZoomControls { zoom: canvas_zoom, document, scaling, print, shown_zoom, has_view: view.is_some(), lang, picked: Outbox::new(&mut picks) };
let _ = MemoView::new("status-bar-zoom", zoom, show_zoom).show(ui);
let navigation = Navigation { has_view: view.is_some(), turned, degrees, cur, revision, artboards, lang, picked: Outbox::new(&mut picks) };
let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui);
Divider::vertical().show(ui);
// An empty readout shows a dash.
@@ -187,13 +176,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// What the status bar's navigation controls read: the Zoom field, the Rotation menu and the artboard navigator. The
/// bar replays them while these hold still and nothing reaches them (`MemoView`), as most frames only move the
/// readouts.
/// What the status bar's Zoom field and Zoom Presets menu read. The bar replays them while these hold still and
/// nothing reaches them (`MemoView`). The canvas view's center is not among them, so a pan replays them.
#[derive(MemoProps)]
struct Navigation<'a> {
/// The canvas view the Zoom field shows and edits.
view: Option<CanvasView>,
struct ZoomControls<'a> {
/// The canvas view's zoom (`CanvasView::zoom`), which the Zoom field shows and edits.
zoom: Option<f64>,
/// The size of the artboard the navigator shows, which the Zoom field fits.
document: Size,
/// UI Scaling, which divides the canvas view's zoom.
@@ -202,6 +190,45 @@ struct Navigation<'a> {
print: Option<f64>,
/// The view's zoom percentage, which the Zoom Presets menu checks.
shown_zoom: Option<f64>,
/// Whether the active document has a view to zoom.
has_view: bool,
#[memo_props(hash = "an interface language: an index into the languages offered")]
lang: crate::i18n::Lang,
/// What the controls chose in the pass.
picked: Outbox<'a, NavigationPick>,
}
/// The Zoom field and the Zoom Presets menu of the status bar, from [`ZoomControls`].
fn show_zoom(p: &mut ZoomControls<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::ZOOM_RUNS.with(|n| n.set(n.get() + 1));
// The field reads only the view's zoom, and the bar reads only the zoom of the view it commits.
let view = p.zoom.map(|zoom| CanvasView::new(egui::Rect::ZERO, Point::ZERO, zoom));
let document = p.document;
let zoom = Field::new(tl!("Zoom"))
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).status_bar().show(ui));
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
if let Some(zoom) = zoom.inner {
if let Some(view) = zoom.view.committed() {
let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print);
p.picked.send(NavigationPick::Zoom(percent));
}
if let Some(invalid) = zoom.invalid_zoom {
p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui))));
}
}
let presets = zoom_presets(p.shown_zoom, p.print);
let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui);
if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked {
p.picked.send(NavigationPick::Preset(preset));
}
}
/// What the status bar's Rotation menu and artboard navigator read. The bar replays them while these hold still and
/// nothing reaches them (`MemoView`), as most frames only move the readouts, and a pan or a zoom leaves them alone.
#[derive(MemoProps)]
struct Navigation<'a> {
/// Whether the active document has a view to turn.
has_view: bool,
/// The Rotate View preset the view is turned to, else `usize::MAX`.
@@ -234,29 +261,10 @@ enum NavigationPick {
Artboard(serde_json::Value),
}
/// The Zoom field, the Rotation menu and the artboard navigator of the status bar, from [`Navigation`].
/// The Rotation menu and the artboard navigator of the status bar, from [`Navigation`].
fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::NAVIGATION_RUNS.with(|n| n.set(n.get() + 1));
let (view, document) = (p.view, p.document);
let zoom = Field::new(tl!("Zoom"))
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).show(ui));
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
if let Some(zoom) = zoom.inner {
if let Some(view) = zoom.view.committed() {
let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print);
p.picked.send(NavigationPick::Zoom(percent));
}
if let Some(invalid) = zoom.invalid_zoom {
p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui))));
}
}
let presets = zoom_presets(p.shown_zoom, p.print);
let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui);
if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked {
p.picked.send(NavigationPick::Preset(preset));
}
let angles: Vec<Entry<usize>> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect();
let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view);
let mut rotate_to = None;
@@ -388,13 +396,15 @@ mod tests {
thread_local! {
/// How many times this thread ran the status bar's navigation controls ([`show_navigation`]).
pub(super) static NAVIGATION_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// How many times this thread ran the status bar's Zoom field and Zoom Presets menu ([`show_zoom`]).
pub(super) static ZOOM_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Frames that change nothing the navigation controls show replay them instead of laying them out again; a new
/// zoom or a new artboard runs them once, and they show it.
/// Frames that change nothing the zoom and navigation controls show replay them instead of laying them out again;
/// a new zoom or a new artboard runs them once, and they show it.
#[test]
fn idle_frames_replay_the_navigation_controls() {
let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get);
let runs = || ZOOM_RUNS.with(std::cell::Cell::get) + NAVIGATION_RUNS.with(std::cell::Cell::get);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
@@ -423,6 +433,34 @@ mod tests {
assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard");
}
/// Scrolling the view moves its center and nothing the navigation controls show, so frames of a wheel pan replay
/// them; a new zoom runs only the Zoom field and its presets, not the Rotation menu and the artboard navigator.
#[test]
fn wheel_frames_run_only_the_controls_that_show_what_changed() {
let runs = || (ZOOM_RUNS.with(std::cell::Cell::get), NAVIGATION_RUNS.with(std::cell::Cell::get));
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
let mut panel = Panel::new(app, status_bar);
panel.room(egui::vec2(1200.0, 300.0));
panel.frame();
panel.frame();
let before = runs();
for i in 0..10 {
panel.app().view_mut().unwrap().center.y += if i % 2 == 0 { 40.0 } else { -25.0 };
panel.frame();
}
assert_eq!(runs(), before, "a pan runs neither the zoom controls nor the navigation controls");
for i in 0..4 {
panel.app().run("view.setZoom", json!({"zoom": 150 + 25 * i})).unwrap();
panel.frame();
}
let after = runs();
assert!(after.0 > before.0, "a new zoom runs the zoom controls");
assert_eq!(after.1, before.1, "a new zoom does not run the Rotation menu and the artboard navigator");
assert_eq!(panel.value("Zoom").as_deref(), Some("225%"), "the field shows the last zoom");
}
#[test]
fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
@@ -500,6 +538,27 @@ mod tests {
}
}
/// The Zoom field draws in the status bar's look: no outline while it does not have the focus.
#[test]
fn the_zoom_field_draws_in_the_status_bars_look() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
let mut panel = Panel::new(app, status_bar);
panel.room(egui::vec2(1200.0, 300.0));
panel.frame();
let field = panel.rect("Zoom");
let (shapes, _) = panel.paint_at(1.0);
let outlines = shapes
.iter()
.filter(|shape| match shape {
egui::Shape::Rect(rect) => rect.stroke.width > 0.0 && rect.stroke.color.a() > 0 && rect.rect.intersects(field),
_ => false,
})
.count();
assert_eq!(outlines, 0, "the status bar's Zoom field draws no outline");
}
#[test]
fn with_no_document_the_artboard_navigator_shows_a_dash() {
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
+1 -11
View File
@@ -3292,13 +3292,6 @@ struct StyleFace {
/// The Style field of the settled bar. `textures` holds the textures the frames uploaded since the fixture began
/// recording; the uploads of these frames are applied to it.
fn style_face(bar: &mut Shown, textures: &mut std::collections::HashMap<egui::TextureId, egui::ColorImage>) -> StyleFace {
fn flat(shape: egui::Shape, out: &mut Vec<egui::Shape>) {
if let egui::Shape::Vec(shapes) = shape {
shapes.into_iter().for_each(|s| flat(s, out));
} else {
out.push(shape);
}
}
let field = bar.settle().named("Graphic Styles").rect;
let mut paint = bar.fixture.take_paint().expect("the fixture records what it paints");
for (id, delta) in paint.textures_delta.set.iter().flat_map(|(id, deltas)| deltas.iter().map(move |delta| (id, delta))) {
@@ -3320,10 +3313,7 @@ fn style_face(bar: &mut Shown, textures: &mut std::collections::HashMap<egui::Te
}
// The uploads are applied to `textures`, not to a renderer.
paint.textures_delta.clear();
let mut shapes = Vec::new();
for clipped in std::mem::take(&mut paint.shapes) {
flat(clipped.shape, &mut shapes);
}
let shapes = crate::tests_labels::flat_painted_shapes(&paint.shapes);
let mut face = StyleFace { field, pictures: Vec::new(), fills: Vec::new() };
for shape in shapes {
match shape {
+17 -8
View File
@@ -32,6 +32,7 @@ use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::dialog::DialogResult;
use craft::ui::display::{Divider, Shade, Text};
use craft::ui::layout_components::Row;
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::patterns::form_dialogs::{
DialogFields, FieldValue, HostedListManager, HostedParamDialog, ListManagerAction, ListManagerChoice, ListManagerEntry, ListManagerWords, Param,
@@ -895,21 +896,29 @@ fn command_button(app: &VectorcraftApp, ui: &mut egui::Ui, bar: &str, look: &Com
(Some(t), Some(keys)) => format!("{} {keys}", t.name),
(Some(t), None) => t.name.clone(),
};
let button = match &look.text {
Some(t) => Button::command(t.command.clone()).label(look.said()),
None => Button::new(look.said()).enabled(false),
};
// The face paints the label; the accessible name stays `said`.
let button = if look.own.is_some() { button.painted(look.label().to_string()) } else { button };
let response = button.tooltip(tip).show(ui).response;
let mut response = None;
// A menu owned by a dimmed button takes no clicks, so the row around the button owns the menu and a right
// click on the button opens it: Rename Button… and the rest work while the command is dimmed.
let row = Row::new()
.show(ui, |ui, _| {
let button = match &look.text {
Some(t) => Button::command(t.command.clone()).label(look.said()),
None => Button::new(look.said()).enabled(false),
};
// The face paints the label; the accessible name stays `said`.
let button = if look.own.is_some() { button.painted(look.label().to_string()) } else { button };
response = Some(button.tooltip(tip.clone()).show(ui).response);
})
.output;
if measuring {
return;
}
let Some(response) = response else { return };
let (i, n) = place;
let moved = |at: usize| CommandRef::with_params("toolbar.addCommand", json!({ "command": look.id, "toolbar": bar, "at": at }));
let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": bar }));
let renamed = CommandRef::with_params("toolbar.renameCommand", json!({ "command": look.id, "toolbar": bar }));
Menu::context(look.name().to_string(), &response).show(ui, |ui, _| {
Menu::context(look.name().to_string(), &row).opened_by(&response, Trigger::Context).show(ui, |ui, _| {
MenuItem::command(moved(i.saturating_sub(1))).label(tl!("Move Up")).enabled(i > 0).show(ui);
MenuItem::command(moved(i + 1)).label(tl!("Move Down")).enabled(i + 1 < n).show(ui);
MenuItem::command(renamed.clone()).label(tl!("Rename Button…")).show(ui);
@@ -362,6 +362,52 @@ fn canceled_pattern_scale_edits_do_not_reach_the_brush() {
assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original);
}
/// Bristle Brush Options' sliders: a held drag ended with Escape leaves the open dialog's field as it
/// opened, and OK then leaves the brush as it was; a released drag is kept by OK.
#[test]
fn canceled_bristle_slider_drags_do_not_reach_the_brush() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
for (key, label, _) in BRISTLE {
let mut app = app();
let params = json!({"length": 150.0, "density": 50.0, "thickness": 50.0, "opacity": 50.0, "stiffness": 50.0});
app.run("brush.options", json!({"name": "Bristle Round", "params": params})).unwrap();
let original = app.run("brush.get", json!({"name": "Bristle Round"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, draw_hosted_options);
panel.room(egui::vec2(1000.0, 1000.0));
open(&mut panel.app(), "Bristle Round");
panel.frame();
let initial = fields_of(&panel.app()).number(key).unwrap();
panel.drag_hold_role(label, Role::SLIDER, egui::vec2(40.0, 0.0));
assert_ne!(fields_of(&panel.app()).number(key), Some(initial), "the held drag previews another {key}");
panel.key(Key::Escape, Modifiers::NONE);
panel.release();
assert!(is_open(&panel.app()));
assert_eq!(fields_of(&panel.app()).number(key), Some(initial), "the canceled drag restores the opening {key}");
panel.click("OK");
panel.frame();
assert!(!is_open(&panel.app()));
assert_eq!(panel.app().run("brush.get", json!({"name": "Bristle Round"})).unwrap(), original, "OK after a canceled {key} drag");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
open(&mut panel.app(), "Bristle Round");
panel.frame();
panel.drag_hold_role(label, Role::SLIDER, egui::vec2(40.0, 0.0));
panel.release();
let accepted = fields_of(&panel.app()).number(key).unwrap();
assert_ne!(accepted, initial);
panel.click("OK");
panel.frame();
assert_eq!(panel.app().run("brush.get", json!({"name": "Bristle Round"})).unwrap()[key], accepted);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().run("brush.get", json!({"name": "Bristle Round"})).unwrap(), original);
}
}
/// What a step of the table expects at a JSON pointer of the saved brush.
enum Expect {
Is(Value),
@@ -1079,6 +1079,38 @@ fn new_character_style_refuses_size_and_leading_errors_at_ok() {
}
}
/// Character Style Options and New Character Style opened on a tab other than General still show that tab after
/// their first frames, which measure the dialog before its body runs.
#[test]
fn a_style_dialog_opened_on_a_later_tab_keeps_it_through_its_first_frames() {
use egui::{Pos2, RawInput, Rect, vec2};
let mut app = app();
app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() });
};
frame(&mut app);
open(&mut app, "Body");
set::<Existing>(&app, "tab", json!("advanced"));
for _ in 0..5 {
frame(&mut app);
}
assert_eq!(fields::<Existing>(&app)["tab"], json!("advanced"), "Character Style Options left Advanced Character Formats");
cancel::<Existing>(&mut app);
app.run("ui.newCharStyle", json!({})).unwrap();
set::<Fresh>(&app, "tab", json!("color"));
for _ in 0..5 {
frame(&mut app);
}
assert_eq!(fields::<Fresh>(&app)["tab"], json!("color"), "New Character Style left Character Color");
}
#[test]
fn invalid_number_keeps_last_valid_preview() {
let mut app = app();
@@ -907,6 +907,34 @@ mod tests {
assert!(st.history.undo.is_empty());
}
/// Document Setup opened on a tab other than General still shows that tab after its first frames, which
/// measure the dialog before its body runs.
#[test]
fn a_later_tab_picked_before_the_first_frame_stays_shown() {
for tab in ["Transparency", "Type", "Color"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp| {
time += 0.25;
crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() });
};
frame(&mut app);
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "tab", json!(tab));
for _ in 0..5 {
frame(&mut app);
}
let shown = app.dialogs().unwrap().with(|h| {
use craft::ui::dialog::StackDialog as _;
h.get_by_id::<HostedPropertiesDialog>(id()).and_then(|d| d.json_fields())
});
assert_eq!(shown.map(|f| f["tab"].clone()), Some(json!(tab)), "Document Setup left {tab}");
}
}
#[test]
fn every_tab_draws_and_ok_is_one_undo_step() {
let (mut app, ctx) = setup_open();
+14
View File
@@ -537,6 +537,20 @@ mod tests {
assert_eq!(host::fields(&panel.app(), KIND)["scale"], 1.0);
}
#[test]
fn a_scale_the_field_refuses_on_tab_imports_the_scale_it_restores() {
let mut panel = actual_dialog();
panel.click("Scale");
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("2");
assert_eq!(host::fields(&panel.app(), KIND)["scale"], 2.0);
panel.type_text("*");
panel.key(Key::Tab, Modifiers::NONE);
assert!(host::is_open(&panel.app(), KIND));
assert_eq!(host::fields(&panel.app(), KIND)["scale"], 1.0, "the refused text restores the scale from before the edit");
accept_and_check_width(&mut panel, Unit::Millimeters, 100.0 * Unit::Millimeters.points());
}
#[test]
fn actual_layout_and_unit_enter_and_scale_blur_import_the_accepted_choices() {
let mut panel = actual_dialog();
@@ -30,13 +30,13 @@
use std::borrow::Cow;
use std::sync::Arc;
use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, GesturePhase, IconId, ItemSource, SelectionChange};
use craft::behavior::{ColumnKey, ColumnWidth, DisplayOrder, GesturePhase, IconId, ItemSource, Selection, SelectionChange};
use craft::host::PickRequest;
use craft::ui::buttons::Button;
use craft::ui::choice::{Checkbox, Radio, RadioGroup, Segmented};
use craft::ui::contract::{
Bind, CollectionEvent, ColumnSpec, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, SpaceAction, SweepApply, SweepStep,
ToggleColumn,
Bind, CollectionEvent, ColumnSpec, Entry, Pad, Props as _, Show as _, ShowCollection as _, ShowContainer as _, SpaceAction, SweepApply,
SweepStep, ToggleColumn,
};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::display::{Shade, Text};
@@ -46,6 +46,7 @@ use craft::ui::patterns::form_dialogs::{FormDialog, PathRow};
use craft::ui::primitives::{ContentPainterCx, fit_rect};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::focus::Initial;
use craft::ui::style::SurfaceKind;
use craft::ui::tabs::{Tab, TabKind, TabStrip};
use craft::ui::text::TextField;
use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent};
@@ -93,10 +94,11 @@ const SETTABLE: [&str; 20] = [
/// The check column of the list view and its name column.
const CHECK: ColumnKey = ColumnKey::new("check");
const NAME: ColumnKey = ColumnKey::new("name");
/// Rows of the list view and of the grid view the items pane shows before it scrolls, a pane as tall as the options
/// column's first sections.
/// How many items the list view and the grid view hold before they scroll, and how tall they are with fewer: a
/// missing item counts a control row, so the pane stays about as tall as the options column's first sections with
/// one artboard. The framework counts a grid's items, not its rows of tiles.
const LIST_ROWS: u16 = 9;
const GRID_ROWS: u16 = 3;
const GRID_ITEMS: u16 = 4;
/// The longest side of an artboard thumbnail, in pixels.
const THUMB_PX: u32 = 92;
@@ -219,6 +221,7 @@ pub fn open(app: &mut VectorcraftApp) {
pending: None,
renaming_in: None,
rename: None,
leads: Default::default(),
held: HeldAnswer::new(),
};
if let Some(dialogs) = app.dialogs() {
@@ -541,6 +544,8 @@ pub(crate) struct ExportForScreensDialog {
renaming_in: Option<(u64, u64)>,
/// A committed artboard name: ((document uid, reverts), artboard id, name), for the pump to run.
rename: Option<((u64, u64), u32, String)>,
/// The lead and anchor of the Artboards and the Assets view, by tab.
leads: [Selection<u64>; 2],
held: HeldAnswer<Map<String, Value>>,
}
@@ -616,7 +621,7 @@ impl ExportForScreensDialog {
let checked = |at: usize| on.get(at).copied().unwrap_or(false);
let shelf =
Shelf { items: &items, enabled: text(fields, "select") != "full", reveal: None, caption: &caption, checked: &checked, paint: &paint };
let picks = shelf.show(ui, text(fields, "view") == "list");
let picks = shelf.show(ui, text(fields, "view") == "list", &mut self.leads[0]);
for key in picks.toggled {
if let Some(b) = items.index_of(&key).and_then(|at| on.get_mut(at)) {
*b ^= true;
@@ -654,7 +659,7 @@ impl ExportForScreensDialog {
let checked = |at: usize| items.0.get(at).is_some_and(|(id, _)| on.contains(id));
let reveal = fields.get("__scrollTo").and_then(Value::as_u64).filter(|id| items.index_of(id).is_some());
let shelf = Shelf { items: &items, enabled: true, reveal, caption: &caption, checked: &checked, paint: &paint };
let picks = shelf.show(ui, text(fields, "view") == "list");
let picks = shelf.show(ui, text(fields, "view") == "list", &mut self.leads[1]);
for id in picks.toggled {
if on.contains(&id) {
on.retain(|a| *a != id);
@@ -724,23 +729,30 @@ struct Shelf<'a> {
}
impl Shelf<'_> {
/// Shows the items as a list of rows (`list`) or a grid of tiles → what the user did to them.
fn show(self, ui: &mut Ui, list: bool) -> Picks {
/// Shows the items as a list of rows (`list`) or a grid of tiles in a sunken frame, with the checked items
/// selected → what the user did to them. `lead` holds the selection's lead and anchor from pass to pass; its
/// items are the checked ones.
fn show(self, ui: &mut Ui, list: bool, lead: &mut Selection<u64>) -> Picks {
let Shelf { items, enabled, reveal, caption, checked, paint } = self;
let mut picks = Picks::default();
let rename = reveal.is_none();
let at = |key: &u64| items.index_of(key).unwrap_or(usize::MAX);
let state = |at: usize| if checked(at) { ToggleState::On } else { ToggleState::Off };
let mut selection = Selection::new((0..items.len()).filter(|at| checked(*at)).map(|at| items.key(at)).collect(), lead.lead, lead.anchor);
if list {
let columns =
vec![ColumnSpec::toggle(CHECK, Label::Empty, ToggleColumn::default()), ColumnSpec::new(NAME, Label::Empty, ColumnWidth::fill(1.0))];
let mut view = List::<u64>::new(tl!("Export for Screens"))
.surface(SurfaceKind::Sunken)
.pad(Pad::Control)
.header(false)
.space(SpaceAction::ToggleCell)
.columns(columns)
.rename(rename)
.enabled(enabled)
.max_rows(LIST_ROWS);
.min_rows(LIST_ROWS)
.max_rows(LIST_ROWS)
.selection(Bind::bound(&mut selection));
if rename {
view = view.rename_column(NAME);
}
@@ -763,7 +775,15 @@ impl Shelf<'_> {
}
}
} else {
let mut grid = TileGrid::<u64>::new(tl!("Export for Screens")).checks(true).rename(rename).enabled(enabled).max_rows(GRID_ROWS);
let mut grid = TileGrid::<u64>::new(tl!("Export for Screens"))
.surface(SurfaceKind::Sunken)
.pad(Pad::Control)
.checks(true)
.rename(rename)
.enabled(enabled)
.min_rows(GRID_ITEMS)
.max_rows(GRID_ITEMS)
.selection(Bind::bound(&mut selection));
if let Some(key) = reveal {
grid = grid.reveal(key);
}
@@ -778,6 +798,13 @@ impl Shelf<'_> {
}
}
}
// A click picks the item it lands on as the lead; the checks alone say which items are selected.
(lead.lead, lead.anchor) = (selection.lead, selection.anchor);
// Space on a selected item flips that item first and then the other selected items to the same value. The
// selection here is every checked item, so only the first item's flips are kept.
if let Some(&first) = picks.toggled.first() {
picks.toggled.retain(|key| *key == first);
}
picks
}
}
+15 -7
View File
@@ -19,6 +19,7 @@
// PLAN: the imports below assume `craft_ui` paths as the framework's own code uses them; `ui::brush_settings`
// of the draw crate is where `TipEllipse` and `TipAngle` live.
use craft::behavior::EditEvents;
use craft::draw::ui::brush_settings::{TipAngle, TipEllipse};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Picture, PictureSize};
@@ -116,9 +117,10 @@ fn fidelity_round(v: f64) -> f64 {
}
/// The Fidelity field of tool `tool`, showing `v` to two decimals from the tool's lowest Fidelity to
/// 100 and stepping by [`fidelity_step`], named by the label drawn just before it. Returns the value
/// typed or stepped to. The Contextual Task Bar shows the Smooth tool's.
pub(crate) fn fidelity_field(ui: &mut Ui, id: &str, v: f64, tool: &str) -> Option<f64> {
/// 100 and stepping by [`fidelity_step`], named by the label drawn just before it. Returns the field's
/// edit events: the value typed or stepped to as a proposal, then its commit, or the cancel that
/// restores `v`. The Contextual Task Bar shows the Smooth tool's.
pub(crate) fn fidelity_field(ui: &mut Ui, id: &str, v: f64, tool: &str) -> EditEvents<Option<f64>> {
let min = vectorcraft_tools::draw2::min_fidelity(tool);
NumberField::new(tl!("Fidelity"), Bind::given(Some(v)))
.id_salt(id.to_owned())
@@ -128,8 +130,7 @@ pub(crate) fn fidelity_field(ui: &mut Ui, id: &str, v: f64, tool: &str) -> Optio
.stepper(|v, dir, scale| fidelity_step(v, f64::from(dir) * scale))
.show(ui)
.edit
.value()
.and_then(|typed| typed.to_owned())
.events
}
/// The Fidelity row: a logarithmic slider from the tool's lowest Fidelity to [`FIDELITY_MAX`] with the field at its
@@ -145,10 +146,17 @@ fn fidelity_row(ui: &mut Ui, fields: &mut DialogFields, tool: &str) -> Response
.label(tl!("Fidelity"))
.id_salt("fidelity-slider")
.show(ui);
if let Some(x) = slid.value() {
// The draft follows a drag unrounded, as a rounded value would end the slider's gesture, and takes the rounded
// value once the drag ends. Escape puts back the value from before the drag or the typing, which the field
// allows above the slider's end.
if let Some(x) = slid.events.committed() {
set = Some(fidelity_round(*x).clamp(min, FIDELITY_MAX));
} else if let Some(x) = slid.events.value() {
set = Some(x.clamp(min, FIDELITY_MAX));
} else if let Some(x) = slid.events.landed() {
set = Some(*x);
}
if let Some(x) = fidelity_field(ui, "fidelity-field", v, tool) {
if let Some(x) = fidelity_field(ui, "fidelity-field", v, tool).landed().and_then(|typed| typed.to_owned()) {
set = Some(x);
}
});
@@ -416,3 +416,76 @@ fn the_blob_brush_size_offers_the_stylus_wheel() {
let text = shown_text(&mut app);
assert!(text.contains("Stylus Wheel"), "it shows again on the next open: {text}");
}
/// The Fidelity the open Tool Options dialog holds, `None` once it is closed.
fn draft_fidelity(panel: &crate::tests::panel_harness::Panel) -> Option<f64> {
panel.app().dialogs().and_then(|d| d.with(|host| host.get::<HostedParamDialog>().and_then(|dialog| dialog.fields().number("fidelity"))))
}
/// The Smooth tool's Fidelity slider and field: a drag or a typed value that Escape cancels leaves the dialog's Fidelity
/// and the tool's as they were; a finished drag or a typed value left with Tab sets the dialog's, and OK sets the tool's.
#[test]
fn a_canceled_fidelity_drag_or_typed_value_leaves_the_dialog_and_the_tool() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers, vec2};
let mut app = app();
app.run("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": 2.5}})).unwrap();
let original = app.session.tool_options_of("smooth");
let document = app.session.active().unwrap().doc.clone();
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
panel.room(vec2(1000.0, 1200.0));
crate::toolbar::open_options(&mut panel.app(), "smooth").unwrap();
panel.frame();
assert_eq!(draft_fidelity(&panel), Some(2.5));
// On the track, above the Accurate and Smooth marks.
let track = |panel: &crate::tests::panel_harness::Panel| {
let r = panel.rect_role("Fidelity", Role::SLIDER);
egui::pos2(r.center().x, r.top() + 5.0)
};
let from = track(&panel);
panel.drag_hold_between(from, from + vec2(60.0, 0.0));
assert_ne!(draft_fidelity(&panel), Some(2.5), "the dialog's Fidelity follows the drag");
panel.key(Key::Escape, Modifiers::NONE);
panel.release();
assert_eq!(draft_fidelity(&panel), Some(2.5), "Escape puts back the Fidelity from before the drag");
panel.click_role("Fidelity", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("7");
panel.key(Key::Escape, Modifiers::NONE);
assert_eq!(panel.app().session.tool_options_of("smooth"), original, "the canceled typed value leaves the tool");
if draft_fidelity(&panel).is_none() {
crate::toolbar::open_options(&mut panel.app(), "smooth").unwrap();
panel.frame();
}
assert_eq!(draft_fidelity(&panel), Some(2.5), "the dialog shows the Fidelity from before the typing");
let from = track(&panel);
panel.drag_hold_between(from, from + vec2(60.0, 0.0));
panel.release();
let dragged = draft_fidelity(&panel).unwrap();
assert!(dragged > 2.5, "a finished drag sets the dialog's Fidelity: {dragged}");
assert_eq!(dragged, fidelity_round(dragged), "to the slider's step");
panel.click_role("Fidelity", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("7");
panel.key(Key::Tab, Modifiers::NONE);
assert_eq!(draft_fidelity(&panel), Some(7.0), "a typed value left with Tab sets the dialog's Fidelity");
assert_eq!(panel.app().session.tool_options_of("smooth"), original, "the tool keeps its Fidelity until OK");
panel.click("OK");
panel.frame();
assert_eq!(draft_fidelity(&panel), None, "OK closes the dialog");
assert_eq!(panel.app().session.tool_options_of("smooth")["fidelity"].as_f64(), Some(7.0));
assert_eq!(panel.app().session.active().unwrap().doc, document);
panel.app().run("tool.setOption", json!({"tool": "smooth", "values": {"fidelity": 50}})).unwrap();
crate::toolbar::open_options(&mut panel.app(), "smooth").unwrap();
panel.frame();
let from = track(&panel);
panel.drag_hold_between(from, from - vec2(60.0, 0.0));
assert!(draft_fidelity(&panel).is_some_and(|x| x <= FIDELITY_MAX), "the drag runs along the slider");
panel.key(Key::Escape, Modifiers::NONE);
panel.release();
assert_eq!(draft_fidelity(&panel), Some(50.0), "Escape puts back a Fidelity above the slider's end");
}
+34
View File
@@ -1219,6 +1219,40 @@ mod tests {
}
}
/// A number or text row leaves the draft alone while its text is still being typed, and writes
/// the typed value once Tab commits it.
#[test]
fn typed_number_and_text_rows_reach_the_draft_only_when_committed() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let mut app = app_with_graph("column");
app.run(COMMAND, json!({"columnWidth": 80, "prefix": "USD"})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(900.0, 900.0));
open(&mut panel.app()).unwrap();
panel.frame();
panel.click_role("Column Width", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("140");
panel.frame();
assert_eq!(field(&panel.app(), "columnWidth"), json!(80.0), "a number being typed is not in the draft");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert_eq!(field(&panel.app(), "columnWidth"), json!(140.0), "Tab commits the typed number");
set(&panel.app(), PAGE, json!("valueAxis")).unwrap();
panel.frame();
panel.click_role("Prefix", Role::TEXT_INPUT);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("EUR");
panel.frame();
assert_eq!(field(&panel.app(), "prefix"), json!("USD"), "text being typed is not in the draft");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert_eq!(field(&panel.app(), "prefix"), json!("EUR"), "Tab commits the typed text");
}
/// Object › Graph › Type… opens the dialog on the selected graph's options, on its Graph
/// Options page; each page the type has can be shown, and Override Calculated Values of the
/// right axis takes input only while that axis has a scale of its own.
-1
View File
@@ -207,7 +207,6 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
super::graph_design::pump,
super::perspective_grid::pump,
super::perspective_presets::pump,
super::slices::pump,
super::blend_options::pump,
super::saved_names::pump,
super::object_mosaic::pump,
+1 -1
View File
@@ -441,7 +441,7 @@ fn pages_body(ui: &mut egui::Ui, s: &mut State, preview: Option<&(Revision, Arc<
Text::new(crate::i18n::fmt(tl!("of {count}"), &[("count", &count.to_string())])).shade(Shade::Muted).show(ui);
let next = nav(ui, "chevron-right", tl!("Next Page"), (current + 1).min(count), current < count);
let last = nav(ui, "chevrons-right", tl!("Last Page"), count, current < count);
to = first.or(previous).or(next).or(last).or(typed.value().copied().flatten().map(|v| v as usize));
to = first.or(previous).or(next).or(last).or(typed.edit.events.landed().copied().flatten().map(|v| v as usize));
});
if let Some(page) = to {
s.page = page.clamp(1, count.max(1));
+40 -9
View File
@@ -980,6 +980,10 @@ mod tests {
canceled_detail_number("Height", "150");
}
#[test]
fn canceled_new_document_artboards_preserve_preset() {
canceled_detail_number("Artboards", "3");
}
#[test]
fn canceled_new_document_bleed_preserves_preset() {
canceled_detail_number("Top", "3");
}
@@ -1084,16 +1088,13 @@ mod tests {
/// did; before, it showed the words, and Landscape, cut short, ran into Artboards.
#[test]
fn orientation_shows_two_page_icons_beside_artboards() {
fn texts(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect().center())),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut app = app();
open(&mut app);
let out = laid_out(&mut app);
let drawn: Vec<(String, egui::Pos2)> = crate::tests_labels::text_shapes(&out)
.into_iter()
.map(|(t, transform)| (t.galley.text().to_string(), (transform * t.visual_bounding_rect()).center()))
.collect();
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
let bounds = |label: &str, role: egui::accesskit::Role| {
let (_, n) = nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).unwrap_or_else(|| panic!("no {role:?} {label}"));
@@ -1104,8 +1105,6 @@ mod tests {
// Artboards follows Landscape on its line, or wraps below it when the column has no room for it.
assert!(landscape.x1 <= artboards.x0 || landscape.y1 <= artboards.y0, "Landscape {landscape:?} stays clear of Artboards {artboards:?}");
let group = bounds("Orientation", egui::accesskit::Role::RadioGroup);
let mut drawn = Vec::new();
out.shapes.iter().for_each(|s| texts(&s.shape, &mut drawn));
let inside: Vec<_> = drawn
.iter()
.filter(|(_, at)| (group.x0..=group.x1).contains(&f64::from(at.x)) && (group.y0..=group.y1).contains(&f64::from(at.y)))
@@ -1113,6 +1112,38 @@ mod tests {
assert!(inside.is_empty(), "the segments draw icons, not words: {inside:?}");
}
/// Each preset card rests on a tile, a light veil of the scrim over the dialog's surface, with its paper on it, so a
/// card that is not selected still stands apart from the dialog.
#[test]
fn resting_preset_cards_stand_on_a_tile() {
use craft::ui::runtime::env::Env;
use craft::ui::style::rgba_color;
let mut scrim = egui::Color32::TRANSPARENT;
let mut theme =
crate::testing::ui_context().run_ui(Default::default(), |ui| scrim = rgba_color(Env::of(ui).tokens.tokens().color.surface.scrim));
// The test reads the theme; no renderer applies the frame's textures.
theme.textures_delta.clear();
let mut app = app();
open(&mut app);
let out = laid_out(&mut app);
let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default();
let card = nodes
.iter()
.find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label().is_some_and(|l| !l.is_empty()) && n.is_selected() == Some(false))
.and_then(|(_, n)| n.bounds())
.map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
.expect("a preset card that is not selected");
let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes);
let rects: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }).collect();
let veil = |fill: egui::Color32| fill.a() > 0 && fill.a() < scrim.a() && fill.to_opaque() == scrim.to_opaque();
assert!(
rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)),
"a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}",
rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::<Vec<_>>()
);
assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile");
}
/// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and
/// the built-in cards turn to the picked orientation (#2860).
#[test]
+1 -3
View File
@@ -4,8 +4,7 @@ use super::path_ops::PathOp;
use super::simplify_slider::StripKind;
use super::{
blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form,
path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, slices, smooth_slider, transform, transform_each,
width_point,
path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, transform, transform_each, width_point,
};
use crate::VectorcraftApp;
@@ -58,7 +57,6 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
graph_design::pump(app, ctx);
perspective_grid::pump(app, ctx);
perspective_presets::pump(app, ctx);
slices::pump(app, ctx);
blend_options::pump(app, ctx);
saved_names::pump(app, ctx);
object_mosaic::pump(app, ctx);
+19 -1
View File
@@ -507,6 +507,15 @@ pub(super) mod tests {
crate::toolbar::open_options(&mut panel.app(), "livePaintBucket").unwrap();
panel.frame();
assert_eq!(fields(&panel.app()), before);
panel.click_role("Width", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("9");
assert_eq!(fields(&panel.app())["width"], 9.0, "typing proposes the width");
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving the field keeps the dialog open");
assert_eq!(fields(&panel.app()), before, "leaving the field on text that is not a number restores the opening width");
if commit {
panel.click_role("Width", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
@@ -530,7 +539,7 @@ pub(super) mod tests {
/// Normal Gap Options supplies numeric points. This hosted row fixture separately checks
/// the nullable length helper's contract, including restoring an empty opening value.
#[test]
fn a_nullable_length_row_restores_null_on_escape() {
fn a_nullable_length_row_restores_null_when_its_typing_is_canceled() {
static NULL_LENGTH: OptionSpec = OptionSpec {
key: "nullableLengthTest",
title: || "Nullable Length".into(),
@@ -555,6 +564,15 @@ pub(super) mod tests {
open(&mut panel.app(), &NULL_LENGTH, Map::from_iter([("length".into(), Value::Null)]), Value::Null).unwrap();
panel.frame();
assert_eq!(fields(&panel.app())["length"], Value::Null);
panel.click_role("Length", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("9 pt");
assert_eq!(fields(&panel.app())["length"], 9.0);
panel.type_text("x");
panel.key(Key::Tab, Modifiers::NONE);
panel.frame();
assert!(is_open(&panel.app()), "leaving the field keeps the dialog open");
assert_eq!(fields(&panel.app())["length"], Value::Null, "leaving the field on text that is not a length restores null");
}
/// Whether `a` and `b` are the same value, numbers by their value.
@@ -609,7 +609,9 @@ fn tabs_buttons(unit: Unit) -> Param {
let (rows, _, _) = tab_rows(fields);
let can_add = new_tab_position(&rows, unit).is_some();
let (mut add, mut delete, mut clear) = (false, false, false);
let line = Row::new().wrap(true).show(ui, |ui, _| {
// Wrap against the form's offered width rather than measuring an intrinsic-width
// strip that may be clipped by the property group on small screens.
let line = Row::new().fill_width().wrap(true).show(ui, |ui, _| {
add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui));
delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui));
clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui));
@@ -574,11 +574,17 @@ fn clear_all_tabs_can_be_clicked_in_a_narrow_viewport() {
for _ in 0..5 {
frame(&mut app, vec![]);
}
// The dialog's first frames measure it before its body runs; the Tabs pane picked before them stays shown.
assert_eq!(fields(&app)["tab"], json!("tabs"), "the dialog left Tabs in its first frames at {width} points");
let out = frame(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let clear = nodes.iter().find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs")).unwrap();
let clear = nodes
.iter()
.find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs"))
.unwrap_or_else(|| panic!("Clear All Tabs is missing at {width} points"));
let bounds = clear.1.bounds().unwrap();
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
assert!(screen.contains(at), "Clear All Tabs at {bounds:?} is outside the {width}-point viewport");
assert_eq!(tab_rows(&app).len(), 2);
frame(&mut app, vec![Event::PointerMoved(at)]);
@@ -532,14 +532,15 @@ fn labelled_controls(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> {
.collect()
}
/// The bounds of the control labelled `label` in `controls`, with or without a final colon.
/// The bounds of the control labelled `label` in `controls`, with or without a final colon. A check box and the text of
/// its label are two nodes with the same name side by side, so the bounds take in every node so named on the first
/// one's line.
fn control(controls: &[(String, egui::Rect)], label: &str) -> egui::Rect {
let bare = |l: &str| l.trim_end_matches(':').to_string();
controls
.iter()
.find(|(l, _)| bare(l) == bare(label))
.map(|(_, r)| *r)
.unwrap_or_else(|| panic!("no control labelled {label:?} in {:?}", controls.iter().map(|(l, _)| l).collect::<Vec<_>>()))
let named: Vec<egui::Rect> = controls.iter().filter(|(l, _)| bare(l) == bare(label)).map(|(_, r)| *r).collect();
let first =
*named.first().unwrap_or_else(|| panic!("no control labelled {label:?} in {:?}", controls.iter().map(|(l, _)| l).collect::<Vec<_>>()));
named.iter().filter(|r| r.top() < first.bottom() && first.top() < r.bottom()).fold(first, |all, r| all.union(*r))
}
/// The All and Range radios stand right under the artboard check box, and EPS's Transparent and Opaque radios right
@@ -567,6 +568,31 @@ fn save_options_radios_have_no_empty_caption_over_them() {
}
}
/// The All and Range radios start where the artboard check box above them starts, in the control column past the
/// captions, and EPS's Transparent and Opaque radios start where the Preview menu starts.
#[test]
fn save_options_radios_start_in_the_control_column() {
for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] {
let (mut app, _, _) = desktop(picked);
save_as(&mut app, "file.saveAs");
let controls = labelled_controls(&mut app);
let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:"));
assert!((all.left() - check.left()).abs() < 1.0, "{picked}: All at {all:?}, the check box at {check:?}");
assert!((range.left() - check.left()).abs() < 1.0, "{picked}: Range at {range:?}, the check box at {check:?}");
if picked == "art.eps" {
let (transparent, opaque) = (control(&controls, "Transparent"), control(&controls, "Opaque"));
let preview = controls
.iter()
.filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top())
.map(|(_, r)| *r)
.max_by(|a, b| a.bottom().total_cmp(&b.bottom()))
.expect("the Preview menu above Transparent");
assert!((transparent.left() - preview.left()).abs() < 1.0, "Transparent at {transparent:?}, Preview at {preview:?}");
assert!((opaque.left() - preview.left()).abs() < 1.0, "Opaque at {opaque:?}, Preview at {preview:?}");
}
}
}
#[test]
fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() {
let (mut app, written, _) = desktop("original.vectorcraft");
+68 -51
View File
@@ -24,12 +24,6 @@ pub const OPTIONS: &str = "sliceOptions";
/// The dialog kind of Divide Slices.
pub const DIVIDE: &str = "divideSlices";
#[derive(Default)]
pub(crate) struct SliceDialogs {
options: Option<Target>,
divide: Option<Target>,
}
/// The document, its revert count and the effective slice selection used when opening either dialog.
#[derive(PartialEq)]
struct Target {
@@ -134,12 +128,8 @@ pub fn open_options(app: &mut VectorcraftApp) -> Result<Value, String> {
kinds.push(SliceKind::HtmlText);
}
let dialog = SliceOptionsDialog::new(options_of(&map)).kinds(&kinds);
app.dialogs().ok_or("no window")?.with(|host| {
host.open(dialog);
// Replacing a still-open dialog leaves its Cancel behind.
let _ = host.take::<SliceOptionsDialog>();
});
app.slice_dialogs.options = Some(source);
crate::dialogs::host::open_held(app, dialog, move |app, o: &SliceOptions| apply(app, &source, "object.slice.options", options_json(o)))
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -152,44 +142,27 @@ pub fn open_divide(app: &mut VectorcraftApp) -> Result<Value, String> {
let source = Target::new(st.uid, st.reverts, selected);
let (w, h) = first.map_or((50.0, 50.0), |r| (r.width() / 2.0, r.height() / 2.0));
let dialog = DivideSlicesDialog::new(DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(2)))).lengths(lengths).start_sizes(h, w);
app.dialogs().ok_or("no window")?.with(|host| {
host.open(dialog);
let _ = host.take::<DivideSlicesDialog>();
});
app.slice_dialogs.divide = Some(source);
crate::dialogs::host::open_held(app, dialog, move |app, d: &DivideSlices| apply(app, &source, "object.slice.divide", divide_json(d)))
.ok_or("no window")?;
Ok(Value::Null)
}
/// Run the answer of whichever slice dialog closed with OK. The framework dialogs hold no answer, so a
/// refusal goes to the status line and the dialog is already closed.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(host) = app.dialogs() else { return };
let (options, divide) = host.with(|h| (h.take::<SliceOptionsDialog>(), h.take::<DivideSlicesDialog>()));
let answers = [
options.and_then(|r| {
let source = app.slice_dialogs.options.take();
r.ok().map(|o| (source, "object.slice.options", options_json(&o)))
}),
divide.and_then(|r| {
let source = app.slice_dialogs.divide.take();
r.ok().map(|d| (source, "object.slice.divide", divide_json(&d)))
}),
];
for (source, cmd, params) in answers.into_iter().flatten() {
if source.as_ref().is_some_and(|source| source.reverted(app)) {
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
} else if !source.is_some_and(|source| Some(source) == Target::current(app)) {
app.status(tl!("The slice selection changed while the dialog was open."));
} else if let Err(e) = app.run(cmd, params) {
app.status(e);
}
/// Runs a slice dialog's OK on the document and slices it opened with. A refusal keeps the dialog open with
/// what was typed and the reason under its rows.
fn apply(app: &mut VectorcraftApp, source: &Target, cmd: &str, params: Value) -> Result<(), String> {
if source.reverted(app) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if Target::current(app).as_ref() != Some(source) {
return Err(tl!("The slice selection changed while the dialog was open.").to_owned());
}
app.run(cmd, params).map(|_| ())
}
#[cfg(test)]
mod tests {
use super::*;
use craft::ui::dialog::{DialogHost, DialogId};
use craft::ui::dialog::{DialogHost, DialogId, HeldOk};
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
@@ -217,12 +190,20 @@ mod tests {
host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap();
}
/// OK on the open dialog, then the frame's pump runs its answer; whether OK was enabled.
/// OK on the open dialog, then the frame's pump runs its held answer, and an accepted answer closes the
/// dialog; whether OK was enabled.
fn ok(app: &mut VectorcraftApp) -> bool {
let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), the_dialog(app));
let enabled = host(app, |h| h.confirm_by_id(&ctx, id));
let closed = host(app, |h| h.confirm_by_id(&ctx, id));
if !closed && host(app, |h| h.held_state(id)) != Some(HeldOk::Waiting) {
return false;
}
crate::dialogs::host::pump(app, &ctx);
enabled
if host(app, |h| h.held_state(id)) == Some(HeldOk::Accepted) {
host(app, |h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(app, &ctx);
}
true
}
fn add_slice(app: &mut VectorcraftApp, x: f64) -> NodeId {
@@ -235,15 +216,33 @@ mod tests {
app.run("object.slice.select", json!({"slices": [id.0]})).unwrap();
}
/// The reason the open dialog shows for its refused OK, if it has one.
fn refusal(app: &VectorcraftApp) -> Option<String> {
let (id, _) = the_dialog(app);
match host(app, |h| h.held_state(id)) {
Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_string()),
_ => None,
}
}
/// Whether either slice dialog is open.
fn slice_dialog_open(app: &VectorcraftApp) -> bool {
host(app, |h| h.is_open::<SliceOptionsDialog>() || h.is_open::<DivideSlicesDialog>())
}
/// The field each dialog's test types into, and the value typed.
fn draft(divide: bool) -> (&'static str, Value) {
if divide { ("columns", json!(3)) } else { ("name", json!("Original")) }
}
fn check_changed_selection(dialog: &str, divide: bool) {
let mut app = app();
let source = app.session.active().unwrap().doc.slice_ids()[0];
let destination = add_slice(&mut app, 80.0);
select_slice(&mut app, source);
app.run(dialog, json!({})).unwrap();
if !divide {
set(&app, "name", json!("Original"));
}
let (field, typed) = draft(divide);
set(&app, field, typed.clone());
select_slice(&mut app, destination);
let st = app.session.active().unwrap();
let undo = st.history.undo.len();
@@ -253,7 +252,22 @@ mod tests {
let st = app.session.active().unwrap();
assert_eq!(*st.doc, *document, "the changed selection is untouched");
assert_eq!(st.history.undo.len(), undo);
assert_eq!(app.ui.status, "The slice selection changed while the dialog was open.");
assert!(slice_dialog_open(&app), "the refused dialog stays open");
assert_eq!(refusal(&app).as_deref(), Some("The slice selection changed while the dialog was open."));
assert_eq!(the_dialog(&app).1[field], typed, "the refused dialog keeps what was typed");
// With the opening slice selected again, the same draft applies.
select_slice(&mut app, source);
assert!(ok(&mut app));
assert!(!slice_dialog_open(&app), "the accepted dialog closes");
let st = app.session.active().unwrap();
assert_eq!(st.history.undo.len(), undo + 1, "the accepted OK is one undo step");
if divide {
assert_eq!(st.doc.slices.len(), document.slices.len() + 6, "the opening slice is divided into six cells");
} else {
assert_eq!(st.doc.slice_options(source).unwrap().name, "Original");
assert_eq!(st.doc.slice_options(destination).unwrap().name, "", "the other slice keeps its options");
}
}
#[test]
@@ -267,7 +281,7 @@ mod tests {
}
/// Opens `dialog` on the saved document's slice, edits the document, reverts it and reselects the same slice id;
/// OK then leaves the restored document as it is and reports the revert. Returns the app and the slice.
/// OK then leaves the restored document as it is and the dialog open with the reason. Returns the app and the slice.
fn check_refused_after_file_revert(dialog: &str, divide: bool, tag: &str) -> (VectorcraftApp, NodeId) {
let mut app = app();
let slice = app.session.active().unwrap().doc.slice_ids()[0];
@@ -292,7 +306,8 @@ mod tests {
let st = app.session.active().unwrap();
assert_eq!(*st.doc, *restored, "OK leaves the restored document's slices unchanged");
assert_eq!(st.history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
assert!(slice_dialog_open(&app), "the refused dialog stays open");
assert_eq!(refusal(&app).as_deref(), Some("The document was reverted. Reopen this dialog to continue."));
(app, slice)
}
@@ -332,6 +347,8 @@ mod tests {
let st = app.session.active().unwrap();
assert_eq!(st.doc.slice_options(to).unwrap().name, "");
assert_eq!(st.history.undo.len(), undo);
assert_eq!(refusal(&app).as_deref(), Some("The slice selection changed while the dialog was open."), "the refused dialog stays open");
assert_eq!(the_dialog(&app).1["name"], "Source", "the refused dialog keeps what was typed");
}
#[test]
@@ -342,7 +359,7 @@ mod tests {
select_slice(&mut app, other);
app.run("object.slice.options", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
pump(&mut app, &ctx);
crate::dialogs::host::pump(&mut app, &ctx);
set(&app, "name", json!("Replacement"));
assert!(ok(&mut app));
@@ -678,3 +678,29 @@ fn an_empty_password_still_asks_for_the_password() {
assert!(!import_pdf::offer_place_password(&mut app, &p), "a given password is placed with");
assert!(!is_open(&app));
}
/// A page number the Page field refuses when Tab leaves it goes back to the page shown before the edit, and OK places
/// that page.
#[test]
fn a_page_the_field_refuses_on_tab_places_the_page_it_restores() {
use crate::tests::panel_harness::Panel;
use egui::{Key, Modifiers};
let mut panel = Panel::new(app(), crate::tests::picks::dialogs);
panel.room(egui::vec2(1000.0, 800.0));
place(&mut panel.app(), &three_pages(), json!({"at": [100, 120], "link": false})).unwrap();
panel.frame();
panel.click("Page");
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("2");
assert_eq!(field(&panel.app(), "page"), 2);
panel.type_text("*");
panel.key(Key::Tab, Modifiers::NONE);
assert!(is_open(&panel.app()));
assert_eq!(field(&panel.app(), "page"), 1, "the refused text restores the page from before the edit");
panel.click("OK");
panel.frame();
assert!(!is_open(&panel.app()));
let (_, bounds) = placed(&panel.app());
assert_eq!((bounds.width(), bounds.height()), (100.0, 100.0), "the first page is placed");
}
+96 -18
View File
@@ -295,18 +295,15 @@ fn checked_artboards_read_as_a_range() {
/// The rect the frame `shapes` paint `texture` over; `None` when none paints it.
fn painted(shapes: &[egui::epaint::ClippedShape], texture: egui::TextureId) -> Option<egui::Rect> {
fn walk(shape: &egui::Shape, texture: egui::TextureId, out: &mut Option<egui::Rect>) {
match shape {
egui::Shape::Vec(all) => all.iter().for_each(|s| walk(s, texture, out)),
egui::Shape::Mesh(mesh) if mesh.texture_id == texture => {
let at = mesh.calc_bounds();
*out = Some(out.map_or(at, |r| r.union(at)));
}
_ => {}
let mut out: Option<egui::Rect> = None;
for (shape, transform, _) in crate::tests_labels::painted_shapes(shapes) {
if let egui::Shape::Mesh(mesh) = shape
&& mesh.texture_id == texture
{
let at = transform * mesh.calc_bounds();
out = Some(out.map_or(at, |r| r.union(at)));
}
}
let mut out = None;
shapes.iter().for_each(|clipped| walk(&clipped.shape, texture, &mut out));
out
}
@@ -943,14 +940,11 @@ fn a_preset_export_reopens_on_its_rows() {
}
fn screen_text_at(out: &egui::FullOutput, label: &str) -> egui::Pos2 {
fn find(shape: &egui::Shape, label: &str) -> Option<egui::Pos2> {
match shape {
egui::Shape::Text(t) if t.galley.text().trim() == label => Some(t.visual_bounding_rect().center()),
egui::Shape::Vec(v) => v.iter().find_map(|s| find(s, label)),
_ => None,
}
}
out.shapes.iter().find_map(|s| find(&s.shape, label)).unwrap_or_else(|| panic!("missing {label}: {}", crate::tests_labels::shapes_text(out)))
crate::tests_labels::text_shapes(out)
.into_iter()
.find(|(t, _)| t.galley.text().trim() == label)
.map(|(t, transform)| (transform * t.visual_bounding_rect()).center())
.unwrap_or_else(|| panic!("missing {label}: {}", crate::tests_labels::shapes_text(out)))
}
/// First-directory entries of the big-endian TIFF chosen below: tag, type, count, inline value.
@@ -1670,3 +1664,87 @@ fn the_format_rows_fit_the_right_column_at_the_default_and_least_window_sizes()
}
}
}
/// The items pane, in the grid and in the list, with one artboard and with many: the artboards sit in a sunken frame
/// at least one and a half tiles or five rows tall, the view buttons and the prefix sit under the frame, and the checked
/// artboards are the selected ones.
#[test]
fn the_artboards_sit_in_a_framed_view_as_tall_as_the_pane_and_the_checked_ones_are_selected() {
for (boards, view) in [(1, "grid"), (1, "list"), (12, "grid"), (12, "list")] {
let (mut app, _) = app(boards, false);
let mut w = Window::default();
w.run(&mut app, vec![]);
open(&mut app);
set(&mut app, "view", json!(view));
let shown = |w: &mut Window, app: &mut VectorcraftApp| {
w.run(app, vec![]);
let out = w.run(app, vec![]);
let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
(out.shapes, nodes)
};
let rect = |n: &egui::accesskit::Node| {
n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
};
let (shapes, nodes) = shown(&mut w, &mut app);
let find = |label: &str, role: Role| {
nodes
.iter()
.find(|(_, n)| n.label() == Some(label) && n.role() == role)
.and_then(|(_, n)| rect(n))
.unwrap_or_else(|| panic!("{view}: no {role:?} {label:?}"))
};
let pane = nodes
.iter()
.find(|(_, n)| n.label() == Some("Export for Screens") && matches!(n.role(), Role::ListBox | Role::List))
.and_then(|(_, n)| rect(n))
.unwrap_or_else(|| panic!("{boards} {view}: no items view"));
let clear = find("Clear Selection", Role::Button);
let tile = find("1 Artboard 1", Role::ListItem);
// The frame: a filled or outlined rectangle that holds the items view.
fn rects(shape: &egui::Shape, out: &mut Vec<egui::epaint::RectShape>) {
match shape {
egui::Shape::Rect(r) => out.push(r.clone()),
egui::Shape::Vec(v) => v.iter().for_each(|s| rects(s, out)),
_ => {}
}
}
let mut painted = Vec::new();
shapes.iter().for_each(|c| rects(&c.shape, &mut painted));
let near: Vec<_> = painted.iter().filter(|r| r.rect.expand(4.0).contains_rect(pane) && pane.expand(4.0).contains_rect(r.rect)).collect();
let framed = near.iter().any(|r| r.stroke.width > 0.0 || r.fill.a() > 0);
assert!(framed, "{boards} {view}: the items view at {pane:?} has a frame: {near:?}");
assert!(clear.top() >= pane.bottom(), "{boards} {view}: Clear Selection {clear:?} is under the items {pane:?}");
// One and a half tiles tall in the grid, five rows in the list, whatever the count of artboards.
let least = if view == "grid" { 1.5 } else { 5.0 } * tile.height();
assert!(pane.height() >= least, "{boards} {view}: the items view {pane:?} is at least {least} tall (an item is {tile:?})");
let selected = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)]| {
nodes.iter().find(|(_, n)| n.label() == Some("1 Artboard 1") && n.role() == Role::ListItem).and_then(|(_, n)| n.is_selected())
};
assert_eq!(selected(&nodes), Some(true), "{boards} {view}: the checked artboard is selected");
let mut off = vec![true; boards];
off[0] = false;
set(&mut app, "boards", json!(off));
let (_, nodes) = shown(&mut w, &mut app);
assert_ne!(selected(&nodes), Some(true), "{boards} {view}: an artboard that is not checked is not selected");
}
}
/// With two artboards checked, the arrow keys move to a checked one and, a frame later, Space unchecks only that one,
/// in the grid and in the list.
#[test]
fn space_on_a_checked_artboard_flips_only_its_own_check() {
for (view, back) in [("grid", egui::Key::ArrowLeft), ("list", egui::Key::ArrowUp)] {
let (mut app, _) = app(3, false);
let mut w = Window::default();
w.names(&mut app);
open(&mut app);
set(&mut app, "view", json!(view));
set(&mut app, "boards", json!([true, true, false]));
w.press(&mut app, "3 Artboard 3", Role::ListItem);
assert_eq!(field(&app, "boards"), json!([true, true, false]), "{view}: a click on the third artboard leaves the checks");
w.key(&mut app, back);
w.run(&mut app, vec![]);
w.key(&mut app, egui::Key::Space);
assert_eq!(field(&app, "boards"), json!([true, false, false]), "{view}: Space unchecks only the second artboard");
}
}
@@ -72,16 +72,6 @@ fn frame_texts(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
/// The texts the dialogs paint with where each is drawn and its font, once they have faded in.
fn frame_runs(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::Rect, Option<egui::FontId>)> {
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect, Option<egui::FontId>)>) {
match s {
egui::Shape::Text(t) => {
let font = t.galley.job.sections.first().map(|section| section.format.font_id.clone());
out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()), font));
}
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let dialogs = app.dialogs().expect("a window");
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 1200.0));
let mut texts = vec![];
@@ -89,8 +79,13 @@ fn frame_runs(app: &VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::R
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| dialogs.with(|host| host.run(ui)));
out.textures_delta.clear();
texts.clear();
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
texts = crate::tests_labels::text_shapes(&out)
.into_iter()
.map(|(t, transform)| {
let font = t.galley.job.sections.first().map(|section| section.format.font_id.clone());
(t.galley.text().to_string(), transform * t.galley.rect.translate(t.pos.to_vec2()), font)
})
.collect();
}
texts
}
+2 -10
View File
@@ -15,18 +15,10 @@ fn app_with(n: usize) -> VectorcraftApp {
/// One headless frame of the canvas panel's body (the tabs and the canvas or panes) on a
/// 1200 × 800 window, then the floating document windows, which egui draws inside the window, run
/// as the hosts run a frame → the shapes it drew, `Shape::Vec`s flattened.
/// as the hosts run a frame → the shapes it drew, `Shape::Vec`s and retained paint chunks flattened.
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<Shape> {
fn flat(s: Shape, out: &mut Vec<Shape>) {
match s {
Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)),
s => out.push(s),
}
}
let out = run_frame(app, ctx, events);
let mut shapes = vec![];
out.shapes.into_iter().for_each(|c| flat(c.shape, &mut shapes));
shapes
crate::tests_labels::flat_painted_shapes(&out.shapes)
}
/// One headless frame of the canvas panel's body and the floating document windows on a 1200 ×
+3 -5
View File
@@ -132,11 +132,9 @@ mod tests {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::show(app, ui));
out.textures_delta.clear();
let mut texts = String::new();
for shape in out.shapes {
if let egui::epaint::Shape::Text(t) = shape.shape {
texts.push_str(t.galley.text());
texts.push('\n');
}
for (t, _) in crate::tests_labels::text_shapes(&out) {
texts.push_str(t.galley.text());
texts.push('\n');
}
texts
}
-2
View File
@@ -288,8 +288,6 @@ pub struct VectorcraftApp {
pub(crate) three_d: panels::three_d::Model,
/// The open export option dialogs and what runs after each.
pub(crate) export_dialogs: dialogs::export_host::ExportDialogs,
/// The document and selection used by each open slice dialog.
pub(crate) slice_dialogs: dialogs::slices::SliceDialogs,
/// The drawing and loaded contents the open Package dialog saves and collects.
pub(crate) package_document: Option<(u64, u64)>,
/// Save for Web's renders and colour table.
+1 -1
View File
@@ -738,7 +738,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
// Tab: hide the panels, the toolbars and the Control bar, or show what the last Tab
// hid; the window's shell applies it in its next pass.
Some(ctx) => {
let hidden = craft::ui::shell::chrome_state(&ctx, egui::ViewportId::ROOT).hidden;
let hidden = crate::panel_docking::tab_hidden(app);
request_chrome_toggle(&ctx, egui::ViewportId::ROOT, if hidden { ChromeToggle::ShowPanels } else { ChromeToggle::Panels });
Ok(json!(hidden))
}
+20 -13
View File
@@ -262,6 +262,21 @@ fn help_f1_opens_discover_without_a_document() {
assert!(crate::panel_docking::showing(&app.ui, "discover"));
}
/// In Standard Screen Mode Tab hides the panels, the toolbars and the Control bar, and the next Tab
/// shows them again.
#[test]
fn a_second_tab_shows_what_the_first_hid() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
let ctx = crate::testing::ui_context();
app.ui_ctx = Some(ctx.clone());
assert_eq!(app.run("window.dock", json!({})).unwrap(), json!(false));
app_frame(&mut app, &ctx, vec![]);
assert!(crate::panel_docking::tab_hidden(&app));
assert_eq!(app.run("window.dock", json!({})).unwrap(), json!(true), "the second Tab shows what the first hid");
app_frame(&mut app, &ctx, vec![]);
assert!(!crate::panel_docking::tab_hidden(&app));
}
/// With the toolbars hidden by Tab, choosing a tool in Help, or a tool's link in a tutorial Help
/// shows, marks nothing and the status bar says why.
#[test]
@@ -273,18 +288,10 @@ fn discover_says_why_a_tool_cannot_be_marked() {
}
fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
let out = pass(ctx, app, events);
fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
_ => {}
}
}
let mut texts = vec![];
for c in &out.shapes {
collect(&c.shape, &mut texts);
}
texts
crate::tests_labels::text_shapes(&out)
.into_iter()
.map(|(t, transform)| (t.galley.text().to_string(), transform * t.visual_bounding_rect()))
.collect()
}
fn click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) {
texts(ctx, app, vec![]);
@@ -314,7 +321,7 @@ fn discover_says_why_a_tool_cannot_be_marked() {
// Tab hides the toolbars in the shell's next pass.
app.run("window.dock", json!({})).unwrap();
app_frame(&mut app, &ctx, vec![]);
assert!(craft::ui::shell::chrome_state(&ctx, egui::ViewportId::ROOT).hidden);
assert!(crate::panel_docking::tab_hidden(&app));
let reason = app.run("learn.locateTool", json!({"tool": "rectangle"})).unwrap()["reason"].as_str().unwrap().to_string();
let found = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap();
+3 -5
View File
@@ -522,11 +522,9 @@ fn progress(app: &mut VectorcraftApp, ctx: &egui::Context) -> String {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::export_progress::show(app, ui));
out.textures_delta.clear();
let mut texts = String::new();
for shape in out.shapes {
if let egui::epaint::Shape::Text(t) = shape.shape {
texts.push_str(t.galley.text());
texts.push('\n');
}
for (t, _) in crate::tests_labels::text_shapes(&out) {
texts.push_str(t.galley.text());
texts.push('\n');
}
texts
}
+1 -1
View File
@@ -534,7 +534,7 @@ fn tool_home(app: &VectorcraftApp, tool: &str) -> String {
None => name.to_string(),
};
// Tab hides every toolbar with the panels, as the main window's shell left it.
let tab_hidden = app.ui_ctx.as_ref().is_some_and(|ctx| craft::ui::shell::chrome_state(ctx, egui::ViewportId::ROOT).hidden);
let tab_hidden = crate::panel_docking::tab_hidden(app);
let toolbars_shown = app.ui.screen_mode < 3 && !tab_hidden;
let main = crate::toolbar::slots(app).into_iter().map(|(_, s)| s).find(|s| s.contains(&tool));
// A group torn off into a strip shows each of its tools on its own button.
+7 -27
View File
@@ -226,20 +226,23 @@ fn settle(app: &mut VectorcraftApp) {
/// last pass left it, and Presentation Mode is off? With no window yet nothing hides them.
pub(crate) fn panels_shown(app: &VectorcraftApp) -> bool {
let chrome = app.ui_ctx.as_ref().map(|ctx| chrome_state(ctx, egui::ViewportId::ROOT)).unwrap_or_default();
!chrome.hidden && !chrome.panels_hidden && app.ui.screen_mode < 3
!chrome.hidden && !chrome.chrome_hidden && !chrome.panels_hidden && app.ui.screen_mode < 3
}
/// Whether Tab hides the main window's panels, toolbars and Control bar (Shift+Tab leaves the
/// toolbars).
pub(crate) fn tab_hidden(app: &VectorcraftApp) -> bool {
app.ui_ctx.as_ref().is_some_and(|ctx| chrome_state(ctx, egui::ViewportId::ROOT).hidden)
app.ui_ctx.as_ref().is_some_and(|ctx| {
let chrome = chrome_state(ctx, egui::ViewportId::ROOT);
chrome.hidden || chrome.chrome_hidden
})
}
/// Ends Tab and Shift+Tab hiding the panels in the main window; nothing while they show.
pub(crate) fn show_panels(app: &VectorcraftApp) {
let Some(ctx) = &app.ui_ctx else { return };
let chrome = chrome_state(ctx, egui::ViewportId::ROOT);
if chrome.hidden || chrome.panels_hidden {
if chrome.hidden || chrome.chrome_hidden || chrome.panels_hidden {
request_chrome_toggle(ctx, egui::ViewportId::ROOT, ChromeToggle::ShowPanels);
}
}
@@ -518,22 +521,6 @@ fn flyout_tab(layout: &Layout<String>, panel: &str) -> Option<String> {
.map(|front| front.to_string())
}
/// The actions that expand each floating window the pass made from part of a column collapsed to
/// icons, so a group or tab dragged out of an icon column floats as an expanded panel with its tabs
/// in the window. A whole icon column floated stays collapsed.
fn floated_from_icons(before: &Layout<String>, after: &Layout<String>) -> Vec<Action<String>> {
after
.floating
.iter()
.filter(|window| window.column.iconic && !before.floating.iter().any(|old| old.id == window.id))
.filter_map(|window| {
let first = window.panels().next()?;
let (_, column) = column_of(before, first)?;
(column.iconic && column.panels().count() > window.panels().count()).then(|| Action::set_iconic(first.clone(), false))
})
.collect()
}
/// Show `panel` as `window.panel` does, but leave it be when it can be seen already ([`visible`]):
/// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. A flyout
/// keeps the name of the icon that opened it after another of its tabs is clicked, so a panel whose
@@ -1390,20 +1377,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
app.dock_rt.rails = rails;
// A workspace a command switched to or changed in this pass (`Workspace::replace`) stays; the
// pass's edits were to the one it replaced.
let mut expand = Vec::new();
if app.ui.dock_workspace.revision() == revision {
let before = std::mem::replace(&mut app.ui.dock_workspace, workspace);
expand = floated_from_icons(before.layout(), layout_of(&app.ui));
app.ui.dock_workspace = workspace;
}
// A command of this pass that opened or closed a flyout wins over the area's own change.
if app.ui.open_panel == flyout_before {
app.ui.open_panel = flyout;
}
if !expand.is_empty()
&& let Err(error) = apply(app, None, expand)
{
app.status(error);
}
if output.error.is_some() {
Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[]));
app.status(tl!("Invalid panel layout; restored the default dock").to_string());
@@ -113,15 +113,10 @@ impl Host {
};
let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui));
full.textures_delta.clear();
fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) {
match s {
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let mut shown = Vec::new();
full.shapes.iter().for_each(|c| texts(&c.shape, &mut shown));
let shown: Vec<(String, Rect)> = crate::tests_labels::text_shapes(&full)
.into_iter()
.map(|(t, transform)| (t.galley.text().to_string(), transform * t.visual_bounding_rect()))
.collect();
let nodes = full.platform_output.accesskit_update.as_ref().map_or_else(Vec::new, |update| {
let rect = |b: egui::accesskit::Rect| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32));
update.nodes.iter().filter_map(|(_, node)| Some((node.label()?.to_string(), rect(node.bounds()?)))).collect()
+4 -5
View File
@@ -1080,11 +1080,10 @@ fn footer_strip_shows_no_rows(h: &mut Harness, case: &str) {
egui::Shape::Mesh(m) => m.vertices.iter().all(|v| v.color.a() == 0),
_ => false,
};
let showing: Vec<Rect> = h
.shapes
.iter()
.filter(|c| !transparent(&c.shape))
.map(|c| (c.shape.visual_bounding_rect(), c.clip_rect))
let showing: Vec<Rect> = crate::tests_labels::painted_shapes(&h.shapes)
.into_iter()
.filter(|(shape, ..)| !transparent(shape))
.map(|(shape, transform, clip)| (transform * shape.visual_bounding_rect(), clip))
.filter(|(bounds, clip)| {
let seen = clip.intersect(*bounds).intersect(strip);
bounds.height() < 60.0 && bounds.top() < footer.top() && seen.is_positive() && seen.height() > 0.5
+12
View File
@@ -614,6 +614,16 @@ pub(crate) fn panel_menu_states(app: &VectorcraftApp, states: &mut CommandStates
crate::canvas::task_bar::menu_states(app, states);
}
/// Names the panel menu rows `rows` in `states`, each by its English label shown in the UI language: a row the menu bar
/// and the keymap do not list has no catalog label, and shows its command id without one. The state set for a row
/// keeps its enabled and checked flags.
pub(crate) fn name_rows<'a>(states: &mut CommandStates, rows: impl IntoIterator<Item = (CommandRef, &'a str)>) {
for (command, label) in rows {
let state = states.get(&command).cloned().unwrap_or_default();
states.set(command, state.title(crate::i18n::t(label)));
}
}
/// Runs panel menu command `id` when a panel runs it itself; `None` otherwise.
pub(crate) fn run_menu_command(app: &mut VectorcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
if id == "ui.libraryPanel.add" {
@@ -1318,6 +1328,8 @@ mod tests_links;
#[cfg(test)]
mod tests_maskview;
#[cfg(test)]
mod tests_menu_names;
#[cfg(test)]
mod tests_panel_rows;
#[cfg(test)]
mod tests_panel_spacing;
+4 -4
View File
@@ -145,17 +145,17 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
set(Row::Panel(C::InsertStop), recording || has);
set(Row::Panel(C::InsertMenuItem), recording || has);
set(Row::Panel(C::InsertPath), (recording || has) && f.path);
set(Row::SelectObject, recording || has);
set(Row::Options, has);
set(Row::Panel(C::PlaybackOptions), true);
set(Row::Panel(C::Save), f.current.is_some());
set(Row::Panel(C::Load), can_load(app));
set(Row::Panel(C::Replace), can_load(app) && f.idle);
set(Row::Panel(C::ClearAll), f.idle && f.sets > 0);
set(Row::Panel(C::Reset), f.idle);
// The framework's labels differ from the panel's own words on these rows.
let titled = |row: Row, title: &str, enabled: bool| (row.command(), CommandState::new().enabled(enabled).title(title.to_string()));
// The framework's labels differ from the panel's own words on these rows, and the panel's own rows have none.
let titled = |row: Row, title: &str, enabled: bool| (row.command(), CommandState::new().enabled(enabled).title(crate::i18n::t(title)));
for (command, state) in [
titled(Row::SelectObject, "Select Object…", recording || has),
titled(Row::Options, "Action Options…", has),
titled(Row::Panel(C::Play), "Play Current Selection", has || f.waiting),
titled(Row::Panel(C::InsertPath), "Insert Select Path", (recording || has) && f.path),
titled(Row::Panel(C::ClearAll), "Clear Actions", f.idle && f.sets > 0),
+5 -4
View File
@@ -604,13 +604,14 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let hidden = part_hidden(app, HIDE_OPTIONS);
let prefs = &app.session.prefs;
states.set(CommandRef::new("ui.align.hideOptions"), CommandState::new().title(if hidden { tl!("Show Options") } else { tl!("Hide Options") }));
states.set(CommandRef::new("ui.align.usePreviewBounds"), CommandState::new().checked(prefs.use_preview_bounds));
states.set(CommandRef::new("ui.align.cancelKeyObject"), CommandState::new().enabled(align_to(app) == AlignTo::Key));
states.set(CommandRef::new("ui.align.usePreviewBounds"), CommandState::new().checked(prefs.use_preview_bounds).title(tl!("Use Preview Bounds")));
let cancel = CommandState::new().enabled(align_to(app) == AlignTo::Key).title(tl!("Cancel Key Object"));
states.set(CommandRef::new("ui.align.cancelKeyObject"), cancel);
// The key choice is named for what the key is: Align to Key Anchor while it is an anchor point.
let key = CommandState::new().enabled(can_choose(app, AlignTo::Key)).checked(shown_align_to(app) == AlignTo::Key);
states.set(CommandRef::new("align.toKeyObject"), key.title(align_to_icon_name(AlignTo::Key, key_is_anchor(app)).1));
states.set(CommandRef::new("ui.align.glyphBoundsPoint"), CommandState::new().checked(prefs.align_glyph_bounds_point));
states.set(CommandRef::new("ui.align.glyphBoundsArea"), CommandState::new().checked(prefs.align_glyph_bounds_area));
states.set(CommandRef::new("ui.align.glyphBoundsPoint"), CommandState::new().checked(prefs.align_glyph_bounds_point).title(tl!("Point Text")));
states.set(CommandRef::new("ui.align.glyphBoundsArea"), CommandState::new().checked(prefs.align_glyph_bounds_area).title(tl!("Area Text")));
}
/// Runs the Align panel menu command `id`; `None` when `id` is not one of them. The glyph-bounds
+12 -7
View File
@@ -44,7 +44,7 @@ use craft::ui::primitives::IconSpec;
use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates};
use craft::ui::runtime::env::Label;
use craft::ui::sections::{FooterAction, FooterBar};
use craft::ui::text::NumberOutput;
use craft::ui::text::{NumberField, NumberOutput};
use egui::{Rect, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
@@ -860,11 +860,9 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> {
if let Some(st) = stroke_layer {
let target = if new_art { WeightTarget::Shown } else { WeightTarget::Item(i) };
let pass = cx.pass;
row = row.trailing_field(stroke::weight_number(cx.app, Some(st.width)), move |out| {
pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out)))
});
row = row.trailing_field(row_weight(cx.app, Some(st.width)), move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out))));
} else {
row = row.trailing_space(stroke::weight_number(cx.app, None));
row = row.trailing_space(row_weight(cx.app, None));
}
let painted = if new_art { Painted::NewArt { fill } } else { Painted::Item(i) };
let pass = cx.pass;
@@ -892,6 +890,13 @@ fn paint_swatch(fill: bool, paint: &Paint) -> Swatch {
.tooltip(tl!("Click to choose a swatch, Shift-click to mix a colour"))
}
/// The weight field of a stroke row, or the room it takes in a fill row: the Stroke panel's field as a small control,
/// as the row's swatch is, without the presets list (a step still stops at each preset), so the row's label shows
/// whole in the narrowest group.
fn row_weight(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
stroke::steps_weight(app, weight).size(ControlSize::Sm)
}
/// A stroke row's notes after the weight: its brush and "Dashed".
fn stroke_notes(st: &vectorcraft_doc::StrokeLayer) -> Option<String> {
let dashed = st.dash.as_ref().is_some_and(|d| d.is_dashed()).then_some(tl!("Dashed"));
@@ -1898,8 +1903,8 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let enabled = |on: bool| CommandState::new().enabled(on);
states.set("appearance.addFill", enabled(has));
states.set("appearance.addStroke", enabled(has));
states.set(DUPLICATE_ITEM, enabled(has && sel.editable()));
states.set(REMOVE_ITEM, enabled(has && sel.deletable()));
states.set(DUPLICATE_ITEM, enabled(has && sel.editable()).title(tl!("Duplicate Item")));
states.set(REMOVE_ITEM, enabled(has && sel.deletable()).title(tl!("Remove Item")));
states.set("appearance.clear", enabled(has));
states.set("appearance.reduceToBasic", enabled(any_subject_needs_reduction(app)));
states.set(new_art_basic(app), enabled(true).checked(app.session.prefs.new_art_basic));
@@ -677,6 +677,34 @@ fn an_appearance_row_held_across_file_revert_is_not_dropped_on_the_footer() {
assert_eq!(items(&panel), before + 1, "a drag started after the revert still duplicates the row");
}
/// A floating group at the narrowest panel width shows the "Stroke:" and "Fill:" links whole, as wide as a wide group
/// shows them: the stroke weight beside them is a small field inside the panel, and the stroke and fill swatches still
/// stand in one column.
#[test]
fn the_narrowest_group_shows_the_stroke_and_fill_labels_whole() {
use crate::panel_docking::PANEL_MIN_WIDTH;
use crate::tests::panel_harness::{Place, floated};
let one = |shown: &crate::tests::panel_harness::Shown, name: &str, width: f32| {
let rects = shown.rects(name);
assert_eq!(rects.len(), 1, "one {name:?} at {width} pt: {rects:?}");
rects[0]
};
let links = |width: f32| {
let shown = floated(app_with_a_selected_rectangle(), "appearance", "en", Place::Floating(width), &["Stroke:", "Fill:"]);
let [stroke, fill] = ["Stroke:", "Fill:"].map(|name| one(&shown, name, width).width());
let [stroke_well, fill_well] = ["Stroke swatch", "Fill swatch"].map(|name| one(&shown, name, width).left());
assert!((stroke_well - fill_well).abs() < 0.5, "the swatches stand at {stroke_well} and {fill_well} pt at {width} pt");
let weight = one(&shown, "Weight", width);
assert!(shown.body.contains_rect(weight), "the weight field {weight:?} stands inside the panel {:?} at {width} pt", shown.body);
([stroke, fill], format!("stroke swatch at {stroke_well} pt, weight {weight:?}"))
};
let (wide, _) = links(400.0);
let (narrow, row) = links(PANEL_MIN_WIDTH);
for (at, name) in ["Stroke:", "Fill:"].iter().enumerate() {
assert!(narrow[at] >= wide[at] - 0.5, "{name:?} is {} pt wide at {PANEL_MIN_WIDTH} pt and {} pt at 400 pt ({row})", narrow[at], wide[at]);
}
}
/// The panel's subject is the `Arc` the document holds for the selected object, a targeted group
/// or a targeted layer, not a copy of it; nothing with nothing selected.
#[test]
+38 -17
View File
@@ -824,25 +824,46 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let facts = Facts::of(app);
for panel_row in menu_rows(app) {
let PanelRow::Command(command) = panel_row else { continue };
let Some(f) = &facts else {
states.set(command, CommandState::new().enabled(false));
continue;
let row = command.id.strip_prefix(PREFIX).unwrap_or_default();
let state = match (&facts, row) {
(None, _) => CommandState::new().enabled(false),
(Some(f), "add" | "add3D") => CommandState::new().enabled(f.has_art),
(Some(f), "selectAll") => CommandState::new().enabled(!f.all.is_empty()),
(Some(f), "remove") => CommandState::new().enabled(!f.sel.is_empty()),
(Some(f), "subfolders") => CommandState::new().checked(f.subfolders),
(Some(f), "openLocation") => CommandState::new().checked(f.open_location),
(Some(f), "applyPreset") => CommandState::new().checked(f.applied == command.params["name"].as_str().unwrap_or_default()),
(Some(f), "saveChanges" | "deletePreset") => CommandState::new().enabled(f.saved),
(Some(f), "exportPreset") => CommandState::new().enabled(f.known),
_ => CommandState::new(),
};
let state = match command.id.strip_prefix(PREFIX).unwrap_or_default() {
"add" | "add3D" => CommandState::new().enabled(f.has_art),
"selectAll" => CommandState::new().enabled(!f.all.is_empty()),
"remove" => CommandState::new().enabled(!f.sel.is_empty()),
"subfolders" => CommandState::new().checked(f.subfolders),
"openLocation" => CommandState::new().checked(f.open_location),
"applyPreset" => {
let name = command.params["name"].as_str().unwrap_or_default().to_string();
CommandState::new().checked(f.applied == name).title(name)
}
"saveChanges" | "deletePreset" => CommandState::new().enabled(f.saved),
"exportPreset" => CommandState::new().enabled(f.known),
_ => continue,
let title = match row {
"applyPreset" => command.params["name"].as_str().unwrap_or_default().to_string(),
"add" if command.params["multiple"] == true => tl!("Add Selected Artwork as Multiple Assets").to_string(),
row => tl!(menu_label(row)).to_string(),
};
states.set(command, state);
states.set(command, state.title(title));
}
}
/// The English label of the panel menu's row `row` (`ui.assetExport.<row>`); Add Selected Artwork as Multiple Assets
/// and the presets' rows are named by [`menu_states`].
fn menu_label(row: &str) -> &'static str {
match row {
"add" => "Add Selected Artwork as One Asset",
"add3D" => "Export 3D Object",
"selectAll" => "Select All Assets",
"remove" => "Remove Selected Assets",
"exportForScreens" => "Export for Screens…",
"formatSettings" => "Format Settings…",
"subfolders" => "Create Sub-folders",
"openLocation" => "Open Location after Export",
"savePresetAs" => "Save As Preset…",
"saveChanges" => "Save Changes",
"deletePreset" => "Delete Preset",
"importPreset" => "Import Preset…",
"exportPreset" => "Export Preset…",
_ => "",
}
}
+19
View File
@@ -767,6 +767,25 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
states.set(CommandRef::new(THUMBNAIL_VIEW), on(true).checked(!view.list));
states.set(CommandRef::new(LIST_VIEW), on(true).checked(view.list));
states.set(CommandRef::new(SAVE_LIBRARY), on(!list.is_empty()));
let names = [
(new_brush("calligraphic"), "New Calligraphic Brush"),
(new_brush("bristle"), "New Bristle Brush"),
(new_brush("art"), "New Art Brush from Selection"),
(new_brush("scatter"), "New Scatter Brush from Selection"),
(new_brush("pattern"), "New Pattern Brush from Selection"),
(CommandRef::new(DUPLICATE), "Duplicate Brush"),
(CommandRef::new(DELETE_BRUSH), "Delete Brush"),
(CommandRef::new(SELECT_UNUSED), "Select All Unused"),
(CommandRef::new(THUMBNAIL_VIEW), "Thumbnail View"),
(CommandRef::new(LIST_VIEW), "List View"),
(CommandRef::new(SAVE_LIBRARY), "Save Brush Library…"),
];
super::name_rows(states, names);
for (ty, label) in KINDS {
let title = crate::i18n::fmt(tl!("Show {kind} Brushes"), &[("kind", tl!(label))]);
let state = states.get(&show_kind(ty)).cloned().unwrap_or_default();
states.set(show_kind(ty), state.title(title));
}
}
/// Runs the panel menu's own row `id`; `None` for an id that is not one of them.
@@ -412,6 +412,7 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
for id in [SAVE, ADD_TO_SWATCHES, EDIT, DELETE] {
states.set(CommandRef::new(id), CommandState::new().enabled(enabled(app, id)));
}
super::name_rows(states, [(CommandRef::new(SAVE), "Save Theme"), (CommandRef::new(ADD_TO_SWATCHES), "Add to Swatches")]);
states.set(CommandRef::new(SHOW_FIND), CommandState::new().checked(app.ui.color_themes_panel.show_find));
}
+8 -7
View File
@@ -285,17 +285,18 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let panel = &app.ui.css_properties_panel;
let selection = app.session.active().map(|st| !st.selection.is_empty());
let (has_doc, selected) = (selection.is_some(), selection == Some(true));
states.set(CommandRef::new(COPY_SELECTED), CommandState::new().enabled(selected));
states.set(CommandRef::new(EXPORT_SELECTED), CommandState::new().enabled(selected));
states.set(CommandRef::new(EXPORT_ALL), CommandState::new().enabled(has_doc));
states.set(CommandRef::new(GENERATE), CommandState::new().enabled(has_doc).checked(panel.all));
states.set(CommandRef::new(COPY_SELECTED), CommandState::new().enabled(selected).title(tl!("Copy Selected Style")));
states.set(CommandRef::new(EXPORT_SELECTED), CommandState::new().enabled(selected).title(tl!("Export Selected CSS…")));
states.set(CommandRef::new(EXPORT_ALL), CommandState::new().enabled(has_doc).title(tl!("Export All…")));
states.set(CommandRef::new(GENERATE), CommandState::new().enabled(has_doc).checked(panel.all).title(tl!("Generate CSS")));
for units in CssUnits::ALL {
states.set(units_ref(units), CommandState::new().checked(panel.options.units == units));
states.set(units_ref(units), CommandState::new().checked(panel.options.units == units).title(units.name()));
}
let mut options = panel.options.clone();
for name in FLAGS {
let labels = [tl!("Absolute Position"), tl!("Width and Height"), tl!("Unnamed Objects"), tl!("Rasterize Unsupported Art")];
for (name, label) in FLAGS.into_iter().zip(labels) {
let on = flag_mut(&mut options, name).is_some_and(|on| *on);
states.set(option_ref(name), CommandState::new().checked(on));
states.set(option_ref(name), CommandState::new().checked(on).title(label));
}
}
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more