Merge upstream/main into fix/2414-svg-classes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
vangel76
2026-11-07 16:21:40 +01:00
co-authored by Claude Sonnet 5.5
514 changed files with 51708 additions and 3000 deletions
+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+56 -5
View File
@@ -1,3 +1,56 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# VectorCraft — instructions for agents
VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions.
@@ -6,10 +59,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
2. `plan/` is an optional gitignored notebook. Behaviour notes may be in `plan/illustrator/*.md`. Do not ask for it and do not stop when it is absent. Orient, implement, test, verify, then record in the public docs.
## Non-negotiables
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
@@ -45,7 +95,6 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
@@ -88,3 +137,5 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
+16
View File
@@ -1,5 +1,21 @@
# Asset attribution
## Indic hyphenation patterns
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/text/patterns/hyph-hi.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-hi.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-mr.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-mr.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-gu.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-gu.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-bn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-bn.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-pa.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pa.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-ta.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ta.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-te.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-te.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-kn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-kn.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-ml.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ml.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
+17
View File
@@ -0,0 +1,17 @@
# Attribution
The complete historical asset manifest is [ASSETS.md](ASSETS.md). These hyphenation assets use the MIT option, with the complete copyright and permission notices preserved in each file.
| Asset | Author | Source | SPDX license | Notes |
|---|---|---|---|---|
| `crates/text/patterns/hyph-hi.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-hi.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-mr.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-mr.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-gu.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-gu.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-bn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-bn.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-pa.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pa.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-ta.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ta.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-te.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-te.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-kn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-kn.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-ml.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ml.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT | Unmodified; full license in file |
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT | Unmodified; full license in file |
+1 -76
View File
@@ -1,76 +1 @@
# VectorCraft — instructions for agents
VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions.
Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format": "drawcraft"` headers still open (`vectorcraft_format::LEGACY_EXTENSION`), and preferences migrate from the old config folder. Keep those paths working; use the new name everywhere else.
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
## Non-negotiables
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
- Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones.
- Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles).
- Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS).
- Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names.
- If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications.
- Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).**
- Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it.
- Every image, icon, font or other asset must be one of:
- original work created for VectorCraft by a contributor (who licenses it MIT OR Apache-2.0);
- OSI open source;
- public domain / CC0;
- Creative Commons with redistribution allowed.
- **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`.
- `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts.
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input.
- Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort.
- Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible.
- New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare `#![forbid(unsafe_code)]` before modules or other crate items; crate-level `//!` documentation may precede it.
- Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them.
- Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why.
- Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that.
- `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net.
- Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, cover it in `cursor_icon` (`crates/ui-egui/src/canvas.rs`), draw it in `crates/ui-egui/src/cursors.rs` or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`.
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise).
- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`).
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`).
## Roadmap and progress docs
The progress docs:
- [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log.
- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships).
- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus.
- Checklists: [`ui-parity.md`](docs/ui-parity.md), [`file-format-parity.md`](docs/file-format-parity.md), [`hardware-parity.md`](docs/hardware-parity.md), [`localization-parity.md`](docs/localization-parity.md), [`effects-parity.md`](docs/effects-parity.md), [`type-parity.md`](docs/type-parity.md); [`architecture.md`](docs/architecture.md).
When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history.
- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated.
- Keep the README's Status section in step with the ROADMAP headline.
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
@AGENTS.md
Generated
+15
View File
@@ -1093,6 +1093,17 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
dependencies = [
"js-sys",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
]
[[package]]
name = "craft-window"
version = "0.1.0"
@@ -6100,6 +6111,7 @@ dependencies = [
"serde_json",
"smithay-clipboard",
"socket2",
"tempfile",
"vectorcraft-engine",
"vectorcraft-render",
"vectorcraft-text",
@@ -6163,6 +6175,7 @@ dependencies = [
"objc2-core-foundation",
"objc2-core-text",
"serde_json",
"tempfile",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-engine",
@@ -6469,6 +6482,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-testkit",
"vectorcraft-text",
]
@@ -6591,6 +6605,7 @@ dependencies = [
name = "vectorcraft-web"
version = "0.21.0"
dependencies = [
"craft-web-api",
"eframe",
"egui",
"js-sys",
+5
View File
@@ -136,3 +136,8 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Indic hyphenation patterns (crates/text/patterns/):
Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
Original copyright and full license notices are preserved in each hyph-*.tex file.
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
+1 -1
View File
@@ -253,7 +253,7 @@ The scores are self-assessed from our code against public documentation;
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
**What's missing:**
- reliable exchange of .ai files (layer structure in real files; proprietary editing data isn't written);
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes leaves out live effects and writes symbols and live objects as their art);
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
+6 -4
View File
@@ -1,6 +1,7 @@
# VectorCraft Roadmap
- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged.
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
@@ -13,7 +14,7 @@
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
@@ -22,8 +23,8 @@ and the work list in [`docs/gaps.md`](docs/gaps.md).
**Why alpha:** the core workflows exist end to end (drawing and path editing, Pathfinder, paint and appearance,
type, SVG/PDF/EPS, print, export) and feature depth is ~75%, but a professional can't yet switch: Illustrator's
own `.ai` files open with a wrong layer structure in real cases and can't be saved back with Illustrator's
editing data, the interaction details have never been checked side by side, and some machines fail to start the
own `.ai` files open with a wrong layer structure in real cases and are saved back with an editing copy that
leaves out live effects and writes symbols and live objects as their art, the interaction details have never been checked side by side, and some machines fail to start the
app. Beta needs those closed (the beta list in [gaps.md](docs/gaps.md)). It passes the core-workflow
gate: all six core workflows (path drawing and editing, paint and style, type, layers/artboards/export, print
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
@@ -106,7 +107,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| English | `en` | full | 100% |
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
| Spanish | `es` | full | 100% |
| Hindi | `hi` | none | 0% |
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
@@ -222,6 +223,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. |
+1
View File
@@ -45,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
[dev-dependencies]
tempfile = "3"
vectorcraft-testkit = { workspace = true }
serde_json = { workspace = true }
+45 -19
View File
@@ -2,9 +2,9 @@
//!
//! ```text
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2]
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
@@ -81,11 +81,12 @@ USAGE:
allowed, and a kind left out grants none of its access. They imply --headless: a running app
enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N]
vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N]
Headless batch: open FILE (any readable format) or start a new document, run commands in
order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE
is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports
(pixels per point, default 1); other formats leave it out. Prints one JSON result per step.
is a template, written as file.saveAsTemplate writes it). Raster exports use the document's
raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins
over --scale) is given; other formats leave them out. Prints one JSON result per step.
--commands reads steps from FILE, or from standard input for -, where it stands among the
--cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for
\"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps.
@@ -94,10 +95,10 @@ USAGE:
vectorcraft-cli commands
Print the command catalogue as JSON.
vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it
out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
unless one of them is given, EPS the bounds of the art, the other formats the first artboard.
A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with
--artboard or --range).
@@ -279,13 +280,15 @@ fn commands() -> Result<(), String> {
}
fn convert(args: &[String]) -> Result<(), String> {
let valued = ["--scale", "-s", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
let valued =
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
if help_requested(args, &valued) {
return help();
}
let mut files = vec![];
let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) =
(1.0f64, None::<u64>, None::<String>, false, false, false, false);
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
let mut ppi = None::<f64>;
let mut decimals = None::<u64>;
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
// `transparentImages`); the engine checks their values.
@@ -293,7 +296,15 @@ fn convert(args: &[String]) -> Result<(), String> {
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"--scale" | "-s" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?,
"--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?),
"--ppi" => {
ppi = Some(
it.next()
.and_then(|v| v.parse().ok())
.filter(|n: &f64| n.is_finite() && *n > 0.0)
.ok_or("--ppi needs a positive finite number")?,
);
}
"--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?),
"--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?),
"--outline-text" => outline_text = true,
@@ -326,7 +337,7 @@ fn convert(args: &[String]) -> Result<(), String> {
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
// PSD).
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale);
let mut params = with_pixel_scale(params, &output, scale, ppi);
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
@@ -372,12 +383,17 @@ fn is_template(path: &str) -> bool {
vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait")
}
/// The export `params` for `path`, with `--scale` (pixels per point) when its format is raster.
/// The export `params` for `path`, with explicit raster resolution options only for raster formats.
/// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave
/// its units unset.
fn with_pixel_scale(mut params: Value, path: &str, scale: f64) -> Value {
fn with_pixel_scale(mut params: Value, path: &str, scale: Option<f64>, ppi: Option<f64>) -> Value {
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) {
params["scale"] = json!(scale);
if let Some(scale) = scale {
params["scale"] = json!(scale);
}
if let Some(ppi) = ppi {
params["ppi"] = json!(ppi);
}
}
params
}
@@ -485,7 +501,7 @@ fn command_step(v: Value) -> Result<Step, String> {
}
fn run(args: &[String]) -> Result<(), String> {
let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"];
let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"];
if help_requested(args, &valued) {
return help();
}
@@ -494,7 +510,8 @@ fn run(args: &[String]) -> Result<(), String> {
// The step of the `--cmd` just given, which a `--params` sets.
let mut params_for: Option<usize> = None;
let mut stdin_read = false;
let mut scale = 1.0;
let mut scale = None::<f64>;
let mut ppi = None::<f64>;
let mut it = args.iter();
while let Some(a) = it.next() {
let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}"));
@@ -531,7 +548,16 @@ fn run(args: &[String]) -> Result<(), String> {
}
"--scale" | "-s" => {
let raw = val("a number")?;
scale = raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?;
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
}
"--ppi" => {
let raw = val("a number")?;
ppi = Some(
raw.parse::<f64>()
.ok()
.filter(|n| n.is_finite() && *n > 0.0)
.ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?,
);
}
other => return Err(format!("unknown run option `{other}`")),
}
@@ -576,7 +602,7 @@ fn run(args: &[String]) -> Result<(), String> {
let r = if is_template(&path) {
h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}}))
} else {
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale))
h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi))
};
let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?;
emit(json!({"step": "export", "result": r}))?;
+44
View File
@@ -187,6 +187,48 @@ fn budget_row(name: &str, ms: f64, budget: f64, ok: bool) -> String {
format!(" {name:<42} {ms:>8.2} ms {budget:>7.0} ms {}", if ok { "ok" } else { "OVER" })
}
/// Tracked rows for pointing at things in an n-path document: what hovering, clicking, marquee
/// selection and snapping cost when nothing narrows the search.
fn pointing(n: usize, rows: &mut Vec<(String, f64)>) -> Result<(), String> {
use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
let err = |e: vectorcraft_engine::EngineError| e.to_string();
let mut s = vectorcraft_engine::Session::new();
s.add_document(synthetic(n)?, None);
let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() };
s.select_tool("selection", view).map_err(err)?;
// Off the art (nothing under the pointer), the case every hover over empty canvas pays.
let off = Point::new(-200.0, -200.0);
let hover = |s: &mut vectorcraft_engine::Session| {
let _ = s.pointer(&PointerEvent::new(PointerKind::Move, off.x, off.y), view);
let _ = s.cursor(off, Mods::default(), view);
};
rows.push((format!("hover over empty canvas ({n} paths)"), median_ms(5, || hover(&mut s))));
s.execute("select.all", &json!({})).map_err(err)?;
rows.push((format!("hover over empty canvas, all selected ({n} paths)"), median_ms(5, || hover(&mut s))));
let doc = s.doc().map_err(err)?.doc.clone();
rows.push((format!("hit test, a miss ({n} paths)"), median_ms(5, || drop(hit::hit_test(&doc, off, hit::HitOptions::default())))));
let r = Rect::new(600.0, 450.0, 1000.0, 750.0);
rows.push((format!("marquee 400×300 ({n} paths)"), median_ms(5, || drop(hit::marquee(&doc, r, None, false)))));
let view_rect = Rect::new(0.0, 0.0, 1600.0, 1200.0);
rows.push((
format!("smart guide targets in view ({n} paths)"),
median_ms(5, || drop(vectorcraft_engine::tools::guides::Targets::collect(&doc, &[], Some(view_rect)))),
));
// Adding one more object to a selection of half the document: the command a shift-click ends
// in, without the pointer handling and hit test before it.
let ids: Vec<u64> = doc.layers[0].children().map(|c| c.iter().map(|n| n.id.0).collect()).unwrap_or_default();
s.execute("select.set", &json!({"ids": ids[..ids.len() / 2]})).map_err(err)?;
let mut k = ids.len() / 2;
rows.push((
format!("select.toggle in a {}-object selection", ids.len() / 2),
median_ms(5, || {
k += 1;
let _ = s.execute("select.toggle", &json!({"id": ids[k % ids.len()]}));
}),
));
Ok(())
}
/// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole
/// selection, live effects, every Pathfinder operation, typing in a long story, and memory, with
/// the peak so far where `rss_mb` reads one.
@@ -282,6 +324,8 @@ fn deep(n: usize) -> Result<(), String> {
}),
));
note("after typing");
pointing(n, &mut rows)?;
note("after pointing");
// Four embedded 24 MP photos drawn at fit page by three renderers, as the app's canvas, render
// worker and a panel each draw them.
{
+32
View File
@@ -105,6 +105,38 @@ fn images_open_at_their_pixel_size() {
assert_eq!(&std::fs::read(&png).unwrap()[16..24], [0, 0, 0, 6, 0, 0, 0, 4], "IHDR 6×4");
}
#[test]
fn raster_exports_use_document_resolution_unless_overridden() {
let source = tmp("resolution.vectorcraft");
ok(&["run", "--cmd", "file.new", "--params", r#"{"width":72,"height":36,"rasterEffectsPpi":300}"#, "--export", &source]);
for (flags, width, height) in [(vec![], 300u32, 150u32), (vec!["--scale", "1"], 72, 36), (vec!["--ppi", "150", "--scale", "2"], 150, 75)] {
for mode in ["run", "convert"] {
for format in ["png", "psd"] {
let path = tmp(&format!("resolution-{mode}-{width}.{format}"));
let mut args = if mode == "run" { vec!["run", "--in", &source, "--export", &path] } else { vec!["convert", &source, &path] };
args.extend_from_slice(&flags);
ok(&args);
let bytes = std::fs::read(&path).unwrap();
let dimensions = if format == "png" { &bytes[16..24] } else { &bytes[14..22] };
let expected =
if format == "png" { [width.to_be_bytes(), height.to_be_bytes()] } else { [height.to_be_bytes(), width.to_be_bytes()] };
assert_eq!(dimensions, expected.concat(), "{args:?}");
}
}
}
}
#[test]
fn raster_export_rejects_invalid_ppi() {
for ppi in ["0", "-150", "NaN", "inf", "high"] {
for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] {
let out = Command::new(BIN).args(&args).output().unwrap();
assert!(!out.status.success(), "{args:?}");
assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}");
}
}
}
#[test]
fn help_lists_readable_formats() {
let out = ok(&["--help"]);
+2
View File
@@ -16,6 +16,8 @@ path = "src/main.rs"
[dependencies]
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
vectorcraft-ui-egui = { workspace = true }
# 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 = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
egui = { workspace = true }
+84 -60
View File
@@ -1,14 +1,18 @@
//! `window.vectorcraft`: the control channel for the page, as promises.
//!
//! `request`, `execute`, `commands`, `docInspect`, `uiInspect` and `screenshot` come from
//! `craft-web-api` (storytold/craft-libs#413), the same in every Craft app; VectorCraft adds its own
//! functions on the same object.
//!
//! The same JSON methods as the desktop control server (`docs/control-protocol.md`), so an agent
//! driving VectorCraft in a browser tab (or an `<iframe>` in another app) uses the same commands as
//! the CLI and the MCP server:
//!
//! ```js
//! await vectorcraft.execute("object.rectangle", {x: 0, y: 0, width: 100, height: 50}) // engine command → its result
//! await vectorcraft.execute("shape.rectangle", {x: 0, y: 0, width: 100, height: 50}) // engine command → its result
//! await vectorcraft.request("ui.inspect") // control method → its result
//! await vectorcraft.commands() // command list
//! const {base64} = await vectorcraft.screenshot() // the canvas as PNG (base64)
//! const {data} = await vectorcraft.screenshot() // the canvas as PNG (base64)
//! await vectorcraft.openFile("logo.svg", bytes) // opened as a dropped file is
//! vectorcraft.captureDownloads(true) // saves stay in the page…
//! vectorcraft.files(); await vectorcraft.readFile("logo.png") // …to be read back
@@ -17,21 +21,24 @@
//! Results resolve with the method's `result`; errors reject with an `Error`.
use std::cell::{Cell, RefCell};
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use craft_web_api::methods::Methods;
use craft_web_api::page::{PageApi, Request};
use serde_json::{Value, json};
use vectorcraft_ui_egui::ControlRequest;
use vectorcraft_ui_egui::{ControlRequest, ControlTicket as Ticket};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, future_to_promise};
use crate::saved_files::SavedFiles;
use crate::web::Inbox;
type Waiting = (Receiver<Value>, js_sys::Function, js_sys::Function);
thread_local! {
static TX: RefCell<Option<Sender<ControlRequest>>> = const { RefCell::new(None) };
static WAITING: RefCell<Vec<Waiting>> = const { RefCell::new(Vec::new()) };
static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
static INBOX: RefCell<Option<Inbox>> = const { RefCell::new(None) };
static CAPTURE: Cell<bool> = const { Cell::new(false) };
@@ -69,77 +76,96 @@ fn to_js(v: &Value) -> JsValue {
js_sys::JSON::parse(&v.to_string()).unwrap_or(JsValue::NULL)
}
fn from_js(v: &JsValue) -> Value {
if v.is_undefined() || v.is_null() {
return json!({});
/// A reply as a promise outcome: the `result`, or an `Error` carrying the `error`.
fn outcome(reply: &Value) -> Result<JsValue, JsValue> {
if reply.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(to_js(reply.get("result").unwrap_or(&Value::Null)))
} else {
Err(js_sys::Error::new(reply.get("error").and_then(Value::as_str).unwrap_or("error")).into())
}
js_sys::JSON::stringify(v).ok().and_then(|s| s.as_string()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}))
}
/// Settle the promises of answered requests (called every frame).
pub fn poll_replies() {
WAITING.with(|w| {
w.borrow_mut().retain(|(rx, resolve, reject)| match rx.try_recv() {
Ok(v) => {
if v.get("ok").and_then(Value::as_bool) == Some(true) {
let _ = resolve.call1(&JsValue::NULL, &to_js(v.get("result").unwrap_or(&Value::Null)));
} else {
let msg = v.get("error").and_then(Value::as_str).unwrap_or("error").to_string();
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new(&msg));
}
false
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
const POLL_MS: i32 = 16;
/// A queued control request whose reply has not arrived. Dropping it before the reply (the page's
/// timeout fired) gives the request up if the app has not started it, so the app never runs it late.
struct Waiting {
reply: Receiver<Value>,
ticket: Ticket,
answered: bool,
}
impl Waiting {
/// The app's reply once it has answered or gone away; `None` while the request is waiting.
fn poll(&mut self) -> Option<Value> {
match self.reply.try_recv() {
Ok(reply) => {
self.answered = true;
Some(reply)
}
Err(TryRecvError::Empty) => true,
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => {
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new("request dropped"));
false
self.answered = true;
Some(json!({"ok": false, "error": "request dropped"}))
}
});
});
}
}
}
fn request(method: &str, params: Value) -> js_sys::Promise {
let method = method.to_string();
let p = js_sys::Promise::new(&mut |resolve, reject| {
let (req, rx) = ControlRequest::new(method.clone(), params.clone());
let sent = TX.with(|t| t.borrow().as_ref().is_some_and(|tx| tx.send(req).is_ok()));
if sent {
WAITING.with(|w| w.borrow_mut().push((rx, resolve, reject)));
} else {
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new("VectorCraft is not running yet"));
impl Drop for Waiting {
fn drop(&mut self) {
if !self.answered {
self.ticket.give_up();
}
}
}
/// Queue a control request for the app and wait for its reply, as the protocol's `{ok, result}` /
/// `{ok: false, error}` object.
fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
let (req, rx) = ControlRequest::new(method, params);
let ticket = req.ticket();
let sent = TX.with(|t| t.borrow().as_ref().is_some_and(|tx| tx.send(req).is_ok()));
if !sent {
return Box::pin(async { json!({"ok": false, "error": "VectorCraft is not running yet"}) });
}
repaint();
let mut waiting = Waiting { reply: rx, ticket, answered: false };
Box::pin(async move {
loop {
if let Some(reply) = waiting.poll() {
return reply;
}
sleep(POLL_MS).await;
}
})
}
async fn sleep(ms: i32) {
let promise = js_sys::Promise::new(&mut |resolve, _| {
if let Some(window) = web_sys::window() {
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
}
});
repaint();
p
let _ = JsFuture::from(promise).await;
}
fn set_fn(obj: &js_sys::Object, name: &str, f: JsValue) -> Result<(), JsValue> {
js_sys::Reflect::set(obj, &name.into(), &f).map(|_| ())
}
/// Install `window.vectorcraft`.
/// Install `window.vectorcraft`: the crate's functions, then VectorCraft's own (`inspect` is its
/// `ui.inspect`).
pub fn install() -> Result<(), JsValue> {
let obj = js_sys::Object::new();
let request: Request = Rc::new(|method, params| send(&method, params));
Rc::new(PageApi::new("vectorcraft", Methods::default(), request)).install()?;
let window = web_sys::window().ok_or("no window")?;
let obj: js_sys::Object = js_sys::Reflect::get(&window, &"vectorcraft".into())?.unchecked_into();
set_fn(
&obj,
"request",
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|method: String, params: JsValue| request(&method, from_js(&params)))
.into_js_value(),
)?;
set_fn(
&obj,
"execute",
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|command: String, params: JsValue| {
request("engine.execute", json!({"command": command, "params": from_js(&params)}))
})
.into_js_value(),
)?;
set_fn(&obj, "commands", Closure::<dyn Fn() -> js_sys::Promise>::new(|| request("engine.commands", json!({}))).into_js_value())?;
set_fn(&obj, "inspect", Closure::<dyn Fn() -> js_sys::Promise>::new(|| request("ui.inspect", json!({}))).into_js_value())?;
set_fn(
&obj,
"screenshot",
Closure::<dyn Fn(JsValue) -> js_sys::Promise>::new(|params: JsValue| request("ui.screenshot", from_js(&params))).into_js_value(),
"inspect",
Closure::<dyn Fn() -> js_sys::Promise>::new(|| future_to_promise(async { outcome(&send("ui.inspect", json!({})).await) })).into_js_value(),
)?;
set_fn(
&obj,
@@ -178,7 +204,5 @@ pub fn install() -> Result<(), JsValue> {
})
.into_js_value(),
)?;
let w = web_sys::window().ok_or("no window")?;
js_sys::Reflect::set(&w, &"vectorcraft".into(), &obj)?;
Ok(())
}
-2
View File
@@ -370,7 +370,6 @@ impl eframe::App for WebShell {
}
let Some(app) = &mut self.app else { return };
app.tick(ctx);
crate::api::poll_replies();
app.finish_ime_logic(ctx);
}
@@ -423,7 +422,6 @@ impl eframe::App for WebShell {
}
app.ui(ui);
}
crate::api::poll_replies();
}
}
+1
View File
@@ -119,6 +119,7 @@ zbus = "=5.19.0"
winresource = "0.1"
[dev-dependencies]
tempfile = "3"
# Bound socket buffers in real loopback transport deadline regressions.
socket2 = { workspace = true }
# src/portal_save.rs's tests build and read the portal's D-Bus values on every system.
+3
View File
@@ -51,6 +51,9 @@ impl eframe::App for App {
// A pen contact with the barrel button held presses the secondary button (Windows Ink).
#[cfg(windows)]
windows_stylus::raw_input_hook(raw);
// The characters Alt + keypad codes typed (#5108).
#[cfg(windows)]
super::windows_alt_codes::raw_input_hook(raw);
file_access::unconfined(|| self.app.raw_input_hook(ctx, raw));
// A mouse-up that never reached the window (#4326) is delivered once AppKit reports
// that no mouse button is down.
+17 -8
View File
@@ -978,10 +978,17 @@ mod tests {
use super::*;
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
d
fn dir(name: &str) -> tempfile::TempDir {
tempfile::Builder::new().prefix(&format!("vectorcraft-clipboard-{name}-")).tempdir().unwrap()
}
#[test]
fn test_directory_is_removed_when_its_handle_is_dropped() {
let dir = dir("cleanup");
let path = dir.path().to_path_buf();
assert!(path.exists());
drop(dir);
assert!(!path.exists());
}
fn png(w: u32, h: u32) -> Vec<u8> {
@@ -993,12 +1000,12 @@ mod tests {
#[test]
fn the_first_copied_file_that_is_art_pastes() {
let d = dir("art");
let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg"));
let (notes, red, art) = (d.path().join("notes.txt"), d.path().join("red image.png"), d.path().join("art.svg"));
std::fs::write(&notes, "not art").unwrap();
std::fs::write(&red, png(3, 2)).unwrap();
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
// Missing files, folders and text are skipped.
let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
let f = copied_file(vec![d.path().join("gone.png"), d.path().to_path_buf(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// Only what Paste asks for.
@@ -1032,7 +1039,8 @@ mod tests {
/// An .eps file copied in a file manager pastes as EPS.
#[test]
fn a_copied_eps_file_pastes() {
let eps = dir("eps").join("equation.eps");
let d = dir("eps");
let eps = d.path().join("equation.eps");
std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap();
assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS));
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
@@ -1040,7 +1048,8 @@ mod tests {
#[test]
fn a_crlf_left_by_the_uri_list_is_ignored() {
let red = dir("crlf").join("red.png");
let d = dir("crlf");
let red = d.path().join("red.png");
std::fs::write(&red, png(2, 2)).unwrap();
let with_cr = PathBuf::from(format!("{}\r", red.display()));
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
+8 -10
View File
@@ -150,18 +150,16 @@ mod tests {
#[cfg(target_os = "linux")]
#[test]
fn the_gpu_behind_a_device_number_comes_from_sysfs() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("vectorcraft-dev-char-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let dir = tempfile::Builder::new().prefix("vectorcraft-dev-char-").tempdir()?;
// /sys/dev/char/226:128 links to the render node, whose `device` is the PCI GPU.
std::fs::create_dir_all(dir.join("226:128/device"))?;
std::fs::write(dir.join("226:128/device/vendor"), "0x10de\n")?;
std::fs::write(dir.join("226:128/device/device"), "0x25ac\n")?;
std::fs::create_dir_all(dir.path().join("226:128/device"))?;
std::fs::write(dir.path().join("226:128/device/vendor"), "0x10de\n")?;
std::fs::write(dir.path().join("226:128/device/device"), "0x25ac\n")?;
// A device that isn't a PCI GPU (a virtual one) has no ids.
std::fs::create_dir_all(dir.join("226:0/device"))?;
let render = super::pci_ids(&dir, makedev(226, 128));
let virtual_gpu = super::pci_ids(&dir, makedev(226, 0));
let missing = super::pci_ids(&dir, makedev(226, 1));
std::fs::remove_dir_all(&dir)?;
std::fs::create_dir_all(dir.path().join("226:0/device"))?;
let render = super::pci_ids(dir.path(), makedev(226, 128));
let virtual_gpu = super::pci_ids(dir.path(), makedev(226, 0));
let missing = super::pci_ids(dir.path(), makedev(226, 1));
assert_eq!(render, Some((0x10de, 0x25ac)));
assert_eq!(virtual_gpu, None);
assert_eq!(missing, None);
+24 -14
View File
@@ -242,8 +242,8 @@ fn internal_panels_are_edp_lvds_and_dsi_connectors() {
/// PCI ids. Each GPU is listed once, the one with the panel as primary.
#[test]
fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let temp = tempfile::Builder::new().prefix("vectorcraft-drm-").tempdir()?;
let dir = temp.path();
let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> {
std::fs::create_dir_all(dir.join(name).join("device"))?;
std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?;
@@ -262,11 +262,11 @@ fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()
connector("card1-DP-2", "connected")?;
connector("card2-Virtual-1", "connected")?;
std::fs::write(dir.join("renderD128"), "")?;
let mut gpus = linux_display_gpus(&dir);
let mut gpus = linux_display_gpus(dir);
gpus.sort_by_key(|g| g.pci);
assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]);
assert!(linux_display_gpus(&dir.join("no such dir")).is_empty());
std::fs::remove_dir_all(&dir)
Ok(())
}
#[test]
@@ -616,11 +616,26 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
/// program while it runs: the test releases the start file's lock and takes it again, and a child
/// starting meanwhile would keep it held (`crate::no_spawns`).
fn start_dir(tag: &str) -> (std::path::PathBuf, std::sync::RwLockReadGuard<'static, ()>) {
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
type Target = std::path::Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
impl AsRef<std::path::Path> for TestDir {
fn as_ref(&self) -> &std::path::Path {
self.0.path()
}
}
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
let spawns = crate::no_spawns();
let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
(d, spawns)
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
(TestDir(dir), spawns)
}
/// What a start in `dir` leaves out; it then ends without crashing.
@@ -670,7 +685,6 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept");
assert_eq!(left_out.crash, None, "the note is shown once");
third.ended();
let _ = std::fs::remove_dir_all(&dir);
}
/// A start whose first frame reached the screen, or that ended without crashing (a normal exit,
@@ -693,7 +707,6 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
assert!(finish(Ok(Ok(())), &first).is_ok());
drop(first);
assert_eq!(next_start(&dir, false), LeftOut::default());
let _ = std::fs::remove_dir_all(&dir);
}
/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a
@@ -721,7 +734,6 @@ fn a_crash_while_listing_lists_opengl_alone() {
second.none_left();
second.ended();
assert_eq!(next_start(&dir, false), LeftOut::default());
let _ = std::fs::remove_dir_all(&dir);
}
/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that
@@ -742,7 +754,6 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
explicit.picked(&c[0].key, &c[0].name, true);
explicit.presented();
assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window");
let _ = std::fs::remove_dir_all(&dir);
}
/// A damaged record, a file that can't be opened and one another starting copy of the app holds
@@ -777,10 +788,9 @@ fn a_damaged_or_unreadable_start_file_is_ignored() {
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]);
// A folder in the file's place.
let _ = std::fs::remove_dir_all(&dir);
std::fs::remove_file(dir.join(START_FILE)).unwrap();
std::fs::create_dir_all(dir.join(START_FILE)).unwrap();
assert_eq!(next_start(&dir, false), LeftOut::default());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
+35 -12
View File
@@ -198,6 +198,30 @@ fn read_file_refuses_what_is_not_a_regular_file() {
assert!(read_file("/dev/zero").is_err());
}
/// Read the first `max` bytes of a file (all of it when it is shorter), and nothing past them. Only
/// a regular file is read.
fn read_file_head(path: &str, max: usize) -> Result<Vec<u8>, String> {
use std::io::Read;
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
return Err(format!("{path}: not a file"));
}
let mut out = vec![];
std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| e.to_string())?;
Ok(out)
}
#[cfg(test)]
#[test]
fn read_file_head_reads_no_more_than_it_is_asked_for() {
use std::io::Write as _;
let mut f = tempfile::Builder::new().prefix("vectorcraft-read-head-").tempfile().unwrap();
f.write_all(b"0123456789").unwrap();
let p = f.path().to_string_lossy();
assert_eq!(read_file_head(&p, 4).unwrap(), b"0123");
assert_eq!(read_file_head(&p, 20).unwrap(), b"0123456789", "a shorter file is read whole");
assert!(read_file_head(&std::env::temp_dir().to_string_lossy(), 4).is_err(), "a folder is not read");
}
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
@@ -325,6 +349,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
#[cfg(windows)]
stylus: Some(windows_stylus::start()),
read: Some(Box::new(read_file)),
// Load Actions… refuses a file over its size limit without reading all of it.
read_head: Some(Box::new(read_file_head)),
write: Some(Box::new(write_file)),
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
// Background Save and Export write from a worker thread.
@@ -569,22 +595,20 @@ mod open_with_tests {
use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates};
/// A fresh, empty folder under the system's temporary folder.
fn scratch(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
fn scratch(name: &str) -> tempfile::TempDir {
tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap()
}
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
/// path.
#[test]
fn only_applications_are_started() {
let d = scratch("check");
let temp = scratch("check");
let d = temp.path();
let doc = d.join("notes.txt");
std::fs::write(&doc, "hi").unwrap();
assert!(check_app(&doc).is_err(), "a document");
assert!(check_app(&d).is_err(), "a folder");
assert!(check_app(d).is_err(), "a folder");
assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path");
if cfg!(target_os = "macos") {
let app = d.join("Editor.app");
@@ -600,19 +624,19 @@ mod open_with_tests {
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(check_app(&tool).is_ok(), "an executable file");
}
let _ = std::fs::remove_dir_all(&d);
}
/// PhotoCraft is looked for only where it installs.
#[test]
fn photocraft_is_found_where_it_installs() {
let d = scratch("find");
let temp = scratch("find");
let d = temp.path();
if cfg!(target_os = "macos") {
let candidates = photocraft_candidates(Some(&d), None);
let candidates = photocraft_candidates(Some(d), None);
assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app"));
assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}");
std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap();
assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app"));
assert!(find_photocraft(Some(d), None).unwrap().ends_with("PhotoCraft.app"));
} else {
let bin = d.join("bin");
std::fs::create_dir_all(&bin).unwrap();
@@ -636,7 +660,6 @@ mod open_with_tests {
assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe));
}
}
let _ = std::fs::remove_dir_all(&d);
}
/// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it
+23 -6
View File
@@ -1,12 +1,29 @@
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, UNIX_EPOCH};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
d
struct TestPath {
_parent: tempfile::TempDir,
path: PathBuf,
}
impl std::ops::Deref for TestPath {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.path
}
}
impl AsRef<Path> for TestPath {
fn as_ref(&self) -> &Path {
&self.path
}
}
fn temp_dir(tag: &str) -> TestPath {
let parent = tempfile::Builder::new().prefix(&format!("vectorcraft-logging-{tag}-")).tempdir().unwrap();
let path = parent.path().join("log");
TestPath { _parent: parent, path }
}
fn read(path: &Path) -> String {
+2 -4
View File
@@ -63,11 +63,10 @@ mod tests {
/// fonts, is listed while it is registered.
#[test]
fn fonts_registered_from_other_folders_are_listed() {
let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap();
// A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS
// installs.
let file = dir.join("Registered Font.ttf");
let file = dir.path().join("Registered Font.ttf");
std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
let want = std::fs::canonicalize(&file).unwrap();
let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want));
@@ -78,7 +77,6 @@ mod tests {
let registered = listed();
// SAFETY: as above.
unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };
std::fs::remove_dir_all(&dir).unwrap();
assert!(registered);
}
}
+8 -2
View File
@@ -56,6 +56,7 @@ mod system_fonts;
mod tablet;
mod window;
mod window_frame;
mod windows_alt_codes;
#[cfg(windows)]
mod windows_cores;
mod windows_stylus;
@@ -314,13 +315,18 @@ fn main() -> std::process::ExitCode {
};
// With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end
// is down; the message hook notes each pointer contact and whether it starts with the barrel
// button held, and writes the pen's end into the pen feed (`windows_stylus`).
// button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the
// characters Alt + keypad codes type (`windows_alt_codes`).
#[cfg(windows)]
let options = {
use winit::platform::windows::EventLoopBuilderExtWindows as _;
let mut options = options;
options.event_loop_builder = Some(Box::new(|builder| {
builder.with_msg_hook(windows_stylus::msg_hook);
builder.with_msg_hook(|msg| {
// Alt + keypad codes (#5108), which winit drops; neither hook consumes a message.
windows_alt_codes::msg_hook(msg);
windows_stylus::msg_hook(msg)
});
}));
options
};
+2 -4
View File
@@ -335,13 +335,11 @@ mod tests {
#[test]
fn a_kept_preferences_copy_is_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap();
let dir = temp.path();
super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable");
let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
+18 -7
View File
@@ -192,7 +192,22 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
impl AsRef<Path> for TestDir {
fn as_ref(&self) -> &Path {
self.0.path()
}
}
fn environment(key: &str) -> Option<OsString> {
match key {
@@ -287,12 +302,8 @@ mod tests {
assert_eq!(install_dir("macos", mounted, &appimage), Some("/tmp/.mount_vc/usr/bin".into()));
}
fn temp(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("vectorcraft-profile-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
fn temp(tag: &str) -> TestDir {
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-profile-{tag}-")).tempdir().unwrap())
}
#[test]
+18 -15
View File
@@ -263,15 +263,23 @@ mod tests {
use super::*;
struct TestDir(tempfile::TempDir);
impl std::ops::Deref for TestDir {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.0.path()
}
}
/// A fresh folder for one test, with an existing file in it.
fn folder(name: &str) -> (PathBuf, PathBuf, String) {
let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let file = dir.join("a b.svg");
fn folder(name: &str) -> (PathBuf, TestDir, String) {
let dir = tempfile::Builder::new().prefix(&format!("vc-single-instance-{name}-")).tempdir().unwrap();
let file = dir.path().join("a b.svg");
fs::write(&file, "<svg/>").unwrap();
let file = file.to_string_lossy().into_owned();
(dir.join(FILE_NAME), dir, file)
(dir.path().join(FILE_NAME), TestDir(dir), file)
}
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
@@ -303,12 +311,11 @@ mod tests {
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
drop(primary);
assert!(!path.exists(), "the endpoint file goes with the app");
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
let (path, dir, file) = folder("refused");
let (path, _dir, file) = folder("refused");
let (_primary, rx) = primary(&path);
let token = read_endpoint(&path).unwrap().token;
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
@@ -323,12 +330,11 @@ mod tests {
// The listener still serves a launch with the right token.
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_stale_endpoint_file_is_ignored_and_replaced() {
let (path, dir, file) = folder("stale");
let (path, _dir, file) = folder("stale");
// The recorded app is gone: whatever holds the port closes without a greeting. (A freed
// port can be taken by another test's listener meanwhile, which would then accept this
// connection in place of its own client's.)
@@ -357,18 +363,16 @@ mod tests {
let (_primary, rx) = primary(&path);
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() {
let (path, dir, _) = folder("replaced");
let (path, _dir, _) = folder("replaced");
let (first, _rx1) = primary(&path);
let (_second, _rx2) = primary(&path);
let second_token = read_endpoint(&path).unwrap().token;
drop(first);
assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token));
let _ = fs::remove_dir_all(dir);
}
#[test]
@@ -383,9 +387,8 @@ mod tests {
#[test]
fn the_endpoint_file_is_the_users_alone() {
use std::os::unix::fs::PermissionsExt as _;
let (path, dir, _) = folder("mode");
let (path, _dir, _) = folder("mode");
let _primary = primary(&path);
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = fs::remove_dir_all(dir);
}
}
+2 -3
View File
@@ -284,8 +284,8 @@ mod tests {
#[test]
fn fonts_only_gdi_has_loaded_are_listed_by_their_files() {
use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW};
let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let temp = tempfile::Builder::new().prefix("vc-gdi-fonts-").tempdir().unwrap();
let dir = temp.path();
let file = dir.join("29457");
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
let mut data = std::fs::read(source).unwrap();
@@ -303,7 +303,6 @@ mod tests {
assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1);
let files = super::font_files();
let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) };
let _ = std::fs::remove_dir_all(&dir);
let wanted = file.to_string_lossy().to_lowercase();
assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len());
}
+2 -4
View File
@@ -99,9 +99,8 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
#[test]
fn an_unreadable_ui_json_is_kept_beside_it() {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap();
let dir = temp.path();
let path = dir.join("ui.json");
super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable");
super::keep_prefs_copy(&path, b"not json", "ui.unreadable");
@@ -109,7 +108,6 @@ fn an_unreadable_ui_json_is_kept_beside_it() {
let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();
let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();
let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");
assert_eq!(second, b"not json");
assert_eq!(before, b"{}");
+225
View File
@@ -0,0 +1,225 @@
//! Alt + numeric-keypad codes on Windows (#5108): holding Alt, typing a decimal code on the
//! numeric keypad (NumLock on) and releasing Alt types that character (`Alt+0176` → `°`).
//!
//! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a
//! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code
//! with a leading 0, else its OEM code page), the convention every Windows text field follows
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). winit
//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which
//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees
//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes
//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed
//! text, so the Type tool (or a panel's text field) types it like any other character, in the
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
//! so they don't run a shortcut bound to Alt and a digit.
//!
//! egui reports a keypad digit as the same key as the digit above the letters, so the other
//! platforms, whose systems have no such convention, can't tell them apart either.
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::RefCell;
use egui::{Event, Key};
const WM_KEYDOWN: u32 = 0x0100;
const WM_KEYUP: u32 = 0x0101;
const WM_CHAR: u32 = 0x0102;
const WM_SYSKEYDOWN: u32 = 0x0104;
const WM_SYSKEYUP: u32 = 0x0105;
const WM_SYSCHAR: u32 = 0x0106;
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. With it off the keys
/// are Insert, End, … and type no code.
const VK_NUMPAD0: usize = 0x60;
const VK_NUMPAD9: usize = 0x69;
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
thread_local! {
/// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it.
static CODES: RefCell<AltCodes> = RefCell::new(AltCodes::default());
}
/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue.
#[derive(Default)]
struct AltCodes {
/// Keypad digits typed while Alt has been held.
digits: usize,
/// Alt came up after keypad digits: the next character message is the code's character.
armed: bool,
/// A high surrogate waiting for its low half.
high: Option<u16>,
/// Characters the codes typed, for the next frame.
typed: String,
/// Keypad digit presses and releases with Alt held since the last frame, which egui reports
/// as Alt and a digit: taken out of the frame.
keypad_events: usize,
}
impl AltCodes {
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit).
fn message(&mut self, message: u32, wparam: usize) {
let keypad = (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam);
match message {
// Windows sends a key pressed with Alt held as a system key.
WM_SYSKEYDOWN if keypad => {
self.digits += 1;
self.keypad_events += 1;
self.armed = false;
}
WM_SYSKEYUP if keypad => self.keypad_events += 1,
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
// Any other key ends the sequence and keeps its own meaning.
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => {
self.armed = self.digits > 0;
self.digits = 0;
}
WM_CHAR | WM_SYSCHAR if self.armed => {
let unit = (wparam & 0xffff) as u16;
if (0xd800..0xdc00).contains(&unit) {
self.high = Some(unit);
return;
}
let units: Vec<u16> = self.high.take().into_iter().chain([unit]).collect();
self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control()));
self.armed = false;
}
_ => {}
}
}
fn reset(&mut self) {
self.digits = 0;
self.armed = false;
self.high = None;
}
/// Hand the frame `events` the characters typed since the last frame, as typed text, and take
/// out the keypad digits typed with Alt held.
fn drain(&mut self, events: &mut Vec<Event>) {
let mut keypad = std::mem::take(&mut self.keypad_events);
if keypad > 0 {
events.retain(|e| {
let digit = matches!(e, Event::Key { key: Key::Num0 | Key::Num1 | Key::Num2 | Key::Num3 | Key::Num4 | Key::Num5 | Key::Num6 | Key::Num7 | Key::Num8 | Key::Num9, modifiers, .. } if modifiers.alt);
if digit && keypad > 0 {
keypad -= 1;
return false;
}
true
});
}
if !self.typed.is_empty() {
events.push(Event::Text(std::mem::take(&mut self.typed)));
}
}
}
/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type.
/// It never consumes the message.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn msg_hook(msg: *const std::ffi::c_void) {
use windows::Win32::UI::WindowsAndMessaging::MSG;
// SAFETY: winit passes the `MSG` that `PeekMessageW` has just filled, which lives for this
// call; `as_ref` gives `None` for a null pointer.
let Some(msg) = (unsafe { msg.cast::<MSG>().as_ref() }) else {
return;
};
if (WM_KEYDOWN..=WM_SYSCHAR).contains(&msg.message) {
CODES.with(|c| {
if let Ok(mut c) = c.try_borrow_mut() {
c.message(msg.message, msg.wParam.0);
}
});
}
}
/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text.
pub fn raw_input_hook(raw: &mut egui::RawInput) {
CODES.with(|c| {
if let Ok(mut c) = c.try_borrow_mut() {
c.drain(&mut raw.events);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
const ALT: usize = 0x12;
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
c.message(WM_SYSKEYDOWN, ALT);
for d in code.bytes() {
let vk = VK_NUMPAD0 + usize::from(d - b'0');
c.message(WM_SYSKEYDOWN, vk);
c.message(WM_SYSKEYUP, vk);
}
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, usize::from(posted));
}
fn key(key: Key, alt: bool, pressed: bool) -> Event {
let modifiers = egui::Modifiers { alt, ..Default::default() };
Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
}
#[test]
fn an_alt_code_types_its_character_when_alt_comes_up() {
let mut c = AltCodes::default();
alt_code(&mut c, "0176", 0xB0);
alt_code(&mut c, "0151", 0x2014);
let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)];
c.drain(&mut events);
// The keypad digits typed with Alt are gone (eight presses and eight releases, two here);
// the digit typed without Alt stays, and the characters follow.
assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]);
let mut events = vec![key(Key::Num0, true, true)];
c.drain(&mut events);
assert_eq!(events.len(), 1, "counts don't carry over to a later frame");
}
#[test]
fn a_character_without_a_code_before_it_is_left_to_winit() {
let mut c = AltCodes::default();
// A plain key press's character (winit types it), and Alt pressed and released alone.
c.message(WM_KEYDOWN, 0x41);
c.message(WM_CHAR, usize::from(b'a'));
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, usize::from(b'b'));
let mut events = vec![];
c.drain(&mut events);
assert!(events.is_empty(), "{events:?}");
}
#[test]
fn another_key_while_alt_is_held_cancels_the_code() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
// Alt+F: a shortcut, not a code.
c.message(WM_SYSKEYDOWN, 0x46);
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, 0x41);
let mut events = vec![];
c.drain(&mut events);
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
}
#[test]
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
let mut c = AltCodes::default();
c.message(WM_SYSKEYDOWN, ALT);
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1);
c.message(WM_KEYUP, ALT);
c.message(WM_CHAR, 0xD83D);
c.message(WM_CHAR, 0xDE00);
let mut events = vec![];
c.drain(&mut events);
assert_eq!(events, vec![Event::Text("😀".into())]);
}
}
+50 -13
View File
@@ -16,6 +16,14 @@
//! mouse message that Windows did not make from a pen or a touch
//! (<https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages>)
//! clears the feed.
//!
//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a
//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen
//! reports it (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-mask-constants>):
//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and
//! `rotation` in degrees 0..359 clockwise
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come.
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::RefCell;
@@ -37,6 +45,11 @@ const PEN_FLAG_INVERTED: u32 = 0x0002;
const PEN_FLAG_ERASER: u32 = 0x0004;
/// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure.
const PEN_MASK_PRESSURE: u32 = 0x0001;
/// `PEN_MASK_ROTATION`, `PEN_MASK_TILT_X` and `PEN_MASK_TILT_Y` (`winuser.h`): the pen reports its
/// barrel rotation, its tilt along x and its tilt along y.
const PEN_MASK_ROTATION: u32 = 0x0002;
const PEN_MASK_TILT_X: u32 = 0x0004;
const PEN_MASK_TILT_Y: u32 = 0x0008;
/// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows
/// made from a pen or a touch.
const MI_WP_SIGNATURE: u32 = 0xFF51_5700;
@@ -94,7 +107,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
// pointer that is not a pen.
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact))
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
};
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
@@ -106,15 +120,25 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
/// in contact that reports none; and the eraser end while it is inverted or its eraser button is
/// pressed.
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample {
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
/// pressed; and how it is held, `pose` ([`pen_pose`]).
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample {
let pressure = match pressure {
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
_ if in_contact => 1.0,
_ => 0.0,
};
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose: PenPose::default() }
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose }
}
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
/// rotation when it reports one, each kept within [`PenPose`]'s ranges.
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
PenPose { tilt, rotation }.sanitized()
}
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
@@ -390,7 +414,7 @@ mod tests {
#[test]
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser;
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser;
assert!(!eraser(0), "the tip");
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
@@ -399,19 +423,32 @@ mod tests {
assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL));
}
#[test]
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) });
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis");
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel");
let wild = pen_pose(all, 400, i32::MIN, 720);
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges");
let pose = pen_pose(all, 10, 20, 180);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
}
#[test]
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0);
assert_eq!(
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false),
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()),
PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() },
"hovering"
);
assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0);
assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0);
}
#[test]
+12 -1
View File
@@ -208,4 +208,15 @@ sync_github_name = true
[people.sadkotheguest]
real_name = "Alexander Buraga"
display_name = "Alexander Buraga"
sync_github_name = false
sync_github_name = false
[people.adikshan11]
real_name = "Adithya Shankaran"
sync_github_name = true
[people.slafebre]
real_name = "Sven Lafebre"
[people.kylekanouse]
real_name = "Kyle Kanouse"
sync_github_name = true
+16 -5
View File
@@ -13,15 +13,26 @@ fn luminance(c: &Color) -> f32 {
}
fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
let lum = luminance(c);
// Black ink alone is its own tint: its amount is the tint, not how light it displays (100% K
// displays lighter than black).
let light = match *c {
Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 => 1.0 - k,
_ => luminance(c),
};
// A process or gray stroke color's tints and shades stay in its model.
let (white, black) = match key {
Color::Cmyk { .. } => (Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0)),
Color::Gray { .. } => (Color::gray(0.0), Color::gray(1.0)),
_ => (Color::WHITE, Color::BLACK),
};
match mode {
Colorization::None => *c,
Colorization::Tints => key.lerp(&Color::WHITE, lum),
Colorization::Tints => key.lerp_keep_model(&white, light),
Colorization::TintsAndShades => {
if lum < 0.5 {
Color::BLACK.lerp(key, lum * 2.0)
if light < 0.5 {
key.lerp_keep_model(&black, 1.0 - light * 2.0)
} else {
key.lerp(&Color::WHITE, (lum - 0.5) * 2.0)
key.lerp_keep_model(&white, (light - 0.5) * 2.0)
}
}
Colorization::HueShift { key: art_key } => {
+49
View File
@@ -701,6 +701,55 @@ fn tints_colorization_uses_stroke_colour() {
assert_eq!(white.appearance.fill_paint().color().unwrap().to_rgb(), [1.0, 1.0, 1.0]);
}
/// Black ink alone is a tint by its amount: a process black stroke leaves it as it is, and another
/// process stroke color takes that share of its inks. Tints of a process color stay process.
#[test]
fn tints_of_black_ink_are_its_amount_of_the_stroke_color() {
let tinted = |art: Color, stroke: Color| {
let mut n = rect_art(1.0, 1.0);
n.appearance.set_fill(Paint::solid(art));
colorize(&mut n, Colorization::Tints, &Paint::solid(stroke));
n.appearance.fill_paint().color().unwrap()
};
let ink = Color::cmyk(0.0, 0.0, 0.0, 0.6);
let close = |a: Color, b: Color| {
let (Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) = (a, b) else { panic!("{a:?} {b:?}") };
(c - c2).abs() < 1e-5 && (m - m2).abs() < 1e-5 && (y - y2).abs() < 1e-5 && (k - k2).abs() < 1e-5
};
assert!(close(tinted(ink, Color::cmyk(0.0, 0.0, 0.0, 1.0)), ink));
assert!(close(tinted(ink, Color::cmyk(0.0, 1.0, 1.0, 0.0)), Color::cmyk(0.0, 0.6, 0.6, 0.0)));
let [r, g, b] = tinted(ink, Color::rgb(1.0, 0.0, 0.0)).to_rgb();
assert!((r - 1.0).abs() < 1e-5 && (g - 0.4).abs() < 1e-5 && (b - 0.4).abs() < 1e-5, "{r} {g} {b}");
let Color::Gray { k } = tinted(ink, Color::gray(0.5)) else { panic!("tints of a gray stroke color stay gray") };
assert!((k - 0.3).abs() < 1e-5, "{k}");
}
/// Under Tints and Shades black ink stays black, however light 100% K displays, and a band of black
/// ink is its amount: K 0.5 is the stroke color. A process or gray stroke color stays in its model.
#[test]
fn tints_and_shades_of_black_ink_go_by_its_amount() {
let mapped = |k: f32, stroke: Color| {
let mut n = rect_art(1.0, 1.0);
n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, k)));
colorize(&mut n, Colorization::TintsAndShades, &Paint::solid(stroke));
n.appearance.fill_paint().color().unwrap()
};
let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-5);
let inks = |c: Color| {
let Color::Cmyk { c, m, y, k } = c else { panic!("a process color: {c:?}") };
[c, m, y, k]
};
let orange = Color::cmyk(0.0, 0.6, 1.0, 0.0);
assert!(close(inks(mapped(1.0, orange)), [0.0, 0.0, 0.0, 1.0]), "black stays black");
assert!(close(inks(mapped(0.5, orange)), [0.0, 0.6, 1.0, 0.0]), "the stroke color");
assert!(close(inks(mapped(0.25, orange)), [0.0, 0.3, 0.5, 0.0]), "a tint");
assert!(close(inks(mapped(0.75, orange)), [0.0, 0.3, 0.5, 0.5]), "a shade");
let Color::Gray { k } = mapped(0.75, Color::gray(0.4)) else { panic!("a gray stroke color stays gray") };
assert!((k - 0.7).abs() < 1e-5, "{k}");
let [r, g, b] = mapped(1.0, Color::rgb(1.0, 0.0, 0.0)).to_rgb();
assert!(r < 1e-5 && g < 1e-5 && b < 1e-5, "black stays black: {r} {g} {b}");
}
/// Point type at (0, 0) whose characters are painted `fill` and `stroke` (1 pt wide).
fn type_art(fill: Paint, stroke: Paint) -> Node {
use vectorcraft_doc::{CharStyle, TextObject};
+154 -10
View File
@@ -22,11 +22,15 @@ pub struct ProfilePreset {
}
impl WidthProfile {
/// (left, right) width factors at `t`, linear between points.
/// (left, right) width factors at `t`: a smooth curve through the points ([`Self::at_points`]).
pub fn at(&self, t: f64) -> (f64, f64) {
Self::at_points(&self.points, t)
}
/// [`Self::at`] of a profile's points (a preset's or a saved profile's).
/// [`Self::at`] of a profile's points (a preset's or a saved profile's). Each side runs through
/// its points on a monotone cubic curve (Fritsch–Carlson): it flows through a width point
/// without a kink, turns flat at a point wider or narrower than both neighbours, and never
/// goes past either point of the span it is in (#5714). Points on one straight line stay on
/// it. A step (two points at one position, [`Self::around`]) ends the curve on each side of it.
pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {
if p.is_empty() {
return (1.0, 1.0);
@@ -36,9 +40,21 @@ impl WidthProfile {
}
// (Positions go forward; found in log time, so a long profile read from a file is cheap to ask.)
let i = p.partition_point(|q| q.0 < t);
if let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
let u = (t - a.0) / (b.0 - a.0).max(1e-9);
return (a.1 + (b.1 - a.1) * u, a.2 + (b.2 - a.2) * u);
if let (Some(j), Some(b)) = (i.checked_sub(1), p.get(i))
&& let Some(a) = p.get(j)
{
let h = b.0 - a.0;
let u = (t - a.0) / h.max(1e-9);
let linear = (a.1 + (b.1 - a.1) * u, a.2 + (b.2 - a.2) * u);
if h <= STEP {
return linear;
}
let side = |v: fn(&(f64, f64, f64)) -> f64, straight: f64| {
let y = hermite(v(a), v(b), tangent(p, j, v) * h, tangent(p, i, v) * h, u);
// Widths read from a file may be huge: where the curve overflows, the straight line.
if y.is_finite() { y } else { straight }
};
return (side(|q| q.1, linear.0), side(|q| q.2, linear.1));
}
p.last().map_or((1.0, 1.0), |l| (l.1, l.2))
}
@@ -55,14 +71,17 @@ impl WidthProfile {
// Two swells between narrow necks.
ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] },
];
/// The widest the stroke gets, as a multiple of its weight: the largest total of the left and
/// right factors at any of the points (between them the profile is straight), 1 for a profile
/// without points.
/// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. Each
/// side stays between the widths of the two points of each span ([`Self::at_points`]), but the
/// two sides needn't peak together, so a span counts its wider left and its wider right.
pub fn widest(&self) -> f64 {
if self.points.is_empty() {
let p = &self.points;
if p.is_empty() {
return 1.0;
}
self.points.iter().map(|&(_, l, r)| (l.max(0.0) + r.max(0.0)) / 2.0).fold(0.0, f64::max)
let total = |l: f64, r: f64| (l.max(0.0) + r.max(0.0)) / 2.0;
let spans = p.windows(2).map(|w| total(w[0].1.max(w[1].1), w[0].2.max(w[1].2)));
p.iter().map(|&(_, l, r)| total(l, r)).chain(spans).fold(0.0, f64::max)
}
/// The built-in profile with this id.
pub fn preset(id: &str) -> Option<Self> {
@@ -227,6 +246,41 @@ impl AngleProfile {
}
}
/// How close two width points' positions are to make a step ([`WidthProfile::around`]).
const STEP: f64 = 1e-7;
/// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in
/// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where
/// the point is wider or narrower than both neighbours, the weighted harmonic mean of the slopes
/// of the spans on either side elsewhere (never more than three times either, so no span
/// overshoots its points), and the span's own slope at an end of the profile or beside a step.
fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 {
let Some(q) = p.get(j) else { return 0.0 };
let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP);
let after = p.get(j + 1).filter(|b| b.0 - q.0 > STEP);
let slope = |a: &(f64, f64, f64), b: &(f64, f64, f64)| (v(b) - v(a)) / (b.0 - a.0);
match (before, after) {
(Some(a), Some(b)) => {
let (d0, d1) = (slope(a, q), slope(q, b));
if d0 * d1 <= 0.0 {
return 0.0;
}
let (h0, h1) = (q.0 - a.0, b.0 - q.0);
3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1)
}
(Some(a), None) => slope(a, q),
(None, Some(b)) => slope(q, b),
(None, None) => 0.0,
}
}
/// The cubic Hermite curve from `y0` to `y1` at `u` (0..1), with end slopes `m0` and `m1` per
/// whole span.
fn hermite(y0: f64, y1: f64, m0: f64, m1: f64, u: f64) -> f64 {
let (u2, u3) = (u * u, u * u * u);
(2.0 * u3 - 3.0 * u2 + 1.0) * y0 + (u3 - 2.0 * u2 + u) * m0 + (-2.0 * u3 + 3.0 * u2) * y1 + (u3 - u2) * m1
}
/// The value of samples `p` (position, value) at `t`, linear between them; `None` without any.
fn interpolated(p: &[(f64, f64)], t: f64) -> Option<f64> {
let (first, last) = (p.first()?, p.last()?);
@@ -341,6 +395,7 @@ pub struct SavedProfile {
mod tests {
use super::*;
/// Widths and steps are found by search, at the ends, between points and at a step.
#[test]
fn width_profile_lookups_by_search() {
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25), (1.0, 0.0, 0.0)] };
@@ -358,4 +413,93 @@ mod tests {
let near = WidthProfile { points: vec![(0.4999999, 2.0, 2.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25)] };
assert_eq!(near.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
}
/// The slope of one side of `p` just before and just after `t`.
fn slopes(p: &WidthProfile, t: f64) -> (f64, f64) {
let e = 1e-6;
((p.at(t).0 - p.at(t - e).0) / e, (p.at(t + e).0 - p.at(t).0) / e)
}
/// #5714: the width flows through a width point instead of turning a corner there.
#[test]
fn widths_run_smoothly_through_width_points() {
// A swell in the middle: flat at its widest, and a quarter of the way along above the
// straight ramp from 1 to 3 (2).
let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] };
let (before, after) = slopes(&swell, 0.5);
assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}");
let (l, r) = swell.at(0.25);
assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}");
// Rising on both sides of a point: the slope is the same either side of it.
let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] };
let (before, after) = slopes(&rise, 0.3);
assert!(before > 0.0 && (before - after).abs() < 1e-3 * before, "{before} {after}");
// Points on one line stay on it.
let straight = WidthProfile { points: vec![(0.0, 0.0, 1.0), (0.25, 0.5, 1.0), (1.0, 2.0, 1.0)] };
for t in [0.1, 0.25, 0.6, 0.9] {
let (l, r) = straight.at(t);
assert!((l - 2.0 * t).abs() < 1e-12 && (r - 1.0).abs() < 1e-12, "{t}: {l} {r}");
}
}
/// Neither side of a profile goes wider or narrower than the two points of the span it is in.
#[test]
fn widths_never_pass_the_points_either_side() {
for preset in WidthProfile::PRESETS {
let p = WidthProfile { points: preset.points.to_vec() };
for w in p.points.windows(2) {
let (lo, hi) = (w[0].1.min(w[1].1), w[0].1.max(w[1].1));
for k in 0..=100 {
let t = w[0].0 + (w[1].0 - w[0].0) * k as f64 / 100.0;
let l = p.at(t).0;
assert!(l >= lo - 1e-12 && l <= hi + 1e-12, "{}: {l} at {t} outside {lo}..{hi}", preset.id);
}
}
}
// Uneven spacing and a steep jump next to a gentle rise.
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.05, 1.0, 1.0), (0.9, 1.1, 1.1), (1.0, 5.0, 5.0)] };
for k in 0..=1000 {
let t = k as f64 / 1000.0;
let l = p.at(t).0;
let span = p.points.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).map(|w| (w[0].1.min(w[1].1), w[0].1.max(w[1].1)));
let (lo, hi) = span.unwrap();
assert!(l >= lo - 1e-12 && l <= hi + 1e-12, "{l} at {t}");
}
}
/// A step still breaks the width sharply, and the curve on either side ends at it.
#[test]
fn a_step_ends_the_curve_on_each_side() {
let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 3.0), (0.5, 1.0, 1.0), (1.0, 2.0, 2.0)] };
assert_eq!(p.around(0.5), ((3.0, 3.0), (1.0, 1.0)));
// Two points between ends: each side of the step is a straight ramp.
assert!((p.at(0.25).0 - 2.0).abs() < 1e-12 && (p.at(0.75).0 - 1.5).abs() < 1e-12);
}
/// `widest()` is at least the stroke's width anywhere along the profile, even where the sides peak apart.
#[test]
fn widest_covers_every_width_along_the_profile() {
let profiles = [
vec![(0.0, 1.0, 0.0), (0.5, 0.2, 1.0), (1.0, 1.0, 0.0)],
vec![(0.0, 0.0, 1.0), (0.3, 1.0, 0.0), (0.6, 0.0, 1.0), (1.0, 1.0, 1.0)],
vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)],
];
for points in profiles {
let p = WidthProfile { points };
let most = (0..=1000).map(|k| p.at(k as f64 / 1000.0)).map(|(l, r)| (l.max(0.0) + r.max(0.0)) / 2.0).fold(0.0, f64::max);
assert!(p.widest() >= most - 1e-12, "{} < {most}: {:?}", p.widest(), p.points);
}
assert_eq!(WidthProfile::lens().widest(), 1.0);
assert_eq!(WidthProfile::default().widest(), 1.0);
}
/// Widths read from a file may be absurd: the curve stays finite or falls back to the line.
#[test]
fn huge_widths_stay_finite() {
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, f64::MAX, 1.0), (1.0, -f64::MAX, 0.0)] };
for k in 0..=10 {
let (l, r) = p.at(k as f64 / 10.0);
assert!(!l.is_nan() && r.is_finite(), "{l} {r}");
}
}
}
+4 -1
View File
@@ -192,11 +192,14 @@ fn strokes_without_pressure_round_trip_unchanged() {
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None));
}
/// The Lens profile's widths at its middle, a quarter of the way along and past its end.
#[test]
fn profile_interp() {
let p = WidthProfile::lens();
assert_eq!(p.at(0.5), (1.0, 1.0));
assert_eq!(p.at(0.25), (0.5, 0.5));
// Half way up the lens the width curves above the straight ramp (0.5), flattening into its
// widest point (#5714).
assert_eq!(p.at(0.25), (0.625, 0.625));
assert_eq!(p.at(2.0), (0.0, 0.0));
}
+50
View File
@@ -195,6 +195,24 @@ impl ImageBlob {
jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16)))
}
/// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8
/// bits? Reads only its header.
pub fn is_cmyk16(&self) -> bool {
tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16)))
}
/// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header.
pub fn header_size(&self) -> Option<(u32, u32)> {
let bytes = self.bytes.as_slice();
if bytes.starts_with(&[0xFF, 0xD8]) {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let (w, h) = d.dimensions()?;
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
}
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
}
/// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded
/// or are larger than [`MAX_CMYK_PIXELS`].
pub fn cmyk(&self) -> Option<Inks> {
@@ -633,6 +651,38 @@ mod tests {
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
}
#[test]
fn a_header_gives_the_size_without_the_samples() {
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
// A CMYK TIFF of 6000 × 6000 pixels whose samples aren't there.
let mut t = b"II*\0\x08\0\0\0\x07\0".to_vec();
// Bits per sample: four values, after the entries (8 + 2 + 7 × 12 + 4 = 98).
let entries = [
(256u16, 4u16, 1u32, 6000u32),
(257, 4, 1, 6000),
(258, 3, 4, 98),
(262, 3, 1, 5),
(273, 4, 1, 106),
(277, 3, 1, 4),
(279, 4, 1, 144_000_000),
];
for (tag, kind, count, value) in entries {
t.extend_from_slice(&tag.to_le_bytes());
t.extend_from_slice(&kind.to_le_bytes());
t.extend_from_slice(&count.to_le_bytes());
t.extend_from_slice(&value.to_le_bytes());
}
t.extend_from_slice(&0u32.to_le_bytes());
t.extend_from_slice(&[8, 0, 8, 0, 8, 0, 8, 0]);
let big = ImageBlob::new("image/tiff", t);
assert!(big.is_cmyk());
assert_eq!(big.header_size(), Some((6000, 6000)));
assert_eq!(big.cmyk(), None);
let mut png = Vec::new();
image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF");
}
#[test]
fn a_cmyk_image_samples_its_ink_amounts() {
let b = ImageBlob::cmyk_tiff(&inks()).unwrap();
+2
View File
@@ -72,6 +72,7 @@ impl Document {
new_art,
dimensions,
retired_artboard_id: _,
opened_artboard: _,
index: _,
} = self;
*version == other.version
@@ -248,6 +249,7 @@ impl Document {
new_art: Default::default(),
dimensions: false,
retired_artboard_id: Default::default(),
opened_artboard: None,
index: Default::default(),
};
let id = d.alloc_id();
+77 -2
View File
@@ -6,9 +6,10 @@ use std::rc::Rc;
use std::sync::{Arc, OnceLock};
use vectorcraft_geom::hit::{fill_contains, stroke_contains};
use vectorcraft_geom::{BezPath, FillRule, Point, Rect};
use vectorcraft_geom::kurbo::ParamCurveNearest;
use vectorcraft_geom::{BezPath, FillRule, PathData, PathSeg, Point, Rect};
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, SymbolBoxes};
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeAlign, SymbolBoxes};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HitKind {
@@ -724,6 +725,43 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
}
/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a
/// miter or square cap, so the caller falls back to the full stroke check there.
fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> {
if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 {
return None;
}
let radius_sq = radius * radius;
let decoration_sq = decoration_reach * decoration_reach;
let mut near_decoration = false;
for sp in &path.subpaths {
for i in 0..sp.segment_count() {
let c = sp.segment(i);
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
near_decoration = true;
}
let controls = [c.p0, c.p1, c.p2, c.p3];
if controls.iter().all(|q| q.x < p.x - radius)
|| controls.iter().all(|q| q.x > p.x + radius)
|| controls.iter().all(|q| q.y < p.y - radius)
|| controls.iter().all(|q| q.y > p.y + radius)
{
continue;
}
let seg = if sp.segment_is_line(i) { PathSeg::Line(vectorcraft_geom::kurbo::Line::new(c.p0, c.p3)) } else { PathSeg::Cubic(c) };
if seg.nearest(p, 1e-9).distance_sq <= radius_sq {
if vectorcraft_geom::bez::has_length(&seg) {
return Some((true, near_decoration));
}
// A zero-length segment can still hit as an outline, though a painted stroke
// needs a segment with direction. Let the existing check decide its hit kind.
near_decoration = true;
}
}
}
Some((false, near_decoration))
}
#[cfg(test)]
thread_local! {
/// How many objects [`hit_leaf`] tested on this thread.
@@ -735,6 +773,43 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
LEAVES_TESTED.with(|c| c.set(c.get() + 1));
match &n.kind {
NodeKind::Path { path, rule, .. } => {
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
if hit {
return Some(HitKind::Outline);
}
if !needs_full_check {
return None;
}
}
let mut strokes = n.appearance.painted_strokes();
if !opt.outline
&& n.appearance.fill().is_none_or(|f| f.paint.is_none())
&& let Some(s) = strokes.next()
&& strokes.next().is_none()
&& s.align == StrokeAlign::Center
&& s.width.is_finite()
&& s.width > 0.0
&& s.dash.as_ref().is_none_or(|d| !d.is_dashed())
&& s.profile.is_none()
&& s.start_arrow.is_none()
&& s.end_arrow.is_none()
&& s.brush.is_none()
&& let Some((hit, near_decoration)) = near_path_body(
path,
p,
s.width / 2.0 + opt.tol,
if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 },
)
{
if hit {
return Some(HitKind::Stroke);
}
if !near_decoration {
return None;
}
}
let bp = path.to_bezpath();
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
+33
View File
@@ -38,6 +38,39 @@ fn unfilled_interior_misses() {
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
}
#[test]
fn long_plain_stroke_hits_its_middle_and_curved_end() {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let mut sp = vectorcraft_geom::SubPath::polyline(&(0..=4097).map(|i| Point::new(i as f64 * 10.0, 0.0)).collect::<Vec<_>>(), false);
sp.anchors[4096].h_out = Point::new(40960.0, 100.0);
sp.anchors[4097].h_in = Point::new(40970.0, 100.0);
sp.anchors.push(vectorcraft_geom::Anchor::corner(Point::new(40970.0, 100.0)));
sp.anchors.push(vectorcraft_geom::Anchor::corner(Point::new(0.0, 100.0)));
let path = vectorcraft_geom::PathData::single(sp);
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(Some(l), 0, Node::path(id, path, look)).unwrap();
let outline = HitOptions { outline: true, ..Default::default() };
for point in [Point::new(20485.0, 0.0), Point::new(40965.0, 75.0)] {
assert_eq!(hit_test(&d, point, HitOptions::default()).map(|h| h.kind), Some(HitKind::Stroke));
assert_eq!(hit_test(&d, point, outline).map(|h| h.kind), Some(HitKind::Outline));
}
assert!(hit_test(&d, Point::new(20485.0, 50.0), HitOptions::default()).is_none());
}
#[test]
fn coincident_anchors_remain_hittable_as_an_outline() {
let mut d = Document::new(200.0, 200.0);
let id = d.alloc_id();
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(50.0, 50.0); 2], false));
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(d.layers.first().map(|l| l.id), 0, Node::path(id, path, look)).unwrap();
let at = Point::new(50.0, 50.0);
assert_eq!(hit_test(&d, at, HitOptions::default()).map(|h| h.kind), Some(HitKind::Outline));
assert_eq!(hit_test(&d, at, HitOptions { outline: true, ..Default::default() }).map(|h| h.kind), Some(HitKind::Outline));
}
/// #1103: a marquee drawn over a background picks what is on it, not the background, whose
/// outline it doesn't touch.
#[test]
+5
View File
@@ -325,6 +325,11 @@ pub struct Document {
/// Never saved.
#[serde(skip)]
pub retired_artboard_id: RetiredArtboardId,
/// The id of the artboard an imported file names as its active one (a `.ai` file's
/// `CropAreaActive`): the document opens with that artboard active. A `.ai` save or export
/// names it as the file's active artboard. `None`: the first. Native files do not keep it.
#[serde(skip)]
pub opened_artboard: Option<u32>,
/// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this
/// is set, so documents without any pay nothing for them.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
+78 -2
View File
@@ -46,10 +46,26 @@ impl LinkInfo {
Self { path: path.into(), ..Self::default() }
}
/// The file name: the path's last component, whichever system's separators it uses.
/// The file name: the path's last component, whichever system's separators it uses
/// ([`path_separators`]).
pub fn name(&self) -> &str {
self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path)
self.path.rsplit(path_separators(&self.path)).next().unwrap_or(&self.path)
}
/// The folder the file is in: the path without its name and the separators before it.
pub fn folder(&self) -> &str {
let folder = self.path.get(..self.path.len().saturating_sub(self.name().len())).unwrap_or_default();
folder.trim_end_matches(path_separators(&self.path))
}
}
/// The characters that separate the folders of `path`. A path with a colon and no `/` or `\` is a
/// classic Mac OS path (`Disk:Folder:file.tif`, as older documents store links), whose folders are
/// separated by colons. Any other path is separated by `/` and `\`: its file name may hold a colon
/// (`/Users/a/x:y.png`) and never holds a `/` or `\`.
pub fn path_separators(path: &str) -> &'static [char] {
const SLASHES: &[char] = &['/', '\\'];
if path.contains(':') && !path.contains(SLASHES) { &[':'] } else { SLASHES }
}
impl From<&str> for LinkInfo {
@@ -164,6 +180,31 @@ impl ImageBlob {
pub fn is_proxy(&self) -> bool {
self.proxy.as_ref().is_some_and(|p| Arc::ptr_eq(p, &self.bytes))
}
/// Does a colorize paint ([`crate::NodeExtras::colorize`]) show on these bytes? Not while
/// they are a preview whose pixels aren't grayscale, such as [`missing_placeholder`]: until
/// the file is relinked the image shows the preview as it is, and keeps the paint.
pub fn takes_colorize(&self) -> bool {
!self.is_proxy() || self.gray_source().is_some()
}
}
/// The side of [`missing_placeholder`]'s image, in pixels.
pub const MISSING_SIDE: u32 = 64;
/// What a linked image shows when an importer has no pixels for it (its file is missing or isn't
/// in the data): a light tile, crossed out, [`MISSING_SIDE`] pixels a side, as a PNG. `None` when
/// it can't be encoded.
pub fn missing_placeholder() -> Option<Vec<u8>> {
let last = MISSING_SIDE - 1;
let img = image::RgbaImage::from_fn(MISSING_SIDE, MISSING_SIDE, |x, y| {
let edge = x == 0 || y == 0 || x == last || y == last;
let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1;
image::Rgba(if edge || cross { [200, 60, 60, 255] } else { [236, 236, 236, 255] })
});
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
}
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
@@ -445,6 +486,12 @@ mod tests {
.unwrap()
}
#[test]
fn the_placeholder_is_a_png() {
let png = missing_placeholder().unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().width(), MISSING_SIDE);
}
#[test]
fn a_path_string_from_older_files_reads_as_a_link() {
let old: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":"C:\\art\\photo.png"}"#).unwrap();
@@ -460,6 +507,35 @@ mod tests {
assert_eq!(v["link"], serde_json::json!({"path": "/a/b.png", "size": 9, "page": 2}));
}
/// A classic Mac OS path is named by its last colon-separated component, and its folder is
/// what comes before; other paths keep their `/` and `\` separators, and a name never holds
/// one.
#[test]
fn a_classic_mac_path_is_named_by_its_last_component() {
let parts = |path: &str| {
let l = LinkInfo::new(path);
(l.name().to_string(), l.folder().to_string())
};
assert_eq!(parts("Macintosh HD:Images:photo.tif"), ("photo.tif".into(), "Macintosh HD:Images".into()));
assert_eq!(parts("Disk:photo.tif"), ("photo.tif".into(), "Disk".into()));
assert_eq!(parts("Disk:Art/2024:a\\b.tif"), ("b.tif".into(), "Disk:Art/2024:a".into()));
assert_eq!(parts("Disk:Images:../other.png"), ("other.png".into(), "Disk:Images:..".into()), "a name reaches no other folder");
assert_eq!(parts("C:\\art\\photo.png"), ("photo.png".into(), "C:\\art".into()));
assert_eq!(parts("c:/art/photo.png"), ("photo.png".into(), "c:/art".into()));
assert_eq!(parts("/Users/a/x:y.png"), ("x:y.png".into(), "/Users/a".into()), "a POSIX name may hold a colon");
assert_eq!(parts("./art/x:y.png"), ("x:y.png".into(), "./art".into()));
assert_eq!(parts("..\\art\\x:y.png"), ("x:y.png".into(), "..\\art".into()));
assert_eq!(parts("\\\\?\\C:\\art\\photo.png"), ("photo.png".into(), "\\\\?\\C:\\art".into()));
assert_eq!(parts("file:///art/photo.png"), ("photo.png".into(), "file:///art".into()));
assert_eq!(parts("file:/art/photo.png"), ("photo.png".into(), "file:/art".into()));
assert_eq!(parts("assets/icon:dark.png"), ("icon:dark.png".into(), "assets".into()), "a relative path with slashes");
assert_eq!(parts(":Images:photo.tif"), ("photo.tif".into(), ":Images".into()), "a classic path relative to its folder");
assert_eq!(parts("/Users/a//photo.png").1, "/Users/a", "repeated separators");
assert_eq!(parts("photo.png"), ("photo.png".into(), String::new()));
assert_eq!(parts("C:photo.png"), ("photo.png".into(), "C".into()), "a drive-relative path has the same shape");
assert_eq!(LinkInfo::new("Macintosh HD:Images:photo.tif").path, "Macintosh HD:Images:photo.tif", "the stored path is kept");
}
#[test]
fn a_reader_hashes_as_its_bytes_do() {
// Several 64 KB reads, and none.
+60 -2
View File
@@ -53,8 +53,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
#[cfg(test)]
use blend_spec::{blend_color_shift, blend_ramp};
pub use envelope::{
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, envelope_bounds, envelope_expand, envelope_frame,
envelope_grid, envelope_mapper, envelope_of, envelope_overlay, smooth_handles,
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, envelope_bounds, envelope_content_boxes,
envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, smooth_handles,
};
pub(crate) use expand::max_outset;
pub use expand::{
@@ -233,6 +233,64 @@ mod tests {
assert_eq!(envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 100.0))(p), p);
}
/// `bounds_margin` grows the box an envelope maps from, only while Distort Appearance is on. It
/// holds shares of the box, and an envelope with an uneven frame maps from the same box in that
/// frame. A native file writes it only when it isn't zero.
#[test]
fn an_envelope_maps_from_its_box_with_its_margins() {
let rect = Node::path(NodeId(2), vectorcraft_geom::shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)), crate::Appearance::default_art());
let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true };
let content = [Arc::new(rect)];
let src = |content: &[Arc<Node>], frame: Affine, options: EnvelopeOptions| EnvelopeMap::new(content, &kind, frame, options).unwrap().src();
// Top, bottom, left and right.
let on = EnvelopeOptions { bounds_margin: [0.125, 0.25, 0.0625, 0.5], ..EnvelopeOptions::NEW };
let geometric = Rect::new(10.0, 20.0, 110.0, 70.0);
let grown = Rect::new(3.75, 13.75, 160.0, 82.5);
assert_eq!(src(&content, Affine::IDENTITY, EnvelopeOptions::default()), geometric);
assert_eq!(src(&content, Affine::IDENTITY, on), grown);
assert_eq!(src(&content, Affine::IDENTITY, EnvelopeOptions { distort_appearance: false, ..on }), geometric);
for bad in [f32::NAN, f32::INFINITY, -0.05] {
assert_eq!(src(&content, Affine::IDENTITY, EnvelopeOptions { bounds_margin: [bad, 0.25, 0.0625, 0.5], ..on }), geometric);
}
// A finite share of a box too wide to grow leaves the box as it is.
let wide = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1e308, 10.0)), crate::Appearance::default_art());
let wide = [Arc::new(wide)];
let huge = EnvelopeOptions { bounds_margin: [0.0, 0.0, f32::MAX, 0.0], ..on };
assert_eq!(src(&wide, Affine::IDENTITY, huge), src(&wide, Affine::IDENTITY, EnvelopeOptions::NEW));
// Bounds follow the box: a warp that doesn't bend covers it.
let b = envelope_bounds(&content, &kind, Affine::IDENTITY, on).unwrap();
assert!((b.x0 - 3.75).abs() < 1e-6 && (b.y1 - 82.5).abs() < 1e-6, "{b:?}");
// Art taken through an uneven frame maps from the same box in that frame.
let frame = Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(2.0, 0.5);
let mut placed = (*content[0]).clone();
placed.transform(frame, true);
let framed = src(&[Arc::new(placed)], frame, on);
assert!((framed.x0 - 3.75).abs() + (framed.y0 - 13.75).abs() + (framed.x1 - 160.0).abs() + (framed.y1 - 82.5).abs() < 1e-6, "{framed:?}");
// A frame that turns and scales gives the same margins as the art had before it took them.
let mut stroked = (*content[0]).clone();
if let Some(s) = stroked.appearance.stroke_mut() {
s.width = 10.0;
}
let margin = |n: &Node, frame: Affine| {
let (with, plain) = envelope_content_boxes(&[Arc::new(n.clone())], frame).unwrap();
envelope_stroke_margin(with, plain).unwrap()
};
let before = margin(&stroked, Affine::IDENTITY);
assert_eq!(before.map(|m| (m * 1000.0).round()), [100.0, 100.0, 50.0, 50.0]);
let frame = Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(2.0);
let mut turned = stroked.clone();
turned.transform(frame, true);
assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round()));
// Margins an `f32` can't hold are none.
assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None);
assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none());
let saved = serde_json::to_value(on).unwrap();
assert_eq!(saved["boundsMargin"], serde_json::json!([0.125, 0.25, 0.0625, 0.5]));
assert_eq!(serde_json::from_value::<EnvelopeOptions>(saved).unwrap(), on);
}
/// How far the border of `m` strays from the ellipse in `r`, in points (measured across the
/// ellipse's short radius), checked at 20 places along every border edge.
fn mesh_border_off_ellipse(m: &GradientMesh, r: Rect) -> f64 {
+55 -7
View File
@@ -76,6 +76,12 @@ pub struct EnvelopeOptions {
pub distort_linear_gradients: bool,
/// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art.
pub distort_pattern_fills: bool,
/// With Distort Appearance, how far the box the content maps from reaches past its geometric
/// bounds at the top, bottom, left and right, as shares of their height and width. An envelope
/// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes
/// have none. Leaving Edit Contents measures them again when the strokes reach differently.
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub bounds_margin: [f32; 4],
}
impl Default for EnvelopeOptions {
@@ -86,6 +92,7 @@ impl Default for EnvelopeOptions {
distort_appearance: false,
distort_linear_gradients: false,
distort_pattern_fills: false,
bounds_margin: [0.0; 4],
}
}
}
@@ -98,6 +105,7 @@ impl EnvelopeOptions {
distort_appearance: true,
distort_linear_gradients: false,
distort_pattern_fills: false,
bounds_margin: [0.0; 4],
};
/// Do gradients bend with the art?
pub fn gradients(&self) -> bool {
@@ -107,6 +115,45 @@ impl EnvelopeOptions {
pub fn patterns(&self) -> bool {
self.distort_appearance && self.distort_pattern_fills
}
/// The box content with geometric bounds `r` maps from. Margins that aren't finite, are
/// negative or give a box that isn't finite count as none.
fn source_box(&self, r: Rect) -> Rect {
let [top, bottom, left, right] = self.bounds_margin.map(f64::from);
if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) {
return r;
}
let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]);
if grown.is_finite() { grown } else { r }
}
}
/// The bounds of `content` in the axes of `frame`, with its strokes and geometric. Strokes scale
/// with the frame as [`Node::transform`] scales them.
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
let mut m = (**c).clone();
m.transform(to_frame, true);
(vectorcraft_geom::union_opt(stroked, m.visual_bounds()), vectorcraft_geom::union_opt(plain, m.geometric_bounds()))
});
Some((stroked?, plain?))
}
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
/// content with no width or no height, or for margins an `f32` can't hold.
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
if plain.width() < 1e-6 || plain.height() < 1e-6 {
return None;
}
let margin = [
(plain.y0 - stroked.y0) / plain.height(),
(stroked.y1 - plain.y1) / plain.height(),
(plain.x0 - stroked.x0) / plain.width(),
(stroked.x1 - plain.x1) / plain.width(),
]
.map(|m| m as f32);
margin.iter().all(|m| m.is_finite()).then_some(margin)
}
/// Handle slots of a [`MeshPoint`]: towards the next column, previous column, next row, previous row.
@@ -218,9 +265,9 @@ pub struct EnvelopeMap<'a> {
}
impl<'a> EnvelopeMap<'a> {
/// The map of an envelope of `kind` around `content` with `frame`. `None` when the content
/// has no bounds.
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine) -> Option<Self> {
/// The map of an envelope of `kind` around `content` with `frame` and `options`. `None` when
/// the content has no bounds.
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let src = if frame == Affine::IDENTITY {
@@ -232,13 +279,14 @@ impl<'a> EnvelopeMap<'a> {
Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds()))
})??
};
let src = options.source_box(src);
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
}
/// The map of envelope node `n` (`None` for other nodes).
pub fn of(n: &'a Node) -> Option<Self> {
match &n.kind {
NodeKind::Envelope { content, kind, frame, .. } => Self::new(content, kind, **frame),
NodeKind::Envelope { content, kind, frame, options, .. } => Self::new(content, kind, **frame, *options),
_ => None,
}
}
@@ -302,7 +350,7 @@ pub(super) fn expand_envelope(
frame: Affine,
hooks: Hooks,
) -> Vec<Node> {
let Some(map) = EnvelopeMap::new(content, kind, frame) else { return content.iter().map(|c| (**c).clone()).collect() };
let Some(map) = EnvelopeMap::new(content, kind, frame, options) else { return content.iter().map(|c| (**c).clone()).collect() };
let src = map.src();
let fid = if fidelity.is_finite() { fidelity.clamp(0.0, 100.0) / 100.0 } else { 0.5 };
let f = |p: Point| map.map(p);
@@ -319,7 +367,7 @@ pub(super) fn expand_envelope(
}
/// Envelope bounds: a mesh's points, a top object's path, the warp's surface (sampled).
pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine) -> Option<Rect> {
pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Rect> {
match kind {
EnvelopeKind::Mesh { rows, cols, points, handles } if !handles.is_empty() => envelope_grid(*rows, *cols, points, handles)?.outline().bounds(),
EnvelopeKind::Mesh { points, .. } => {
@@ -327,6 +375,6 @@ pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine
Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
}
EnvelopeKind::TopObject { path } => path.bounds(),
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame)?.bounds(),
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame, options)?.bounds(),
}
}
+4
View File
@@ -66,6 +66,9 @@ pub struct NodeExtras {
/// As an instance of a dynamic symbol, its own appearance changes to objects of the symbol's
/// art (see [`crate::symbol_overrides`]); empty for none.
pub symbol_overrides: Vec<crate::SymbolOverride>,
/// As an envelope with margins in Edit Contents, the margins its strokes gave when Edit Contents
/// began ([`crate::live::EnvelopeOptions::bounds_margin`]).
pub envelope_edit_margin: Option<[f32; 4]>,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -91,6 +94,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
compound_shape: false,
shape_mode: crate::ShapeMode::Add,
symbol_overrides: Vec::new(),
envelope_edit_margin: None,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+10 -6
View File
@@ -300,7 +300,7 @@ impl Node {
self.projected(Some(xf.transform_rect_bbox(art)))
}
NodeKind::Blend { children, spec } => vectorcraft_geom::union_opt(union(children), spec.spine.as_ref().and_then(|s| s.bounds())),
NodeKind::Envelope { content, kind, frame, .. } => crate::live::envelope_bounds(content, kind, **frame),
NodeKind::Envelope { content, kind, frame, options, .. } => crate::live::envelope_bounds(content, kind, **frame, *options),
NodeKind::Mesh(m) => m.bounds(),
// Each copy is measured where the repeat draws it: `RepeatSpec::transforms` lays the
// copies out by the source's bounds measured without the document.
@@ -332,6 +332,14 @@ impl Node {
self.visual(Some(symbols))
}
/// The visual box of a group or layer without a clipping path, from the visual boxes of its
/// [`Node::editing_children`]: for a walk that measures the members as well.
pub fn visual_of_members(&self, members: impl Iterator<Item = Option<Rect>>) -> Option<Rect> {
// The container's own strokes paint around its members.
let o = self.appearance.outset();
members.fold(None, vectorcraft_geom::union_opt).map(|b| b.inflate(o, o))
}
/// The box of [`Node::visual_bounds`], or of [`Node::visual_bounds_with`] when `symbols` is
/// given.
pub(crate) fn visual(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
@@ -346,11 +354,7 @@ impl Node {
}
}
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))),
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
// The container's own strokes paint around its members.
let o = self.appearance.outset();
self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))).map(|b| b.inflate(o, o))
}
NodeKind::Layer { .. } | NodeKind::Group { .. } => self.visual_of_members(self.editing_children().iter().map(|c| c.visual(symbols))),
NodeKind::Blend { children, spec } => {
let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols)));
let o = crate::live::max_outset(children, symbols);
+16
View File
@@ -21,6 +21,7 @@ fn extras_are_written_flat_in_order() {
e.live_paint_gaps = Some(Box::default());
e.compound_shape = true;
e.shape_mode = crate::ShapeMode::Exclude;
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
}
/// The top-level keys of a JSON object, in the order written.
struct Keys(Vec<String>);
@@ -65,6 +66,7 @@ fn extras_are_written_flat_in_order() {
"live_paint_gaps",
"compound_shape",
"shape_mode",
"envelope_edit_margin",
];
assert_eq!(keys, order);
assert_eq!(v["shape_mode"], "exclude");
@@ -443,6 +445,20 @@ fn visual_bounds_include_stroke() {
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
}
/// A group's box from its members' boxes grows by the group's own strokes, leaves out members
/// without a box, and is `None` when none has one.
#[test]
fn visual_of_members_unions_the_members_and_grows_by_the_group_stroke() {
let mut g = Node::group(NodeId(1), vec![]);
g.appearance = Appearance::default_art().into();
let (a, b) = (Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(20.0, 5.0, 30.0, 8.0));
let o = g.appearance.outset();
assert!(o > 0.0);
assert_eq!(g.visual_of_members([Some(a), None, Some(b)].into_iter()), Some(Rect::new(0.0, 0.0, 30.0, 10.0).inflate(o, o)));
assert_eq!(g.visual_of_members([None, None].into_iter()), None);
assert_eq!(g.visual_of_members([].into_iter()), None);
}
/// Type's visual bounds grow by how far its character strokes paint past the glyphs: half the
/// weight centred, the whole weight outside, nothing inside; scaled with the type.
#[test]
+5
View File
@@ -53,6 +53,7 @@ impl Serialize for Node {
is_default(&e.compound_shape),
is_default(&e.shape_mode),
e.symbol_overrides.is_empty(),
e.envelope_edit_margin.is_none(),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -94,6 +95,7 @@ impl Serialize for Node {
field!("compound_shape", &e.compound_shape);
field!("shape_mode", &e.shape_mode);
field!("symbol_overrides", &e.symbol_overrides);
field!("envelope_edit_margin", &e.envelope_edit_margin);
st.end()
}
}
@@ -232,6 +234,8 @@ pub(super) struct NodeWire {
shape_mode: crate::ShapeMode,
#[serde(default, deserialize_with = "counted_list")]
symbol_overrides: Vec<crate::SymbolOverride>,
#[serde(default)]
envelope_edit_margin: Option<[f32; 4]>,
}
impl From<NodeWire> for Node {
@@ -258,6 +262,7 @@ impl From<NodeWire> for Node {
compound_shape: w.compound_shape,
shape_mode: w.shape_mode,
symbol_overrides: w.symbol_overrides,
envelope_edit_margin: w.envelope_edit_margin,
};
Node {
id: w.id,
+14
View File
@@ -164,6 +164,9 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("Polish", "pl", Quotes { double: ['„', '”'], single: ['‚', '’'] }),
("Czech", "cs", Quotes { double: ['„', '“'], single: ['‚', '‘'] }),
("Russian", "ru", Quotes { double: ['«', '»'], single: ['„', '“'] }),
// „…“ at either level: CLDR (https://github.com/unicode-org/cldr/blob/main/common/main/bg.xml,
// `delimiters`). Shaped as `bg`, fonts draw their Bulgarian forms (`locl` for `BGR`, #5945).
("Bulgarian", "bg", Quotes { double: ['„', '“'], single: ['„', '“'] }),
// „…” outside, ’…’ inside: Pravopis srpskoga jezika (Matica srpska, 2010, ISBN
// 978-86-7946-079-0, т. 168, pp. 133–135) and CLDR
// (https://github.com/unicode-org/cldr/blob/main/common/main/sr.xml, `delimiters`).
@@ -185,6 +188,8 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("Kannada", "kn", Quotes::ENGLISH),
("Malayalam", "ml", Quotes::ENGLISH),
("Odia", "or", Quotes::ENGLISH),
("Assamese", "as", Quotes::ENGLISH),
("Sanskrit", "sa", Quotes::ENGLISH),
("Urdu", "ur", Quotes::ENGLISH),
];
@@ -374,6 +379,8 @@ mod tests {
fn char_languages_are_stored_by_tag() {
assert_eq!(char_language("Turkish"), Ok(Some("tr")));
assert_eq!(char_language("MR"), Ok(Some("mr")));
assert_eq!(char_language("Assamese"), Ok(Some("as")));
assert_eq!(char_language("Sanskrit"), Ok(Some("sa")));
assert_eq!(char_language("english: usa"), Ok(None));
assert_eq!(char_language("en-US"), Ok(None));
assert!(char_language("Klingon").is_err() && char_language("").is_err());
@@ -385,6 +392,10 @@ mod tests {
assert_eq!(char_language("Serbian: Cyrillic"), Ok(Some("sr-Cyrl")));
assert_eq!(char_language("sr-latn"), Ok(Some("sr-Latn")));
assert_eq!(char_language("Croatian"), Ok(Some("hr")));
// Bulgarian (#5945), by name or tag.
assert_eq!(char_language("Bulgarian"), Ok(Some("bg")));
assert_eq!(char_language("BG"), Ok(Some("bg")));
assert_eq!(char_language_name(Some("bg")), Some("Bulgarian"));
assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic"));
// Every entry has a tag of its own, and a name of its own.
for (i, (n, t, _)) in LANGUAGES.iter().enumerate() {
@@ -409,6 +420,9 @@ mod tests {
}
let mut prev = None;
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
// Bulgarian: „…“ at either level, as CLDR has it.
let mut prev = None;
assert_eq!(language_quotes("bulgarian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a „b“ c“");
// Converting in pieces keeps the context.
let mut prev = None;
let a = Quotes::ENGLISH.apply("\"", &mut prev);
+7 -1
View File
@@ -307,7 +307,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
),
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})),
r(
"blur.gaussian",
"Gaussian Blur…",
BLUR,
"{radius: pt (5), linear?: bool (false; blurs the colours in linear light, as an SVG filter with color-interpolation-filters=\"linearRGB\" does)}",
json!({"radius": 5.0}),
),
r(
"artistic.coloredPencil",
"Colored Pencil…",
+41
View File
@@ -1079,6 +1079,47 @@ pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) {
}
}
/// [`gaussian_rgba`] with the colours mixed in linear light: decoded from sRGB before the blur
/// and encoded again after it (Filter Effects 1 §16, `color-interpolation-filters: linearRGB`,
/// <https://www.w3.org/TR/filter-effects-1/#ColorInterpolationFiltersProperty>). The blur runs on
/// 16-bit values, so dark linear tones keep their steps.
pub fn gaussian_rgba_linear(data: &mut [u8], w: usize, h: usize, sigma: f64) {
use vectorcraft_doc::color::cms::lab::{linear_to_srgb, srgb_to_linear};
if let Some(px) = pixels(data, w, h)
&& sigma >= 0.2
{
// Each colour is unpremultiplied, decoded (by table) and premultiplied again.
let decode: Vec<f32> = (0..=255u8).map(|v| srgb_to_linear(f32::from(v) / 255.0)).collect();
let mut wide: Vec<Px16> = px
.iter()
.map(|p| {
let a = f32::from(p[3]) / 255.0;
let lin = |v: u8| {
if p[3] == 0 {
return 0;
}
let straight = (f32::from(v) / f32::from(p[3]) * 255.0).round().clamp(0.0, 255.0) as usize;
(decode.get(straight).copied().unwrap_or(0.0) * a * 65535.0).round().clamp(0.0, 65535.0) as u16
};
[lin(p[0]), lin(p[1]), lin(p[2]), u16::from(p[3]) * 257]
})
.collect();
gaussian(&mut wide, w, sigma);
for (p, q) in px.iter_mut().zip(&wide) {
let a = to8(q[3]);
let alpha = f32::from(q[3]) / 65535.0;
let enc = |v: u16| {
if alpha <= 0.0 {
return 0;
}
let straight = (f32::from(v) / 65535.0 / alpha).clamp(0.0, 1.0);
(linear_to_srgb(straight) * f32::from(a)).round().clamp(0.0, f32::from(a)) as u8
};
*p = [enc(q[0]), enc(q[1]), enc(q[2]), a];
}
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
+22
View File
@@ -887,6 +887,28 @@ fn gaussian_and_plane_blurs_keep_their_mass() {
assert!((plane.iter().sum::<f32>() - 100.0).abs() < 0.5 && plane[15 * w + 13] > 0.0 && plane[13 * w + 15] > 0.0);
}
/// Blurred in linear light, black beside white meets at about 188/255 (half the light, encoded),
/// where the plain blur meets at about 128; flat areas and alpha stay as they are (#5877).
#[test]
fn linear_light_blur_mixes_light_not_values() {
// Large enough that the transparency past the edges doesn't reach the middle.
let (w, h) = (120, 60);
let src = image(w, h, |x, _| if x < 60 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
let (mut plain, mut linear) = (src.clone(), src.clone());
gaussian_rgba(&mut plain, w, h, 3.0);
gaussian_rgba_linear(&mut linear, w, h, 3.0);
let mid = |d: &[u8]| (f32::from(at(d, w, 59, 30)[0]) + f32::from(at(d, w, 60, 30)[0])) / 2.0;
assert!((mid(&plain) - 128.0).abs() < 6.0, "{}", mid(&plain));
assert!((mid(&linear) - 188.0).abs() < 6.0, "{}", mid(&linear));
assert_eq!((at(&linear, w, 30, 30), at(&linear, w, 90, 30)), ([0, 0, 0, 255], [255, 255, 255, 255]));
// Premultiplied input: a half-transparent white square blurs to white at any alpha.
let mut soft = image(30, 30, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [128, 128, 128, 128] } else { [0, 0, 0, 0] });
gaussian_rgba_linear(&mut soft, 30, 30, 2.0);
for p in soft.as_chunks::<4>().0 {
assert!(p[0] <= p[3] && p[3] <= 128 && (p[3] < 8 || p[0] + 2 >= p[3]), "{p:?}");
}
}
/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored
/// --nocapture pixel_timings`).
#[test]
+5 -3
View File
@@ -48,9 +48,11 @@ pub enum RasterFx {
Feather {
radius: f64,
},
/// Blur the whole object (σ = radius / 2).
/// Blur the whole object (σ = radius / 2): its colours mixed as they are, or in linear light
/// (`linear`, as an SVG filter asks with `color-interpolation-filters="linearRGB"`).
GaussianBlur {
radius: f64,
linear: bool,
},
/// A Photoshop-style filter over the object's pixels (Radial Blur, Unsharp Mask…).
Pixel(PixelFx),
@@ -77,7 +79,7 @@ impl RasterFx {
RasterFx::DropShadow { dx, dy, blur, .. } => dx.abs().max(dy.abs()) + 1.5 * blur,
RasterFx::OuterGlow { blur, .. } => 1.5 * blur,
RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => 0.0,
RasterFx::GaussianBlur { radius } => 1.5 * radius,
RasterFx::GaussianBlur { radius, .. } => 1.5 * radius,
RasterFx::Pixel(p) => p.outset(bounds),
RasterFx::Rasterize(r) => r.outset(),
}
@@ -416,7 +418,7 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
center: text(&p, "source", "edge").eq_ignore_ascii_case("center"),
},
"stylize.feather" => RasterFx::Feather { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0), linear: flag(&p, "linear", false) },
RASTERIZE => RasterFx::Rasterize(Rasterize::parse(&p)),
id => RasterFx::Pixel(pixel::parse(id, &p)?),
})
+33 -3
View File
@@ -42,6 +42,31 @@ pub fn has_gradient_copies(n: &Node) -> bool {
(n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && has_transform_copies(n)
}
/// Is `n` a path or compound path with a visible Transform effect that makes copies and fills and
/// strokes that paint the copies differently as one path than as separate objects
/// ([`paints_copies_apart`])? Such an object is drawn through its art ([`outline_art`]), each copy
/// an object of its own above the one before ([`copy_leaf`]), as Expand Appearance makes it
/// (#5920).
pub(crate) fn has_layered_copies(n: &Node) -> bool {
leaf_geometry(n).is_some_and(|(_, rule)| paints_copies_apart(&n.appearance, rule)) && has_transform_copies(n)
}
/// Do the fills and strokes `a` of a path with fill rule `rule` paint a Transform effect's copies
/// differently when the copies are one path than when each is an object of its own? They do
/// unless they paint once, in full and in Normal mode, with a stroke or a nonzero fill: then the
/// one path paints what the copies paint together. A fill and a stroke paint each copy's stroke
/// under the fills of the copies above it, a second fill or stroke likewise, the even-odd rule
/// leaves holes where copies overlap, and a partly transparent or blended fill or stroke paints
/// overlapping copies twice (#5920).
fn paints_copies_apart(a: &Appearance, rule: FillRule) -> bool {
let mut painting = a.items.iter().filter(|i| crate::paints(i));
let (Some(one), None) = (painting.next(), painting.next()) else {
// None paints (nothing to draw either way), or several do.
return a.items.iter().any(crate::paints);
};
one.opacity() < 1.0 || one.blend() != Default::default() || (one.is_fill() && rule != FillRule::NonZero)
}
/// Is `n` a path or compound path with a visible Transform effect that makes copies? Expand
/// Appearance makes each copy an object of its own ([`expand_outlined`]).
pub fn has_transform_copies(n: &Node) -> bool {
@@ -77,10 +102,10 @@ fn reaches_appearance(e: &Effect) -> bool {
}
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
/// ([`has_gradient_copies`], [`has_transform_options`])? It is drawn, baked and expanded through
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`])? It is drawn, baked and expanded through
/// that art ([`reshape`]).
pub fn has_transform_art(n: &Node) -> bool {
has_gradient_copies(n) || has_transform_options(n)
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n)
}
/// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a
@@ -636,7 +661,12 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
// Transform Patterns and Scale Strokes & Effects change each copy's fills and
// strokes; a gradient paints each copy by itself, not the one piece the copies
// make together; and Expand Appearance (`apart`) makes each copy an object.
let separate = copies > 0 && (apart || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient());
// Fills and strokes that stack paint each copy above the one before (#5920).
let separate = copies > 0
&& (apart
|| leaf.appearance.has_unplaced_gradient()
|| leaf.appearance.has_placed_gradient()
|| paints_copies_apart(&leaf.appearance, rule));
if options.reach_appearance() {
let made = transform_leaf(leaf, &path, map, copies, options, room);
used = used.minus(before).plus(made);
+137 -35
View File
@@ -155,18 +155,87 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
crate::lighting::validate(p)?;
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
let (path, rule) =
profile(n).ok_or_else(|| format!("{label} currently requires a path or compound path. Convert type, images and groups to paths first."))?;
let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
if let Some(v) = p.get("bevel")
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
{
let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect();
return Err(format!("bevel must be none or one of {}", names.join(", ")));
}
if is_container(n) {
let shapes = members(n, label)?;
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
return shapes.iter().try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()));
}
let (path, rule) = profile(n).ok_or_else(|| {
format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.")
})?;
let b = path.bounds().ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
facets(id, &path, rule, b, p).map(|_| ())
}
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
/// it, and the opacity of the objects it is in (1 for the object with the effect itself).
struct Profile {
path: PathData,
rule: FillRule,
items: Vec<AppearanceItem>,
opacity: f32,
}
/// Is `n` a group or layer (a 3D effect on it turns its members about one shared axis)?
fn is_container(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })
}
/// The bounds of every shape together: the centre a group's members turn about.
fn union_bounds(shapes: &[Profile]) -> Option<Rect> {
shapes.iter().filter_map(|s| s.path.bounds()).reduce(|a, c| a.union(c))
}
/// The most members a 3D effect on a group builds solids from.
const MAX_MEMBERS: usize = 4096;
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
/// compound path and type in it, at any depth of its groups, each through its own geometry
/// effects and painted with its own fills and strokes. Like the effect on a group in the
/// reference app, they turn about one shared axis (the centre of their bounds together) rather
/// than each about its own. An error names what the group holds that can't become a solid.
fn members(n: &Node, label: &str) -> Result<Vec<Profile>, String> {
fn walk(n: &Node, opacity: f32, label: &str, out: &mut Vec<Profile>) -> Result<(), String> {
for c in n.children().into_iter().flatten() {
if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) {
continue;
}
let opacity = opacity * c.opacity;
if is_container(c) {
walk(c, opacity, label, out)?;
continue;
}
let Some((path, rule)) = profile(c) else {
let what = match &c.kind {
NodeKind::Group { clip: true, .. } => "clipping groups",
NodeKind::Image(_) => "images",
NodeKind::SymbolInstance { .. } => "symbol instances",
NodeKind::Path { clipping: true, .. } => "clipping paths",
_ => "objects other than paths, compound paths and type",
};
return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first."));
};
if out.len() >= MAX_MEMBERS {
return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects"));
}
let path = geometry(&path, &c.appearance.effects, &GeomContext::of(c));
if path.bounds().is_some() {
out.push(Profile { path, rule, items: solid_paints(c), opacity });
}
}
Ok(())
}
let mut out = vec![];
walk(n, 1.0, label, &mut out)?;
Ok(out)
}
/// Can 3D effect `id` (Revolve included, [`is_three_d`]) with parameters `p` draw `n`? Checked
/// before a command changes the document: Revolve by [`crate::validate_revolve`], the others by
/// [`validate_solid`].
@@ -226,10 +295,11 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
fn paint_of(item: &AppearanceItem) -> (Paint, f32, BlendMode) {
/// `item`'s paint, its opacity times `member` (the opacity of the objects it is in) and its blend.
fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
match item {
AppearanceItem::Fill(f) => (f.paint.clone(), f.opacity, f.blend),
AppearanceItem::Stroke(s) => (s.paint.clone(), s.opacity, s.blend),
AppearanceItem::Fill(f) => (f.paint.clone(), f.opacity * member, f.blend),
AppearanceItem::Stroke(s) => (s.paint.clone(), s.opacity * member, s.blend),
}
}
@@ -249,46 +319,50 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where
/// depths tie, as for the caps turned toward the viewer, in the order of the appearance);
/// otherwise each solid is a surface of its own, in that order.
fn art_for(n: &Node, fx: &Effect, path: &PathData, rule: FillRule, items: &[&AppearanceItem]) -> Option<Vec<Arc<Node>>> {
let b = path.bounds()?;
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let colored = view_options(&p).has_colored_lights();
if fx.id == ROTATE {
// Every part turns about the centre of the object's own bounds, so they stay together.
// Every part turns about the centre of the object's own bounds (a group's members about
// the centre of theirs), so they stay together.
let mut out = vec![];
for item in items {
let (paint, opacity, blend) = paint_of(item);
let (area, rule) = region(path, rule, item);
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
out.push(Arc::new(surface(n, f, &paint, opacity, blend, colored)));
for s in shapes {
for item in &s.items {
let (paint, opacity, blend) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
out.push(Arc::new(surface(n, f, &paint, opacity, blend, colored)));
}
}
return Some(out);
}
let top_fill = items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
let parts: Vec<(&AppearanceItem, PathData, FillRule)> = items
// Each shape's top fill and its strokes, a group's members from the back up.
let parts: Vec<(&AppearanceItem, f32, PathData, FillRule)> = shapes
.iter()
.enumerate()
.filter(|(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_)))
.map(|(_, i)| {
let (area, rule) = region(path, rule, i);
(*i, area, rule)
.flat_map(|s| {
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| {
let (area, rule) = region(&s.path, s.rule, i);
(i, s.opacity, area, rule)
})
})
.collect();
// The solids share the bounds of all their shapes: one center to turn, twist and taper about,
// and Inflate's grid reaches over the strokes' outlines.
let bounds = parts.iter().filter_map(|(_, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(b);
let bounds = parts.iter().filter_map(|(_, _, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(b);
let built = if fx.id == INFLATE {
// One eye for every puff, as far away as the highest needs.
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, area, rule)| (area, *rule)).collect();
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
} else {
parts.iter().map(|(_, area, rule)| facets(&fx.id, area, *rule, bounds, &p)).collect()
parts.iter().map(|(_, _, area, rule)| facets(&fx.id, area, *rule, bounds, &p)).collect()
};
let mut solids = vec![];
for ((item, _, _), f) in parts.iter().zip(built) {
for ((item, opacity, _, _), f) in parts.iter().zip(built) {
let item: &AppearanceItem = item;
match f {
Ok(f) => solids.push((item, f)),
Ok(f) => solids.push((item, *opacity, f)),
// A stroke's outline past the limits is left out; the fill's solid still draws.
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
// A loaded file or a shape edited past the limits keeps drawing its source path
@@ -300,15 +374,15 @@ fn art_for(n: &Node, fx: &Effect, path: &PathData, rule: FillRule, items: &[&App
if solids.is_empty() {
return None;
}
let opaque = solids.iter().all(|(item, _)| {
let (_, opacity, blend) = paint_of(item);
let opaque = solids.iter().all(|(item, member, _)| {
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let surfaces: Vec<(Vec<f64>, Node)> = solids
.into_iter()
.map(|(item, f)| {
.map(|(item, member, f)| {
let depths: Vec<f64> = f.iter().map(|f| f.depth).collect();
let (paint, opacity, blend) = paint_of(item);
let (paint, opacity, blend) = paint_of(item, member);
(depths, surface(n, f, &paint, opacity, blend, colored))
})
.collect();
@@ -338,19 +412,23 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// `n` drawn with its Extrude & Bevel, Inflate or Rotate effect: a group of shaded faces keeping
/// the object's id and transparency, the source path untouched. `None` without such an effect.
/// On a group or layer the effect builds a solid from each path, compound path and type in it,
/// all turned about one shared axis ([`members`]).
pub fn solid_art(n: &Node) -> Option<Node> {
if !has_solid(n) {
return None;
}
if is_container(n) {
return group_solid_art(n);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
let painted: Vec<&AppearanceItem> = paints.iter().collect();
let mut children = vec![];
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
children.extend(art_for(n, fx, &path, rule, &painted)?);
children.extend(art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0 }])?);
// Later geometry effects act on the projected art as a whole.
remaining = n
.appearance
@@ -363,16 +441,16 @@ pub fn solid_art(n: &Node) -> Option<Node> {
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
for item in &painted {
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
for mut art in art_for(n, fx, &p, rule, &[*item])? {
for mut art in art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }])? {
Arc::make_mut(&mut art).appearance.effects =
item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
children.push(art);
}
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![(*item).clone()], ..Default::default() })));
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
}
}
}
@@ -382,5 +460,29 @@ pub fn solid_art(n: &Node) -> Option<Node> {
Some(art)
}
/// [`solid_art`] of group or layer `n`: its object-level 3D effect on its members together. The
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
/// group's own fills or strokes, or when its members can't become solids.
fn group_solid_art(n: &Node) -> Option<Node> {
let (index, fx) = solid(&n.appearance.effects)?;
let mut shapes = members(n, "").ok()?;
let before = n.appearance.effects.get(..index)?;
if before.iter().any(|e| e.visible && is_geometry(&e.id)) {
let b = union_bounds(&shapes)?;
let ctx = GeomContext::of(n);
for s in &mut shapes {
s.path = apply_geometry_with(before, &s.path, b, &ctx);
}
}
let children = art_for(n, fx, &shapes)?;
let remaining =
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
Some(art)
}
#[cfg(test)]
mod tests;
+57 -2
View File
@@ -462,8 +462,8 @@ fn parameters_are_validated_and_lengths_scale_with_the_object() {
let n = square_node();
assert!(validate_solid(&n, EXTRUDE, &json!({"bevel": "rounded", "depth": 80})).is_ok());
assert!(validate_solid(&n, EXTRUDE, &json!({"bevel": "fancy"})).unwrap_err().contains("bevel must be"));
let text = Node::group(NodeId(2), vec![]);
assert!(validate_solid(&text, INFLATE, &json!({})).unwrap_err().contains("requires a path"));
let empty = Node::group(NodeId(2), vec![]);
assert!(validate_solid(&empty, INFLATE, &json!({})).unwrap_err().contains("requires a group holding a shape"));
for (id, key) in [(EXTRUDE, "depth"), (EXTRUDE, "bevelWidth"), (EXTRUDE, "bevelHeight"), (INFLATE, "depth")] {
assert!(crate::is_length(id, key, false), "{id} {key}");
}
@@ -540,3 +540,58 @@ fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
assert_eq!(clips, surfaces);
assert_eq!(groups, 1 + 6 * surfaces, "group count must not grow with triangle count");
}
/// `square_node` moved right by `dx`, with id `id` and fill `fill`.
fn square_at(id: u64, dx: f64, fill: Color) -> Node {
let mut n = square_node();
n.id = NodeId(id);
n.transform(Affine::translate((dx, 0.0)), false);
n.appearance.items = Appearance::basic(Paint::solid(fill), Paint::None, 0.0).items;
n
}
#[test]
fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() {
// Two squares side by side, 100 pt apart, in a group: 100–200 and 300–400 across.
let group = |id: &str, params: Value| {
let mut g = Node::group(NodeId(9), vec![Arc::new(square_at(1, 0.0, RED)), Arc::new(square_at(2, 200.0, BLUE))]);
g.appearance.effects.push(fx(id, params));
g
};
let turned = json!({"rotationX": 0, "rotationY": 60, "rotationZ": 0});
for id in SOLIDS {
let g = group(id, json!({}));
assert!(validate_solid(&g, id, &json!({})).is_ok(), "{id}");
let art = solid_art(&g).unwrap_or_else(|| panic!("{id}"));
assert_eq!(art.id, NodeId(9), "{id}: the art is the group's");
assert!(art.appearance.effects.iter().all(|e| !is_three_d(&e.id)), "{id}");
// Both members draw, each in its own fill.
let mut colours = vec![];
art.walk(&mut |c| {
if c.path_data().is_some() {
colours.push(fill_rgb(c));
}
});
assert!(colours.iter().any(|c| c[2] > c[0]) && colours.iter().any(|c| c[0] > c[2]), "{id}: red and blue faces");
}
// Turned 60° about y, the members turn together about the group's centre (x = 250): the
// pair spans half its width; turned each about its own centre they would stay 100 pt apart.
let b = solid_art(&group(ROTATE, turned.clone())).unwrap().visual_bounds().unwrap();
assert!((b.center().x - 250.0).abs() < 1e-3, "{b:?}");
assert!((b.width() - 300.0 * 0.5).abs() < 1.0, "{b:?}");
let mut alone = square_at(2, 200.0, BLUE);
alone.appearance.effects.push(fx(ROTATE, turned));
let own = solid_art(&alone).unwrap().visual_bounds().unwrap();
assert!((own.center().x - 350.0).abs() < 1e-3, "{own:?}");
// Hidden members and guides are left out; a group holding what can't become a solid is
// refused with what to do.
let mut g = group(EXTRUDE, json!({}));
let mut clip = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]);
clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true };
if let NodeKind::Group { children, .. } = &mut g.kind {
children.push(Arc::new(clip));
}
let err = validate_solid(&g, EXTRUDE, &json!({})).unwrap_err();
assert!(err.contains("clipping groups"), "{err}");
assert!(solid_art(&g).is_none(), "drawn as the group it is");
}
+10 -1
View File
@@ -19,7 +19,7 @@ mod width;
use std::borrow::Cow;
use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Shape};
use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Rect, Shape};
use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign, StrokeLayer};
pub(crate) use vectorcraft_geom::bez::{kink, segments, subpaths, tangent, unit};
@@ -120,6 +120,15 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B
}
}
/// The variable-width outline near `near`, with its profile positions measured on the whole
/// undashed line. Returns `None` when no segment is omitted or the stroke is dashed.
pub fn line_outline_profile_near(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64, near: Rect) -> Option<BezPath> {
if st.dash.is_some() || line.elements().is_empty() || width <= 0.0 || !width.is_finite() {
return None;
}
width::width_outline_near(line, width, st.profile.as_ref()?, st, tol, near)
}
/// [`line_outline`] of a dashed line without a width profile, made of only the dashes and dots on
/// the segments of `line` that `keep` accepts ([`dash_kept`]). `None` when `st` has no dash
/// pattern or has a width profile, or when its pattern draws the line solid.
+14 -3
View File
@@ -174,10 +174,21 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64,
}
let steps = if max_dt < 1.0 { (1.0 / max_dt).ceil() as usize } else { 1 };
let profile = st.profile.iter().flat_map(|p| p.points.iter().map(|q| q.0));
let at: Vec<f64> =
marks.iter().copied().chain(profile).chain((1..steps).map(|i| i as f64 / steps as f64)).map(|t| t * total).collect();
let heads = if closed { (0.0, 0.0) } else { heads };
// Where an arrowhead's reach ends gets a rib of its own, so the ribs that reach
// across a head run all the way there instead of narrowing towards the next corner
// from the head's tip, which leaves the corners of its base outside (#5964).
let head_ends = [heads.0, total - heads.1].into_iter().filter(|&s| s > 0.0 && s < total);
let at: Vec<f64> = marks
.iter()
.copied()
.chain(profile)
.chain((1..steps).map(|i| i as f64 / steps as f64))
.map(|t| t * total)
.chain(head_ends)
.collect();
let (pts, _) = split_at(&pts, &corner, closed, &at);
strip(&lay, &pts, closed, total, side, if closed { (0.0, 0.0) } else { heads })
strip(&lay, &pts, closed, total, side, heads)
}
};
out.push(ribs);
+49 -4
View File
@@ -225,20 +225,23 @@ fn expand_stroke_region_of_a_round_line_stays_compact() {
assert_eq!(dense_anchors, anchors, "colinear spine points should not add outline anchors");
}
/// A line's outline takes its width profile, its dashes (each reading the profile where it sits) or neither.
#[test]
fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() {
let l = line(0.0, 100.0);
let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3);
assert!(near(plain.area().abs(), 1000.0, 1e-6));
let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3);
assert!(near(lens.area().abs(), 500.0, 1e-6));
// Each dash takes its widths from where it sits along the lens (0 → 1 → 0): the dash over
// 0..25 averages a quarter of the width, the one over 50..75 three quarters.
// The lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714).
assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05));
// Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens
// rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers
// its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192.
let st = stroke(10.0, |s| {
s.profile = Some(WidthProfile::lens());
s.dash = Some(dashed(&[25.0, 25.0], 0.0));
});
assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 62.5 + 187.5, 1e-6));
assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05));
assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty());
}
@@ -501,3 +504,45 @@ fn a_stroke_narrower_than_the_shape_keeps_its_hole() {
assert_eq!(moves(&outline), 3, "{join:?}: two contours for the ring, one for the blob");
}
}
/// A subpixel stroke must retain its geometric thickness even when the normal display tolerance
/// is close to its weight. Original uneven circular arcs, independent of any user fixture.
#[test]
fn thin_curved_strokes_keep_their_width_between_notches() {
use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Shape};
for (radius, degrees) in [(450.0, 47.0_f64), (438.0, 77.0), (450.0, 54.0)] {
let a = degrees.to_radians();
let k = 4.0 / 3.0 * (a / 4.0).tan();
let curve = CubicBez::new(
(radius, 0.0),
(radius, k * radius),
(radius * a.cos() + k * radius * a.sin(), radius * a.sin() - k * radius * a.cos()),
(radius * a.cos(), radius * a.sin()),
);
let mut line = BezPath::new();
line.move_to(curve.p0);
line.curve_to(curve.p1, curve.p2, curve.p3);
for width in [0.25, 1.0 / 3.0, 0.5, 1.0] {
let st = StrokeLayer::new(Paint::solid(Color::BLACK), width);
let outline = line_outline(&line, &st, width, 0.25);
for step in 1..40 {
let t = step as f64 / 40.0;
let p = curve.eval(t);
let tangent = curve.deriv().eval(t).to_vec2().normalize();
let normal = kurbo::Vec2::new(-tangent.y, tangent.x);
for side in [-1.0, 1.0] {
assert_ne!(
outline.winding(p + normal * (side * width * 0.45)),
0,
"missing inner band at radius {radius}, {degrees} degrees, width {width}, t {t}"
);
assert_eq!(
outline.winding(p + normal * (side * width * 0.55)),
0,
"outside intended band at radius {radius}, {degrees} degrees, width {width}, t {t}"
);
}
}
}
}
}
+29 -3
View File
@@ -117,6 +117,7 @@ fn along_keeps_a_corners_colour_round_its_outside() {
assert!((param(&sl, Point::new(95.0, 8.0)).unwrap() - 0.54).abs() < 1e-6);
}
/// An Across stroke gradient runs from the stroke's left edge to its right edge, also where a width profile moves them.
#[test]
fn across_runs_from_the_left_edge_to_the_right() {
let st = stroke(10.0, StrokeGradientMode::Across);
@@ -137,8 +138,9 @@ fn across_runs_from_the_left_edge_to_the_right() {
let mut lens = st.clone();
lens.profile = Some(WidthProfile::lens());
let sl = slices(&line, &lens);
// A quarter of the way along, the lens is half as wide: its top edge is 2.5 up.
assert!(param(&sl, Point::new(25.0, -2.4)).unwrap() < 0.05);
// A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is
// 3.125 up.
assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05);
assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02);
}
@@ -162,6 +164,7 @@ fn an_aligned_stroke_spans_the_gradient_across_the_side_it_shows_on() {
}
}
/// The gradient slices cover every point the stroke paints, with each join, caps, arrowheads, a profile and dashes.
#[test]
fn slices_cover_everything_the_stroke_paints() {
let zig = poly(&[(0.0, 0.0), (60.0, 40.0), (0.0, 80.0), (70.0, 90.0), (75.0, 20.0)], false);
@@ -182,7 +185,9 @@ fn slices_cover_everything_the_stroke_paints() {
assert_covered(&zig, &st);
st.arrow_align = ArrowAlign::Tip;
assert_covered(&curve, &st);
st.profile = WidthProfile::preset("wave");
// Teardrop, not Wave: with most profiles a dash across the zigzag's sharp corner
// paints outside every slice (#5964). Back to Wave once that is fixed.
st.profile = WidthProfile::preset("teardrop");
st.dash = Some(Dash { pattern: vec![12.0, 6.0], ..Default::default() });
assert_covered(&zig, &st);
st.align = StrokeAlign::Outside;
@@ -211,3 +216,24 @@ fn meshes_colour_the_stroke_as_the_slices_do() {
}
}
}
/// #5964: with ribs only at the path's corners (an Along gradient), an arrowhead whose tip sits on
/// the end of a long straight leg is covered all the way to where it can reach: the ribs that
/// reach across it run to the end of its reach, rather than narrowing from its tip towards the
/// next corner and leaving the corners of its base outside.
#[test]
fn slices_cover_an_arrowhead_on_a_long_straight_leg() {
let zig = poly(&[(0.0, 0.0), (60.0, 40.0), (0.0, 80.0), (70.0, 90.0), (75.0, 20.0)], false);
for profile in [None, WidthProfile::preset("lens"), WidthProfile::preset("taperStart")] {
for align in [ArrowAlign::Tip, ArrowAlign::Extend] {
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
let mut st = stroke(12.0, mode);
st.start_arrow = Some(Arrowhead::Triangle);
st.end_arrow = Some(Arrowhead::Triangle);
st.arrow_align = align;
st.profile = profile.clone();
assert_covered(&zig, &st);
}
}
}
}
+152 -9
View File
@@ -10,7 +10,7 @@
use std::f64::consts::PI;
use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Vec2};
use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Rect, Vec2};
use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile};
use super::{kink, segments, subpaths, unit};
@@ -21,6 +21,70 @@ pub fn width_outline(bp: &BezPath, width: f64, profile: &WidthProfile, st: &Stro
outline_spans(bp, &[], width, profile, st, tol)
}
/// Outline only flattened segments near `near`, retaining each run's original fractions of its
/// whole subpath for the width profile. `None` means no segments could be omitted.
pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64, near: Rect) -> Option<BezPath> {
let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) };
let mut out = BezPath::new();
let mut cut = false;
for (r, closed) in subpaths(bp) {
if closed {
return None;
}
let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol);
let n = pts.len();
if n < 2 {
continue;
}
let count = n - 1;
let mut lengths = Vec::with_capacity(count);
let mut kept = Vec::with_capacity(count);
let mut total = 0.0;
for i in 0..count {
let (a, b) = (pts[i], pts[i + 1]);
let len = a.distance(b);
if !len.is_finite() {
return None;
}
total += len;
lengths.push(len);
kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1));
}
if kept.iter().all(|v| *v) {
ctx.subpath(&mut out, &pts, &corner, closed, (0.0, 1.0));
continue;
}
cut = true;
if total <= 1e-12 {
continue;
}
let mut walked = 0.0;
let mut run = Vec::new();
let mut run_corner = Vec::new();
let mut from = 0.0;
for i in 0..count {
if kept[i] {
if run.is_empty() {
from = walked / total;
run.push(pts[i]);
run_corner.push(corner[i]);
}
run.push(pts[i + 1]);
run_corner.push(corner[i + 1]);
} else if run.len() > 1 {
ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total));
run.clear();
run_corner.clear();
}
walked += lengths[i];
}
if run.len() > 1 {
ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total));
}
}
cut.then_some(out)
}
/// [`width_outline`] of pieces of longer subpaths: subpath `i` of `bp` covers the fractions
/// `spans[i]` of the subpath it was cut from (see [`Dashed::spans`](super::Dashed::spans));
/// subpaths without a span are whole.
@@ -86,17 +150,56 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec<Point>,
(pts, corner)
}
/// Insert samples where the profile has width points (so the piecewise-linear profile is exact
/// along straight runs; the two points of a discontinuous point share one sample). `span` maps the
/// subpath onto the profile (see [`outline_spans`]).
fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64)) -> (Vec<Point>, Vec<bool>) {
/// The most samples added between two width points.
const MAX_SPAN_SAMPLES: usize = 64;
/// The most samples [`densify`] adds between width points along one piece of a subpath.
const MAX_CURVE_SAMPLES: usize = 4096;
/// Insert samples where the profile has width points (the two points of a discontinuous point
/// share one sample), and between them where the profile's curve ([`WidthProfile::at`]) bends, so
/// that a straight run follows it to within `tol` with a stroke of half width `half`. `span` maps
/// the subpath onto the profile (see [`outline_spans`]).
fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64), half: f64, tol: f64) -> (Vec<Point>, Vec<bool>) {
let total = length(pts, closed);
let range = span.1 - span.0;
if total <= 1e-12 || range <= 1e-12 {
return (pts.to_vec(), corner.to_vec());
}
let along = |t: f64| (t - span.0) / range * total;
// Where the profile's points fall along this piece (a span past 1 wraps round a closed path).
let marks: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(|t| (t - span.0) / range * total).collect();
let mut marks: Vec<f64> = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(along).collect();
let mut added = 0;
for shift in [0.0, 1.0] {
for w in profile.points.windows(2) {
let (a, b) = (&w[0], &w[1]);
let (t0, t1) = (a.0 + shift, b.0 + shift);
if t1 - t0 <= 1e-7 || t1 <= span.0 || t0 >= span.1 {
continue;
}
// A span whose curve is the straight line between its points (a two-point taper,
// points on one line) needs nothing between them. A cubic off the line is off it at a
// quarter or three quarters of the way.
let off_line = |u: f64| {
let (l, r) = profile.at(a.0 + (b.0 - a.0) * u);
half * (l - (a.1 + (b.1 - a.1) * u)).abs().max((r - (a.2 + (b.2 - a.2) * u)).abs())
};
if off_line(0.25) <= tol * 1e-3 && off_line(0.75) <= tol * 1e-3 {
continue;
}
// A monotone cubic span bends by at most 12 times its change in width over the span
// squared, so the chords of `n` equal parts stray at most 1.5 · change / n² from it.
let change = half * (b.1 - a.1).abs().max((b.2 - a.2).abs());
let n = (1.5 * change / tol).sqrt().ceil();
let n = if n.is_finite() { n.clamp(1.0, MAX_SPAN_SAMPLES as f64) as usize } else { MAX_SPAN_SAMPLES };
for k in 1..n {
if added >= MAX_CURVE_SAMPLES {
break;
}
marks.push(along(t0 + (t1 - t0) * k as f64 / n as f64));
added += 1;
}
}
}
split_at(pts, corner, closed, &marks)
}
@@ -161,7 +264,7 @@ struct Vertex {
impl Ctx<'_> {
fn subpath(&self, out: &mut BezPath, pts: &[Point], corner: &[bool], closed: bool, span: (f64, f64)) {
let (pts, corner) = densify(pts, corner, closed, self.profile, span);
let (pts, corner) = densify(pts, corner, closed, self.profile, span, self.half, self.tol);
let n = pts.len();
let seg_count = if closed { n } else { n - 1 };
let seg_dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();
@@ -320,10 +423,13 @@ mod tests {
assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6);
}
/// The Lens outline swells on its curve, and a profile with one side at zero paints only the other side.
#[test]
fn lens_profile_is_a_diamond_and_one_sided_profiles_stay_on_their_side() {
fn lens_profile_swells_smoothly_and_one_sided_profiles_stay_on_their_side() {
// Each half of the lens rises on a cubic from 0 to full width, flat at the middle: it
// covers 7/12 of the full-width band (a diamond would cover half).
let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01));
assert!((a - 500.0).abs() < 1e-6, "{a}");
assert!((a - 1000.0 * 7.0 / 12.0).abs() < 0.5, "{a}");
let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] };
let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01);
assert!((area(&o) - 500.0).abs() < 1e-6);
@@ -347,6 +453,43 @@ mod tests {
assert!(a.is_finite() && (a - 3000.0).abs() < 150.0, "{a}");
}
/// #5714: between width points a straight run follows the profile's smooth curve, not a
/// straight line from one width to the next.
#[test]
fn a_straight_run_follows_the_curve_between_width_points() {
// 5 pt either side at the ends, 15 pt at the middle: a quarter of the way along the curve
// is at 2.25 × 5 = 11.25 pt (a straight ramp would be at 10 pt).
let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 3.0), (1.0, 1.0, 1.0)] };
let o = width_outline(&line(), 10.0, &p, &capped(LineCap::Butt), 0.01);
for y in [-11.0, 11.0] {
assert!(o.contains(kurbo::Point::new(25.0, y)), "inside at y {y}");
}
for y in [-11.5, 11.5] {
assert!(!o.contains(kurbo::Point::new(25.0, y)), "outside at y {y}");
}
// Round the widest point the side is flat: no corner sticks out above 15 pt.
let bb = o.bounding_box();
assert!((bb.y0 + 15.0).abs() < 1e-6 && (bb.y1 - 15.0).abs() < 1e-6, "{bb:?}");
}
/// A taper is a straight ramp: its outline gets no samples between the width points.
#[test]
fn a_straight_taper_gets_no_samples_between_its_points() {
let o = width_outline(&line(), 10.0, &WidthProfile::taper_end(), &capped(LineCap::Butt), 0.01);
assert_eq!(o.elements().len(), 5, "{:?}", o.elements());
}
/// A profile read from a file may have thousands of points and absurd widths: the samples added
/// between them stay bounded and the outline finite.
#[test]
fn samples_between_width_points_are_capped() {
let points = (0..=10_000).map(|i| (i as f64 / 10_000.0, if i % 2 == 0 { 0.0 } else { 1e12 }, 1.0)).collect();
let o = width_outline(&line(), 10.0, &WidthProfile { points }, &capped(LineCap::Butt), 0.01);
let n = o.elements().len();
assert!(n < 2 * (2 * 10_001 + MAX_CURVE_SAMPLES) + 64, "{n}");
assert!(o.bounding_box().area().is_finite());
}
#[test]
fn closed_paths_make_a_ring() {
let mut sq = BezPath::new();
+43
View File
@@ -384,3 +384,46 @@ fn a_strokes_own_transform_leaves_room_for_a_fill_above_it() {
assert_eq!(stroked_leaves(&art).len(), 2, "{cost:?}");
assert!(Budget::EFFECTS.fits(cost), "{cost:?}");
}
/// A 100 pt square at the origin painted with `fill` and a 1 pt white stroke, with the Transform
/// effect `params`.
fn filled_and_stroked(fill: Paint, params: Value) -> Node {
let mut n = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(fill, Paint::solid(Color::WHITE), 1.0));
n.appearance.effects.push(transform(params));
n
}
#[test]
fn copies_with_a_fill_and_a_stroke_are_drawn_one_above_another() {
// Black fill, white stroke, each copy scaled and turned (#5920): each copy is an object of its
// own above the one before, so its fill covers the strokes of the copies below.
let params = json!({"scaleH": 97, "scaleV": 97, "rotate": 10, "copies": 25});
let n = filled_and_stroked(Paint::solid(Color::BLACK), params.clone());
assert!(has_transform_art(&n));
let art = reshape(None, &n, None).unwrap();
let paths = leaves(&art);
assert_eq!(paths.len(), 26, "the original and 25 copies");
for p in &paths {
assert!(matches!(p.kind, NodeKind::Path { .. }), "one shape each, not one path of every copy");
assert!(!p.appearance.fill_paint().is_none() && p.appearance.stroke().is_some());
}
// The original is at the bottom, the smallest copy on top.
assert_eq!(paths[0].geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0));
let top = paths[25].geometric_bounds().unwrap();
assert!(top.width() < 100.0 && top.height() < 100.0, "{top:?}");
// Drawn as Expand Appearance makes it.
assert_eq!(leaves(&expand_outlined(None, &n, None).unwrap()).len(), 26);
// One opaque stroke, or one nonzero fill, paints the copies alike as one path: no art.
assert!(!has_transform_art(&filled_and_stroked(Paint::None, params.clone())));
let mut fill_only = filled_and_stroked(Paint::solid(Color::BLACK), params.clone());
fill_only.appearance.items.retain(AppearanceItem::is_fill);
assert!(!has_transform_art(&fill_only));
// A partly transparent fill paints where copies overlap twice.
if let Some(AppearanceItem::Fill(f)) = fill_only.appearance.items.first_mut() {
f.opacity = 0.5;
}
assert!(has_transform_art(&fill_only));
// No copies: nothing to stack.
assert!(!has_transform_art(&filled_and_stroked(Paint::solid(Color::BLACK), json!({"rotate": 10}))));
}
+11
View File
@@ -168,6 +168,17 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
}
/// A path is selected, or inside a selected group or compound path: Object › Path's items that
/// work on paths (not on text, images or other objects alone).
pub fn has_selected_path(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
let st = s.active().ok_or("no document open")?;
// Stops at the first path: menus ask this every frame, and a selected group can hold many.
fn holds_path(n: &vectorcraft_doc::Node) -> bool {
matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, .. }) || n.children().is_some_and(|c| c.iter().any(|c| holds_path(c)))
}
if st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(holds_path) { Ok(()) } else { Err("select a path".into()) }
}
/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take).
pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> {
if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) }
+2
View File
@@ -9,6 +9,7 @@ mod document;
mod pathtools;
mod pen;
mod select;
mod shapes;
mod typetools;
use super::CommandSpec;
@@ -23,6 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(select::specs());
v.extend(shapes::specs());
v.extend(typetools::specs());
v
}
+71 -22
View File
@@ -13,7 +13,7 @@ use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
use crate::cmd::textedit::editing_range;
use crate::cmd::textedit::{editing_range, editing_story};
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{EngineError, Result, Session};
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Breaks",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}",
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
has_selection,
remove_breaks
),
@@ -730,12 +730,11 @@ fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "joined": joined, "lines": count }))
}
/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many
/// went.
fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
let text = t.plain_text();
let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b));
let Some(range) = text.get(a..b) else { return 0 };
/// The breaks `brk` in bytes `a..b` of `text`, each with whether it becomes a space (it is between
/// two words).
fn break_cuts(text: &str, a: usize, b: usize, brk: char) -> Vec<(usize, bool)> {
let (a, b) = (edit::floor_char(text, a), edit::floor_char(text, b));
let Some(range) = text.get(a..b) else { return vec![] };
let mut prev = text.get(..a).and_then(|s| s.chars().next_back());
let mut cuts = vec![];
for (i, c) in range.char_indices() {
@@ -753,6 +752,12 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
}
cuts.push((at, space));
}
cuts
}
/// Remove the breaks `brk` at the bytes of `cuts` from `t`, each one that `cuts` marks becoming a
/// space → how many went.
fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
for &(at, space) in cuts.iter().rev() {
let insert = if space { " " } else { "" };
let end = at + brk.len_utf8();
@@ -763,6 +768,30 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize {
cuts.len()
}
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
/// comes with its own breaks, at its own bytes.
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
// The breaks in story order, handed to the frames in one pass.
let mut cuts = break_cuts(&joined, 0, joined.len(), brk).into_iter().peekable();
let mut out = vec![];
let mut start = 0;
for (id, text) in texts {
let end = start + text.len();
let mut own = vec![];
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
own.push((at - start, space));
}
if d.is_editable(id) {
out.push((id, own));
}
start = end;
}
out
}
fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.removeBreaks";
let (brk, label, none) = match text_param(p, "kind", C)? {
@@ -771,21 +800,41 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))),
None => return Err(bad(C, "missing `kind`")),
};
// The characters a Type tool has selected, else all the text of the selected type.
// The characters a Type tool has selected (after Select All in threaded text, all the text of
// every frame of the story), else all the text of the selected type.
let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) };
let story = if editing.is_some() { editing_story(s) } else { vec![] };
let d = &s.doc()?.doc;
let targets: Vec<(NodeId, usize, usize)> = match editing {
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(),
None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(),
// Each type object with the breaks that go from it.
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
.into_iter()
.filter(|(id, ..)| d.is_editable(*id))
.filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk))))
.collect(),
None => {
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
// A threaded story whose frames are all among them is read as one text, once.
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let mut done = std::collections::HashSet::new();
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
for &id in &ids {
if !done.insert(id) {
continue;
}
let story = crate::cmd::threads::story_of(d, id);
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
done.extend(story.iter().copied());
out.extend(story_cuts(d, &story, brk));
} else if let Some(t) = text_of(d, id) {
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
}
}
out
}
};
let count: usize = targets
.iter()
.filter_map(|(id, a, b)| {
let text = text_of(d, *id)?.plain_text();
let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b));
Some(text.get(a..b)?.matches(brk).count())
})
.sum();
let count: usize = targets.iter().map(|(_, cuts)| cuts.len()).sum();
if count == 0 {
return Err(EngineError::Other(none.into()));
}
@@ -794,9 +843,9 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
}
let (removed, ids) = s.edit(label, |d, _| {
let (mut removed, mut ids) = (0, vec![]);
for (id, a, b) in targets {
for (id, cuts) in targets {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
let n = strip_breaks(t, a, b, brk);
let n = apply_cuts(t, &cuts, brk);
if n > 0 {
refresh_bounds(t);
removed += n;
+120 -6
View File
@@ -3,9 +3,10 @@
//! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
//! Swatch ([`nearest`]) matches colours to a swatch library's, and Create Swatch Legend
//! ([`legend`]) draws labelled chips of the document's swatches. Its panel and its submenu, Object ›
//! Plug-ins › Color Effects, are the UI's.
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu,
//! Object › Plug-ins › Color Effects, are the UI's.
pub mod legend;
mod nearest;
@@ -14,13 +15,14 @@ mod print_fixes;
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind};
use vectorcraft_render::effects;
use super::super::colorcmds::recolor_links;
use super::super::paint::{restore_unpainted_stroke, set_run_stroke};
use super::super::select::walk_selectable;
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, text_param};
use crate::{Result, Session};
use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, paint_targets, switch_or, text_param};
use crate::{EngineError, Result, Session};
/// The kinds Select by Color Kind selects (`addon.color.select`).
pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"];
@@ -72,6 +74,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
nearest::apply
),
cmd!(
"addon.color.fillToStroke",
"Apply Fill to Stroke",
["Object", "Plug-ins", "Color Effects"],
None,
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
has_doc,
|s, p| copy_paint(s, p, true)
),
cmd!(
"addon.color.strokeToFill",
"Apply Stroke to Fill",
["Object", "Plug-ins", "Color Effects"],
None,
"{ids?|id?, skipNone?: bool} each target's top fill takes its own top stroke's paint, as addon.color.fillToStroke does the other way; the stroke itself is unchanged. The default fill takes the default stroke → {objects}",
has_doc,
|s, p| copy_paint(s, p, false)
),
]
.into_iter()
.chain(legend::specs())
@@ -156,3 +176,97 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
let swatches = |name: &str| kinds.get(name).copied();
recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
}
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
/// paints onto the other, so a mixed selection keeps each object's colour (#5530). Aimed and
/// undone like Swap Fill and Stroke; characters selected with the Type tool are the only ones that
/// change, as for `paint.setFill`. A graph's series marks and labels give the graph the paint in
/// the same undo step, as `paint.setFill` does, so drawing the graph again keeps it. When nothing
/// changes, the document and its undo history stay as they are.
fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
let (cmd, label) =
if to_stroke { ("addon.color.fillToStroke", "Apply Fill to Stroke") } else { ("addon.color.strokeToFill", "Apply Stroke to Fill") };
let skip_none = switch_or(p, "skipNone", false, cmd)?;
// One text style: its stroke takes its fill, or the other way.
let copy_run = |st: &mut CharStyle| {
let from = if to_stroke { st.fill.clone() } else { st.stroke.clone() };
if (skip_none && from.is_none()) || from == if to_stroke { st.stroke.clone() } else { st.fill.clone() } {
return;
}
if to_stroke {
set_run_stroke(st, from);
} else {
st.fill = from;
}
};
if p.get("ids").is_none()
&& p.get("id").is_none()
&& let Some((id, a, b)) = super::super::textedit::editing_range(s)?
&& a != b
{
// After Select All in threaded text, every frame's text takes it.
let story = super::super::textedit::editing_story(s);
let ranges: Vec<(NodeId, usize, usize)> =
if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() };
let ids: Vec<NodeId> = ranges.iter().map(|(f, _, _)| *f).collect();
let before = s.doc()?.doc.clone();
let n = super::super::overprint::edit_counted(s, label, |d| {
for &(id, a, b) in &ranges {
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
vectorcraft_text::edit::style_range(&mut t.runs, a, b, copy_run);
super::super::typecmd::refresh_bounds(t);
}
Ok(super::super::appearance::count_changed(d, &before, &ids))
})?;
return Ok(json!({"objects": n}));
}
// A graph's series group stands for its marks, as for `paint.setFill`.
let ids = super::super::graph::paint_targets(&s.doc()?.doc, &paint_targets(s, p)?);
let mut objects = 0;
if !ids.is_empty() {
let before = s.doc()?.doc.clone();
super::super::overprint::edit_counted(s, label, |d| {
for id in &ids {
let Some(node) = d.node_mut(*id) else { continue };
if let NodeKind::Text(t) = &mut node.kind {
for r in &mut t.runs {
copy_run(&mut r.style);
}
super::super::typecmd::refresh_bounds(t);
continue;
}
let ap = &mut node.appearance;
let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) };
// A missing item reads as None: copying None onto it would add an item that
// changes nothing.
if (skip_none && from.is_none()) || from == to {
continue;
}
if to_stroke {
restore_unpainted_stroke(ap, None, &from);
ap.set_stroke(from);
} else {
ap.set_fill(from);
}
}
objects = super::super::appearance::count_changed(d, &before, &ids);
// The graph keeps the paint its series marks and labels now have.
let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke);
let labels = super::super::graph::capture_label_styles(d, &ids, &copy_run);
Ok(objects + usize::from(series || labels))
})?;
}
// The defaults for new art change the same way, as Swap Fill and Stroke changes them.
let from = if to_stroke { s.paint.fill.clone() } else { s.paint.stroke.clone() };
if !(skip_none && from.is_none()) {
if to_stroke {
if s.paint.stroke.is_none() && !from.is_none() && s.paint.stroke_width == 0.0 {
s.paint.stroke_width = 1.0;
}
s.paint.stroke = from;
} else {
s.paint.fill = from;
}
}
Ok(json!({"objects": objects}))
}
+1 -1
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch Trace Folder",
["Object", "Plug-ins", "Document Tools"],
None,
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
"{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as <name>.<ext> (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Optional settings use their defaults only when omitted; null and values of the wrong type return an error before any image is opened. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)",
always,
batch_trace::batch_trace_folder
),
@@ -8,9 +8,9 @@ use serde_json::json;
#[cfg(not(target_arch = "wasm32"))]
use super::super::super::fileio;
use super::super::super::{Result, Session, bad};
#[cfg(not(target_arch = "wasm32"))]
use super::super::super::{bool_or, str_param};
use super::super::super::str_param;
use super::super::super::{Result, Session, bad};
/// The command id.
pub(super) const ID: &str = "addon.document.batchTraceFolder";
@@ -69,20 +69,39 @@ fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec<String>) -> Resu
pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result<Value> {
let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?;
let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?;
let format = str_param(p, "format").unwrap_or("vectorcraft");
let format = match p.get("format") {
None => "vectorcraft",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(ID, "`format` must be a string")),
};
let preset = match p.get("preset") {
None => "Default",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(ID, "`preset` must be a string")),
};
let expand = match p.get("expand") {
None => false,
Some(Value::Bool(value)) => *value,
Some(_) => return Err(bad(ID, "`expand` must be true or false")),
};
let include_subdirs = match p.get("includeSubdirs") {
None => false,
Some(Value::Bool(value)) => *value,
Some(_) => return Err(bad(ID, "`includeSubdirs` must be true or false")),
};
if !FORMATS.contains(&format) {
return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", "))));
}
let preset = str_param(p, "preset").unwrap_or("Default").to_string();
let preset = preset.to_string();
let presets = s.execute("imageTrace.presets", &json!({}))?;
if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) {
return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)")));
}
let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
let trace = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
fileio::may_read(&folder)?;
fileio::may_write(&dest)?;
let mut files = vec![];
images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?;
images(&folder, include_subdirs, 0, &mut files)?;
files.sort();
if files.is_empty() {
return Err(bad(ID, "no images in the folder"));
@@ -333,6 +333,35 @@ fn batch_trace_folder_traces_and_saves_each_image() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Batch Trace Folder rejects optional values with the wrong type before opening images.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn batch_trace_folder_rejects_wrong_typed_options() {
const C: &str = "addon.document.batchTraceFolder";
let dir = folder("batch-trace-bad-options");
let src = dir.join("in");
let out = dir.join("out");
std::fs::create_dir_all(&src).unwrap();
let mut s = Session::new();
for (key, value) in [
("format", json!(42)),
("format", Value::Null),
("preset", json!(false)),
("preset", Value::Null),
("expand", json!("true")),
("expand", Value::Null),
("includeSubdirs", json!(1)),
("includeSubdirs", Value::Null),
] {
let mut params = json!({"folder": src, "destinationFolder": out});
params[key] = value;
let error = s.execute(C, &params).unwrap_err();
assert!(error.to_string().contains(&format!("`{key}`")), "{key}: {error}");
assert!(!out.exists(), "invalid options must not create a destination folder");
}
let _ = std::fs::remove_dir_all(&dir);
}
/// A folder too big to list in full is refused rather than traced in part.
#[cfg(not(target_arch = "wasm32"))]
#[test]
+147 -15
View File
@@ -1,33 +1,56 @@
//! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu
//! (Object › Plug-ins › Selection Tools) and dialog are the UI's.
//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by
//! Link Status selects the images and placed documents whose file is linked, embedded, missing or
//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins
//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's.
#[cfg(test)]
mod tests;
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::Point;
use super::super::select::{on_artboard, selectable};
use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param};
use crate::{Result, Session};
use super::super::links::{Status, statuses};
use super::super::select::{is_selectable, on_artboard, selectable};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
use crate::{DocState, Result, Session};
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"];
/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept
/// in the document, a file not found, a file changed since it was read.
pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"];
/// The add-on's commands: Select by Artboards and Select by Link Status.
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.select.byArtboards",
"Select by Artboards",
["Object", "Plug-ins", "Selection Tools"],
None,
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
has_doc,
by_artboards
)]
vec![
cmd!(
"addon.select.byArtboards",
"Select by Artboards",
["Object", "Plug-ins", "Selection Tools"],
None,
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
has_doc,
by_artboards
),
cmd!(
"addon.select.byLinkStatus",
"Select by Link Status",
["Object", "Plug-ins", "Selection Tools"],
None,
"{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}",
has_doc,
by_link_status
),
]
}
/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie
/// outside the chosen artboards.
fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.select.byArtboards";
let relation = text_param(p, "relation", C)?.unwrap_or("overlap");
@@ -61,3 +84,112 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
s.select(|_, sel| sel.set(ids))?;
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
/// The link statuses `p` asks for (`status`: one, or a list of them), each once.
fn link_statuses(p: &Value, cmd: &str) -> Result<Vec<&'static str>> {
let given: Vec<&Value> = match p.get("status") {
None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")),
Some(Value::Array(v)) => v.iter().collect(),
Some(v) => vec![v],
};
let mut out = vec![];
for v in given {
let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?;
let known =
LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?;
if !out.contains(known) {
out.push(*known);
}
}
if out.is_empty() {
return Err(bad(cmd, "choose at least one status"));
}
Ok(out)
}
/// The link status of every image object and placed document in the layers of `st`, as
/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is
/// looked at once.
pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> {
let linked = statuses(st);
let mut out = vec![];
st.doc.walk(|n| {
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) {
let status = match linked.get(&n.id).map(|(s, ..)| *s) {
Some(Status::Ok) => "linked",
Some(Status::Modified) => "modified",
Some(Status::Missing) => "missing",
None => "embedded",
};
out.push((n.id, status));
}
});
out
}
/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated
/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside
/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's
/// [`vectorcraft_doc::Document::locked_artboards`].
fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> {
let d = &st.doc;
if is_selectable(d, st.isolation, locks, id) {
return None;
}
let ancestry = d.ancestry(id).unwrap_or_default();
// Outside the isolated container, or the isolated container itself (its art is what's taken).
if let Some(c) = st.isolation.and_then(|i| d.node(i))
&& ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container())
{
return Some("isolation");
}
let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect();
Some(if held.iter().any(|n| n.is_template()) {
"template"
} else if held.iter().any(|n| !n.visible) {
"hidden"
} else {
// A locked object, group or layer, or the locked artboard that holds it.
"locked"
})
}
/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the
/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list
/// those left out with the reason ([`skip_reason`]).
fn by_link_status(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.select.byLinkStatus";
let wanted = link_statuses(p, C)?;
let add = switch_or(p, "add", false, C)?;
let zoom = switch_or(p, "zoom", false, C)?;
let only: Option<BTreeSet<NodeId>> = match p.get("ids") {
None | Some(Value::Null) => None,
Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()),
};
let st = s.doc()?;
let locks = st.doc.locked_artboards();
let (mut picked, mut skipped) = (vec![], vec![]);
for (id, status) in link_status_of_objects(st) {
if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) {
continue;
}
match skip_reason(st, &locks, id) {
None => picked.push(id),
Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })),
}
}
s.select(|_, sel| {
if add {
for id in &picked {
sel.add(*id);
}
} else {
sel.set(picked.iter().copied());
}
})?;
let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::<Vec<_>>(), "skipped": skipped });
if zoom {
out["zoom"] = json!(true);
}
Ok(out)
}
@@ -126,3 +126,185 @@ fn a_symbol_instance_is_measured_by_its_art() {
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]);
assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]);
}
/// Select by Link Status.
mod by_link_status {
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId};
use crate::Session;
use crate::tests_links::{BLUE, Folder, RED, place, png, session, write};
const C: &str = "addon.select.byLinkStatus";
/// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`),
/// one whose file goes (`missing`), an embedded one, and a placed document whose file goes
/// (missing too), bottom to top.
struct Links {
s: Session,
ok: NodeId,
modified: NodeId,
missing: NodeId,
embedded: NodeId,
document: NodeId,
_dir: Folder,
}
/// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two
/// removed.
fn links(name: &str) -> Links {
let dir = Folder::new(name);
let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft"));
write(&a, &png(10, 10, RED));
write(&b, &png(12, 10, RED));
write(&c, &png(14, 10, BLUE));
write(&e, &png(16, 10, BLUE));
write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0)));
let mut s = session();
let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c));
let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap());
let document = place(&mut s, &d);
write(&b, &png(13, 10, BLUE));
std::fs::remove_file(&c).unwrap();
std::fs::remove_file(&d).unwrap();
Links { s, ok, modified, missing, embedded, document, _dir: dir }
}
/// Run the command with `p`, which must succeed.
fn run(s: &mut Session, p: Value) -> Value {
s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}"))
}
/// `v` sorted.
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
/// The selected objects, sorted.
fn selection(s: &Session) -> Vec<NodeId> {
sorted(s.doc().unwrap().selection.objects.clone())
}
/// The ids of a JSON list, sorted.
fn ids(v: &Value) -> Vec<NodeId> {
sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect())
}
#[test]
fn each_status_selects_its_images_and_placed_documents() {
let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status");
// As the Links panel lists them.
let listed = s.execute("links.list", &json!({})).unwrap();
let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone();
assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s)));
let undo = s.doc().unwrap().history.undo.len();
for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])]
{
s.execute("select.none", &json!({})).unwrap();
let r = run(&mut s, json!({"status": status}));
assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}");
assert_eq!(selection(&s), sorted(want), "{status}");
assert_eq!(r["skipped"], json!([]));
assert!(r.get("zoom").is_none());
}
// Several at once, in stacking order (bottom first); a status listed twice counts once.
let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]}));
assert_eq!(r["selected"], json!([ok.0, missing.0, document.0]));
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes");
}
#[test]
fn ids_add_and_zoom() {
let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options");
// Only among the ids given; other objects among them (a rectangle) are passed over.
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap();
let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]}));
assert_eq!(r["selected"], json!([document.0]));
assert_eq!(selection(&s), vec![document]);
// Added to the selection.
let r = run(&mut s, json!({"status": "embedded", "add": true}));
assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0])));
assert_eq!(selection(&s), sorted(vec![document, embedded]));
// Replacing it by default.
run(&mut s, json!({"status": "modified"}));
assert_eq!(selection(&s), vec![modified]);
// Nothing to select: added, the selection stays; replacing, it empties.
let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true}));
assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([])));
assert_eq!(selection(&s), vec![modified]);
run(&mut s, json!({"status": "linked", "ids": [embedded.0]}));
assert_eq!(selection(&s), vec![]);
// Zoom is reported for the caller (the desktop app zooms).
assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true);
assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none());
}
#[test]
fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() {
let dir = Folder::new("select-skipped");
let files: Vec<String> = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect();
for (i, f) in files.iter().enumerate() {
write(f, &png(10 + i as u32, 10, RED));
}
let mut s = session();
let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i]));
s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap();
// Inside a locked group.
s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap();
// On a template layer.
let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap();
let on_template = place(&mut s, &files[5]);
s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap();
let r = run(&mut s, json!({"status": "linked"}));
assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}");
let mut reasons: Vec<(u64, String)> =
r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect();
reasons.sort();
let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")]
.into_iter()
.map(|(id, why)| (id.0, why.to_string()))
.collect();
want.sort();
assert_eq!(reasons, want, "{r}");
assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str())));
// In isolation mode, those outside the isolated group are left out.
s.execute("select.set", &json!({"ids": [mate.0]})).unwrap();
let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.isolate", &json!({"id": iso})).unwrap();
let r = run(&mut s, json!({"status": "linked"}));
assert_eq!(r["selected"], json!([mate.0]), "{r}");
let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone());
assert_eq!(why(free), Some(json!("isolation")));
assert_eq!(why(hidden), Some(json!("isolation")));
}
#[test]
fn bad_params_are_errors_and_leave_the_selection() {
let Links { mut s, ok, _dir, .. } = links("select-bad");
for p in [
json!({}),
json!({"status": null}),
json!({"status": []}),
json!({"status": "lost"}),
json!({"status": ["linked", "lost"]}),
json!({"status": 3}),
json!({"status": [true]}),
json!({"status": "linked", "add": "yes"}),
json!({"status": "linked", "zoom": 1}),
json!({"status": "linked", "ids": "1"}),
json!({"status": "linked", "ids": [999_999]}),
json!({"status": "linked", "ids": [-1]}),
json!({"status": "linked", "stauts": "missing"}),
] {
s.execute("select.set", &json!({"ids": [ok.0]})).unwrap();
assert!(s.execute(C, &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}");
}
// Without a document it is off, not a crash.
assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err());
}
}
+477
View File
@@ -0,0 +1,477 @@
//! 3D Box and customizable shapes (`addon.shapes.*`), a built-in add-on: creates rotatable 3D boxes
//! (`addon.shapes.box3d`) and customizable rectangles, ellipses, polygons, stars and spirals
//! (`addon.shapes.rectangle`, `addon.shapes.ellipse`, `addon.shapes.polygon`, `addon.shapes.star`,
//! `addon.shapes.spiral`), and configures extended live-shape parameters on selected shapes
//! (`addon.shapes.configure`: symmetric or per-corner radii, pie/chord/arc/whole modes, polygon/star
//! spoke ratio, corner rounding, randomization, spiral turns/divergence/inner radius, and 3D box
//! rotation angles).
#[cfg(test)]
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
use vectorcraft_tools::addons::box3d::CustomShape;
use super::super::create::insert_look;
use super::super::{
CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets,
};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.shapes.rectangle",
"Rectangle",
[],
None,
"{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
rectangle
),
cmd!(
"addon.shapes.ellipse",
"Ellipse",
[],
None,
"{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
ellipse
),
cmd!(
"addon.shapes.polygon",
"Polygon",
[],
None,
"{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
polygon
),
cmd!(
"addon.shapes.star",
"Star",
[],
None,
"{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}",
has_doc,
star
),
cmd!(
"addon.shapes.spiral",
"Spiral",
[],
None,
"{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}",
has_doc,
spiral
),
cmd!(
"addon.shapes.box3d",
"3D Box",
[],
None,
"{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}",
has_doc,
box3d
),
cmd!(
"addon.shapes.configure",
"Configure Shape",
[],
None,
"{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}",
has_selection,
configure
),
]
}
fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) {
let start = f64_or(p, "startAngle", 0.0);
let end = f64_or(p, "endAngle", 360.0);
let mode = match str_param(p, "arcMode") {
Some("pie" | "slice") => shapes::EllipseMode::Slice,
Some("chord") => shapes::EllipseMode::Chord,
Some("arc" | "open") => shapes::EllipseMode::Arc,
_ => shapes::EllipseMode::Whole,
};
let span = (end - start).rem_euclid(360.0);
let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) };
(pie, mode)
}
fn rect_of(p: &Value, c: &str) -> Result<Rect> {
let x = f64_req(p, "x", c)?;
let y = f64_req(p, "y", c)?;
let w = f64_req(p, "width", c)?;
let h = f64_req(p, "height", c)?;
Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs())
}
fn rect_xf(r: Rect, rot: f64) -> Affine {
if rot == 0.0 || !rot.is_finite() {
Affine::translate(r.origin().to_vec2())
} else {
Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rot) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0))
}
}
fn insert_custom(s: &mut Session, label: &str, live: Option<LiveShape>, cs: CustomShape) -> Result<Value> {
let path = match (&live, cs.needs_extra_storage()) {
(Some(l), false) => l.to_path(),
_ => cs.to_path(),
};
let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false };
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let val = insert_look(s, label, kind, look, None, true)?;
if cs.needs_extra_storage()
&& let Some(raw_id) = val.get("id").and_then(Value::as_u64)
&& let Ok(st) = s.doc_mut()
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
{
cs.write_to_node(n);
}
Ok(val)
}
fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.rectangle";
check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?;
let r = rect_of(p, c)?;
let radius = f64_or(p, "radius", 0.0).max(0.0);
let mut radii = [radius; 4];
if let Some(arr) = p.get("radii").and_then(Value::as_array)
&& arr.len() == 4
{
for (i, item) in arr.iter().enumerate() {
if let Some(val) = item.as_f64().filter(|n| n.is_finite()) {
radii[i] = val.max(0.0);
}
}
}
let (pie, arc_mode) = parse_arc_params(p);
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf };
let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode };
let label = if radii.iter().any(|&v| v > 0.0) { "Rounded Rectangle" } else { "Rectangle" };
insert_custom(s, label, Some(live), cs)
}
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.ellipse";
check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?;
let r = rect_of(p, c)?;
let (pie, arc_mode) = parse_arc_params(p);
let xf = rect_xf(r, f64_or(p, "rotation", 0.0));
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf };
let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf };
insert_custom(s, "Ellipse", Some(live), cs)
}
fn polygon(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.polygon";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r = f64_req(p, "radius", c)?.abs();
check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32;
let rot = f64_or(p, "rotation", 0.0);
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
let (pie, arc_mode) = parse_arc_params(p);
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false };
let cs = CustomShape::Polygon {
radius: r,
sides,
xf,
radii: vec![],
kinds: vec![],
radii_relative: false,
spoke_ratio: None,
rounded,
randomized,
pie,
arc_mode,
};
insert_custom(s, "Polygon", Some(live), cs)
}
fn star(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.star";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r1 = f64_req(p, "radius1", c)?.abs();
check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?;
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32;
let rot = f64_or(p, "rotation", 0.0);
let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0);
let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0);
let (pie, arc_mode) = parse_arc_params(p);
let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 };
let cs = CustomShape::Polygon {
radius: r1,
sides: points,
xf,
radii: vec![],
kinds: vec![],
radii_relative: false,
spoke_ratio: Some(ratio),
rounded,
randomized,
pie,
arc_mode,
};
insert_custom(s, "Star", None, cs)
}
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.spiral";
let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?);
let r = f64_req(p, "radius", c)?.abs();
check_numbers(p, &["turns", "divergence", "innerRadius"], c)?;
check_switches(p, &["clockwise"], c)?;
let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0);
let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0);
let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999);
let clockwise = bool_or(p, "clockwise", true);
let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise };
insert_custom(s, "Spiral", None, cs)
}
fn box3d(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.box3d";
let r = rect_of(p, c)?;
check_numbers(p, &["angleX", "angleY", "angleZ"], c)?;
check_switches(p, &["parallelX", "parallelY", "parallelZ"], c)?;
let angle_x = f64_or(p, "angleX", 30.0);
let angle_y = f64_or(p, "angleY", 30.0);
let angle_z = f64_or(p, "angleZ", 0.0);
let parallel_x = bool_or(p, "parallelX", false);
let parallel_y = bool_or(p, "parallelY", true);
let parallel_z = bool_or(p, "parallelZ", false);
let cs = CustomShape::Box3d {
w: r.width(),
h: r.height(),
angle_x,
angle_y,
angle_z,
parallel_x,
parallel_y,
parallel_z,
xf: Affine::translate(r.origin().to_vec2()),
};
let kind = NodeKind::Path { path: cs.to_path(), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let val = insert_look(s, "3D Box", kind, look, Some("3D Box".into()), true)?;
if let Some(raw_id) = val.get("id").and_then(Value::as_u64)
&& let Ok(st) = s.doc_mut()
&& let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id))
{
cs.write_to_node(n);
}
Ok(val)
}
fn configure(s: &mut Session, p: &Value) -> Result<Value> {
let c = "addon.shapes.configure";
check_numbers(
p,
&[
"radius",
"startAngle",
"endAngle",
"sides",
"spokeRatio",
"rounded",
"randomized",
"turns",
"divergence",
"innerRadius",
"angleX",
"angleY",
"angleZ",
],
c,
)?;
check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?;
let ids = targets(s, p)?;
let reset = bool_or(p, "reset", false);
let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some();
let updated = s.edit("Live Shape", |d, _| {
let mut count = 0usize;
for id in ids {
let Some(n) = d.node_mut(id) else { continue };
let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue };
if apply_shape_params(&mut cs, p, reset) {
cs.write_to_node(n);
count += 1;
}
}
Ok(count)
})?;
Ok(json!({ "updated": updated }))
}
fn num_param(p: &Value, k: &str) -> Option<f64> {
p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite())
}
fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool {
let mut changed = false;
if let Some(a0) = num_param(p, "startAngle") {
pie.0 = a0.rem_euclid(360.0);
changed = true;
}
if let Some(a1) = num_param(p, "endAngle") {
pie.1 = a1.rem_euclid(360.0);
changed = true;
}
if let Some(m) = str_param(p, "arcMode") {
*arc_mode = parse_mode(m);
if *arc_mode == shapes::EllipseMode::Whole {
*pie = (0.0, 360.0);
} else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 {
*pie = (0.0, 270.0);
}
changed = true;
}
changed
}
fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool {
let mut changed = false;
if reset {
*radii = [0.0; 4];
*pie = (0.0, 360.0);
*arc_mode = shapes::EllipseMode::Whole;
changed = true;
}
if let Some(r) = num_param(p, "radius") {
*radii = [r.clamp(0.0, max_r); 4];
changed = true;
}
if let Some(arr) = p.get("radii").and_then(Value::as_array)
&& arr.len() == 4
{
for (i, v) in arr.iter().enumerate() {
if let Some(r) = v.as_f64().filter(|x| x.is_finite()) {
radii[i] = r.clamp(0.0, max_r);
changed = true;
}
}
}
changed | apply_arc_params(p, pie, arc_mode)
}
fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut Option<f64>, rounded: &mut f64, randomized: &mut f64) -> bool {
let mut changed = false;
if reset {
*rounded = 0.0;
*randomized = 0.0;
if spoke_ratio.is_some() {
*spoke_ratio = Some(0.5);
}
changed = true;
}
if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) {
*sides = (n_sides as u32).clamp(3, 1000);
changed = true;
}
if let Some(star) = p.get("isStar").and_then(Value::as_bool) {
*spoke_ratio = if star { Some(spoke_ratio.unwrap_or(0.5)) } else { None };
changed = true;
}
if let Some(sr) = num_param(p, "spokeRatio") {
*spoke_ratio = Some(sr.clamp(0.01, 1.0));
changed = true;
}
if let Some(rnd) = num_param(p, "rounded") {
*rounded = rnd.clamp(-10.0, 10.0);
changed = true;
}
if let Some(rand) = num_param(p, "randomized") {
*randomized = rand.clamp(-10.0, 10.0);
changed = true;
}
changed
}
fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool {
match cs {
CustomShape::Rectangle { w, h, radii, pie, arc_mode, .. } => apply_rect_params(p, reset, w.min(*h) / 2.0, radii, pie, arc_mode),
CustomShape::Ellipse { pie, arc_mode, .. } => {
let mut changed = false;
if reset {
*pie = (0.0, 360.0);
*arc_mode = shapes::EllipseMode::Whole;
changed = true;
}
changed | apply_arc_params(p, pie, arc_mode)
}
CustomShape::Polygon { sides, spoke_ratio, rounded, randomized, pie, arc_mode, .. } => {
if reset {
*pie = (0.0, 360.0);
*arc_mode = shapes::EllipseMode::Whole;
}
apply_poly_params(p, reset, sides, spoke_ratio, rounded, randomized) | apply_arc_params(p, pie, arc_mode)
}
CustomShape::Spiral { turns, divergence, inner_radius, .. } => {
let mut changed = false;
if reset {
*turns = 3.0;
*divergence = 1.0;
*inner_radius = 0.0;
changed = true;
}
if let Some(t) = num_param(p, "turns") {
*turns = t.clamp(0.01, 1024.0);
changed = true;
}
if let Some(div) = num_param(p, "divergence") {
*divergence = div.clamp(0.0, 1000.0);
changed = true;
}
if let Some(ir) = num_param(p, "innerRadius") {
*inner_radius = ir.clamp(0.0, 0.999);
changed = true;
}
changed
}
CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. } => {
let mut changed = false;
if reset {
*angle_x = 30.0;
*angle_y = 30.0;
*angle_z = 0.0;
*parallel_x = false;
*parallel_y = true;
*parallel_z = false;
changed = true;
}
for (k, slot) in [("angleX", angle_x), ("angleY", angle_y), ("angleZ", angle_z)] {
if let Some(v) = num_param(p, k) {
*slot = v;
changed = true;
}
}
for (k, slot) in [("parallelX", parallel_x), ("parallelY", parallel_y), ("parallelZ", parallel_z)] {
if let Some(v) = p.get(k).and_then(Value::as_bool) {
*slot = v;
changed = true;
}
}
changed
}
}
}
fn parse_mode(m: &str) -> shapes::EllipseMode {
match m {
"pie" | "slice" => shapes::EllipseMode::Slice,
"chord" => shapes::EllipseMode::Chord,
"arc" | "open" => shapes::EllipseMode::Arc,
_ => shapes::EllipseMode::Whole,
}
}
@@ -0,0 +1,137 @@
use serde_json::json;
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect, shapes};
use vectorcraft_tools::addons::box3d::CustomShape;
use crate::Session;
fn new_session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s
}
#[test]
fn default_shapes_do_not_alter_standard_documents() {
let mut s = new_session();
// Default rectangle: standard LiveShape::Rectangle, no vc-shape-tools attribute.
let rect_id =
NodeId(s.execute("shape.rectangle", &json!({"x": 10.0, "y": 20.0, "width": 100.0, "height": 50.0})).unwrap()["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(rect_id).unwrap();
assert!(n.extras().attrs.is_none());
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") };
assert_eq!(
**live,
LiveShape::Rectangle {
w: 100.0,
h: 50.0,
radii: [0.0; 4],
kinds: Default::default(),
radii_relative: false,
xf: Affine::translate((10.0, 20.0))
}
);
assert_eq!(path, &shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0)));
// Default ellipse: standard LiveShape::Ellipse, no vc-shape-tools attribute.
let ell_id = NodeId(s.execute("shape.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap());
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
assert!(n.extras().attrs.is_none());
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") };
assert_eq!(**live, LiveShape::Ellipse { w: 80.0, h: 60.0, pie: (0.0, 360.0), xf: Affine::IDENTITY });
assert_eq!(path, &shapes::ellipse(Rect::new(0.0, 0.0, 80.0, 60.0)));
}
#[test]
fn addon_shapes_commands_and_format_roundtrip_preserve_paths() {
let mut s = new_session();
// Create customizable shapes through addon.shapes.* commands.
let box_id = NodeId(
s.execute(
"addon.shapes.box3d",
&json!({"x": 10.0, "y": 10.0, "width": 100.0, "height": 80.0, "angleX": 30.0, "angleY": 35.0, "angleZ": 0.0}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(box_id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
assert_eq!(path.subpaths.len(), 3);
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, angle_y, .. }) if (angle_x - 30.0).abs() < 1e-6 && (angle_y - 35.0).abs() < 1e-6)
);
s.execute("addon.shapes.configure", &json!({"angleX": 45.0, "parallelX": true})).unwrap();
let n = s.doc().unwrap().doc.node(box_id).unwrap();
assert!(matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, parallel_x: true, .. }) if (angle_x - 45.0).abs() < 1e-6));
let ell_id = NodeId(
s.execute(
"addon.shapes.ellipse",
&json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 100.0, "arcMode": "arc", "startAngle": 30.0, "endAngle": 210.0}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
assert!(!path.subpaths[0].closed);
s.execute("addon.shapes.configure", &json!({"arcMode": "chord"})).unwrap();
let n = s.doc().unwrap().doc.node(ell_id).unwrap();
let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") };
assert!(path.subpaths[0].closed);
let rect_id = NodeId(
s.execute("addon.shapes.rectangle", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": [10.0, 20.0, 5.0, 0.0], "arcMode": "pie", "startAngle": 0.0, "endAngle": 180.0}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(rect_id).unwrap();
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Rectangle { radii, arc_mode: shapes::EllipseMode::Slice, .. }) if radii == [10.0, 20.0, 5.0, 0.0])
);
let poly_id = NodeId(
s.execute("addon.shapes.polygon", &json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.25, "randomized": 0.1})).unwrap()
["id"]
.as_u64()
.unwrap(),
);
s.execute("addon.shapes.configure", &json!({"isStar": true, "spokeRatio": 0.4})).unwrap();
let n = s.doc().unwrap().doc.node(poly_id).unwrap();
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Polygon { spoke_ratio: Some(sr), rounded, .. }) if (sr - 0.4).abs() < 1e-6 && (rounded - 0.25).abs() < 1e-6)
);
let spiral_id = NodeId(
s.execute("addon.shapes.spiral", &json!({"cx": 60.0, "cy": 60.0, "radius": 45.0, "turns": 4.0, "divergence": 1.4, "innerRadius": 0.2}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
let n = s.doc().unwrap().doc.node(spiral_id).unwrap();
assert!(
matches!(CustomShape::read(n), Some(CustomShape::Spiral { turns, divergence, .. }) if (turns - 4.0).abs() < 1e-6 && (divergence - 1.4).abs() < 1e-6)
);
// Verify that saving and reopening a document containing add-on shapes preserves both the
// baked PathData/LiveShape (for a build that ignores the add-on attribute) and the stored
// extras attribute across a save/load roundtrip.
let doc_before = s.doc().unwrap().doc.clone();
let bytes = vectorcraft_format::save(&doc_before, false);
let doc_after = vectorcraft_format::load(&bytes).unwrap();
let re_saved = vectorcraft_format::save(&doc_after, false);
assert_eq!(bytes, re_saved);
for id in [box_id, ell_id, rect_id, poly_id, spiral_id] {
let a = doc_before.node(id).unwrap();
let b = doc_after.node(id).unwrap();
assert_eq!(a.kind, b.kind);
assert_eq!(CustomShape::read(a), CustomShape::read(b));
}
}
+21 -16
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art) → {ids}",
has_doc,
copy_from
),
@@ -190,7 +190,7 @@ impl Session {
let ids: Vec<u64> = ids.into_iter().map(|id| id.0).collect();
let aligned = match item {
ItemTarget::Item { aligned, .. } => aligned,
ItemTarget::Top => aligned(params),
ItemTarget::Top => aligned(params, "effect.apply").ok()?,
};
Some((json!({"ids": ids, "item": at, "aligned": aligned}), effects.as_slice()))
}
@@ -241,11 +241,12 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result<ItemTarge
/// [`item_target`] read from param `key` (e.g. `fromItem`).
pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<ItemTarget> {
let aligned = aligned(p, cmd)?;
match p.get(key) {
Some(Value::Null) => Ok(ItemTarget::Top),
Some(v) => v
.as_u64()
.map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned: aligned(p) })
.map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned })
.ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))),
// The active item is a row of the first selected object's own stack.
None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top),
@@ -337,8 +338,8 @@ impl ItemTarget {
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
pub(crate) fn aligned(p: &Value) -> bool {
p.get("aligned").and_then(Value::as_bool).unwrap_or(false)
pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
switch_or(p, "aligned", false, cmd)
}
/// What the appearances of `ids` share, when there are several of them and they all exist.
@@ -745,7 +746,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
// When every object comes out as it was (for example, when none has item `index`), the document
// and its undo history stay as they are.
let before = s.doc()?.doc.clone();
let per = items_per_target(&before, &ids, &[idx], aligned(p));
let per = items_per_target(&before, &ids, &[idx], aligned(p, "appearance.setItem")?);
super::overprint::edit_counted(s, "Appearance", |d| {
let mut edited = Vec::new();
for (id, at) in ids.iter().zip(&per) {
@@ -818,7 +819,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
// When no object has an item at any of the indices, the document and its undo history stay as
// they are.
let before = s.doc()?.doc.clone();
let per = items_per_target(&before, &ids, &idx, aligned(p));
let per = items_per_target(&before, &ids, &idx, aligned(p, "appearance.removeItem")?);
super::overprint::edit_counted(s, "Remove Item", |d| {
for (id, idx) in ids.iter().zip(&per) {
if let Some(n) = d.node_mut(*id) {
@@ -854,11 +855,11 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
let mut active_at = None;
// Aligned rows of a mixed selection are copied right above themselves in each object.
if aligned(p) && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
if aligned(p, C)? && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
}
let before = s.doc()?.doc.clone();
let per = items_per_target(&before, &ids, &idx, aligned(p));
let per = items_per_target(&before, &ids, &idx, aligned(p, C)?);
s.edit("Duplicate Item", |d, _| {
let mut any = false;
for (id, idx) in ids.iter().zip(&per) {
@@ -932,11 +933,12 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.moveItem";
let to = index_param(p, "to", C)?;
let ids = require_targets(s, p, C)?;
let aligned = aligned(p, C)?;
if p.get("from").and_then(Value::as_str) == Some("contents") {
return move_contents(s, &ids, to);
}
// Where an aligned row would go in each of several different stacks isn't one place.
if aligned(p) && appearances_differ(&s.doc()?.doc, &ids) {
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
}
if p.get("indices").is_some() {
@@ -1101,14 +1103,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
if !reverse && !defaults_only {
s.eyedropper_sample = Some(node);
}
let range = range.filter(|(id, _, _)| targets.contains(id));
// The highlighted characters' type objects and ranges: after Select All in threaded text, all
// the text of every frame of the story.
// the text of every frame of the story, except a frame the attributes come from, in place of
// the object selection.
let story = super::textedit::editing_story(s);
let ranges: Vec<(NodeId, Option<(usize, usize)>)> = match range {
Some((id, _, _)) if story.contains(&id) => story.iter().map(|f| (*f, None)).collect(),
Some((id, start, end)) => vec![(id, Some((start, end)))],
None => vec![],
Some((id, _, _)) if story.contains(&id) => {
targets.clear();
story.iter().copied().filter(|f| Some(*f) != source).map(|f| (f, None)).collect()
}
Some((id, start, end)) if targets.contains(&id) => vec![(id, Some((start, end)))],
_ => vec![],
};
// Character styles cannot represent object transparency. Refuse before even changing
// paint defaults; applying it to the object would also alter the unselected characters.
@@ -1126,7 +1131,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
if !reverse {
picked.to_defaults(s, &attrs.appearance);
}
if targets.is_empty() || attrs.is_empty() {
if (targets.is_empty() && ranges.is_empty()) || attrs.is_empty() {
return Ok(json!({ "ids": [] }));
}
if !ranges.is_empty() {
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Attributes",
[],
None,
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG export links the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
has_doc,
set
),
+1
View File
@@ -37,6 +37,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
use symbols::selected_instances;
pub(crate) use symbols::{
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
stored_natural_size,
};
use symbols::{
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
+6 -5
View File
@@ -8,11 +8,12 @@ use super::{
// ---------- symbols ----------
pub(crate) fn natural_size(d: &Document, name: &str) -> (f64, f64) {
d.unknown
.get(SIZES_KEY)
.and_then(|m| m.get(name))
.and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)))
.unwrap_or((2.0 * HALF, 2.0 * HALF))
stored_natural_size(d, name).unwrap_or((2.0 * HALF, 2.0 * HALF))
}
/// The natural size `d` records for symbol `name` (`None` when it records none).
pub(crate) fn stored_natural_size(d: &Document, name: &str) -> Option<(f64, f64)> {
d.unknown.get(SIZES_KEY).and_then(|m| m.get(name)).and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)))
}
pub(crate) fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) {
+135 -8
View File
@@ -11,20 +11,21 @@
mod flavours;
pub(crate) mod resources;
mod table;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
use vectorcraft_geom::Rect;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub use flavours::{ImageRead, read_image};
pub(crate) use resources::SwatchChoices;
pub use resources::{ArtResources, art_resources};
pub use resources::{ArtResources, SymbolOptions, art_resources};
use super::{CommandSpec, Result, Session, always, bad, cmd, f64_or, has_doc, point_param, str_param};
use crate::DocState;
@@ -70,6 +71,8 @@ pub struct Clipboard {
pub images: BTreeMap<String, ImageBlob>,
/// Symbols the objects place (also inside other symbols and patterns).
pub symbols: Vec<Symbol>,
/// The Symbol Options of [`Self::symbols`] (which the document keeps by name), by symbol name.
pub symbol_options: BTreeMap<String, SymbolOptions>,
/// Patterns the objects paint with (pasting makes their swatches again).
pub patterns: Vec<PatternDef>,
/// Global and spot swatches the objects' colours link to, the tint swatches of the tints they
@@ -98,6 +101,114 @@ pub struct Clipboard {
pub guides: Vec<vectorcraft_doc::Guide>,
}
/// Indices of segments selected on `sp` (either explicitly or via incident anchors).
pub(crate) fn subpath_selected_segments(
sp: &vectorcraft_geom::SubPath,
si: usize,
seg_refs: Option<&BTreeSet<(usize, usize)>>,
anchor_refs: Option<&BTreeSet<(usize, usize)>>,
) -> BTreeSet<usize> {
let seg_count = sp.segment_count();
if seg_count == 0 {
return BTreeSet::new();
}
let n = sp.anchors.len();
let mut selected_segs = BTreeSet::new();
let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si));
if has_explicit_segs {
if let Some(segments) = seg_refs {
for &(s, seg) in segments {
if s == si && seg < seg_count {
selected_segs.insert(seg);
}
}
}
return selected_segs;
}
if let Some(anchors) = anchor_refs {
let sub_anchors: BTreeSet<usize> = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect();
if !sub_anchors.is_empty() {
for i in 0..seg_count {
let next = (i + 1) % n;
if sub_anchors.contains(&i) && sub_anchors.contains(&next) {
selected_segs.insert(i);
}
}
for &i in &sub_anchors {
let prev_selected = if sp.closed { sub_anchors.contains(&((i + n - 1) % n)) } else { i > 0 && sub_anchors.contains(&(i - 1)) };
let next_selected = if sp.closed { sub_anchors.contains(&((i + 1) % n)) } else { i + 1 < n && sub_anchors.contains(&(i + 1)) };
if !prev_selected && !next_selected {
if sp.closed {
selected_segs.insert((i + n - 1) % n);
selected_segs.insert(i);
} else {
if i > 0 {
selected_segs.insert(i - 1);
}
if i < seg_count {
selected_segs.insert(i);
}
}
}
}
}
}
selected_segs
}
/// When direct selection is active on a path (some anchors or segments selected), extract only
/// the selected runs as new open path nodes (with retracted endpoint handles). Returns `None`
/// when the node is selected whole or is not a path.
pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Option<Vec<Node>> {
let seg_refs = selection.segments.get(&node.id);
let anchor_refs = selection.anchors.get(&node.id);
if seg_refs.is_none() && anchor_refs.is_none() {
return None;
}
let path = node.path_data()?;
let mut subpath_segs = Vec::new();
let mut total_segs = 0;
let mut total_selected = 0;
for (si, sp) in path.subpaths.iter().enumerate() {
let segs = subpath_selected_segments(sp, si, seg_refs, anchor_refs);
total_segs += sp.segment_count();
total_selected += segs.len();
subpath_segs.push(segs);
}
if total_selected == 0 {
return None;
}
// When every segment of the path is selected, copy the object unchanged.
if total_segs > 0 && total_selected == total_segs {
return None;
}
let mut pieces = vec![];
for (sp, selected_segs) in path.subpaths.iter().zip(subpath_segs) {
let seg_count = sp.segment_count();
if selected_segs.is_empty() || seg_count == 0 {
continue;
}
let unselected: BTreeSet<usize> = (0..seg_count).filter(|i| !selected_segs.contains(i)).collect();
let surviving = if unselected.is_empty() { vec![sp.clone()] } else { super::path::without_segments(sp.clone(), &unselected) };
for surviving_sp in surviving {
let mut piece = node.clone();
if let NodeKind::Path { rule, clipping, guide, .. } = &node.kind {
piece.kind = NodeKind::Path { path: PathData::single(surviving_sp), rule: *rule, live: None, clipping: *clipping, guide: *guide };
}
pieces.push(piece);
}
}
if pieces.is_empty() { None } else { Some(pieces) }
}
impl Clipboard {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty()
@@ -118,15 +229,31 @@ impl Clipboard {
}
/// Objects `roots` of `st`'s document with their resources, source artboard and layers.
pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self {
pub(crate) fn copy(st: &DocState, roots: &[NodeId], direct: bool) -> Self {
let d = &*st.doc;
let mut nodes = vec![];
let mut source_layers = vec![];
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
nodes.push(n.clone());
// The nearest enclosing layer (or sublayer).
source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()));
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
let inherit_appearance = |mut piece: Node| {
if let Some(parent) = compound_parent
&& piece.appearance.items.is_empty()
{
piece.appearance = parent.appearance.clone();
}
piece
};
if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) {
for piece in pieces {
nodes.push(inherit_appearance(piece));
source_layers.push(layer_name.clone());
}
} else {
nodes.push(inherit_appearance(n.clone()));
source_layers.push(layer_name);
}
}
// Symbol instances are measured by their art.
let symbols = d.symbol_boxes();
+19 -4
View File
@@ -191,7 +191,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Text into Clipboard",
[],
None,
"{text, center?: [x, y]} replace the clipboard with point text of `text` (one paragraph per line; trailing line breaks dropped) in the default type style, centred on `center` (default: the first artboard) → {count}; then run edit.paste",
"{text, center?: [x, y], table?: true} replace the clipboard with point text of `text` (one paragraph per line; trailing line breaks dropped) in the default type style, centred on `center` (default: the first artboard) → {count}; then run edit.paste. Cells copied from a spreadsheet (tab-separated, at least two columns, every row with the same number of cells, cells in double quotes may hold tabs and line breaks; at most 1000 rows, 256 columns and 20,000 cells) become a group \"Table\": point type for each cell that holds text, in columns as wide as their widest cell and rows as tall as their tallest, over a group \"Gridlines\" of 0.5 pt black lines around every cell → {count, rows, columns}; table: false pastes them as plain text",
has_doc,
import_text
),
@@ -491,9 +491,24 @@ fn import_text(s: &mut Session, p: &Value) -> Result<Value> {
if text.trim().is_empty() {
return Err(bad(C, "the text is empty"));
}
let mut t = TextObject::point(Point::ZERO, text, super::super::create::new_type_style(s, &Value::Null));
t.system_layout = s.doc()?.doc.setup.system_layout;
crate::cmd::typecmd::refresh_bounds(&mut t);
let style = super::super::create::new_type_style(s, &Value::Null);
let system_layout = s.doc()?.doc.setup.system_layout;
let layout = |t: &mut TextObject| {
t.system_layout = system_layout;
crate::cmd::typecmd::refresh_bounds(t);
};
let table = match p.get("table").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(C, "table must be true or false"))?,
};
// Cells copied from a spreadsheet paste as a table of type over gridlines.
if let Some(rows) = table.then(|| super::table::parse(text)).flatten() {
let n = super::table::table(&rows, &style, layout);
let count = s.load_clipboard(Clipboard { nodes: vec![n], ..Default::default() }, p)?;
return Ok(json!({ "count": count, "rows": rows.len(), "columns": rows.first().map_or(0, Vec::len) }));
}
let mut t = TextObject::point(Point::ZERO, text, style);
layout(&mut t);
let n = Node::new(NodeId(1), NodeKind::Text(Box::new(t)));
let count = s.load_clipboard(Clipboard { nodes: vec![n], ..Default::default() }, p)?;
Ok(json!({ "count": count }))
+62 -5
View File
@@ -20,7 +20,12 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, TextStyleDef};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration,
TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
use super::super::patterncmds::add_pattern;
use super::super::{Result, bad, unique_name};
@@ -628,6 +633,38 @@ fn shows_definitions(b: &Brush) -> bool {
found
}
/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and
/// given to it under the name pasting adds it as.
#[derive(Clone, Debug, PartialEq)]
pub struct SymbolOptions {
/// Natural size `(w, h)` (`None`: the document records none).
pub size: Option<(f64, f64)>,
pub registration: SymbolRegistration,
pub export_type: SymbolExportType,
/// 9-slice guides (`None`: 9-slice scaling off).
pub nine_slice: Option<SymbolNineSlice>,
}
impl SymbolOptions {
/// The options `d` keeps for symbol `name`.
fn of(d: &Document, name: &str) -> Self {
Self {
size: stored_natural_size(d, name),
registration: d.symbol_registration(name),
export_type: d.symbol_export_type(name),
nine_slice: d.symbol_nine_slice(name),
}
}
/// Make them the options of `d`'s symbol `name`.
fn give(&self, d: &mut Document, name: &str) {
set_natural_size(d, name, self.size);
d.set_symbol_registration(name, self.registration);
d.set_symbol_export_type(name, self.export_type);
d.set_symbol_nine_slice(name, self.nine_slice);
}
}
/// What pasting did to the document's resources (part of the paste result).
#[derive(Debug, Default)]
pub(crate) struct Imported {
@@ -671,6 +708,12 @@ impl Clipboard {
Self {
images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(),
symbols: src.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).cloned().collect(),
symbol_options: src
.symbols
.iter()
.filter(|s| used.has(Res::Symbol, &s.name))
.map(|s| (s.name.clone(), SymbolOptions::of(src, &s.name)))
.collect(),
patterns: src.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).cloned().collect(),
swatches: src.swatches_iter().filter(|w| used.carries(w)).cloned().collect(),
graphic_styles: src.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)).cloned().collect(),
@@ -725,13 +768,27 @@ impl Clipboard {
out.placed(r, &def.name, &p);
}
}
// Symbols and patterns, compared once relinked. Those added are relinked at the end, when
// every new name and graphic style id is known.
// Symbols and patterns, compared once relinked (symbols with their options too). Those
// added are relinked at the end, when every new name and graphic style id is known.
let mut added_symbols = HashSet::new();
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
let options = self.symbol_options.get(&def.name);
let theirs: HashMap<String, SymbolOptions> = match options {
Some(_) => {
d.symbols.iter().filter(|s| copy_of(&def.name, &s.name)).map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))).collect()
}
None => HashMap::new(),
};
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)));
added_symbols.extend(p.new_name(&def.name));
let p = place(&mut d.symbols, def, same_doc, |a, b| {
options.is_none_or(|o| theirs.get(&a.name) == Some(o)) && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
o.give(d, &name);
}
added_symbols.insert(name);
}
out.placed(Res::Symbol, &def.name, &p);
}
let mut added_patterns = HashSet::new();
+203
View File
@@ -0,0 +1,203 @@
//! Cells copied from a spreadsheet (Excel, Google Sheets, LibreOffice Calc, Numbers): the plain
//! text they put on the clipboard is tab-separated values, one row a line, every row with the
//! same number of cells. `clipboard.importText` pastes such text as a table: a group of point
//! type, one object for each cell that holds text, laid out in columns as wide as their widest
//! cell and rows as tall as their tallest, over gridlines around every cell.
use std::sync::Arc;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect};
/// Most rows a pasted table takes; more pastes as plain text.
pub(crate) const MAX_ROWS: usize = 1000;
/// Most columns a pasted table takes; more pastes as plain text.
pub(crate) const MAX_COLUMNS: usize = 256;
/// Most cells (rows × columns) a pasted table takes; more pastes as plain text.
pub(crate) const MAX_CELLS: usize = 20_000;
/// Space between a cell's text and its gridlines, in points.
const PAD: f64 = 4.0;
/// The gridlines' stroke weight, in points.
const GRIDLINE: f64 = 0.5;
/// The rows of `text` (line breaks already `\n`, trailing ones dropped) when it is a table copied
/// from a spreadsheet: tab-separated cells, at least two columns, every row with the same number
/// of cells, within the caps above. A cell in double quotes may hold tabs, line breaks and
/// doubled quotes (`""`), as the spreadsheets write them. `None` for any other text, which pastes
/// as it always has.
pub(crate) fn parse(text: &str) -> Option<Vec<Vec<String>>> {
if !text.contains('\t') {
return None;
}
let mut rows: Vec<Vec<String>> = vec![];
let mut row: Vec<String> = vec![];
let mut cell = String::new();
let mut chars = text.chars().peekable();
// At the start of a cell, a quote opens a quoted cell.
let mut start = true;
let mut quoted = false;
let mut cells = 0usize;
while let Some(c) = chars.next() {
if quoted {
if c == '"' {
if chars.peek() == Some(&'"') {
chars.next();
cell.push('"');
} else {
quoted = false;
}
} else {
cell.push(c);
}
continue;
}
match c {
'"' if start => {
quoted = true;
start = false;
}
'\t' | '\n' => {
row.push(std::mem::take(&mut cell));
cells += 1;
if row.len() > MAX_COLUMNS || cells > MAX_CELLS {
return None;
}
if c == '\n' {
rows.push(std::mem::take(&mut row));
if rows.len() > MAX_ROWS {
return None;
}
}
start = true;
}
c => {
cell.push(c);
start = false;
}
}
}
// A quote left open is not a spreadsheet's.
if quoted {
return None;
}
row.push(cell);
rows.push(row);
if rows.iter().any(|r| r.len() > MAX_COLUMNS) || cells + 1 > MAX_CELLS {
return None;
}
let columns = rows.first()?.len();
let fits = columns >= 2 && rows.len() <= MAX_ROWS && rows.iter().all(|r| r.len() == columns);
// The first and last columns hold something: text indented with tabs is not a table.
let used = |k: usize| rows.iter().any(|r| r.get(k).is_some_and(|c| !c.trim().is_empty()));
(fits && used(0) && used(columns - 1)).then_some(rows)
}
/// `rows` laid out as a table (see the module docs) with its top left at the origin: one group
/// holding a group of gridlines and the cells' type. `style` is the type's style; `layout`
/// refreshes a type object's bounds.
pub(crate) fn table(rows: &[Vec<String>], style: &CharStyle, layout: impl Fn(&mut TextObject)) -> Node {
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
let mut next = 0u64;
let mut id = || {
next += 1;
NodeId(next)
};
// Each cell's type, at the origin, with its bounds.
let mut cells: Vec<Vec<Option<(Node, Rect)>>> = vec![];
for row in rows {
let mut out = vec![];
for text in row {
if text.trim().is_empty() {
out.push(None);
continue;
}
let text = text.replace("\r\n", "\n").replace('\r', "\n");
let mut t = TextObject::point(Point::ZERO, &text, style.clone());
layout(&mut t);
let n = Node::new(id(), NodeKind::Text(Box::new(t)));
out.push(n.geometric_bounds().filter(|b| b.is_finite()).map(|b| (n, b)));
}
cells.push(out);
}
// A row with nothing in it is as tall as one line of the type.
let line = style.size.max(1.0) * 1.2;
let widths: Vec<f64> =
(0..columns).map(|k| cells.iter().filter_map(|r| r.get(k)?.as_ref()).map(|(_, b)| b.width()).fold(line, f64::max) + 2.0 * PAD).collect();
let heights: Vec<f64> = cells.iter().map(|r| r.iter().flatten().map(|(_, b)| b.height()).fold(line, f64::max) + 2.0 * PAD).collect();
let xs: Vec<f64> = std::iter::once(0.0)
.chain(widths.iter().scan(0.0, |x, w| {
*x += w;
Some(*x)
}))
.collect();
let ys: Vec<f64> = std::iter::once(0.0)
.chain(heights.iter().scan(0.0, |y, h| {
*y += h;
Some(*y)
}))
.collect();
let (right, bottom) = (xs.last().copied().unwrap_or(0.0), ys.last().copied().unwrap_or(0.0));
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), GRIDLINE);
let mut lines = vec![];
for y in &ys {
lines.push(segment(id(), (0.0, *y), (right, *y), &stroke));
}
for x in &xs {
lines.push(segment(id(), (*x, 0.0), (*x, bottom), &stroke));
}
let mut grid = Node::group(id(), lines);
grid.name = Some("Gridlines".into());
let mut children = vec![Arc::new(grid)];
for (r, row) in cells.into_iter().enumerate() {
for (k, cell) in row.into_iter().enumerate() {
let (Some((mut n, b)), Some(x), Some(y)) = (cell, xs.get(k), ys.get(r)) else { continue };
// The text's top left a pad inside the cell's.
n.transform(Affine::translate((x + PAD - b.x0, y + PAD - b.y0)), false);
children.push(Arc::new(n));
}
}
let mut group = Node::group(id(), children);
group.name = Some("Table".into());
group
}
/// A straight stroked line from `a` to `b`.
fn segment(id: NodeId, a: (f64, f64), b: (f64, f64), stroke: &Appearance) -> Arc<Node> {
let mut p = BezPath::new();
p.move_to(a);
p.line_to(b);
Arc::new(Node::path(id, PathData::from_bezpath(&p), stroke.clone()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spreadsheet_cells_are_told_from_other_text() {
let rows = parse("Name\tQty\nApples\t3\nPears\t").unwrap();
assert_eq!(rows, vec![vec!["Name", "Qty"], vec!["Apples", "3"], vec!["Pears", ""]]);
// Quoted cells hold line breaks, tabs and quotes.
let rows = parse("\"Two\nlines\"\t\"a\tb\"\n\"say \"\"hi\"\"\"\tx").unwrap();
assert_eq!(rows, vec![vec!["Two\nlines", "a\tb"], vec!["say \"hi\"", "x"]]);
// Not tables: no tabs, ragged rows, indented text, an unclosed quote.
for t in ["plain words", "one\ntwo", "a\tb\nc", "\tindented\n\tcode", "a\t\"open", "x\t"] {
assert_eq!(parse(t), None, "{t:?}");
}
// A quote inside a cell is just a character.
assert_eq!(parse("5\" pipe\t2").unwrap(), vec![vec!["5\" pipe", "2"]]);
}
#[test]
fn tables_past_the_caps_paste_as_text() {
let wide = vec!["x"; MAX_COLUMNS + 1].join("\t");
assert_eq!(parse(&wide), None);
let tall = vec!["a\tb"; MAX_ROWS + 1].join("\n");
assert_eq!(parse(&tall), None);
let many = vec![vec!["c"; 100].join("\t"); MAX_CELLS / 100 + 1].join("\n");
assert_eq!(parse(&many), None);
let fits = vec!["a\tb"; MAX_ROWS].join("\n");
assert_eq!(parse(&fits).map(|r| r.len()), Some(MAX_ROWS));
}
}
+1 -1
View File
@@ -721,7 +721,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
if rotation != 0.0 {
t.xf *= vectorcraft_geom::rotate_deg(rotation);
}
t.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false);
t.vertical = switch_or(p, "vertical", false, "text.create")?;
t.para = new_type_para();
new_type_alignment(s, p, "text.create", &mut t)?;
if let Some(a) = p.get("area") {
+2 -2
View File
@@ -14,7 +14,7 @@ use super::pathops::Beside;
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
use super::{
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
str_param,
str_param, switch_or,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -716,7 +716,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
}
fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("locked").and_then(Value::as_bool).unwrap_or(!s.menu.guides_locked);
let v = switch_or(p, "locked", !s.menu.guides_locked, "view.guides.lock")?;
s.menu.guides_locked = v;
// Locked guides can't stay selected, ruler guides or guide paths, in any open document
// ([`Session::select`] lets those go in the active one).
+2 -2
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
has_doc,
freehand
),
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join",
[],
None,
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over → {id}",
"{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}",
has_doc,
join_scrub
),
+7 -1
View File
@@ -336,7 +336,13 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(st) = look.appearance.stroke_mut() {
pen.write(st);
}
insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)
let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
s.select(|_, sel| sel.clear())?;
}
Ok(out)
}
// ---------- Blob Brush ----------
+114 -2
View File
@@ -1,4 +1,6 @@
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, target_paths};
use vectorcraft_pathops::addons::pathtools as pt;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
@@ -179,11 +181,121 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Join tool ----------
/// Most open subpaths the Join tool compares pairwise for crossings before it only joins ends.
const MAX_TRIM_SUBPATHS: usize = 64;
/// One end of an open subpath that runs on past where it crosses another: the part kept, which
/// ends at the crossing, and the part past it.
struct Overhang {
kept: SubPath,
cut: SubPath,
}
impl Overhang {
fn at(&self) -> Option<Point> {
self.kept.anchors.last().map(|a| a.p)
}
}
/// The overhangs of `sp` at its first and last crossing (`places`: subpath, segment, t, in order).
/// A crossing on an end anchor leaves no overhang there.
fn overhangs(sp: &SubPath, places: &[(usize, usize, f64)]) -> Vec<Overhang> {
let mut out = vec![];
for (place, at_start) in [(places.first(), true), (places.last(), false)] {
let Some(&(_, seg, t)) = place else { continue };
let (split, marks) = pt::insert_at(sp, &[(seg, t)]);
let Ok([first, second]) = <[SubPath; 2]>::try_from(split.cut_at(&marks)) else { continue };
let (mut kept, cut) = if at_start { (second, first) } else { (first, second) };
if at_start {
kept.reverse();
}
out.push(Overhang { kept, cut });
}
out
}
/// Does the scrub `pts` (`scrub` as a path) cross `cut` or pass within `tol` of it?
fn scrubbed(cut: &SubPath, pts: &[Point], scrub: &PathData, tol: f64) -> bool {
let pd = PathData::single(cut.clone());
pt::crossings(&[&pd, scrub], false).is_some_and(|c| c.first().is_some_and(|v| !v.is_empty()))
|| cut.anchors.iter().any(|a| dist_to_polyline(pts, a.p) <= tol)
|| pts.iter().any(|q| pd.nearest(*q).is_some_and(|n| n.4 <= tol))
}
/// Two crossing open subpaths, each `(path, subpath)`, trimmed and joined at the crossing.
struct TrimJoin {
a: (NodeId, usize),
b: (NodeId, usize),
joined: SubPath,
}
/// #5844: two open subpaths among `ids` that cross, where the scrub runs over the part of each
/// that overhangs the crossing, trimmed at the crossing and joined there with a corner. When
/// several pairs or ends qualify, the one trimming the least wins.
fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: f64) -> Result<Option<TrimJoin>> {
let mut open = vec![];
for &id in ids {
let (pd, _) = path_of(d, id)?;
open.extend(pd.subpaths.into_iter().enumerate().filter(|(_, sp)| !sp.closed && sp.anchors.len() >= 2).map(|(si, sp)| (id, si, sp)));
}
if open.len() > MAX_TRIM_SUBPATHS {
return Ok(None);
}
let scrub = PathData::single(SubPath::polyline(pts, false));
let mut best: Option<(f64, TrimJoin)> = None;
for (i, (ida, sa, a)) in open.iter().enumerate() {
for (idb, sb, b) in open.iter().skip(i + 1) {
let (pa, pb) = (PathData::single(a.clone()), PathData::single(b.clone()));
let Some(places) = pt::crossings(&[&pa, &pb], false) else { continue };
let (Some(on_a), Some(on_b)) = (places.first(), places.get(1)) else { continue };
let (oa, ob) = (overhangs(a, on_a), overhangs(b, on_b));
for x in oa.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) {
for y in ob.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) {
let (Some(xa), Some(ya)) = (x.at(), y.at()) else { continue };
let trimmed = subpath_len(&x.cut) + subpath_len(&y.cut);
if xa.distance(ya) > 1e-2 || best.as_ref().is_some_and(|b| b.0 <= trimmed) {
continue;
}
// `x` ends at the crossing; `y`, reversed, starts there: one corner anchor.
let mut joined = x.kept.clone();
let mut rest = y.kept.clone();
rest.reverse();
let (Some(last), Some(first)) = (joined.anchors.last_mut(), rest.anchors.first()) else { continue };
*last =
Anchor { p: last.p, h_in: last.h_in, h_out: first.h_out + (last.p - first.p), kind: vectorcraft_geom::AnchorKind::Corner };
joined.anchors.extend(rest.anchors.into_iter().skip(1));
best = Some((trimmed, TrimJoin { a: (*ida, *sa), b: (*idb, *sb), joined }));
}
}
}
}
Ok(best.map(|(_, t)| t))
}
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.joinScrub";
let pts = points_param(p, "points", C)?;
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
let st = s.doc()?;
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
if let Some(TrimJoin { a: (ida, sa), b: (idb, sb), joined }) = trim_join(&st.doc, &targets, &pts, tol)? {
s.edit("Join", |d, sel| {
let missing = || crate::EngineError::Other("Join: a subpath went missing".into());
*path_mut(d, ida)?.subpaths.get_mut(sa).ok_or_else(missing)? = joined;
let pbm = path_mut(d, idb)?;
if sb >= pbm.subpaths.len() {
return Err(missing());
}
pbm.subpaths.remove(sb);
if ida != idb && pbm.is_empty() {
d.remove(idb)?;
}
sel.set([ida]);
Ok(())
})?;
return Ok(json!({ "id": ida.0 }));
}
// Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start).
let poly = {
let mut bp = BezPath::new();
@@ -202,7 +314,7 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
};
let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied());
let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![];
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) {
for id in targets {
let (pd, _) = path_of(&st.doc, id)?;
for (si, sp) in pd.subpaths.iter().enumerate() {
if sp.closed || sp.anchors.len() < 2 {
+178 -39
View File
@@ -4,14 +4,14 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, RulerMode, Unit};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit};
use vectorcraft_geom::{Affine, Point, Vec2};
use super::clipboard::SwatchChoices;
use super::{
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
point_param, str_param,
point_param, str_param, switch_or,
};
use crate::{Clipboard, EngineError, inspect};
@@ -157,7 +157,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
@@ -626,7 +626,7 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
/// rest still go to the compound path, which holds the paint.
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
let st = s.doc()?;
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true))
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
}
/// [`selected_roots`] for the selected objects inside the isolated object `root`
@@ -637,18 +637,18 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_within(&st.doc, ids, |compound| members || compound == root))
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
}
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
/// compound, and ids whose ancestor is also listed, and layers, are dropped.
pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
roots_within(doc, ids, |_| false)
roots_within(doc, ids, |_, _| false)
}
/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the
/// compound's id.
fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bool) -> Vec<NodeId> {
/// [`roots_of`]; a compound path's member listed stays itself when `keep_member` holds for the
/// compound's id or the member's id.
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
let paths = doc.index_paths(ids.iter().copied());
// A compound-path member acts as its compound (compounds are one object).
@@ -658,7 +658,7 @@ fn roots_within(doc: &Document, ids: Vec<NodeId>, members: impl Fn(NodeId) -> bo
let path = paths.get(&id);
let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty());
match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) {
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())),
Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !keep_member(n.id, id) => (n.id, Some(up.to_vec())),
_ => (id, path.cloned()),
}
})
@@ -689,11 +689,24 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option<Vec<usize>>)>) -> i
})
}
/// The direct-selection flag and resolved root nodes for Copy and Cut operations.
fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
let st = s.doc()?;
let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature");
let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty());
let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| {
in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member)))
});
Ok((direct, roots))
}
fn copy(s: &mut Session, _: &Value) -> Result<Value> {
// The Artboard tool copies its artboard (and the art on it).
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), false);
}
let (direct, targets) = copy_cut_targets(s)?;
let st = s.doc()?;
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
// behind.
@@ -704,9 +717,13 @@ fn copy(s: &mut Session, _: &Value) -> Result<Value> {
.filter_map(|i| st.doc.guides.get(*i))
.map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() })
.collect();
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? };
let st = s.doc()?;
let mut clip = Clipboard::copy(st, &roots);
let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets };
let mut clip = Clipboard::copy(st, &roots, direct);
// Direct-selected anchors or segments that make no segment: nothing to copy, so the
// clipboard keeps what it held.
if direct && clip.nodes.is_empty() {
return Ok(json!({ "copied": 0 }));
}
// Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes
// measure from, as the objects' artboard is.
if clip.nodes.is_empty()
@@ -729,23 +746,81 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &json!({}), true);
}
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
// Ruler guides selected on their own: Copy takes them, Clear removes them.
if s.doc()?.selection.is_empty() {
copy(s, p)?;
return clear(s, &json!({}));
}
let ids = selected_roots(s)?;
copy(s, p)?;
// Copy promotes a compound member to its compound. Cut must remove the same objects it
// copied, while Clear on its own deletes exactly the selected members.
let (direct, roots) = copy_cut_targets(s)?;
let res = copy(s, p)?;
if res.get("copied").and_then(Value::as_u64) == Some(0) {
return Ok(res);
}
// The selected ruler guides it copied go with the objects, in the same undo step (#3226).
if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) }
if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) }
}
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
s.edit("Cut", |d, selection| {
// The selected ruler guides were copied too (#3226): they go in the same undo step.
let gone = selection.guides.clone();
d.retain_guides(selection, |i, _| !gone.contains(&i));
let mut survivors = vec![];
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
if !has_direct {
d.remove(*id)?;
continue;
}
let Some(path) = node.path_data() else {
d.remove(*id)?;
continue;
};
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
for (si, sp) in path.subpaths.iter().enumerate() {
let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp.clone());
} else {
subpaths.extend(super::path::without_segments(sp.clone(), &cuts));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
if subpaths.is_empty() {
let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
d.remove(*id)?;
if let Some(p) = parent
&& d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))
{
d.remove(p)?;
}
} else {
let path_node = super::path::path_mut(d, *id)?;
path_node.subpaths = subpaths;
survivors.push(*id);
}
}
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
Ok(())
})?;
ok()
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
if explicit.is_none() && !s.doc()?.selection.anchors.is_empty() {
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
return super::path::delete_anchors(s, p);
}
// Selected ruler guides (selected on their own).
@@ -755,7 +830,8 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
// Guides selected with the art go with it (not when ids are given, unless `guides` says so:
// Cut, which names the objects it copied).
let with_guides = explicit.is_none() || bool_or(p, "guides", false);
let with_guides = explicit.is_none() || guides;
let is_explicit = explicit.is_some();
let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc));
// Keep the selected ids themselves, without promoting compound members. Delete a selected
// ancestor just once; its selected descendants leave with it. Layers themselves are kept.
@@ -769,12 +845,26 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Clear", |d, sel| {
let parents: Vec<_> =
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
d.remove_many(&ids)?;
for p in parents {
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
d.remove(p)?;
}
}
if with_guides {
let gone = sel.guides.clone();
d.retain_guides(sel, |i, _| !gone.contains(&i));
}
sel.clear();
if is_explicit {
for id in &ids {
sel.remove(*id);
}
sel.prune(d);
} else {
sel.clear();
}
Ok(())
})?;
ok()
@@ -803,7 +893,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) {
return Err(EngineError::NoNode(*id));
}
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids));
let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false);
let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?;
let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]);
if !center.x.is_finite() || !center.y.is_finite() {
@@ -872,19 +962,28 @@ fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine {
/// Insert clipboard resources atomically in the active editable context using the requested placement mode.
fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, choices: &SwatchChoices) -> Result<Value> {
let off = s.prefs.paste_offset;
let boards_at = match p.get("artboardsAt") {
Some(v) if mode == PasteMode::Offset => Some(
point_param(p, "artboardsAt")
.filter(|c| v.as_array().is_some_and(|a| a.len() == 2) && c.x.is_finite() && c.y.is_finite())
.ok_or_else(|| bad("edit.paste", "`artboardsAt` must be [x, y]"))?,
),
_ => None,
};
let st = s.doc()?;
let same_doc = clip.source_doc == Some(st.uid);
let parent = st.target_parent()?;
let parent = st.target_parent_for_path()?;
// Copied artboards come back with their art: together right of the last artboard, as they lay,
// or where they were (Paste in Place, in Front, in Back). Paste on All Artboards pastes only the
// art.
let boards = clip
.artboards
.iter()
.map(|a| a.rect)
.reduce(|a, b| a.union(b))
.filter(|_| mode != PasteMode::AllArtboards)
.map(|all| (&clip.artboards, if mode == PasteMode::Offset { super::panelcmds::beside_artboards(&st.doc, all) } else { Vec2::ZERO }));
// or centered on `artboardsAt`, or where they were (Paste in Place, in Front, in Back). Paste on
// All Artboards pastes only the art.
let boards = clip.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b)).filter(|_| mode != PasteMode::AllArtboards).map(|all| {
let dv = match (mode, boards_at) {
(PasteMode::Offset, Some(c)) => c - all.center(),
(PasteMode::Offset, None) => super::panelcmds::beside_artboards(&st.doc, all),
_ => Vec2::ZERO,
};
(&clip.artboards, dv)
});
// Drawing modes (#3705): Draw Inside puts what Paste, Paste in Place and Paste on All
// Artboards bring inside the object it draws into; Draw Behind puts what Paste in Place and
// Paste on All Artboards bring behind the selection, as Paste in Back does. Paste in Front and
@@ -907,8 +1006,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let anchor = if front || back {
let order = st.selection.in_paint_order(&st.doc);
let a = if front { order.last() } else { order.first() };
let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. }));
a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id))
let isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
let can_enter_compound = clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))
|| (isolated_compound && clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })));
a.map(|id| paste_anchor(&st.doc, *id, can_enter_compound)).and_then(|id| st.doc.position(id))
} else {
None
};
@@ -975,7 +1076,45 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}
};
*placed.entry(par).or_default() += 1;
new_ids.push(d.insert(par, idx, c)?);
let compound_par = par.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })));
if let Some(par_id) = compound_par {
match c.kind {
NodeKind::Compound { children, .. } => {
let count = children.len();
for (offset, child) in children.into_iter().enumerate() {
let mut child_node = Arc::unwrap_or_clone(child);
let child_id = d.alloc_id();
child_node.id = child_id;
child_node.appearance = Default::default();
if let NodeKind::Path { live, .. } = &mut child_node.kind {
*live = None;
}
let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) };
new_ids.push(d.insert(par, insert_idx, child_node)?);
}
if count > 1 {
*placed.entry(par).or_default() += count - 1;
}
}
NodeKind::Path { .. } => {
c.appearance = Default::default();
if let NodeKind::Path { live, .. } = &mut c.kind {
*live = None;
}
new_ids.push(d.insert(par, idx, c)?);
}
_ => {
let outer_par = d.parent_of(par_id);
let beside_idx = d.position(par_id).map(|(_, i, _)| i + 1).unwrap_or(usize::MAX);
let offset = *placed.entry(outer_par).or_default();
*placed.entry(outer_par).or_default() += 1;
let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) };
new_ids.push(d.insert(outer_par, insert_idx, c)?);
}
}
} else {
new_ids.push(d.insert(par, idx, c)?);
}
}
}
sel.set(new_ids.iter().copied());
@@ -1016,11 +1155,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
}))
}
/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only
/// paths (a compound path holds paths only).
fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId {
/// What pasted art goes beside: `id`, or the compound path holding it when the art cannot enter
/// the compound path (a compound path holds paths only; compound paths unpack into isolated compounds).
fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId {
match doc.parent_of(id) {
Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
Some(p) if !can_enter_compound && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p,
_ => id,
}
}
+10 -5
View File
@@ -16,7 +16,7 @@ use vectorcraft_render::effects;
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
use super::expand::has_seeded;
use super::rasterfx;
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or};
/// The effect commands of the Effect menu and the Appearance panel.
pub fn specs() -> Vec<CommandSpec> {
@@ -116,12 +116,13 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us
// Whether `item` names an item in the stack it is a row of (else the edit is object-level there).
let anchor = roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a));
let anchor_level = anchor.map(|a| item.effects_item(&a.appearance, cmd)).transpose()?.flatten();
let aligned = aligned(p, cmd)?;
let mut out = Vec::with_capacity(roots.len());
for (id, item) in roots.iter().zip(per) {
let (Some(item), Some(n)) = (item, d.node(*id)) else { continue };
let at = item.effects_item(&n.appearance, cmd)?;
// An object-level effect this target shares with the first is where it is in this target.
let index = match (first.filter(|_| aligned(p)), at, anchor_level) {
let index = match (first.filter(|_| aligned), at, anchor_level) {
(Some(f), None, None) => SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1).unwrap_or(index),
_ => index,
};
@@ -236,6 +237,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let effect = effects::new_effect(id, &params).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?;
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
aligned(p, C)?;
if let Some(loose) = loose_for_pathfinder(s, p, id)? {
let gid = s.edit(&label, |d, sel| {
let gid = super::object::group_nodes(d, &loose)?;
@@ -375,10 +377,10 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
let to = index_param(p, "to", C)?;
let src = item_target_at(s, p, "fromItem", C)?;
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false);
let copy = switch_or(p, "copy", false, C)?;
let roots = appearance_targets(s, p)?;
// Where an aligned effect would go in each of several different stacks isn't one place.
if aligned(p) && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
}
// Where the effect landed in each object it moved in, in the order of `ids`.
@@ -752,7 +754,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
// keeps it as its only member).
Some((image, false)) => Some(rasterfx::replace_with_image(v, image)),
image => {
let m = if container {
let m = if container && effects::has_solid(&v) {
// A group's or layer's 3D effect: the shaded faces of its members' solids.
effects::expand_leaf(d, &v, &mut stroke_art)
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
+35
View File
@@ -79,6 +79,41 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() {
}
}
/// #4506: a 3D effect on a group builds a solid from each member, turned about one shared axis;
/// the members stay editable, and a group holding what can't become a solid is refused.
#[test]
fn solid_effects_apply_to_a_group_and_its_members_stay_editable() {
for effect in effects::SOLIDS {
let (mut s, a) = session_with_rect();
let b = s.execute("shape.ellipse", &json!({"x": 250, "y": 120, "width": 80, "height": 60})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("effect.apply", &json!({"effect": effect, "ids": [g.0], "item": null})).unwrap();
let art = effects::solid_art(&node(&s, g)).unwrap_or_else(|| panic!("{effect}"));
assert_eq!(node(&s, g).children().unwrap().len(), 2, "{effect}: the members stay as they were");
// A member moved, the solid follows.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.move", &json!({"dx": -40, "dy": 0})).unwrap();
assert_ne!(effects::solid_art(&node(&s, g)).unwrap(), art, "{effect}");
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
assert!(vectorcraft_testkit::svg_shapes(&svg) >= 4, "{effect}: both members exported as vector faces");
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
assert!(!effects::has_solid(&node(&s, g)), "{effect}: expanded");
}
// A clipping group in the group: refused, nothing changed.
let (mut s, a) = session_with_rect();
let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone();
let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [clip, c]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string();
assert!(err.contains("clipping groups"), "{err}");
assert!(node(&s, g).appearance.effects.is_empty());
}
/// #4715: type extrudes as its glyph outlines, painted with its characters' colour, and stays
/// type: editing its text reshapes the solid.
#[test]
+1 -1
View File
@@ -57,9 +57,9 @@ use serde_json::{Value, json};
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub use export::export_source;
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{export_crop, isolated};
pub use export::{export_doc, export_source};
pub(crate) use load::check_not_lossy_overwrite;
use load::err;
pub(crate) use load::import_svg;
+2 -2
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
has_doc,
export::export
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Selection…",
["File"],
None,
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
has_selection,
export::export_selection
),
+5 -4
View File
@@ -202,13 +202,14 @@ impl RasterOptions {
}
}
/// The render and encoder settings: `ppi`, else 72 × `scale`, within 0.01–64 pixels per point;
/// The render and encoder settings: `ppi`, else 72 × `scale`, else the document's resolution,
/// within 0.01–64 pixels per point;
/// `background`, else `page` (the document's background).
fn settings(&self, page: Option<[u8; 3]>) -> Result<RasterExportOptions> {
fn settings(&self, page: Option<[u8; 3]>, document_ppi: f64) -> Result<RasterExportOptions> {
if let Some(ppi) = self.ppi.filter(|p| !(p.is_finite() && *p > 0.0)) {
return Err(bad(C, format!("ppi must be a positive number, not {ppi}")));
}
let ppi = self.ppi.unwrap_or(72.0 * self.scale.unwrap_or(1.0));
let ppi = self.ppi.unwrap_or_else(|| self.scale.map_or(document_ppi, |scale| 72.0 * scale));
let color_model = parse(self.color_model.as_deref(), jpeg::ColorModel::from_id, "colorModel", "rgb, cmyk or gray")?;
let embed_icc = self.embed_icc.unwrap_or(true);
Ok(RasterExportOptions {
@@ -544,7 +545,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
// New Document → Background Contents: White makes the export opaque, unless `background`
// says otherwise (JPEG has no alpha: white either way).
let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 3]);
let mut settings = o.settings(page)?;
let mut settings = o.settings(page, doc.raster_ppi())?;
let size = o.pixel_size()?;
let format = match f.id {
"png" => RasterFormat::Png,
+12 -1
View File
@@ -72,6 +72,17 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings }))
}
/// The document an export of `st` in format `f` writes ([`export_source`]): a `.ai` or `.ait`
/// file names the view's active artboard ([`DocState::active_artboard`]) as its active one, as a
/// save does. The open document is unchanged.
pub fn export_doc<'a>(st: &'a DocState, f: &Format, p: &Value) -> Result<Cow<'a, Document>> {
let mut doc = export_source(st, p)?;
if let Some(id) = super::save::moved_active_artboard(st, &doc, f) {
doc.to_mut().opened_artboard = Some(id);
}
Ok(doc)
}
/// The document an export of `st` writes: the whole document, or with `selectedOnly` just the
/// selected objects, each in its layers and groups (a clipping group keeps its clipping path).
pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document>> {
@@ -190,7 +201,7 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
return Ok((Cow::Owned(doc), display_doc_title));
}
let st = s.doc()?;
let doc = export_source(st, p)?;
let doc = export_doc(st, f, p)?;
let display_doc_title = super::has_own_title(&doc);
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
}
+8 -3
View File
@@ -76,7 +76,12 @@ pub(super) const RANGE: FormatOption = FormatOption {
description: "1-based artboards such as \"1-3, 5\", or \"all\" (wins over artboards and artboard)",
};
const SCALE: FormatOption = FormatOption { name: "scale", ty: "number", default: "1", description: "pixels per point (0.01–64)" };
const SCALE: FormatOption = FormatOption {
name: "scale",
ty: "number",
default: "null",
description: "pixels per point (0.01–64); without ppi or scale, uses the document's raster effects resolution",
};
const WIDTH: FormatOption = FormatOption {
name: "width",
@@ -112,8 +117,8 @@ const RECT: FormatOption = FormatOption {
const PPI: FormatOption = FormatOption {
name: "ppi",
ty: "number",
default: "72",
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale",
default: "null",
description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale; without either, uses the document's raster effects resolution",
};
const BACKGROUND: FormatOption = FormatOption {
+86 -25
View File
@@ -14,13 +14,16 @@
//! Images are the exception (`transparentImages`): an image with see-through pixels, opacity or a
//! blending mode written opaque is a box hiding the art under it (version 7 images have no alpha
//! channel, §8.1). With `flatten` (the default) each becomes an opaque image of itself and the art
//! under it, rendered from the document as it is, clipped to the area where it changes what shows;
//! under it, rendered from the document as it is, clipped to the area where it changes what shows
//! (a smooth outline of its rendered pixels, not a staircase of them);
//! the art under it stays as it was. An image in a group with opacity or a blending mode is
//! flattened the same way, and a pattern fill that paints a transparent image (see-through
//! pixels, or opacity or a blending mode on the image, the fill, the shape or a group it is in) is
//! expanded into its tiles first so its images flatten too. With `omit` the images with
//! see-through pixels, opacity or a blending mode of their own are left out, and pattern fills stay
//! as the writer draws them (their tiles opaque over white). An image that can't be decoded is
//! as the writer draws them (their tiles opaque over white). A colorized image is flattened or
//! left out the same way, unless its pixels are all black or white: the writer writes that one as
//! a 1-bit image mask in its color, which keeps its white pixels clear. An image that can't be decoded is
//! missing from the images that flattening and expanding raster effects draw, and the warnings
//! then carry the raster exports' note once.
//!
@@ -179,8 +182,10 @@ fn expand_image_patterns(d: &mut Document) -> Result<()> {
}
/// The images of `d` a legacy `.ai` can't hold, in paint order with their places in it (as
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint, or have opacity
/// or a blending mode of their own or, with `flatten`, of a group they are in.
/// [`Document::walk`] counts). These have see-through pixels or a colorize paint (except the
/// colorized images the writer writes as image masks, clear pixels included,
/// [`vectorcraft_eps::writes_image_mask`]), or
/// have opacity or a blending mode of their own or, with `flatten`, of a group they are in.
/// With `flatten` only visible images are returned, because a hidden one (which the hidden objects
/// option may write) is written over white. With `omit` all of them are returned.
fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
@@ -189,8 +194,7 @@ fn see_through_images(d: &Document, mode: SeeThrough) -> Vec<(usize, NodeId)> {
let mut at = 0;
d.walk(|n| {
if let NodeKind::Image(im) = &n.kind
&& (keys.contains(&im.key)
|| n.extras().colorize.is_some()
&& (((keys.contains(&im.key) || n.extras().colorize.is_some()) && !vectorcraft_eps::writes_image_mask(d, n))
|| n.opacity < 1.0
|| n.blend != BlendMode::Normal
|| (mode == SeeThrough::Flatten && transparent(d, n.id)))
@@ -250,8 +254,11 @@ const MAX_PPI: f64 = 600.0;
const MIN_PPI: f64 = 72.0;
/// A rendered pixel channel changes when it changes by more than this.
const CHANGED: u8 = 2;
/// The clip outline follows cells of about this many points.
const CELL: f64 = 2.0;
/// The clip outline follows the rendered pixels, in blocks of them when there would be more than
/// this many: a huge image's clip would have millions of anchors.
const MAX_CELLS: usize = 4 << 20;
/// How far (in cells) the clip outline may stray from the staircase it smooths.
const SMOOTH: f64 = 0.35;
/// The image `id` (the `at`th node in paint order of `src`) flattened: `src` drawn up to and
/// including it, over white, cropped and clipped to the cells where drawing it changes the
@@ -285,18 +292,21 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result<Option<Flat>> {
if w == 0 || h == 0 || shown.pixels.len() != w * h * 4 || under.pixels.len() != shown.pixels.len() {
return Ok(None);
}
// The cells where it changes anything.
let c = (CELL * scale).round().max(1.0) as usize;
// The cells where it changes anything: its pixels, or blocks of them for a huge image.
let c = if w * h <= MAX_CELLS { 1 } else { ((w * h) as f64 / MAX_CELLS as f64).sqrt().ceil() as usize };
let (cw, ch) = (w.div_ceil(c), h.div_ceil(c));
let mut cells = vec![false; cw * ch];
let mut changed = vec![false; cw * ch];
for (k, (a, b)) in shown.pixels.as_chunks::<4>().0.iter().zip(under.pixels.as_chunks::<4>().0).enumerate() {
if a.iter().zip(b).any(|(a, b)| a.abs_diff(*b) > CHANGED) {
let (x, y) = (k % w, k / w);
if let Some(cell) = cells.get_mut(y / c * cw + x / c) {
if let Some(cell) = changed.get_mut(y / c * cw + x / c) {
*cell = true;
}
}
}
// Grown by a cell, so the clip takes in the whole anti-aliased edge: where the image changes
// nothing it is the art under it, so a clip a little too large shows nothing more.
let cells = grown(&changed, cw, ch);
let marked = || cells.iter().enumerate().filter(|(_, on)| **on).map(|(k, _)| (k % cw, k / cw));
let (Some(x0), Some(x1), Some(y0), Some(y1)) =
(marked().map(|p| p.0).min(), marked().map(|p| p.0).max(), marked().map(|p| p.1).min(), marked().map(|p| p.1).max())
@@ -313,12 +323,16 @@ fn flattened(src: &Document, at: usize, id: NodeId) -> Result<Option<Flat>> {
let crop = vectorcraft_render::Rendered { width: (px1 - px0) as u32, height: (py1 - py0) as u32, pixels };
let png = crop.to_png().map_err(EngineError::Other)?;
let at = |x: usize, y: usize| Point::new(region.x0 + (x.min(w)) as f64 / scale, region.y0 + (y.min(h)) as f64 / scale);
// A cell corner, in cells, as a point of the page.
let (wf, hf, cf) = (w as f64, h as f64, c as f64);
let page = |(x, y): (f64, f64)| Point::new(region.x0 + (x * cf).clamp(0.0, wf) / scale, region.y0 + (y * cf).clamp(0.0, hf) / scale);
let mut clip = PathData::new(vec![]);
for comp in vectorcraft_trace::trace_mask(&cells, cw, ch) {
for lp in std::iter::once(&comp.outer).chain(&comp.holes) {
let pts: Vec<(i32, i32)> = corners(&lp.pts);
let anchors = pts.iter().map(|&(x, y)| Anchor::corner(at(x.max(0) as usize * c, y.max(0) as usize * c))).collect();
clip.subpaths.push(SubPath::new(anchors, true));
let anchors: Vec<Anchor> = smoothed(&lp.pts).into_iter().map(|p| Anchor::corner(page(p))).collect();
if anchors.len() >= 3 {
clip.subpaths.push(SubPath::new(anchors, true));
}
}
}
let xf = Affine::translate(at(px0, py0).to_vec2()) * Affine::scale(1.0 / scale);
@@ -340,17 +354,64 @@ fn up_to(n: &Node, last: usize, i: &mut usize) -> Option<Node> {
Some(n)
}
/// A loop's corners: its points without those in the middle of a straight run.
fn corners(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
/// `mask` (`w × h` cells) with every cell next to a set one set too.
fn grown(mask: &[bool], w: usize, h: usize) -> Vec<bool> {
let set = |x: usize, y: usize| mask.get(y * w + x).copied().unwrap_or(false);
let mut out = vec![false; mask.len()];
for (k, cell) in out.iter_mut().enumerate() {
let (x, y) = (k % w, k / w);
*cell = (y.saturating_sub(1)..(y + 2).min(h)).any(|y| (x.saturating_sub(1)..(x + 2).min(w)).any(|x| set(x, y)));
}
out
}
/// A loop of cell corners (a staircase) as a smooth outline, in cells: the middle of each cell
/// edge along it, so that a run of one-cell steps becomes the sloped line it stands for, without
/// the points that lie (within [`SMOOTH`]) on a straight line between their neighbours.
fn smoothed(pts: &[(i32, i32)]) -> Vec<(f64, f64)> {
let mut mids = Vec::with_capacity(pts.len());
for (k, &(ax, ay)) in pts.iter().enumerate() {
let Some(&(bx, by)) = pts.get(k + 1).or(pts.first()) else { break };
let (dx, dy) = ((bx - ax).signum(), (by - ay).signum());
let steps = (bx - ax).unsigned_abs().max((by - ay).unsigned_abs());
for i in 0..steps as i32 {
let (x, y) = (ax + dx * i, ay + dy * i);
mids.push((f64::from(x) + 0.5 * f64::from(dx), f64::from(y) + 0.5 * f64::from(dy)));
}
}
simplify_closed(&mids, SMOOTH)
}
/// The points of closed polyline `pts` that Douglas–Peucker keeps with tolerance `tol`.
fn simplify_closed(pts: &[(f64, f64)], tol: f64) -> Vec<(f64, f64)> {
let n = pts.len();
let get = |k: usize| pts.get(k % n.max(1)).copied();
(0..n)
.filter_map(|k| {
let (a, b, c) = (get(k + n - 1)?, get(k)?, get(k + 1)?);
let straight = (a.0 == b.0 && b.0 == c.0) || (a.1 == b.1 && b.1 == c.1);
(!straight).then_some(b)
})
.collect()
if n < 4 {
return pts.to_vec();
}
let d2 = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).powi(2) + (a.1 - b.1).powi(2);
let Some(&first) = pts.first() else { return vec![] };
// Split at the first point and the point farthest from it: two open runs.
let far = (1..n).max_by(|&i, &j| d2(first, pts[i]).total_cmp(&d2(first, pts[j]))).unwrap_or(n / 2);
let mut keep = vec![false; n];
keep[0] = true;
keep[far] = true;
let mut todo = vec![(0, far), (far, n)];
while let Some((a, b)) = todo.pop() {
if b <= a + 1 {
continue;
}
let (p, q) = (pts[a], pts[b % n]);
let (ux, uy) = (q.0 - p.0, q.1 - p.1);
let len = ux.hypot(uy);
let dist = |r: (f64, f64)| if len > 0.0 { ((r.0 - p.0) * uy - (r.1 - p.1) * ux).abs() / len } else { d2(p, r).sqrt() };
let Some((m, dm)) = (a + 1..b).map(|i| (i, dist(pts[i]))).max_by(|x, y| x.1.total_cmp(&y.1)) else { continue };
if dm > tol {
keep[m] = true;
todo.push((a, m));
todo.push((m, b));
}
}
pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect()
}
fn note(warnings: &mut Vec<String>, w: &str) {
+2 -2
View File
@@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
name: "editingData",
ty: "boolean",
default: "true",
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)",
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards and which one is active, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
},
FormatOption {
name: "aiVersion",
@@ -121,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
name: "transparentImages",
ty: "string",
default: "\"flatten\"",
description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity or a blending mode): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)",
description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity, a blending mode, or a colorize color unless every pixel is black or white): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)",
},
FormatOption {
name: "hiddenObjects",
+22 -7
View File
@@ -96,7 +96,8 @@ pub struct SavePlan {
/// stamps; `None`: the time it is written.
pub modified: Option<Option<i64>>,
/// Warnings about the params themselves: each native option (`compress`, `version`,
/// `preview`) given beside the path that the format doesn't read.
/// `preview`, `precision`) given beside the path, and each key of `options`, that the format
/// doesn't read, naming the file the save writes.
pub notes: Vec<String>,
}
@@ -289,9 +290,11 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
super::check_not_lossy_overwrite(st, path, p, cmd)?;
}
let written = written_as(cmd, format, &Value::Object(options.clone()));
let notes = NATIVE_OPTIONS
.iter()
.filter(|k| p.get(**k).is_some_and(|v| !v.is_null()) && !reads_option(format, k))
let top = NATIVE_OPTIONS.iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).map(|k| k.to_string());
let nested = p.get("options").and_then(Value::as_object).into_iter().flatten().filter(|(_, v)| !v.is_null()).map(|(k, _)| k);
let notes = top
.filter(|k| !reads_option(format, k))
.chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}")))
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
.collect();
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes })
@@ -447,22 +450,34 @@ fn is_svg(f: &Format) -> bool {
}
/// The document as written: native files carry the view to reopen at and the Layers panel's open
/// rows and transparency grid visibility.
/// rows and transparency grid visibility; a `.ai` file names the view's active artboard
/// ([`DocState::active_artboard`]) as its active one.
fn doc_to_save(st: &DocState, f: &Format) -> Arc<Document> {
if !is_native(f) {
return st.doc.clone();
}
let open = st.layers_open.saved(&st.doc);
if st.doc.last_view == st.view && st.doc.layers_open == open && st.doc.transparency_grid == st.transparency_grid {
let active = moved_active_artboard(st, &st.doc, f);
if st.doc.last_view == st.view && st.doc.layers_open == open && st.doc.transparency_grid == st.transparency_grid && active.is_none() {
return st.doc.clone();
}
let mut d = (*st.doc).clone();
if active.is_some() {
d.opened_artboard = active;
}
d.last_view = st.view.clone();
d.transparency_grid = st.transparency_grid;
d.layers_open = open;
Arc::new(d)
}
/// The artboard a `.ai` or `.ait` file written from `st` (`doc`, the document it writes) names as
/// its active one, when that is not already the one `doc` opened on: the view's active artboard
/// ([`DocState::active_artboard`]), if `doc` has it.
pub(super) fn moved_active_artboard(st: &DocState, doc: &Document, f: &Format) -> Option<u32> {
st.active_artboard.filter(|id| matches!(f.id, "ai" | "ait") && doc.artboards.iter().any(|a| a.id == *id) && doc.opened_artboard != Some(*id))
}
/// What a format loses against a native file (reported whenever a save writes it).
fn fidelity_warning(f: &Format) -> Option<String> {
(!is_native(f)).then(|| {
@@ -1057,7 +1072,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly; separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+1 -1
View File
@@ -459,7 +459,7 @@ fn formats_query_lists_readers_writers_and_options() {
);
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap();
assert_eq!(png["options"]["scale"]["default"], 1);
assert_eq!(png["options"]["scale"]["default"], Value::Null);
assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len());
}
@@ -124,6 +124,85 @@ fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() {
assert_eq!(d.metadata.author, "Ann Lee");
}
#[test]
fn an_ai_file_opens_with_its_active_artboard() {
let board = |x: i32, name: &str| {
format!(
"%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({name}) /UnicodeString (Name) ,\n%_; ,\n",
x + 200
)
};
let document = format!(
"%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /NotRecorded ,\n%_;\n",
board(0, "One"),
board(300, "Two")
);
let data = ai::sample_data();
let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap();
let data = [&data[..at], document.as_bytes(), &data[at..]].concat();
let mut s = Session::new();
let r = open(&mut s, "art.ai", &ai::ai(&compressed(&data), PLACEHOLDER), json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.artboards.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["One", "Two"], "{r}");
assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}");
}
/// A `.ai` save names the view's active artboard in its editing copy, else the one the document
/// opened on, else the first; the file read from that copy opens on it.
#[test]
fn an_ai_save_names_its_active_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 3})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let ids: Vec<u32> = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect();
let opts = LoadOptions { native: false, ..Default::default() };
let active = |s: &mut Session, format: &str| {
let cmd = if format == "ait" { "file.saveAsTemplate" } else { "file.saveCopy" };
let saved = s.execute(cmd, &json!({"format": format})).unwrap();
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let l = load::load_with(&format!("a.{format}"), &bytes, &opts).unwrap();
assert!(l.editing_data && !l.restored, "{:?}", l.warnings);
assert_eq!(l.doc.artboards.len(), 3);
l.doc.opened_artboard.and_then(|id| l.doc.artboards.iter().position(|a| a.id == id)).unwrap_or(0)
};
assert_eq!(active(&mut s, "ai"), 0);
// The view's.
s.doc_mut().unwrap().active_artboard = Some(ids[2]);
assert_eq!((active(&mut s, "ai"), active(&mut s, "ait")), (2, 2));
// The one the document opened on, when the view names none or an artboard it doesn't have.
Arc::make_mut(&mut s.doc_mut().unwrap().doc).opened_artboard = Some(ids[1]);
for view in [None, Some(99)] {
s.doc_mut().unwrap().active_artboard = view;
assert_eq!(active(&mut s, "ai"), 1, "{view:?}");
}
// The view's first artboard over the one the document opened on.
s.doc_mut().unwrap().active_artboard = Some(ids[0]);
assert_eq!(active(&mut s, "ai"), 0);
assert_eq!(s.doc().unwrap().doc.opened_artboard, Some(ids[1]), "the document is unchanged");
}
/// A `.ai` export (`document.serialize`, `document.export`, with or without `selectedOnly`) names
/// the view's active artboard in its editing copy, as a save does.
#[test]
fn an_ai_export_names_its_active_artboard() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 60, "height": 40, "artboards": 3})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let ids: Vec<u32> = s.doc().unwrap().doc.artboards.iter().map(|a| a.id).collect();
s.doc_mut().unwrap().active_artboard = Some(ids[2]);
let opts = LoadOptions { native: false, ..Default::default() };
for (cmd, selected) in [("document.serialize", false), ("document.serialize", true), ("document.export", false)] {
let out = s.execute(cmd, &json!({"format": "ai", "selectedOnly": selected})).unwrap();
let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap();
let l = load::load_with("a.ai", &bytes, &opts).unwrap();
assert!(l.editing_data && !l.restored, "{cmd}: {:?}", l.warnings);
let active = l.doc.opened_artboard.and_then(|id| l.doc.artboards.iter().position(|a| a.id == id));
assert_eq!(active, Some(2), "{cmd} {selected}");
}
assert_eq!(s.doc().unwrap().doc.opened_artboard, None, "the document is unchanged");
}
#[test]
fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() {
let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0));
@@ -287,6 +366,38 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() {
assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}");
}
/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the
/// library the styles of its list, in the list's order, not the default styles; the file opens with
/// them too.
#[test]
fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
let style = |name: &str, xa: &str| {
format!(
"/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
)
};
let styles = format!(
"%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n",
style("Blue", "0 0 0 0 0 0 1 Xa\n"),
style("Green", "0 0 0 0 0 1 0 Xa\n"),
style("Red", "0 0 0 0 1 0 0 Xa\n")
);
let data = ai::editing_data(200.0, 100.0, &styles);
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"});
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}");
let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap();
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Red", "Green", "Blue"], "{lib}");
let r = open(&mut s, "fills.ai", &file, json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect();
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}");
}
/// A 1-bit RGB image opens from the editing data in the colors its PDF part shows.
#[test]
fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
@@ -1023,6 +1134,46 @@ fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() {
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers");
}
/// A story of a `.ai` file's text document with no character or paragraph runs is set in
/// `[Normal Character Style]` and `[Normal Paragraph Style]`; the base attributes give only what
/// those styles leave out.
#[test]
fn an_ai_story_without_runs_takes_the_normal_styles() {
let story = "<< /0 << /0 (Hi\r) >> \
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>";
let char_sheets = "/5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 9.0 \
/53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >>";
let para_sheets = "/6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 6.0 /9 false >> >> >> ] >>";
let document = format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> {char_sheets} {para_sheets} \
/8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
/1 << /1 [ {story} ] /2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 2.0 /9 true >> >>\n"
);
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n";
let data = format!(
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
%AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n",
ai::layer("Art", text),
lines.join("\n")
);
let mut s = Session::new();
let r = open(&mut s, "plain.ai", &ai::ai(&compressed(data.as_bytes()), ""), json!({})).unwrap();
let mut texts = vec![];
s.doc().unwrap().doc.walk(|c| {
if let NodeKind::Text(t) = &c.kind {
texts.push((**t).clone());
}
});
let [t] = texts.as_slice() else { panic!("one text object: {r}") };
assert_eq!(t.plain_text(), "Hi");
let style = &t.runs[0].style;
assert_eq!(style.size, 9.0, "{r}");
assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)));
assert_eq!((t.para.first_line_indent, t.para.hyphenate), (6.0, false));
}
/// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a
/// placeholder): the editing data's type, outlined, as for an empty page.
#[test]

Some files were not shown because too many files have changed in this diff Show More