mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 01:44:57 +01:00
Merge main into release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
96a21d1ea0
449 files changed
+41202
-2311
No files matched your search
@@ -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
|
||||
@@ -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.
|
||||
@@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
@@ -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
+3
@@ -6100,6 +6100,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"smithay-clipboard",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
"vectorcraft-engine",
|
||||
"vectorcraft-render",
|
||||
"vectorcraft-text",
|
||||
@@ -6163,6 +6164,7 @@ dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-engine",
|
||||
@@ -6469,6 +6471,7 @@ dependencies = [
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
"vectorcraft-testkit",
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
+8
-2
@@ -1,5 +1,8 @@
|
||||
# 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.
|
||||
|
||||
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
|
||||
@@ -11,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-03 · **Change:** minor (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
|
||||
@@ -104,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% |
|
||||
@@ -131,6 +134,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
@@ -219,6 +223,8 @@ 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. |
|
||||
| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
|
||||
|
||||
@@ -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 }
|
||||
@@ -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}))?;
|
||||
|
||||
@@ -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.
|
||||
{
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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(¬es, "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));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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"{}");
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="7" width="10" height="10" rx="1.5"/><rect x="3.5" y="3.5" width="17" height="17" rx="5" stroke-dasharray="7.854 7" stroke-dashoffset="7.854"/></svg>
|
||||
|
After Width: | Height: | Size: 347 B |
@@ -209,3 +209,7 @@ sync_github_name = true
|
||||
real_name = "Alexander Buraga"
|
||||
display_name = "Alexander Buraga"
|
||||
sync_github_name = false
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
@@ -151,16 +151,23 @@ pub struct GradientStop {
|
||||
/// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint.
|
||||
#[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")]
|
||||
pub tint: f32,
|
||||
/// Process inks (C, M, Y, K, 0..1) printed together with the linked spot swatch's tint: a
|
||||
/// DeviceN colour of a file that mixes a spot ink with process plates. `color` is how the mix
|
||||
/// looks; separations print the spot ink at `tint` and these plates. `None`: the ink alone.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub plates: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl GradientStop {
|
||||
/// An opaque, unlinked stop of `color` at `offset` with a centred midpoint.
|
||||
pub fn new(offset: f32, color: Color) -> Self {
|
||||
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 }
|
||||
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0, plates: None }
|
||||
}
|
||||
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked.
|
||||
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked, without
|
||||
/// process plates.
|
||||
pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) {
|
||||
self.color = color;
|
||||
self.plates = None;
|
||||
(self.swatch, self.tint) = match link {
|
||||
Some((n, t)) => (Some(n), t),
|
||||
None => (None, 1.0),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Color Halftone's Max Radius was a distance in points until documents of version 3; since then
|
||||
//! it is in pixels of the Document Raster Effects resolution, as public documentation gives it
|
||||
//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents, and
|
||||
//! [`Document::halftone_radii_to_points`] converts them back for a file saved for an older app.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::limits::FORMAT_VERSION;
|
||||
use crate::{Appearance, Document, Effect, Node};
|
||||
|
||||
/// The first document version whose Color Halftone radii are in pixels.
|
||||
const PIXEL_RADII_SINCE: u32 = 3;
|
||||
const HALFTONE: &str = "pixelate.colorHalftone";
|
||||
const RADIUS: &str = "maxRadius";
|
||||
/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s
|
||||
/// `DOC_KEY`), whose art can carry effects.
|
||||
const BRUSHES: &str = "brushes";
|
||||
/// The radius (points) an older document's halftone without one drew with.
|
||||
const OLD_DEFAULT: f64 = 8.0;
|
||||
/// The range the radius was kept within in points, and is kept within in pixels.
|
||||
const RANGE: std::ops::RangeInclusive<f64> = 4.0..=127.0;
|
||||
|
||||
impl Document {
|
||||
/// Saved before version 3: each Color Halftone's Max Radius in points becomes the pixels of
|
||||
/// the document's raster effects resolution that draw the same dots, within the 4 to 127 px
|
||||
/// the effect takes (a radius over 127 px, from a large radius at a high resolution, draws
|
||||
/// smaller dots than before). In the art, symbols, patterns, graph designs, opacity masks and
|
||||
/// graphic styles.
|
||||
pub fn migrate_halftone_radii(&mut self) {
|
||||
if self.version >= PIXEL_RADII_SINCE {
|
||||
return;
|
||||
}
|
||||
self.version = FORMAT_VERSION;
|
||||
let k = self.raster_ppi() / 72.0;
|
||||
self.each_halftone(&mut |e| rescale(e, k));
|
||||
}
|
||||
|
||||
/// For a file saved for an app before version 3 (every native file version before today's):
|
||||
/// each Color Halftone's Max Radius in pixels becomes the points that draw the same dots,
|
||||
/// within the 4 to 127 pt that app takes (a radius under 4 pt, from a fine screen at a high
|
||||
/// resolution, draws bigger dots there), and the document becomes version 2, so reopening the
|
||||
/// file here converts them back.
|
||||
pub fn halftone_radii_to_points(&mut self) {
|
||||
if self.version < PIXEL_RADII_SINCE {
|
||||
return;
|
||||
}
|
||||
self.version = PIXEL_RADII_SINCE - 1;
|
||||
let k = 72.0 / self.raster_ppi();
|
||||
self.each_halftone(&mut |e| rescale(e, k));
|
||||
}
|
||||
|
||||
/// `fix` each effect in the art, symbols, patterns (and the one being edited as it was), graph
|
||||
/// designs, opacity masks, Shaper edits, graphic styles and brush definitions that use a Color
|
||||
/// Halftone.
|
||||
fn each_halftone(&mut self, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
for l in &mut self.layers {
|
||||
node(l, fix);
|
||||
}
|
||||
for s in &mut self.symbols {
|
||||
node(&mut s.art, fix);
|
||||
}
|
||||
// Pattern editing is saved with the pattern as it was, which Cancel puts back.
|
||||
for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) {
|
||||
for a in &mut p.art {
|
||||
node(a, fix);
|
||||
}
|
||||
}
|
||||
for g in &mut self.graph_designs {
|
||||
node(&mut g.art, fix);
|
||||
}
|
||||
if self.graphic_styles.iter().any(|s| has_halftone(&s.appearance)) {
|
||||
for s in self.graphic_styles.iter_mut() {
|
||||
appearance(&mut s.appearance, fix);
|
||||
}
|
||||
}
|
||||
if let Some(b) = self.unknown.get_mut(BRUSHES) {
|
||||
brushes(b, fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `fix` each Color Halftone in JSON `v` (brush definitions): every object whose `id` is
|
||||
/// [`HALFTONE`] is a serialized [`Effect`] (object ids are numbers).
|
||||
fn brushes(v: &mut Value, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
match v {
|
||||
Value::Object(m) if m.get("id").and_then(Value::as_str) == Some(HALFTONE) => {
|
||||
let params = m.get("params").cloned().unwrap_or(Value::Null);
|
||||
let mut e = Effect { id: HALFTONE.into(), params, visible: true };
|
||||
fix(&mut e);
|
||||
m.insert("params".into(), e.params);
|
||||
}
|
||||
Value::Object(m) => m.values_mut().for_each(|v| brushes(v, fix)),
|
||||
Value::Array(a) => a.iter_mut().for_each(|v| brushes(v, fix)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `e`'s radius times `k` (pixels a point, or points a pixel), within the effect's range, when it
|
||||
/// is a Color Halftone. Its default is 8 in either unit.
|
||||
fn rescale(e: &mut Effect, k: f64) {
|
||||
if e.id != HALFTONE {
|
||||
return;
|
||||
}
|
||||
let pt = e.params.get(RADIUS).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(OLD_DEFAULT);
|
||||
let px = pt.clamp(*RANGE.start(), *RANGE.end()) * k;
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Default::default());
|
||||
}
|
||||
e.params[RADIUS] = json!(px.clamp(*RANGE.start(), *RANGE.end()));
|
||||
}
|
||||
|
||||
fn has_halftone(a: &Appearance) -> bool {
|
||||
a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).any(|e| e.id == HALFTONE)
|
||||
}
|
||||
|
||||
fn appearance(a: &mut Appearance, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
|
||||
fix(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fix the effects of `n`'s subtree, its opacity masks and its Shaper edits (copying only what
|
||||
/// changes).
|
||||
fn node(n: &mut Arc<Node>, fix: &mut dyn FnMut(&mut Effect)) {
|
||||
let n = Arc::make_mut(n);
|
||||
if has_halftone(&n.appearance) {
|
||||
appearance(&mut n.appearance, fix);
|
||||
}
|
||||
if let Some(x) = n.extras_if_any() {
|
||||
if let Some(m) = x.mask.as_mut() {
|
||||
node(&mut m.art, fix);
|
||||
}
|
||||
// A Shaper Group's face and edge edits paint with appearances of their own.
|
||||
if let Some(s) = x.shaper.as_mut() {
|
||||
let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut());
|
||||
for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) {
|
||||
appearance(p, fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
node(c, fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn halftone(radius: Option<f64>) -> Effect {
|
||||
let params = radius.map_or_else(|| json!({"channel1": 108.0}), |r| json!({"maxRadius": r, "channel1": 108.0}));
|
||||
Effect { id: HALFTONE.into(), params, visible: true }
|
||||
}
|
||||
|
||||
fn radius(e: &Effect) -> f64 {
|
||||
e.params[RADIUS].as_f64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_radii_become_the_pixels_that_draw_the_same_dots() {
|
||||
for (ppi, pt, px) in [(72.0, 8.0, 8.0), (300.0, 8.0, 33.333333333333336), (300.0, 4.0, 16.666666666666668), (150.0, 127.0, 127.0)] {
|
||||
let mut e = halftone(Some(pt));
|
||||
rescale(&mut e, ppi / 72.0);
|
||||
assert!((radius(&e) - px).abs() < 1e-9, "{pt} pt at {ppi} ppi: {}", radius(&e));
|
||||
assert_eq!(e.params["channel1"], json!(108.0), "the angles stay");
|
||||
}
|
||||
// A radius left out drew at the old default, 8 pt.
|
||||
let mut e = halftone(None);
|
||||
rescale(&mut e, 300.0 / 72.0);
|
||||
assert!((radius(&e) - 33.333333333333336).abs() < 1e-9);
|
||||
// Other effects keep their parameters.
|
||||
let mut blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 8.0}), visible: true };
|
||||
rescale(&mut blur, 300.0 / 72.0);
|
||||
assert_eq!(blur.params, json!({"radius": 8.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_documents_before_version_3_are_converted_once() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let mut style = d.graphic_styles.first().cloned().unwrap();
|
||||
style.appearance.effects.push(halftone(Some(8.0)));
|
||||
d.graphic_styles.push(style);
|
||||
let fresh = d.clone();
|
||||
d.migrate_halftone_radii();
|
||||
assert_eq!(d, fresh, "a new document's radii are already pixels");
|
||||
d.version = 1;
|
||||
d.migrate_halftone_radii();
|
||||
assert_eq!(d.version, FORMAT_VERSION);
|
||||
let r = d.graphic_styles.last().map(|s| radius(&s.appearance.effects[0])).unwrap();
|
||||
assert!((r - 33.333333333333336).abs() < 1e-9, "{r}");
|
||||
let once = d.clone();
|
||||
d.migrate_halftone_radii();
|
||||
assert_eq!(d, once, "converted documents are left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radii_go_back_to_points_for_an_older_app_and_return_unchanged() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let mut style = d.graphic_styles.first().cloned().unwrap();
|
||||
style.appearance.effects.push(halftone(Some(100.0)));
|
||||
style.appearance.effects.push(halftone(Some(4.0)));
|
||||
d.graphic_styles.push(style);
|
||||
let r = |d: &Document, i: usize| d.graphic_styles.last().map(|s| radius(&s.appearance.effects[i])).unwrap();
|
||||
d.halftone_radii_to_points();
|
||||
assert_eq!(d.version, 2, "reopened here, it converts back");
|
||||
assert!((r(&d, 0) - 24.0).abs() < 1e-9, "100 px at 300 ppi is 24 pt: {}", r(&d, 0));
|
||||
assert_eq!(r(&d, 1), 4.0, "0.96 pt is under the 4 pt the older app takes");
|
||||
let points = d.clone();
|
||||
d.halftone_radii_to_points();
|
||||
assert_eq!(d, points, "already in points");
|
||||
d.migrate_halftone_radii();
|
||||
assert!((r(&d, 0) - 100.0).abs() < 1e-9, "{}", r(&d, 0));
|
||||
}
|
||||
|
||||
/// Shaper face and edge edits paint with appearances of their own, and brush definitions keep
|
||||
/// their art as JSON: their radii convert both ways too.
|
||||
#[test]
|
||||
fn shaper_edits_and_brushes_are_converted_both_ways() {
|
||||
use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec};
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
d.version = 1;
|
||||
let mut look = Appearance::default_art();
|
||||
look.effects = vec![halftone(Some(8.0))];
|
||||
let face = FaceEdit {
|
||||
selector: FaceSelector { sources: vec![0], anchor: vectorcraft_geom::Point::ZERO },
|
||||
erase: false,
|
||||
erase_edges: false,
|
||||
paint_source: None,
|
||||
merge: None,
|
||||
paint: Some(look),
|
||||
};
|
||||
let mut shaper = Node::group(d.alloc_id(), vec![]);
|
||||
shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] }));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, shaper).unwrap();
|
||||
let effect = serde_json::to_value(halftone(Some(8.0))).unwrap();
|
||||
d.unknown.insert(BRUSHES.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [effect]}}}]));
|
||||
let radii = |d: &Document| {
|
||||
let shaper = d.layers[0].children().and_then(|c| c.first()).cloned().unwrap();
|
||||
let paint = shaper.extras().shaper.as_ref().and_then(|s| s.faces[0].paint.clone()).unwrap();
|
||||
let brush = d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"][RADIUS].as_f64().unwrap();
|
||||
(radius(&paint.effects[0]), brush)
|
||||
};
|
||||
d.migrate_halftone_radii();
|
||||
let (face, brush) = radii(&d);
|
||||
assert!((face - 33.333333333333336).abs() < 1e-9, "the face edit: {face}");
|
||||
assert!((brush - 33.333333333333336).abs() < 1e-9, "the brush: {brush}");
|
||||
assert_eq!(d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"]["channel1"], json!(108.0));
|
||||
d.halftone_radii_to_points();
|
||||
let (face, brush) = radii(&d);
|
||||
assert!((face - 8.0).abs() < 1e-9 && (brush - 8.0).abs() < 1e-9, "back in points: {face}, {brush}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pattern_being_edited_is_converted_as_it_was() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.raster_effects_ppi = 300.0;
|
||||
let id = d.alloc_id();
|
||||
let mut look = Appearance::default_art();
|
||||
look.effects = vec![halftone(Some(8.0))];
|
||||
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let tile = Arc::new(Node::path(id, square, look));
|
||||
let original = Some(crate::PatternDef::new("Tile", vec![tile]));
|
||||
d.pattern_edit = Some(crate::PatternEdit { pattern: "Tile".into(), layer: crate::NodeId(0), original });
|
||||
d.version = 1;
|
||||
d.migrate_halftone_radii();
|
||||
let art = &d.pattern_edit.as_ref().unwrap().original.as_ref().unwrap().art[0];
|
||||
assert!((radius(&art.appearance.effects[0]) - 33.333333333333336).abs() < 1e-9, "the tile Cancel puts back");
|
||||
}
|
||||
}
|
||||
+83
-4
@@ -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 {
|
||||
@@ -508,8 +509,9 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
&& let Some(mut chain) = doc.ancestry(scope)
|
||||
{
|
||||
// Isolated before its artboard was locked: nothing in it hits.
|
||||
if locks.holds_id(scope) {
|
||||
// Isolated before its artboard, or its layer or a group around it, was locked or hidden:
|
||||
// nothing in it hits (#5309).
|
||||
if !doc.is_editable_with(&locks, scope) {
|
||||
return None;
|
||||
}
|
||||
if isolated.is_container() {
|
||||
@@ -723,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.
|
||||
@@ -734,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);
|
||||
@@ -893,6 +969,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
let mut out = Vec::new();
|
||||
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
|
||||
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match (s.children(), marquee_in(s, r)) {
|
||||
(Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
(Some(_), None) => vec![],
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod corners;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod inks;
|
||||
@@ -324,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. `None`: the first. Never
|
||||
/// saved.
|
||||
#[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")]
|
||||
|
||||
@@ -14,8 +14,10 @@ pub enum DocError {
|
||||
}
|
||||
|
||||
/// The document version new documents get. Version 2: a positive Twist angle turns clockwise
|
||||
/// ([`crate::twist`]).
|
||||
pub const FORMAT_VERSION: u32 = 2;
|
||||
/// ([`crate::twist`]). Version 3: Color Halftone's Max Radius is in pixels of the raster effects
|
||||
/// resolution (older documents are converted on opening,
|
||||
/// [`crate::Document::migrate_halftone_radii`]).
|
||||
pub const FORMAT_VERSION: u32 = 3;
|
||||
|
||||
/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so
|
||||
/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718).
|
||||
|
||||
+78
-2
@@ -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.
|
||||
|
||||
@@ -143,8 +143,11 @@ pub struct CharStyle {
|
||||
pub no_break: bool,
|
||||
/// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these
|
||||
/// characters are shaped in, so that the font uses that language's forms (OpenType `locl`).
|
||||
/// `None`: the default language, English: USA, shaped without a language. New type takes the
|
||||
/// document's language (Document Setup). Saved only when set.
|
||||
/// `None`: the default language, English: USA, shaped without a language, which is what text
|
||||
/// saved without one reads as. A tag the list doesn't have, from a file, is kept and has no
|
||||
/// hyphenation. New type takes the document's language (Document Setup), else the default
|
||||
/// language of Preferences › Hyphenation. Saved only when set. Each run hyphenates in its own
|
||||
/// language (`vectorcraft_text::hyphen`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
/// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates
|
||||
|
||||
@@ -43,13 +43,25 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool {
|
||||
}
|
||||
|
||||
/// The range in points that distance parameter `key` of effect `id` is kept within, as its
|
||||
/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none.
|
||||
/// parameter documentation gives it (`{edgeWidth: pt 1..14 (2), …}`); `None` when it gives none.
|
||||
pub fn length_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
documented_range(id, key, "pt")
|
||||
}
|
||||
|
||||
/// The range of parameter `key` of effect `id` when it is a size in pixels of the Document Raster
|
||||
/// Effects resolution (`{maxRadius: px 4..127 (8), …}`), which no unit setting changes and which
|
||||
/// stays in pixels when the resolution does; `None` for other parameters.
|
||||
pub fn raster_px_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
documented_range(id, key, "px")
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`).
|
||||
fn documented_range(id: &str, key: &str, unit: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' ');
|
||||
let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt "))
|
||||
rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ')
|
||||
})?;
|
||||
let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?;
|
||||
let (lo, hi) = (lo.parse::<f64>().ok()?, hi.trim_end_matches(',').parse::<f64>().ok()?);
|
||||
@@ -81,7 +93,6 @@ fn lengths_of(id: &str) -> Lengths {
|
||||
"brushStrokes.spatter" => always(&["sprayRadius"]),
|
||||
"brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]),
|
||||
"brushStrokes.sumiE" => always(&["strokeWidth"]),
|
||||
"pixelate.colorHalftone" => always(&["maxRadius"]),
|
||||
"pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]),
|
||||
"texture.craquelure" => always(&["crackSpacing"]),
|
||||
"texture.mosaicTiles" => always(&["tileSize"]),
|
||||
@@ -296,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…",
|
||||
@@ -633,7 +650,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"pixelate.colorHalftone",
|
||||
"Color Halftone…",
|
||||
PIXELATE,
|
||||
"{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
|
||||
"{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell",
|
||||
json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}),
|
||||
),
|
||||
r(
|
||||
|
||||
@@ -79,8 +79,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint,
|
||||
needs_outline, outline_art, outline_text, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options,
|
||||
image_paint, needs_outline, outline_art, outline_text, reshape,
|
||||
};
|
||||
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
|
||||
pub use solids::{
|
||||
@@ -95,7 +95,7 @@ mod catalog;
|
||||
mod geometry;
|
||||
mod params;
|
||||
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects};
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
|
||||
pub(crate) use geometry::{Budget, apply_one};
|
||||
pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,13 +95,16 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
}
|
||||
|
||||
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
|
||||
/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the
|
||||
/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
|
||||
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
|
||||
/// keep their share of the object so. A distance left at its default is written out scaled; one
|
||||
/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
|
||||
pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
let Some(info) = catalog_index().get(e.id.as_str()) else { return };
|
||||
let merged = merged_params(&e.id, &e.params);
|
||||
let relative = util::flag(&merged, "relative", false);
|
||||
for k in info.lengths.keys(relative) {
|
||||
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
|
||||
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
|
||||
for k in keys {
|
||||
let v = util::num(&merged, k, f64::NAN);
|
||||
if v.is_finite() {
|
||||
if !e.params.is_object() {
|
||||
|
||||
@@ -254,7 +254,8 @@ pub enum PixelFx {
|
||||
/// Stylize › Glowing Edges: bright coloured Sobel outlines on black.
|
||||
GlowingEdges { width: f64, brightness: f64, smoothness: f64 },
|
||||
/// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels
|
||||
/// 1 to 4) into dots of up to `max_radius`, whose area follows the channel's strength.
|
||||
/// 1 to 4) into dots of up to `max_radius` pixels of the Document Raster Effects resolution
|
||||
/// ([`PixelSpace::line`] each), whose area follows the channel's strength.
|
||||
ColorHalftone { max_radius: f64, angles: [f64; 4] },
|
||||
/// Pixelate › Crystallize: polygons of solid colour around random points about `cell` apart.
|
||||
Crystallize { cell: f64 },
|
||||
@@ -668,9 +669,10 @@ impl PixelFx {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (document units) from a pixel the content that decides it lies; `None` when that
|
||||
/// is anywhere in the object (Radial Blur).
|
||||
pub fn reach(&self) -> Option<f64> {
|
||||
/// How far (document units) from a pixel the content that decides it lies, with lines of the
|
||||
/// raster grid `line` apart ([`PixelSpace::line`]); `None` when that is anywhere in the object
|
||||
/// (Radial Blur).
|
||||
pub fn reach(&self, line: f64) -> Option<f64> {
|
||||
match *self {
|
||||
PixelFx::RadialBlur { .. } => None,
|
||||
PixelFx::SmartBlur { radius, mode: SmartBlurMode::Normal, .. } => Some(radius),
|
||||
@@ -703,7 +705,10 @@ impl PixelFx {
|
||||
PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)),
|
||||
PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)),
|
||||
// The cells around the pixel's, and the cells around theirs.
|
||||
PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius),
|
||||
// (Without a usable grid there are no dots: see `pixelate::color_halftone`.)
|
||||
PixelFx::ColorHalftone { max_radius, .. } => {
|
||||
Some(3.0 * std::f64::consts::SQRT_2 * max_radius * line).filter(|d| d.is_finite()).or(Some(0.0))
|
||||
}
|
||||
PixelFx::Crystallize { cell } => Some(1.5 * cell),
|
||||
PixelFx::ColoredPencil { width, .. } => Some(artistic::colored_pencil_reach(width)),
|
||||
PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH),
|
||||
@@ -1074,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)]
|
||||
|
||||
@@ -436,11 +436,12 @@ impl Screen {
|
||||
}
|
||||
|
||||
/// Color Halftone: each channel screened at its angle in square cells sized so that a dot of
|
||||
/// `max_radius` fills one; each cell's dot covers the share of it that is the channel's mean
|
||||
/// there (white stays white, black black). Coverage stays as it is.
|
||||
/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's
|
||||
/// dot covers the share of it that is the channel's mean there (white stays white, black black).
|
||||
/// Coverage stays as it is.
|
||||
pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) {
|
||||
let Some(place) = Place::new(space, w, h) else { return };
|
||||
let side = max_radius * std::f64::consts::SQRT_2;
|
||||
let side = max_radius * space.line * std::f64::consts::SQRT_2;
|
||||
// Cells under 3 pixels can't show their dots: on average a screen is the image itself.
|
||||
if !(side.is_finite() && side / place.px >= 3.0) {
|
||||
return;
|
||||
|
||||
@@ -80,7 +80,7 @@ fn film_grain_parameters_are_bounded_and_neutral_settings_preserve_the_art() {
|
||||
neutral.apply(&mut out, w, h, &space(w, h));
|
||||
assert_eq!(out, src);
|
||||
assert_eq!(neutral.outset(Rect::new(0.0, 0.0, w as f64, h as f64)), 0.0);
|
||||
assert_eq!(neutral.reach(), Some(0.0));
|
||||
assert_eq!(neutral.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -520,12 +520,12 @@ fn outsets_follow_the_object() {
|
||||
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
|
||||
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(), Some(4.0));
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0));
|
||||
// The edge modes also read the copy blurred over a wide radius's samples.
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(), Some(5.0));
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(1.0), Some(5.0));
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({})).outset(b), 0.0);
|
||||
assert_eq!(spin.reach(), None);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(), Some(6.0));
|
||||
assert_eq!(spin.reach(1.0), None);
|
||||
assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(1.0), Some(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -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]
|
||||
@@ -962,7 +984,7 @@ fn pixelate_params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("pixelate.crystallize", json!({"cellSize": 20})).outset(b), 30.0);
|
||||
assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 20})).outset(b), 30.0);
|
||||
assert_eq!(fx("pixelate.colorHalftone", json!({})).outset(b), 0.0);
|
||||
assert_eq!(fx("pixelate.mezzotint", json!({})).reach(), Some(0.0));
|
||||
assert_eq!(fx("pixelate.mezzotint", json!({})).reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
/// Fraction of `d`'s pixels for which `f` holds.
|
||||
@@ -1002,6 +1024,25 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() {
|
||||
assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() {
|
||||
// Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a
|
||||
// point apart) are the 8 px of 72 ppi, and draw the same dots.
|
||||
let (w, h) = (64, 64);
|
||||
let src = image(w, h, |x, y| [(x * 4) as u8, (y * 4) as u8, 128, 255]);
|
||||
let run = |radius: f64, line: f64| {
|
||||
let mut d = src.clone();
|
||||
fx("pixelate.colorHalftone", json!({"maxRadius": radius})).apply(&mut d, w, h, &PixelSpace { line, ..space(w, h) });
|
||||
d
|
||||
};
|
||||
assert_eq!(run(16.0, 0.5), run(8.0, 1.0));
|
||||
assert_ne!(run(8.0, 0.5), run(8.0, 1.0), "the same radius at a finer resolution draws finer dots");
|
||||
// It looks as far around a pixel as its cells reach, in document units.
|
||||
let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8}));
|
||||
assert_eq!(halftone.reach(0.5), Some(3.0 * std::f64::consts::SQRT_2 * 4.0));
|
||||
assert_eq!(halftone.reach(f64::NAN), Some(0.0), "no grid, no dots");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftone_screens_inks_in_cmyk_documents() {
|
||||
let (w, h) = (64, 64);
|
||||
@@ -1241,8 +1282,8 @@ fn texture_params_take_defaults_and_stay_in_range() {
|
||||
for id in ["texture.craquelure", "texture.grain", "texture.mosaicTiles", "texture.texturizer"] {
|
||||
assert_eq!(fx(id, json!({})).outset(b), 0.0, "{id}");
|
||||
}
|
||||
assert_eq!(fx("texture.grain", json!({})).reach(), Some(0.0));
|
||||
assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(), Some(6.0));
|
||||
assert_eq!(fx("texture.grain", json!({})).reach(1.0), Some(0.0));
|
||||
assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(1.0), Some(6.0));
|
||||
}
|
||||
|
||||
/// The pixels of `d` (`w` wide) in the square `lo..hi` on both axes.
|
||||
@@ -1509,9 +1550,9 @@ fn distort_params_take_defaults_and_stay_in_range() {
|
||||
// Shifted content reaches past the bounds by the longest shift, and comes from as far.
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
let glass = fx("distort.glass", json!({"distortion": 20}));
|
||||
assert_eq!((glass.outset(b), glass.reach()), (10.0, Some(10.0)));
|
||||
assert_eq!((glass.outset(b), glass.reach(1.0)), (10.0, Some(10.0)));
|
||||
let ripple = fx("distort.oceanRipple", json!({}));
|
||||
assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach() == Some(ripple.outset(b)));
|
||||
assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach(1.0) == Some(ripple.outset(b)));
|
||||
assert_eq!(fx("distort.diffuseGlow", json!({})).outset(b), 0.0);
|
||||
}
|
||||
|
||||
@@ -1621,7 +1662,7 @@ fn ocean_ripple_moves_content_no_farther_than_its_magnitude() {
|
||||
fx("distort.oceanRipple", json!({"rippleMagnitude": 0})).apply(&mut d, w, h, &space(w, h));
|
||||
assert_eq!(d, src, "no magnitude, no ripples");
|
||||
let f = fx("distort.oceanRipple", json!({"rippleSize": 6, "rippleMagnitude": 20}));
|
||||
let most = f.reach().unwrap();
|
||||
let most = f.reach(1.0).unwrap();
|
||||
let mut d = src.clone();
|
||||
f.apply(&mut d, w, h, &space(w, h));
|
||||
assert_ne!(d, src);
|
||||
@@ -1765,19 +1806,19 @@ fn brush_strokes_outsets() {
|
||||
let reach = brushstrokes::stroke_reach;
|
||||
assert!((reach(20.0) - (0.75 * 20.0 + 1.5 / 15.0 * 20.0 + 1.0)).abs() < 1e-9);
|
||||
assert_eq!(fx("brushStrokes.accentedEdges", json!({})).outset(b), 0.0);
|
||||
assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0));
|
||||
assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(1.0), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0));
|
||||
assert_eq!(fx("brushStrokes.angledStrokes", json!({})).outset(b), reach(15.0));
|
||||
assert_eq!(fx("brushStrokes.crosshatch", json!({})).outset(b), reach(9.0) + 0.9);
|
||||
assert_eq!(fx("brushStrokes.darkStrokes", json!({})).outset(b), reach(9.0));
|
||||
assert_eq!(fx("brushStrokes.inkOutlines", json!({"strokeLength": 50})).outset(b), reach(50.0));
|
||||
let spatter = fx("brushStrokes.spatter", json!({}));
|
||||
assert_eq!((spatter.outset(b), spatter.reach()), (4.0, Some(4.0)));
|
||||
assert_eq!((spatter.outset(b), spatter.reach(1.0)), (4.0, Some(4.0)));
|
||||
assert_eq!(fx("brushStrokes.spatter", json!({"sprayRadius": 0})).outset(b), 0.0);
|
||||
assert_eq!(fx("brushStrokes.sprayedStrokes", json!({})).outset(b), reach(12.0) + 0.3 * 7.0);
|
||||
assert_eq!(fx("brushStrokes.sumiE", json!({})).outset(b), 0.0);
|
||||
for id in brush_strokes() {
|
||||
let f = fx(id, json!({}));
|
||||
assert!(f.reach().is_some_and(|r| r >= f.outset(b)), "{id}");
|
||||
assert!(f.reach(1.0).is_some_and(|r| r >= f.outset(b)), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1961,7 +2002,7 @@ fn spatter_scatters_content_no_farther_than_its_radius() {
|
||||
let src = image(w, h, |x, _| if x < 32 { grey(255) } else { [0; 4] });
|
||||
assert_eq!(run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 0})), src, "no radius, no spatter");
|
||||
let f = fx("brushStrokes.spatter", json!({"sprayRadius": 15}));
|
||||
let most = f.reach().unwrap();
|
||||
let most = f.reach(1.0).unwrap();
|
||||
let d = run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 15}));
|
||||
assert_ne!(d, src);
|
||||
let inside = |v: usize, n: usize| (v as f64 + 0.5).min(n as f64 - v as f64 - 0.5) > most + 1.0;
|
||||
@@ -1990,7 +2031,7 @@ fn brush_strokes_look_no_farther_than_their_reach() {
|
||||
("brushStrokes.sumiE", json!({"strokeWidth": 15})),
|
||||
]);
|
||||
for (id, p) in cases {
|
||||
let reach = fx(id, p.clone()).reach().unwrap();
|
||||
let reach = fx(id, p.clone()).reach(1.0).unwrap();
|
||||
// Everything from `cut` on differs; the pixels left of 20 can't tell.
|
||||
let cut = 20 + reach.ceil() as usize + 1;
|
||||
assert!(cut < w, "{id}");
|
||||
@@ -2047,7 +2088,7 @@ fn chalk_charcoal_params_take_defaults_and_stay_in_range() {
|
||||
assert!(doc.contains("chalkArea") && doc.contains("charcoalArea") && doc.contains("strokePressure"), "{doc}");
|
||||
let f = fx("sketch.chalkCharcoal", json!({"strokePressure": 5}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert!(f.reach().unwrap() > 0.0);
|
||||
assert!(f.reach(1.0).unwrap() > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2108,7 +2149,7 @@ fn graphic_pen_params_take_defaults_and_stay_in_range() {
|
||||
assert!(STROKE_DIRECTIONS.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}");
|
||||
let f = fx("sketch.graphicPen", json!({"strokeLength": 15}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), brushstrokes::stroke_reach(15.0));
|
||||
assert_eq!(f.reach(), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH)));
|
||||
assert_eq!(f.reach(1.0), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH)));
|
||||
assert_eq!(
|
||||
fx("sketch.graphicPen", json!({"strokeLength": 99})),
|
||||
PixelFx::GraphicPen { length: 15.0, balance: 50.0, direction: StrokeDirection::RightDiagonal }
|
||||
@@ -2148,7 +2189,7 @@ fn halftone_pattern_params_take_defaults_and_stay_in_range() {
|
||||
assert!(HALFTONE_TYPES.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}");
|
||||
let f = fx("sketch.halftonePattern", json!({"size": 12}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(0.0));
|
||||
assert_eq!(f.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2162,7 +2203,7 @@ fn note_paper_params_take_defaults_and_stay_in_range() {
|
||||
assert!(doc.contains("imageBalance") && doc.contains("graininess") && doc.contains("relief"), "{doc}");
|
||||
let f = fx("sketch.notePaper", json!({"relief": 12}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(0.0));
|
||||
assert_eq!(f.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
/// Note Paper embosses a horizontal gradient and graininess adds fibre.
|
||||
@@ -2198,7 +2239,7 @@ fn water_paper_params_take_defaults_and_stay_in_range() {
|
||||
);
|
||||
let f = fx("sketch.waterPaper", json!({"fiberLength": 40}));
|
||||
assert!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)) > 0.0);
|
||||
assert!(f.reach().unwrap_or(0.0) > 0.0);
|
||||
assert!(f.reach(1.0).unwrap_or(0.0) > 0.0);
|
||||
let doc = crate::effect_info("sketch.waterPaper").unwrap().params;
|
||||
assert!(doc.contains("unverified"), "{doc}");
|
||||
}
|
||||
@@ -2281,7 +2322,7 @@ fn plaster_params_take_defaults_and_stay_in_range() {
|
||||
let doc = crate::effect_info("sketch.plaster").unwrap().params;
|
||||
assert!(doc.contains("\"bottomRight\""), "{doc}");
|
||||
let f = fx("sketch.plaster", json!({"smoothness": 24}));
|
||||
assert_eq!(f.reach(), Some(super::sketch::plaster_reach(15.0)));
|
||||
assert_eq!(f.reach(1.0), Some(super::sketch::plaster_reach(15.0)));
|
||||
}
|
||||
|
||||
/// Plaster changes the image and different light directions give different results.
|
||||
@@ -2356,8 +2397,8 @@ fn chrome_params_take_defaults_and_stay_in_range() {
|
||||
assert!(doc.contains("detail") && doc.contains("smoothness"), "{doc}");
|
||||
let f = fx("sketch.chrome", json!({}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(sketch::chrome_reach(4.0)));
|
||||
assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(), Some(sketch::chrome_reach(10.0)));
|
||||
assert_eq!(f.reach(1.0), Some(sketch::chrome_reach(4.0)));
|
||||
assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(1.0), Some(sketch::chrome_reach(10.0)));
|
||||
}
|
||||
|
||||
/// Chrome redraws in greyscale, keeps coverage, and more detail changes the pattern.
|
||||
@@ -2389,7 +2430,7 @@ fn reticulation_params_take_defaults_and_stay_in_range() {
|
||||
);
|
||||
let f = fx("sketch.reticulation", json!({}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0);
|
||||
assert_eq!(f.reach(), Some(0.0));
|
||||
assert_eq!(f.reach(1.0), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2431,7 +2472,7 @@ fn torn_edges_params_take_defaults_and_stay_in_range() {
|
||||
for junk in [json!({"imageBalance": "x"}), json!({"smoothness": null})] {
|
||||
assert_eq!(fx("sketch.tornEdges", junk), fx("sketch.tornEdges", json!({})));
|
||||
}
|
||||
assert_eq!(fx("sketch.tornEdges", json!({})).reach(), None);
|
||||
assert_eq!(fx("sketch.tornEdges", json!({})).reach(1.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2496,7 +2537,7 @@ fn artistic_params_take_defaults_and_stay_in_range() {
|
||||
fx("artistic.coloredPencil", json!({"pencilWidth": 0, "strokePressure": 200, "paperBrightness": -5})),
|
||||
PixelFx::ColoredPencil { width: 1.0, pressure: 15.0, paper: 0.0 }
|
||||
);
|
||||
assert_eq!(fx("artistic.coloredPencil", json!({})).reach(), Some(artistic::colored_pencil_reach(5.0)));
|
||||
assert_eq!(fx("artistic.coloredPencil", json!({})).reach(1.0), Some(artistic::colored_pencil_reach(5.0)));
|
||||
assert_eq!(fx("artistic.cutout", json!({})), PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 });
|
||||
assert_eq!(
|
||||
fx("artistic.cutout", json!({"levels": 1e308, "edgeSimplicity": -5, "edgeFidelity": "NaN"})),
|
||||
@@ -2860,7 +2901,7 @@ fn dry_brush_repaints_and_preserves_coverage() {
|
||||
let before = clear.clone();
|
||||
fx("artistic.dryBrush", json!({})).apply(&mut clear, w, h, &space(w, h));
|
||||
assert_eq!(clear, before);
|
||||
let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach();
|
||||
let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(1.0);
|
||||
assert!(reach.is_some_and(|r| r > 0.0));
|
||||
}
|
||||
|
||||
|
||||
@@ -176,7 +176,7 @@ fn sketch_filters_reach_beyond_nothing_they_do_not_paint() {
|
||||
for id in ["sketch.basRelief", "sketch.charcoal", "sketch.conteCrayon", "sketch.photocopy", "sketch.stamp"] {
|
||||
let f = fx(id, json!({}));
|
||||
assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage");
|
||||
assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach");
|
||||
assert!(f.reach(1.0).is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)?),
|
||||
})
|
||||
|
||||
@@ -39,8 +39,13 @@ pub fn needs_outline(n: &Node) -> bool {
|
||||
/// in a fill or stroke? Such an object is drawn through its art ([`outline_art`]) so that each copy
|
||||
/// paints its gradient by itself ([`copy_leaf`]), as a group's copies do.
|
||||
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? Expand
|
||||
/// Appearance makes each copy an object of its own ([`expand_outlined`]).
|
||||
pub fn has_transform_copies(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
|
||||
&& (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient())
|
||||
&& geometry_effects(n)
|
||||
.iter()
|
||||
.any(|e| e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0)
|
||||
@@ -249,11 +254,20 @@ fn with_id(art: &Node, id: NodeId) -> Node {
|
||||
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false)
|
||||
}
|
||||
|
||||
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with
|
||||
/// `apart`, also a path or compound path whose Transform effect makes copies
|
||||
/// ([`has_transform_copies`]), as the one piece the copies are made from.
|
||||
fn outline_art_with(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
symbol_art: Option<&Node>,
|
||||
outline: OutlineHook,
|
||||
nodes: &SymbolNodes,
|
||||
apart: bool,
|
||||
) -> Option<Node> {
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Text(_) => outline_text(n)?,
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
@@ -268,7 +282,7 @@ fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>,
|
||||
Node::group(n.id, vec![Arc::new(a)])
|
||||
}
|
||||
// The object as the one piece the copies of its Transform effect are made from.
|
||||
_ if has_transform_art(n) => {
|
||||
_ if has_transform_art(n) || (apart && has_transform_copies(n)) => {
|
||||
let mut one = n.clone();
|
||||
one.opacity = 1.0;
|
||||
one.blend = Default::default();
|
||||
@@ -429,10 +443,12 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O
|
||||
/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills
|
||||
/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these.
|
||||
pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
|
||||
// patterns: each copy an object of its own.
|
||||
if has_transform_art(n) {
|
||||
return as_art(doc, n, symbol_art);
|
||||
// A path whose Transform effect copies it, or scales its strokes or moves its patterns: each
|
||||
// copy an object of its own with the path's fills and strokes, the copies of each Transform
|
||||
// effect in a group of their own (copies of copies nest), as the reference app expands them
|
||||
// (#5612).
|
||||
if has_transform_art(n) || has_transform_copies(n) {
|
||||
return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true);
|
||||
}
|
||||
let own_paint = match n.kind {
|
||||
NodeKind::Text(_) => !n.appearance.items.is_empty(),
|
||||
@@ -451,6 +467,12 @@ pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>
|
||||
|
||||
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
|
||||
pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
|
||||
as_art_opts(doc, n, symbol_art, outline, nodes, false)
|
||||
}
|
||||
|
||||
/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an
|
||||
/// object of its own ([`copy_leaf`]) rather than one path of every copy.
|
||||
fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option<Node> {
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
NodeKind::Image(im) => {
|
||||
@@ -478,9 +500,12 @@ pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&
|
||||
Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect())
|
||||
}
|
||||
}
|
||||
_ => outline_art_with(doc, n, symbol_art, outline, nodes)?,
|
||||
_ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?,
|
||||
};
|
||||
reshape_leaves(&mut art, &fx);
|
||||
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
transform_items(&mut art);
|
||||
// Type and symbols in perspective: the art projected onto their plane.
|
||||
if let Some(h) = n.projection() {
|
||||
@@ -546,6 +571,28 @@ pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) {
|
||||
|
||||
/// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost.
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) {
|
||||
reshape_leaves_apart(art, fx, budget, false);
|
||||
}
|
||||
|
||||
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
|
||||
/// the group of its copies ([`copy_leaf`]) as its only member: the copies become its members, so
|
||||
/// the expanded path is one group of its copies rather than a group in a group.
|
||||
fn hoist_copies(art: &mut Node) {
|
||||
let id = art.id;
|
||||
let Some(children) = art.children_mut() else { return };
|
||||
let [only] = children.as_slice() else { return };
|
||||
if only.id != id || !matches!(only.kind, NodeKind::Group { clip: false, .. }) {
|
||||
return;
|
||||
}
|
||||
let copies = only.children().cloned().unwrap_or_default();
|
||||
if !copies.is_empty() {
|
||||
*children = copies;
|
||||
}
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) {
|
||||
if fx.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -588,14 +635,14 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg
|
||||
if let Some((m, copies, options, map)) = transform {
|
||||
// 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.
|
||||
let gradient = copies > 0 && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient());
|
||||
// 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());
|
||||
if options.reach_appearance() {
|
||||
let made = transform_leaf(leaf, &path, map, copies, options, room);
|
||||
used = used.minus(before).plus(made);
|
||||
return;
|
||||
}
|
||||
if gradient {
|
||||
if separate {
|
||||
let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room);
|
||||
used = used.minus(before).plus(made);
|
||||
return;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -501,3 +501,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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -1231,14 +1231,29 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() {
|
||||
|
||||
#[test]
|
||||
fn a_distance_parameters_range_comes_from_its_documentation() {
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0));
|
||||
assert_eq!(length_range("stylize.glowingEdges", "edgeWidth"), Some(1.0..=14.0));
|
||||
// A distance documented without a range, and unknown effects and parameters, have none.
|
||||
assert_eq!(length_range("path.offsetPath", "offset"), None);
|
||||
assert_eq!(length_range("stylize.glowingEdges", "edgeBrightness"), None);
|
||||
assert_eq!(length_range("no.such", "edgeWidth"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_halftones_radius_is_in_raster_pixels_not_a_distance() {
|
||||
// Pixels of the Document Raster Effects resolution, as public documentation gives it (#3260):
|
||||
// no unit setting changes it, so it isn't a distance in points.
|
||||
assert_eq!(raster_px_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0));
|
||||
assert!(!is_length("pixelate.colorHalftone", "maxRadius", false));
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), None);
|
||||
assert_eq!(raster_px_range("pixelate.colorHalftone", "channel1"), None);
|
||||
assert_eq!(raster_px_range("stylize.glowingEdges", "edgeWidth"), None);
|
||||
// The effect applies the range's floor to a radius below it.
|
||||
assert_eq!(
|
||||
crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})),
|
||||
crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4}))
|
||||
);
|
||||
// A distance documented without a range, and unknown effects and parameters, have none.
|
||||
assert_eq!(length_range("path.offsetPath", "offset"), None);
|
||||
assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None);
|
||||
assert_eq!(length_range("no.such", "maxRadius"), None);
|
||||
// Scale Strokes & Effects scales it with the object, as it does distances.
|
||||
let mut e = crate::new_effect("pixelate.colorHalftone", &json!({"maxRadius": 10})).unwrap();
|
||||
crate::scale_effect(&mut e, 2.0);
|
||||
assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0)));
|
||||
}
|
||||
@@ -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) }
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
mod arrange;
|
||||
mod cleanup;
|
||||
mod color;
|
||||
mod contour;
|
||||
mod document;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
mod shapes;
|
||||
mod typetools;
|
||||
|
||||
use super::CommandSpec;
|
||||
@@ -17,10 +19,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = arrange::specs();
|
||||
v.extend(cleanup::specs());
|
||||
v.extend(color::specs());
|
||||
v.extend(contour::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
v.extend(shapes::specs());
|
||||
v.extend(typetools::specs());
|
||||
v
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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, ©_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}))
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Contour (`addon.contour.*`), a built-in add-on: the Contour tool's command. A Contour is a copy of a selected shape that
|
||||
//! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its
|
||||
//! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The
|
||||
//! original stays where it is. Running the command on an object that already carries an Offset
|
||||
//! Path effect (a Contour made earlier) changes that effect instead of nesting another one.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::edit::{copy_above, selected_roots};
|
||||
use super::super::pathops::{len_param, num_param};
|
||||
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param};
|
||||
|
||||
const C: &str = "addon.contour.set";
|
||||
/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies).
|
||||
const EFFECT: &str = "path.offsetPath";
|
||||
/// The largest offset, in points; Offset Path takes the same.
|
||||
const MAX_OFFSET: f64 = 1e5;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.contour.set",
|
||||
"Contour",
|
||||
[],
|
||||
None,
|
||||
"{offset: pt (negative insets), corners?: \"sharp\"|\"round\"|\"square\" (default sharp; square cuts each corner off flat), miterLimit?: 1..500 (4; sharp corners only)} make a copy of each selected path or shape directly above it with a live Offset Path effect, or, for a selected object that already has one (a Contour), change that effect: nothing is baked (Expand Appearance bakes it) and the original is kept → {ids, created, updated}",
|
||||
has_selection,
|
||||
contour
|
||||
)]
|
||||
}
|
||||
|
||||
/// The Offset Path join a Contour corner style stands for.
|
||||
fn joins_for(corners: Option<&str>) -> Result<&'static str> {
|
||||
match corners.map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("sharp") => Ok("miter"),
|
||||
Some("round") => Ok("round"),
|
||||
Some("square") => Ok("bevel"),
|
||||
Some(other) => Err(bad(C, format!("`corners` must be sharp, round or square, not `{other}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn contour(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?;
|
||||
if offset.abs() > MAX_OFFSET {
|
||||
return Err(bad(C, "offset out of range"));
|
||||
}
|
||||
let joins = joins_for(str_param(p, "corners"))?;
|
||||
let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0);
|
||||
let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter}))
|
||||
.ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?;
|
||||
let roots = selected_roots(s)?;
|
||||
let (updated, created) = s.edit("Contour", |d, sel| {
|
||||
// A shape that already carries Offset Path is a Contour: change it. Any other path or
|
||||
// shape gets a Contour copy above it. Type, images and the rest are left alone.
|
||||
let (mut again, mut fresh) = (vec![], vec![]);
|
||||
for id in roots {
|
||||
let Some(n) = d.node(id) else { continue };
|
||||
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
continue;
|
||||
}
|
||||
if n.appearance.effects.iter().any(|e| e.id == EFFECT) {
|
||||
again.push(id);
|
||||
} else {
|
||||
fresh.push(id);
|
||||
}
|
||||
}
|
||||
if again.is_empty() && fresh.is_empty() {
|
||||
return Err(EngineError::Other("Contour: select paths or shapes".into()));
|
||||
}
|
||||
for id in &again {
|
||||
if let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects.iter_mut().rev().find(|e| e.id == EFFECT)) {
|
||||
e.params = effect.params.clone();
|
||||
}
|
||||
}
|
||||
let made = copy_above(d, &fresh, |_, _, copy| copy.appearance.effects.push(effect.clone()))?;
|
||||
sel.set(again.iter().chain(made.iter()).copied());
|
||||
Ok((again, made))
|
||||
})?;
|
||||
let list = |ids: &[NodeId]| ids.iter().map(|i| i.0).collect::<Vec<_>>();
|
||||
Ok(json!({ "ids": list(&[updated.as_slice(), created.as_slice()].concat()), "created": list(&created), "updated": list(&updated) }))
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Tests for `addon.contour.set`: a live Offset Path copy of a shape that stays editable until baked.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value, key: &str) -> Vec<NodeId> {
|
||||
v[key].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn effects_of(s: &Session, id: NodeId) -> Vec<(String, Value)> {
|
||||
node(s, id).appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect()
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, id: NodeId) -> Rect {
|
||||
node(s, id).geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn node_count(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.node_count()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_is_a_live_copy_above_the_original() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let before = bounds(&s, a);
|
||||
let r = s.execute("addon.contour.set", &json!({"offset": 10})).unwrap();
|
||||
let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated"));
|
||||
assert_eq!((made.len(), updated.len()), (1, 0));
|
||||
// The original is untouched, the copy is above it and selected, and nothing is baked: the
|
||||
// copy's own path is still the original's, with the effect on top.
|
||||
assert!(effects_of(&s, a).is_empty());
|
||||
assert_eq!(bounds(&s, a), before);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, made);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.index_path(made[0]).unwrap() > d.index_path(a).unwrap());
|
||||
assert_eq!(bounds(&s, made[0]), before);
|
||||
let fx = effects_of(&s, made[0]);
|
||||
assert_eq!(fx.len(), 1);
|
||||
assert_eq!(fx[0].0, "path.offsetPath");
|
||||
assert_eq!(fx[0].1["offset"], json!(10.0));
|
||||
assert_eq!(fx[0].1["joins"], json!("miter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] {
|
||||
select(&mut s, &[a]);
|
||||
s.execute("addon.contour.set", &json!({"offset": offset})).unwrap();
|
||||
let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids");
|
||||
let b = bounds(&s, baked[0]);
|
||||
// The default stroke widens the baked art by its weight; compare the fill's edges.
|
||||
let fill = baked_fill_bounds(&s, baked[0]);
|
||||
assert!((fill.x0 - want.x0).abs() < 1e-2 && (fill.y1 - want.y1).abs() < 1e-2, "{offset}: {fill:?} vs {want:?} ({b:?})");
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of the fill path inside a baked object (a group of its fill and stroke), or of the
|
||||
/// object itself when it is one path.
|
||||
fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Group { children, .. } => children.iter().filter_map(|c| c.geometric_bounds()).next().unwrap(),
|
||||
_ => bounds(s, id),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_drag_changes_the_contour_instead_of_nesting_one() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(), "created");
|
||||
let count = node_count(&s);
|
||||
// The Contour is selected: the next call edits it.
|
||||
let r = s.execute("addon.contour.set", &json!({"offset": -4, "corners": "round"})).unwrap();
|
||||
assert_eq!(ids_of(&r, "updated"), made);
|
||||
assert!(ids_of(&r, "created").is_empty());
|
||||
assert_eq!(node_count(&s), count, "no new object");
|
||||
let fx = effects_of(&s, made[0]);
|
||||
assert_eq!(fx.len(), 1, "one Offset Path, not two");
|
||||
assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone()), (json!(-4.0), json!("round")));
|
||||
assert!(effects_of(&s, a).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_styles_choose_the_join() {
|
||||
for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 3, "corners": corners})).unwrap(), "created");
|
||||
assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_keeps_the_color_and_stroke_editable_on_the_copy() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(), "created");
|
||||
let original = node(&s, a).appearance.items.clone();
|
||||
assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint");
|
||||
// Recolouring the Contour (it is the selection) changes its fill only: the live effect stays
|
||||
// and the original keeps its paint.
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
assert_ne!(node(&s, made[0]).appearance.items, original, "the copy took the new fill");
|
||||
assert_eq!(node(&s, a).appearance.items, original, "the original is untouched");
|
||||
assert_eq!(effects_of(&s, made[0]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let count = node_count(&s);
|
||||
s.execute("addon.contour.set", &json!({"offset": 6})).unwrap();
|
||||
assert_eq!(node_count(&s), count + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node_count(&s), count);
|
||||
assert!(effects_of(&s, a).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_refuses_what_it_cannot_offset() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 30.0, 30.0);
|
||||
let count = node_count(&s);
|
||||
for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] {
|
||||
assert!(s.execute("addon.contour.set", ¶ms).is_err(), "{params}");
|
||||
}
|
||||
// Nothing was added by the refused calls.
|
||||
assert_eq!(node_count(&s), count);
|
||||
// Type is not a path to offset.
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap();
|
||||
let err = s.execute("addon.contour.set", &json!({"offset": 5})).unwrap_err().to_string();
|
||||
assert!(err.contains("select paths or shapes"), "{err}");
|
||||
}
|
||||
|
||||
/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then
|
||||
/// the gap taken out of the border with Minus Front, leaves a ring between the two.
|
||||
#[test]
|
||||
fn border_with_a_gap_from_two_contours_and_minus_front() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
// Strip the default stroke so the areas are plain.
|
||||
s.execute("paint.setStroke", &json!({"none": true})).ok();
|
||||
// The gap first (+8), then the border (+20) from the same shape: both land directly above it,
|
||||
// the later one lower, so the gap ends up in front of the border.
|
||||
select(&mut s, &[a]);
|
||||
let gap = ids_of(&s.execute("addon.contour.set", &json!({"offset": 8})).unwrap(), "created")[0];
|
||||
select(&mut s, &[a]);
|
||||
let border = ids_of(&s.execute("addon.contour.set", &json!({"offset": 20})).unwrap(), "created")[0];
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border");
|
||||
select(&mut s, &[border, gap]);
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let both: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
|
||||
assert_eq!(both.len(), 2);
|
||||
let ring = ids_of(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap(), "ids");
|
||||
assert_eq!(ring.len(), 1);
|
||||
// 90 x 80 outer minus 66 x 56 inner, with sharp corners.
|
||||
let area = vectorcraft_pathops::area(&ring_path(&s, ring[0]).0, ring_path(&s, ring[0]).1);
|
||||
assert!((area - (90.0 * 80.0 - 66.0 * 56.0)).abs() < 1.0, "{area}");
|
||||
}
|
||||
|
||||
fn ring_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, vectorcraft_geom::FillRule) {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Path { path, rule, .. } => (path.clone(), *rule),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
(vectorcraft_geom::PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule)
|
||||
}
|
||||
NodeKind::Group { children, .. } => children.first().map(|c| ring_path(s, c.id)).unwrap(),
|
||||
_ => panic!("not a path"),
|
||||
}
|
||||
}
|
||||
|
||||
mod tool {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::*;
|
||||
use crate::tooling::ViewInfo;
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..Default::default() }
|
||||
}
|
||||
|
||||
fn at(s: &mut Session, kind: PointerKind, x: f64, y: f64, mods: Mods) {
|
||||
s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view()).unwrap();
|
||||
}
|
||||
|
||||
fn undo_depth(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// A 50 x 40 rectangle at (100, 100), selected, with the Contour tool active.
|
||||
fn ready() -> (Session, NodeId) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
select(&mut s, &[a]);
|
||||
s.select_tool("contour", view()).unwrap();
|
||||
(s, a)
|
||||
}
|
||||
|
||||
fn offset_of(s: &Session, id: NodeId) -> f64 {
|
||||
effects_of(s, id)[0].1["offset"].as_f64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_out_previews_live_and_commits_one_undo_step() {
|
||||
let (mut s, a) = ready();
|
||||
let (before, nodes) = (undo_depth(&s), node_count(&s));
|
||||
// Press on the right edge and pull 10 pt away from the shape.
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default());
|
||||
assert!(s.in_interaction(), "the Contour is previewed while the button is down");
|
||||
at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default());
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!(undo_depth(&s), before + 1);
|
||||
assert_eq!(node_count(&s), nodes + 1);
|
||||
assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("addon.contour.set"));
|
||||
let made = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(made.len(), 1);
|
||||
assert_ne!(made[0], a);
|
||||
assert!((offset_of(&s, made[0]) - 10.0).abs() < 1e-6, "{}", offset_of(&s, made[0]));
|
||||
assert!(effects_of(&s, a).is_empty(), "the original is kept as it was");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node_count(&s), nodes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_in_shrinks_and_a_second_drag_continues_from_where_the_contour_stands() {
|
||||
let (mut s, _) = ready();
|
||||
// From inside, 5 pt toward the middle of the right edge's neighbourhood.
|
||||
at(&mut s, PointerKind::Down, 145.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 140.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 140.0, 120.0, Mods::default());
|
||||
let contour = s.doc().unwrap().selection.objects[0];
|
||||
assert!((offset_of(&s, contour) + 5.0).abs() < 1e-6);
|
||||
// The Contour is selected: pressing at the edge and pulling out 12 pt adds to its -5.
|
||||
let nodes = node_count(&s);
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 162.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 162.0, 120.0, Mods::default());
|
||||
assert_eq!(node_count(&s), nodes, "the same Contour changed, none was nested");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![contour]);
|
||||
assert_eq!(effects_of(&s, contour).len(), 1);
|
||||
assert!((offset_of(&s, contour) - 7.0).abs() < 1e-6, "{}", offset_of(&s, contour));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_and_a_plain_click_change_nothing() {
|
||||
let (mut s, _) = ready();
|
||||
let (before, nodes) = (undo_depth(&s), node_count(&s));
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default());
|
||||
assert!(s.in_interaction());
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default());
|
||||
assert!(!s.in_interaction());
|
||||
assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes));
|
||||
// A click with no movement.
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 150.0, 120.0, Mods::default());
|
||||
assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_rounds_to_whole_points_and_the_corner_option_is_used() {
|
||||
let (mut s, _) = ready();
|
||||
s.set_tool_option("corners", &json!("round"));
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, shift);
|
||||
at(&mut s, PointerKind::Drag, 160.4, 120.0, shift);
|
||||
at(&mut s, PointerKind::Up, 160.4, 120.0, shift);
|
||||
let contour = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(offset_of(&s, contour), 10.0);
|
||||
assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round"));
|
||||
}
|
||||
|
||||
/// A Contour keeps its own corner style and miter limit when it is dragged again, whatever the
|
||||
/// tool's options are by then (they said Sharp when the Contour was made Square).
|
||||
#[test]
|
||||
fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() {
|
||||
let (mut s, _) = ready();
|
||||
s.execute("addon.contour.set", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap();
|
||||
let contour = s.doc().unwrap().selection.objects[0];
|
||||
s.set_tool_option("corners", &json!("sharp"));
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 158.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 158.0, 120.0, Mods::default());
|
||||
let fx = effects_of(&s, contour);
|
||||
assert_eq!(fx.len(), 1);
|
||||
assert!((offset_of(&s, contour) - 13.0).abs() < 1e-6, "{}", offset_of(&s, contour));
|
||||
assert_eq!(fx[0].1["joins"], json!("bevel"), "{:?}", fx[0].1);
|
||||
assert_eq!(fx[0].1["miterLimit"], json!(7.0), "{:?}", fx[0].1);
|
||||
}
|
||||
|
||||
/// A drag that never moves the distance (along the edge, or rounded back to nothing by Shift)
|
||||
/// leaves no unchanged copy and no undo step.
|
||||
#[test]
|
||||
fn a_drag_along_the_edge_changes_nothing() {
|
||||
let (mut s, _) = ready();
|
||||
let (before, nodes) = (undo_depth(&s), node_count(&s));
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
for (mods, to) in [(Mods::default(), (150.0, 135.0)), (shift, (150.3, 120.0))] {
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, mods);
|
||||
at(&mut s, PointerKind::Drag, to.0, to.1, mods);
|
||||
at(&mut s, PointerKind::Up, to.0, to.1, mods);
|
||||
assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes), "{to:?}");
|
||||
assert!(!s.in_interaction());
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads
|
||||
/// over any fill); a shape that is not a Contour yet has none.
|
||||
#[test]
|
||||
fn a_selected_contour_shows_the_outline_it_was_made_from() {
|
||||
use vectorcraft_tools::Overlay;
|
||||
let (mut s, _) = ready();
|
||||
let paths = |s: &mut Session| -> Vec<(bool, f32)> {
|
||||
s.overlays(view())
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Overlay::Path { dashed, width, .. } => Some((dashed, width)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert!(paths(&mut s).is_empty(), "a plain shape has no guide");
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default());
|
||||
// The solid halo first, the dashes on top of it.
|
||||
assert_eq!(paths(&mut s), [(false, 3.0), (true, 1.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_selected_does_nothing() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("contour", view()).unwrap();
|
||||
let before = undo_depth(&s);
|
||||
at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default());
|
||||
at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default());
|
||||
assert_eq!(undo_depth(&s), before);
|
||||
}
|
||||
}
|
||||
@@ -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, ¶ms).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]
|
||||
|
||||
@@ -20,7 +20,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Set Corners",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}",
|
||||
"{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1), minAngle?: degrees 0..180 (default 0), maxAngle?: degrees 0..180 (default 180; of those anchors, only the corners whose sides meet at an angle in this range: small for a sharp spike, near 180 for a shallow bend)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}",
|
||||
has_doc,
|
||||
corner_set
|
||||
),
|
||||
@@ -50,8 +50,108 @@ fn anchors_param(p: &Value, cmd: &str) -> Result<Option<BTreeSet<usize>>> {
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// The corners a request names: each path with the corners (anchor indices of its uncut outline).
|
||||
fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
/// Which of the chosen anchors `cornerSet` takes, by their number along the path's uncut outline
|
||||
/// (the first anchor is number 1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Every {
|
||||
All,
|
||||
/// The 1st, 3rd, 5th… anchors: indices 0, 2, 4….
|
||||
Odd,
|
||||
/// The 2nd, 4th, 6th… anchors: indices 1, 3, 5….
|
||||
Even,
|
||||
}
|
||||
|
||||
impl Every {
|
||||
/// The `every` of `p` (default: all).
|
||||
fn of(p: &Value, cmd: &str) -> Result<Self> {
|
||||
match p.get("every").filter(|v| !v.is_null()) {
|
||||
None => Ok(Self::All),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("all") => Ok(Self::All),
|
||||
Some("odd") => Ok(Self::Odd),
|
||||
Some("even") => Ok(Self::Even),
|
||||
_ => Err(bad(cmd, format!("`every` must be \"all\", \"odd\" or \"even\", not {v}"))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Does it take the anchor at `index`? Anchors that take no corner still count.
|
||||
fn takes(self, index: usize) -> bool {
|
||||
match self {
|
||||
Self::All => true,
|
||||
Self::Odd => index.is_multiple_of(2),
|
||||
Self::Even => !index.is_multiple_of(2),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the corners it takes are, for an error: "" for all of them.
|
||||
fn at(self) -> &'static str {
|
||||
match self {
|
||||
Self::All => "",
|
||||
Self::Odd => " at an odd-numbered anchor (the 1st, 3rd, 5th…)",
|
||||
Self::Even => " at an even-numbered anchor (the 2nd, 4th, 6th…)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (degrees) past the ends of the angle range a corner's angle may be, so that a typed 90
|
||||
/// takes a rectangle's corners whatever the rounding.
|
||||
const ANGLE_SLACK: f64 = 1e-6;
|
||||
/// The error when no anchor named is a corner at all.
|
||||
const NO_CORNER: &str = "choose anchors where two sides meet at an angle: only those take a corner";
|
||||
|
||||
/// Which of the chosen corners `cornerSet` takes: by their number (`every`) and by the angle their
|
||||
/// sides meet at (`minAngle`..`maxAngle`, degrees).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Pick {
|
||||
every: Every,
|
||||
min_angle: f64,
|
||||
max_angle: f64,
|
||||
}
|
||||
|
||||
impl Pick {
|
||||
/// Every chosen corner.
|
||||
const ALL: Self = Self { every: Every::All, min_angle: 0.0, max_angle: 180.0 };
|
||||
|
||||
/// The `every`, `minAngle` and `maxAngle` of `p`.
|
||||
fn of(p: &Value, cmd: &str) -> Result<Self> {
|
||||
let every = Every::of(p, cmd)?;
|
||||
let angle = |key: &str, default: f64| -> Result<f64> {
|
||||
let a = number_or(p, key, default, cmd)?;
|
||||
if !(a.is_finite() && (0.0..=180.0).contains(&a)) {
|
||||
return Err(bad(cmd, format!("`{key}` must be from 0 to 180 degrees, not {a}")));
|
||||
}
|
||||
Ok(a)
|
||||
};
|
||||
let (min_angle, max_angle) = (angle("minAngle", 0.0)?, angle("maxAngle", 180.0)?);
|
||||
if min_angle > max_angle {
|
||||
return Err(bad(cmd, format!("`minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°)")));
|
||||
}
|
||||
Ok(Self { every, min_angle, max_angle })
|
||||
}
|
||||
|
||||
/// Does it take corner `index` of `lc`?
|
||||
fn takes(&self, lc: &LiveCorners, index: usize) -> bool {
|
||||
self.every.takes(index)
|
||||
&& lc.corner(index).is_some_and(|c| (self.min_angle - ANGLE_SLACK..=self.max_angle + ANGLE_SLACK).contains(&c.angle_deg()))
|
||||
}
|
||||
|
||||
/// The error when it takes none of the chosen corners.
|
||||
fn none(&self) -> String {
|
||||
let at = self.every.at();
|
||||
if self.min_angle > 0.0 || self.max_angle < 180.0 {
|
||||
format!("none of the chosen corners{at} has an angle from {}° to {}°", self.min_angle, self.max_angle)
|
||||
} else if at.is_empty() {
|
||||
NO_CORNER.into()
|
||||
} else {
|
||||
format!("none of the chosen corners is{at}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners a request names: each path with the corners (anchor indices of its uncut outline)
|
||||
/// that `pick` takes.
|
||||
fn named_corners(s: &Session, p: &Value, cmd: &str, pick: Pick) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
let shared = anchors_param(p, cmd)?;
|
||||
// Each path with its own `anchors`, or sharing the request's.
|
||||
let mut own: Vec<Option<BTreeSet<usize>>> = vec![];
|
||||
@@ -71,10 +171,10 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTree
|
||||
let d = &st.doc;
|
||||
check_size(ids.iter().filter_map(|id| d.node(*id)?.path_data()), cmd)?;
|
||||
let editable = d.editable();
|
||||
let mut out = vec![];
|
||||
let (mut out, mut chosen) = (vec![], false);
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
let Some(lc) = d.node(*id).filter(|_| editable(*id)).and_then(LiveCorners::of) else { continue };
|
||||
let corners = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) {
|
||||
let corners: BTreeSet<usize> = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) {
|
||||
Some(given) => {
|
||||
let n = lc.base.anchor_count();
|
||||
if let Some(past) = given.iter().find(|k| **k >= n) {
|
||||
@@ -84,12 +184,14 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTree
|
||||
}
|
||||
None => st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)),
|
||||
};
|
||||
chosen |= !corners.is_empty();
|
||||
let corners: BTreeSet<usize> = corners.into_iter().filter(|k| pick.takes(&lc, *k)).collect();
|
||||
if !corners.is_empty() {
|
||||
out.push((*id, corners));
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner"));
|
||||
return Err(bad(cmd, if chosen { pick.none() } else { NO_CORNER.into() }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -134,11 +236,12 @@ fn corner_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}")))
|
||||
})
|
||||
.transpose()?;
|
||||
let corners = named_corners(s, p, C)?;
|
||||
let pick = Pick::of(p, C)?;
|
||||
let corners = named_corners(s, p, C, pick)?;
|
||||
edit_corners(s, "Set Corners", corners, radius, kind)
|
||||
}
|
||||
|
||||
fn corner_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?;
|
||||
let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Pick::ALL)?;
|
||||
edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round))
|
||||
}
|
||||
@@ -567,6 +567,170 @@ fn corner_commands_refuse_bad_params() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd
|
||||
/// numbers counting from 1), its inner corners at the odd ones.
|
||||
fn star_path(s: &mut Session) -> NodeId {
|
||||
let pts: Vec<(f64, f64)> = (0..10)
|
||||
.map(|i| {
|
||||
let (r, a) = (if i % 2 == 0 { 100.0 } else { 40.0 }, std::f64::consts::PI * f64::from(i) / 5.0);
|
||||
(200.0 + r * a.sin(), 150.0 - r * a.cos())
|
||||
})
|
||||
.collect();
|
||||
line(s, &pts, true)
|
||||
}
|
||||
|
||||
/// The cut corners of `id`: anchor indices of its uncut outline with a radius drawn.
|
||||
fn cut(s: &Session, id: NodeId) -> Vec<usize> {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
(0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_every_takes_the_odd_or_even_numbered_anchors_of_each_path() {
|
||||
let mut s = session();
|
||||
let star = star_path(&mut s);
|
||||
// An open zig-zag: its ends (1st and 5th) take no corner but still count.
|
||||
let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0), (90.0, 250.0)], false);
|
||||
select(&mut s, &[star, zig]);
|
||||
let n = steps(&s);
|
||||
// Odd: the 1st, 3rd, 5th… of each path, as one step.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "odd"})).unwrap();
|
||||
assert_eq!((r["corners"].clone(), steps(&s)), (json!(6), n + 1));
|
||||
assert_eq!((cut(&s, star), cut(&s, zig)), (vec![0, 2, 4, 6, 8], vec![2]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((cut(&s, star), cut(&s, zig), steps(&s)), (vec![], vec![], n));
|
||||
// Even: the 2nd, 4th, 6th….
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "even"})).unwrap();
|
||||
assert_eq!((r["corners"].clone(), steps(&s)), (json!(7), n + 1));
|
||||
assert_eq!((cut(&s, star), cut(&s, zig)), (vec![1, 3, 5, 7, 9], vec![1, 3]));
|
||||
// "all" (and no `every`) is every chosen corner, as before.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [zig.0], "radius": 4, "every": "all"})).unwrap();
|
||||
assert_eq!(cut(&s, zig), vec![1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_every_filters_the_named_and_direct_selected_anchors() {
|
||||
let mut s = session();
|
||||
let star = star_path(&mut s);
|
||||
// Of the named anchors, only the even-numbered ones (indices 1 and 3); numbers stay the path's.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "anchors": [1, 2, 3, 4], "radius": 3, "every": "even"})).unwrap();
|
||||
assert_eq!(r["corners"], json!(2));
|
||||
assert_eq!(cut(&s, star), vec![1, 3]);
|
||||
// Per path through `items`.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": star.0, "anchors": [5, 6, 7]}], "radius": 3, "every": "odd"})).unwrap();
|
||||
assert_eq!(cut(&s, star), vec![1, 3, 6]);
|
||||
// Of the direct-selected anchors.
|
||||
s.execute("addon.pathtools.cornerRemove", &json!({"ids": [star.0]})).unwrap();
|
||||
select_anchors(&mut s, star, &[7, 8, 9]);
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "every": "odd"})).unwrap();
|
||||
assert_eq!(cut(&s, star), vec![8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() {
|
||||
let mut s = session();
|
||||
let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0)], false);
|
||||
select(&mut s, &[zig]);
|
||||
let i = zig.0;
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.cornerSet",
|
||||
&[
|
||||
json!({"ids": [i], "radius": 5, "every": "third"}),
|
||||
json!({"ids": [i], "radius": 5, "every": "Odd"}),
|
||||
json!({"ids": [i], "radius": 5, "every": 2}),
|
||||
json!({"ids": [i], "radius": 5, "every": true}),
|
||||
json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"}),
|
||||
json!({"ids": [i], "anchors": [0, 1], "radius": 5, "every": "odd"}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "radius": 5, "every": "third"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`every` must be \"all\", \"odd\" or \"even\""), "{e}");
|
||||
// The 2nd anchor is a corner, but not an odd-numbered one.
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"})).unwrap_err().to_string();
|
||||
assert!(e.contains("odd-numbered"), "{e}");
|
||||
// An open end is no corner at all, whatever `every` says.
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [0], "radius": 5, "every": "odd"})).unwrap_err().to_string();
|
||||
assert!(e.contains("two sides meet"), "{e}");
|
||||
}
|
||||
|
||||
/// A closed house: a 100 × 100 square under a roof, its corners 90°, 90°, 135°, 90° and 135°.
|
||||
fn house(s: &mut Session) -> NodeId {
|
||||
line(s, &[(250.0, 100.0), (350.0, 100.0), (350.0, 200.0), (300.0, 250.0), (250.0, 200.0)], true)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_angle_range_rounds_only_the_corners_in_it_on_each_path() {
|
||||
let mut s = session();
|
||||
// The star's points meet at about 38°, its inner corners at about 110°.
|
||||
let (star, home) = (star_path(&mut s), house(&mut s));
|
||||
select(&mut s, &[star, home]);
|
||||
let n = steps(&s);
|
||||
// The sharp spikes only: the house has none, the star five, as one step.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "maxAngle": 60})).unwrap();
|
||||
assert_eq!((r["ids"].clone(), r["corners"].clone(), steps(&s)), (json!([star.0]), json!(5), n + 1));
|
||||
assert_eq!((cut(&s, star), cut(&s, home)), (vec![0, 2, 4, 6, 8], vec![]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((cut(&s, star), steps(&s)), (vec![], n));
|
||||
// Exactly 90°: the house's square corners.
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "minAngle": 90, "maxAngle": 90})).unwrap();
|
||||
assert_eq!((cut(&s, star), cut(&s, home)), (vec![], vec![0, 1, 3]));
|
||||
// 100° to 140°: the star's inner corners and the roof's; the square corners stay as they are.
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 2, "minAngle": 100, "maxAngle": 140})).unwrap();
|
||||
assert_eq!(r["corners"], json!(7));
|
||||
assert_eq!((cut(&s, star), cut(&s, home)), (vec![1, 3, 5, 7, 9], vec![0, 1, 2, 3, 4]));
|
||||
assert_eq!((drawn(&s, home, 0), drawn(&s, home, 2)), (3.0, 2.0));
|
||||
// On top of the named anchors and of `every`.
|
||||
s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap();
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [home.0], "anchors": [1, 2, 3], "radius": 4, "minAngle": 80, "maxAngle": 100})).unwrap();
|
||||
assert_eq!(cut(&s, home), vec![1, 3]);
|
||||
s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "radius": 4, "every": "even", "minAngle": 100})).unwrap();
|
||||
assert_eq!(cut(&s, star), vec![1, 3, 5, 7, 9]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_angle_range_on_a_three_anchor_path() {
|
||||
let mut s = session();
|
||||
// An open pen path of three anchors: one corner, of 90°.
|
||||
let id = line(&mut s, &[(10.0, 10.0), (60.0, 60.0), (110.0, 10.0)], false);
|
||||
select(&mut s, &[id]);
|
||||
let e = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "maxAngle": 45})).unwrap_err().to_string();
|
||||
assert!(e.contains("none of the chosen corners has an angle from 0° to 45°"), "{e}");
|
||||
let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "minAngle": 80, "maxAngle": 100})).unwrap();
|
||||
assert_eq!(r["corners"], json!(1));
|
||||
assert_eq!(cut(&s, id), vec![1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_set_angle_range_refuses_bad_values_and_says_when_nothing_matches() {
|
||||
let mut s = session();
|
||||
let star = star_path(&mut s);
|
||||
select(&mut s, &[star]);
|
||||
let i = star.0;
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.cornerSet",
|
||||
&[
|
||||
json!({"ids": [i], "radius": 5, "minAngle": -1}),
|
||||
json!({"ids": [i], "radius": 5, "maxAngle": 181}),
|
||||
json!({"ids": [i], "radius": 5, "minAngle": 1e308}),
|
||||
json!({"ids": [i], "radius": 5, "maxAngle": "sharp"}),
|
||||
json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}),
|
||||
json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}),
|
||||
json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}),
|
||||
],
|
||||
);
|
||||
let err = |s: &mut Session, p: Value| s.execute("addon.pathtools.cornerSet", &p).unwrap_err().to_string();
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "maxAngle": 200}));
|
||||
assert!(e.contains("`maxAngle` must be from 0 to 180 degrees"), "{e}");
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}));
|
||||
assert!(e.contains("`minAngle` (120°) can't be more than `maxAngle` (60°)"), "{e}");
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}));
|
||||
assert!(e.contains("none of the chosen corners has an angle from 50° to 100°"), "{e}");
|
||||
let e = err(&mut s, json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}));
|
||||
assert!(e.contains("none of the chosen corners at an odd-numbered anchor (the 1st, 3rd, 5th…) has an angle from 100° to 180°"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,27 @@
|
||||
//! the selected characters letter by letter, from a start value to an end value along a shape
|
||||
//! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as
|
||||
//! the Character panel sets them (`text.setRangeStyle`), in its units and ranges
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Its submenu
|
||||
//! (Object › Plug-ins › Type Tools) and dialog are the UI's.
|
||||
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
|
||||
//! splits type on a path into point type holding the same text and the plain path it was set on
|
||||
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
|
||||
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{NodeId, TextRun};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, ArcPath, Point};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::choice;
|
||||
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or};
|
||||
use super::super::typemenu::text_ids;
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its
|
||||
@@ -41,17 +46,33 @@ pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"];
|
||||
const MAX_CHARS: usize = 100_000;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.type.textTweaker",
|
||||
"Text Tweaker",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
|
||||
has_selection,
|
||||
text_tweaker
|
||||
)]
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.type.textTweaker",
|
||||
"Text Tweaker",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}",
|
||||
has_selection,
|
||||
text_tweaker
|
||||
),
|
||||
cmd!(
|
||||
"addon.type.releasePath",
|
||||
"Release Type on a Path…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Release Type on a Path's command (the id in [`specs`]).
|
||||
pub const RELEASE: &str = "addon.type.releasePath";
|
||||
/// What Release Type on a Path keeps: both, the path only, or the text only.
|
||||
pub const RELEASE_MODES: [&str; 3] = ["both", "path", "text"];
|
||||
|
||||
/// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the
|
||||
/// random shape.
|
||||
fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 {
|
||||
@@ -187,3 +208,143 @@ fn tweak(runs: Vec<TextRun>, changes: &[(usize, CharChange)]) -> Vec<TextRun> {
|
||||
edit::normalize(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Type on a path among the objects `p` names (or the selection), inside groups too, in stacking
|
||||
/// order. An id that names no object is an error.
|
||||
fn path_types(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
}
|
||||
let on_path = |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::OnPath { .. }));
|
||||
Ok(text_ids(d, &ids).into_iter().filter(on_path).collect())
|
||||
}
|
||||
|
||||
/// Where the first character laid out in `lay` starts its baseline: the pen position of the first
|
||||
/// glyph in text order (a list marker, which has no characters, before the character it leads).
|
||||
/// None without a glyph.
|
||||
fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin)
|
||||
}
|
||||
|
||||
/// `t`, type on a path, as point type on one straight line: the same runs and character and
|
||||
/// paragraph attributes, its baseline starting where its first character sat on the path (in the
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for
|
||||
/// other type, or when it can't be placed.
|
||||
fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
let TextKind::OnPath { path, .. } = &t.kind else { return None };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Where the first character sat. Text that didn't fit on the path has no glyph there: it
|
||||
// starts at the start bracket.
|
||||
let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| {
|
||||
let ap = ArcPath::new(path);
|
||||
let (from, _) = t.kind.path_span()?;
|
||||
let (p, _) = ap.at(from * ap.len());
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
})?;
|
||||
let mut out = t.clone();
|
||||
out.kind = TextKind::Point;
|
||||
out.path_effect = Default::default();
|
||||
out.path_align = Default::default();
|
||||
out.path_spacing = 0.0;
|
||||
// Point type is in no thread: its first paragraph starts in it.
|
||||
out.first_para_continues = false;
|
||||
// Where the point type puts its own first character; the origin moves so it lands at `at`,
|
||||
// whatever the paragraph's alignment and direction.
|
||||
let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO);
|
||||
let shift = at - own;
|
||||
if !(shift.x.is_finite() && shift.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
out.xf *= Affine::translate(shift);
|
||||
refresh_bounds(&mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The path `t` is set on, as a plain path object `id` in document space, with no fill and no
|
||||
/// stroke: type paths carry no paint of their own. None for other type.
|
||||
fn released_path(id: NodeId, t: &TextObject) -> Option<Node> {
|
||||
Some(Node::path(id, t.type_path()?, Appearance::basic(Paint::None, Paint::None, 1.0)))
|
||||
}
|
||||
|
||||
fn release_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = RELEASE;
|
||||
let mode = choice(p, C, "mode", &RELEASE_MODES)?.unwrap_or("both");
|
||||
let keep = switch_or(p, "keepOriginal", false, C)?;
|
||||
let want_path = mode != "text";
|
||||
let ids = path_types(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Ok(json!({ "ids": [], "paths": [], "texts": [] }));
|
||||
}
|
||||
// The point type, worked out before the edit: one object that can't be placed fails the run.
|
||||
let mut plans: Vec<(NodeId, Option<TextObject>)> = Vec::with_capacity(ids.len());
|
||||
{
|
||||
let d = &s.doc()?.doc;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = match mode {
|
||||
"path" => None,
|
||||
_ => Some(released_text(t).ok_or_else(|| bad(C, format!("object {} can't be set as point type", id.0)))?),
|
||||
};
|
||||
plans.push((id, text));
|
||||
}
|
||||
}
|
||||
let (paths, texts) = s.edit("Release Type on a Path", |d, sel| {
|
||||
let (mut paths, mut texts) = (vec![], vec![]);
|
||||
for (id, text) in plans {
|
||||
let (path, text) = release_one(d, id, text, want_path, keep)?;
|
||||
paths.extend(path);
|
||||
texts.extend(text);
|
||||
}
|
||||
sel.set(paths.iter().chain(&texts).copied());
|
||||
Ok((paths, texts))
|
||||
})?;
|
||||
// Bottom to top.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut all: Vec<(Vec<usize>, NodeId)> = paths.iter().chain(&texts).map(|id| (d.index_path(*id).unwrap_or_default(), *id)).collect();
|
||||
all.sort();
|
||||
let nums = |v: &[NodeId]| v.iter().map(|i| i.0).collect::<Vec<_>>();
|
||||
let all: Vec<NodeId> = all.into_iter().map(|(_, id)| id).collect();
|
||||
Ok(json!({ "ids": nums(&all), "paths": nums(&paths), "texts": nums(&texts) }))
|
||||
}
|
||||
|
||||
/// Release type on a path `id` in `d`: its path (`want_path`) where the type was, or just above it
|
||||
/// when the original stays (`keep`), then the point type `text` (None: no text) above that.
|
||||
/// Without `keep` the original goes, and released text takes its place as the same object, so a
|
||||
/// frame of threaded text leaves its thread with the text it holds, as Convert To Point Type's
|
||||
/// does. The released (path, text).
|
||||
fn release_one(d: &mut Document, id: NodeId, text: Option<TextObject>, want_path: bool, keep: bool) -> Result<(Option<NodeId>, Option<NodeId>)> {
|
||||
let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
let original = d.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Text(t) = &original.kind else { return Ok((None, None)) };
|
||||
let path =
|
||||
if want_path { Some(released_path(d.alloc_id(), t).ok_or_else(|| bad(RELEASE, format!("object {} has no path", id.0)))?) } else { None };
|
||||
if !keep && text.is_none() {
|
||||
d.remove(id)?;
|
||||
}
|
||||
// Where the next released object goes: above the original when it stays, else in its place.
|
||||
let mut at = if keep { idx + 1 } else { idx };
|
||||
let path = match path {
|
||||
Some(n) => {
|
||||
at += 1;
|
||||
Some(d.insert(parent, at - 1, n)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let text = match text {
|
||||
None => None,
|
||||
Some(text) if keep => {
|
||||
let mut n = original.clone();
|
||||
n.id = d.alloc_id();
|
||||
n.kind = NodeKind::Text(Box::new(text));
|
||||
Some(d.insert(parent, at, n)?)
|
||||
}
|
||||
Some(text) => {
|
||||
// The original, now just above the path.
|
||||
d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind = NodeKind::Text(Box::new(text));
|
||||
Some(id)
|
||||
}
|
||||
};
|
||||
Ok((path, text))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo
|
||||
//! step, and bad params refused without a change.
|
||||
//! step, and bad params refused without a change. Release Type on a Path ([`release`]).
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject};
|
||||
@@ -221,3 +221,386 @@ fn it_needs_a_selection() {
|
||||
select(&mut s, &[]);
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Release Type on a Path (#5532): each mode, Keep Original, mixed and empty selections, closed,
|
||||
/// open, curved and flipped paths, transformed and grouped type, multi-style and unicode text,
|
||||
/// undo and redo, the preview a dialog shows, and bad params.
|
||||
mod release {
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, NodeId, NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const C: &str = "addon.type.releasePath";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn new_id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// 12 pt type `words` on a path along `d` (SVG path data), starting where the path is nearest
|
||||
/// `at`, selected.
|
||||
fn path_type(s: &mut Session, d: &str, at: [f64; 2], words: &str) -> NodeId {
|
||||
let pid = s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = new_id(&s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": words, "size": 12, "at": at})).unwrap());
|
||||
select(s, &[id]);
|
||||
id
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 20, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
fn point_type(s: &mut Session) -> NodeId {
|
||||
new_id(&s.execute("text.create", &json!({"x": 40, "y": 500, "text": "point", "size": 12})).unwrap())
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> Document {
|
||||
(*s.doc().unwrap().doc).clone()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.clone()
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn path(s: &Session, id: NodeId) -> PathData {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Path { path, .. } => path.clone(),
|
||||
k => panic!("not a path: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// (parent, index) of `id`.
|
||||
fn place(s: &Session, id: NodeId) -> (Option<NodeId>, usize) {
|
||||
let (parent, idx, _) = s.doc().unwrap().doc.position(id).unwrap();
|
||||
(parent, idx)
|
||||
}
|
||||
|
||||
/// Each glyph's pen position in the document and its baseline angle, in text order.
|
||||
fn pens(t: &TextObject) -> Vec<(Point, f64)> {
|
||||
let mut g: Vec<_> =
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.into_iter().map(|g| (g.byte, t.xf * g.origin, g.angle)).collect();
|
||||
g.sort_by_key(|g| g.0);
|
||||
g.into_iter().map(|(_, p, a)| (p, a)).collect()
|
||||
}
|
||||
|
||||
/// How many path objects the document has.
|
||||
fn paths_in(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
for l in &s.doc().unwrap().doc.layers {
|
||||
l.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::Path { .. })));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn close(a: Point, b: Point) -> bool {
|
||||
(a - b).hypot() < 1e-4
|
||||
}
|
||||
|
||||
fn ids(v: &Value, key: &str) -> Vec<NodeId> {
|
||||
v[key].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
/// `after`, released from `before`: point type with the same text and attributes, on one
|
||||
/// straight line whose first character starts where `before`'s did on its path, with no Type
|
||||
/// on a Path Options left.
|
||||
fn assert_released(before: &TextObject, after: &TextObject) {
|
||||
assert_eq!(after.kind, TextKind::Point);
|
||||
assert_eq!(after.runs, before.runs, "the same text and character attributes");
|
||||
assert_eq!((&after.para, &after.paras), (&before.para, &before.paras), "the same paragraph attributes");
|
||||
assert_eq!(after.plain_text(), before.plain_text());
|
||||
assert_eq!((after.path_effect, after.path_align, after.path_spacing), Default::default(), "path options dropped");
|
||||
let (was, now) = (pens(before), pens(after));
|
||||
assert!(!now.is_empty());
|
||||
if let Some((first, _)) = was.first() {
|
||||
assert!(close(now[0].0, *first), "the baseline starts where the first character sat: {:?} vs {first:?}", now[0].0);
|
||||
}
|
||||
assert!(now.iter().all(|(_, a)| *a == 0.0), "a straight baseline");
|
||||
// On one line through the first pen, along the object's own x axis.
|
||||
let [a, b, ..] = after.xf.as_coeffs();
|
||||
let axis = vectorcraft_geom::Vec2::new(a, b);
|
||||
for (p, _) in &now {
|
||||
let off = *p - now[0].0;
|
||||
assert!(off.cross(axis).abs() < 1e-4 * axis.hypot().max(1.0) * off.hypot().max(1.0), "{p:?} is on the line");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_gives_point_type_and_the_path_in_the_types_place() {
|
||||
let mut s = session();
|
||||
let below = rect(&mut s, 10.0);
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Curved line");
|
||||
let above = rect(&mut s, 50.0);
|
||||
select(&mut s, &[id]);
|
||||
let before = text(&s, id);
|
||||
let (layer, idx) = place(&s, id);
|
||||
let (start, n) = (doc(&s), steps(&s));
|
||||
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let (paths, texts) = (ids(&out, "paths"), ids(&out, "texts"));
|
||||
assert_eq!((paths.len(), texts.len()), (1, 1));
|
||||
let (p, t) = (paths[0], texts[0]);
|
||||
assert_eq!(ids(&out, "ids"), [p, t], "bottom to top");
|
||||
assert_eq!(selected(&s), [p, t], "the released objects are selected");
|
||||
|
||||
// The path: its exact shape, anchors and handles, with no fill and no stroke, where the type was.
|
||||
assert_eq!(path(&s, p), before.type_path().unwrap());
|
||||
assert_eq!(*s.doc().unwrap().doc.node(p).unwrap().appearance, Appearance::basic(Paint::None, Paint::None, 1.0));
|
||||
assert_eq!(
|
||||
(place(&s, below), place(&s, p), place(&s, t), place(&s, above)),
|
||||
((layer, idx - 1), (layer, idx), (layer, idx + 1), (layer, idx + 2))
|
||||
);
|
||||
// The text replaces the type on a path.
|
||||
assert_released(&before, &text(&s, t));
|
||||
assert_eq!(t, id, "the same type object, now point type");
|
||||
|
||||
let released = doc(&s);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), start, "undone");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), released, "redone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_only_and_text_only() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "Line");
|
||||
let before = text(&s, id);
|
||||
let (layer, idx) = place(&s, id);
|
||||
let out = s.execute(C, &json!({"mode": "path"})).unwrap();
|
||||
let p = ids(&out, "paths")[0];
|
||||
assert!(ids(&out, "texts").is_empty());
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none(), "the type is gone");
|
||||
assert_eq!((path(&s, p), place(&s, p)), (before.type_path().unwrap(), (layer, idx)));
|
||||
assert_eq!(selected(&s), [p]);
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[id]);
|
||||
let out = s.execute(C, &json!({"mode": "text"})).unwrap();
|
||||
assert!(ids(&out, "paths").is_empty());
|
||||
assert_eq!((ids(&out, "texts"), place(&s, id)), (vec![id], (layer, idx)), "the type stays in its place");
|
||||
assert_released(&before, &text(&s, id));
|
||||
assert_eq!(paths_in(&s), 0, "no path made");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_original_adds_the_released_objects_above_it() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Keep");
|
||||
let (before, (layer, idx)) = (text(&s, id), place(&s, id));
|
||||
let original = s.doc().unwrap().doc.node(id).cloned().unwrap();
|
||||
let out = s.execute(C, &json!({"keepOriginal": true})).unwrap();
|
||||
let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]);
|
||||
assert_eq!(s.doc().unwrap().doc.node(id), Some(&original), "the type on a path stays as it is");
|
||||
assert_eq!((place(&s, id), place(&s, p), place(&s, t)), ((layer, idx), (layer, idx + 1), (layer, idx + 2)));
|
||||
assert_ne!(t, id);
|
||||
assert_eq!(selected(&s), [p, t], "only the released objects are selected");
|
||||
assert_released(&before, &text(&s, t));
|
||||
|
||||
// Text only, kept: the copy goes just above.
|
||||
select(&mut s, &[id]);
|
||||
let out = s.execute(C, &json!({"mode": "text", "keepOriginal": true})).unwrap();
|
||||
let t2 = ids(&out, "texts")[0];
|
||||
assert_eq!(place(&s, t2), (layer, idx + 1));
|
||||
assert_released(&before, &text(&s, t2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_objects_are_left_alone() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let pt = point_type(&mut s);
|
||||
let a = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "One");
|
||||
let b = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "Two");
|
||||
let others = [r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap());
|
||||
select(&mut s, &[r, pt, a, b]);
|
||||
let n = steps(&s);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step for the whole selection");
|
||||
assert_eq!((ids(&out, "paths").len(), ids(&out, "texts")), (2, vec![a, b]));
|
||||
assert_eq!([r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()), others);
|
||||
assert_eq!(selected(&s).len(), 4, "the two paths and the two texts");
|
||||
assert!(!selected(&s).contains(&r) && !selected(&s).contains(&pt));
|
||||
|
||||
// `ids` picks the objects instead of the selection.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
select(&mut s, &[r]);
|
||||
let out = s.execute(C, &json!({"ids": [r.0, b.0]})).unwrap();
|
||||
assert_eq!(ids(&out, "texts"), [b]);
|
||||
assert!(matches!(text(&s, a).kind, TextKind::OnPath { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_release_changes_nothing() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let pt = point_type(&mut s);
|
||||
select(&mut s, &[r, pt]);
|
||||
let (before, n, sel) = (doc(&s), steps(&s), selected(&s));
|
||||
assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"ids": [], "paths": [], "texts": []}));
|
||||
assert_eq!((doc(&s), steps(&s), selected(&s)), (before, n, sel), "no change, no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_and_open_paths_keep_their_shape() {
|
||||
for (d, closed) in [
|
||||
("M200 200 L400 200 L400 400 L200 400 Z", true),
|
||||
("M100 300 C150 100 250 500 300 300 S450 100 500 300", false),
|
||||
("M300 150 C380 150 450 220 450 300 C450 380 380 450 300 450 C220 450 150 380 150 300 C150 220 220 150 300 150 Z", true),
|
||||
] {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, d, [200.0, 200.0], "Round and round");
|
||||
let before = text(&s, id);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
let p = path(&s, ids(&out, "paths")[0]);
|
||||
assert_eq!(p, before.type_path().unwrap(), "{d}");
|
||||
assert_eq!(p.is_closed(), closed, "{d}");
|
||||
assert_released(&before, &text(&s, ids(&out, "texts")[0]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipped_type_releases_its_path_as_it_runs() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [300.0, 200.0], "Flipped");
|
||||
s.execute("type.pathOptions", &json!({"flip": true, "effect": "skew", "alignToPath": "center", "spacing": 4})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap());
|
||||
assert_released(&before, &text(&s, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transformed_type_keeps_its_transform() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Turned");
|
||||
s.execute("object.rotate", &json!({"angle": 30, "origin": [300, 300]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [300, 300]})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap(), "the transform is in the path");
|
||||
let after = text(&s, id);
|
||||
assert_eq!(after.xf.as_coeffs()[..4], before.xf.as_coeffs()[..4], "turned and scaled as the type was");
|
||||
assert_released(&before, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_type_releases_inside_its_group() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0);
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Grouped");
|
||||
select(&mut s, &[r, id]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let g = place(&s, id).0.unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Group { .. }));
|
||||
select(&mut s, &[g]);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]);
|
||||
assert_eq!((place(&s, p).0, place(&s, t).0), (Some(g), Some(g)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_and_unicode_text_survive() {
|
||||
let mut s = session();
|
||||
let words = "Größe ✓ 日本語 éa";
|
||||
let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], words);
|
||||
// "Gr" (bytes 0..2), and "日本" (bytes 12..18, after "Größe ✓ ").
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "size": 24, "fill": "#ff0000"})).unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 12, "end": 18, "tracking": 200, "hScale": 150})).unwrap();
|
||||
// A centred paragraph: the first character still starts where it sat.
|
||||
s.edit("centre", |d, _| {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.para.justify = Justify::Center;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = text(&s, id);
|
||||
assert!(before.runs.len() >= 3, "several styles: {:?}", before.runs);
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
let after = text(&s, ids(&out, "texts")[0]);
|
||||
assert_eq!(after.plain_text(), words);
|
||||
assert_released(&before, &after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_type_starts_at_its_start_bracket() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "");
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!(ids(&out, "texts"), [id]);
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.kind, TextKind::Point);
|
||||
assert!(close(t.xf * Point::ZERO, Point::new(300.0, 300.0)), "{:?}", t.xf * Point::ZERO);
|
||||
}
|
||||
|
||||
/// What a dialog's Preview does: each preview replaces the last, Cancel puts the type back with
|
||||
/// no step of history, and OK keeps the preview as one step.
|
||||
#[test]
|
||||
fn previews_cancel_and_commit() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Preview");
|
||||
let (start, n, sel) = (doc(&s), steps(&s), selected(&s));
|
||||
let count = paths_in;
|
||||
s.begin_interaction("Release Type on a Path").unwrap();
|
||||
s.preview(C, &json!({"mode": "both"})).unwrap();
|
||||
assert_eq!((count(&s), text(&s, id).kind), (1, TextKind::Point));
|
||||
s.preview(C, &json!({"mode": "text"})).unwrap();
|
||||
assert_eq!(count(&s), 0, "the next preview replaces the last");
|
||||
s.preview(C, &json!({"mode": "path", "keepOriginal": true})).unwrap();
|
||||
assert_eq!(count(&s), 1);
|
||||
assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. }));
|
||||
s.cancel_interaction().unwrap();
|
||||
assert_eq!((doc(&s), steps(&s), selected(&s)), (start.clone(), n, sel), "Cancel: as it was, no step");
|
||||
|
||||
s.begin_interaction("Release Type on a Path").unwrap();
|
||||
s.preview(C, &json!({"mode": "both"})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "OK: one step");
|
||||
assert_eq!(text(&s, id).kind, TextKind::Point);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_without_a_change() {
|
||||
let mut s = session();
|
||||
path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Bad");
|
||||
let (before, n) = (doc(&s), steps(&s));
|
||||
for p in [
|
||||
json!({"mode": "all"}),
|
||||
json!({"mode": 1}),
|
||||
json!({"keepOriginal": "yes"}),
|
||||
json!({"ids": [999_999]}),
|
||||
json!({"ids": "1"}),
|
||||
json!({"id": -1}),
|
||||
json!({"colour": "red"}),
|
||||
] {
|
||||
assert!(s.execute(C, &p).is_err(), "{p}");
|
||||
assert_eq!((doc(&s), steps(&s)), (before.clone(), n), "{p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)>) {
|
||||
|
||||
@@ -12,19 +12,19 @@
|
||||
mod flavours;
|
||||
pub(crate) mod resources;
|
||||
|
||||
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 +70,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 +100,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 +228,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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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") {
|
||||
@@ -833,7 +833,10 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(),
|
||||
None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK),
|
||||
};
|
||||
// In the document's language (Document Setup), none for the default.
|
||||
style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string);
|
||||
// In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none
|
||||
// for the default. Type already in a document keeps its own.
|
||||
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
|
||||
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
|
||||
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
|
||||
style
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ use super::{
|
||||
/// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay
|
||||
/// corners) and simplify it to `tol`.
|
||||
fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
|
||||
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3);
|
||||
let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3);
|
||||
let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) };
|
||||
let mut kept: Vec<Point> = vec![p0];
|
||||
for &p in pts.iter().skip(1) {
|
||||
@@ -150,7 +150,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let pen = PenRecord::of_samples(&samples);
|
||||
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0);
|
||||
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0);
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
@@ -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 ----------
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+185
-29
@@ -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};
|
||||
|
||||
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close),
|
||||
cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate),
|
||||
cmd!(
|
||||
"document.move",
|
||||
"Move Document",
|
||||
[],
|
||||
None,
|
||||
"{from?: index (default: the current document), to: index (0 = the first tab; past the last document = the last tab)} → {index}: moves the document to tab `to`, as dragging its tab along the tab strip does; the documents between shift by one, the order Window › Next/Previous Document steps through follows, and the current document stays the current one",
|
||||
has_doc,
|
||||
doc_move
|
||||
),
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
@@ -222,6 +231,23 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
|
||||
}
|
||||
|
||||
fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = s.documents().len();
|
||||
let from = match p.get("from") {
|
||||
None | Some(Value::Null) => s.active_index().ok_or(EngineError::NoDocument)?,
|
||||
Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`from` must be a non-negative integer"))?,
|
||||
};
|
||||
if from >= n {
|
||||
return Err(bad("document.move", "no such document"));
|
||||
}
|
||||
let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?;
|
||||
let to = to.min(n.saturating_sub(1));
|
||||
if !s.move_document(from, to) {
|
||||
return Err(bad("document.move", "no such document"));
|
||||
}
|
||||
Ok(json!({ "index": to }))
|
||||
}
|
||||
|
||||
fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let mut opts = slice_opts(p, "document.node")?;
|
||||
@@ -600,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`
|
||||
@@ -611,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).
|
||||
@@ -632,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()),
|
||||
}
|
||||
})
|
||||
@@ -663,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.
|
||||
@@ -678,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()
|
||||
@@ -703,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).
|
||||
@@ -729,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.
|
||||
@@ -743,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()
|
||||
@@ -777,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() {
|
||||
@@ -848,7 +964,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let off = s.prefs.paste_offset;
|
||||
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.
|
||||
@@ -881,8 +997,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
|
||||
};
|
||||
@@ -949,7 +1067,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());
|
||||
@@ -990,11 +1146,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, ¶ms).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`.
|
||||
@@ -758,11 +760,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) {
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !effects::has_transform_art(&v)
|
||||
&& !effects::has_transform_copies(&v)
|
||||
{
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
} else {
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them with a gradient or changes their fills and strokes): through their outlines.
|
||||
// them, each copy an object of its own, or changes their fills and strokes): through
|
||||
// their outlines.
|
||||
let symbol = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n))
|
||||
|
||||
@@ -366,14 +366,16 @@ fn expand_appearance_bakes_geometry() {
|
||||
assert!(s.execute("effect.expandAppearance", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Each copy is an object of its own (#5612).
|
||||
#[test]
|
||||
fn expand_transform_copies_makes_compound() {
|
||||
fn expand_transform_copies_makes_a_group_of_the_copies() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Compound { .. }));
|
||||
assert!(matches!(n.kind, NodeKind::Group { .. }), "{}", n.kind_label());
|
||||
assert_eq!(n.children().map(|c| c.len()), Some(2));
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
@@ -474,6 +476,53 @@ fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() {
|
||||
assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient");
|
||||
}
|
||||
|
||||
/// Expand Appearance on a solid-filled path whose Transform effect makes copies gives a group of
|
||||
/// one path per copy, each with the path's fill, not one compound path (#5612); a second Transform
|
||||
/// effect's copies of those copies nest, a group per copy of the first.
|
||||
#[test]
|
||||
fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint().color();
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "{}", n.kind_label());
|
||||
assert!(n.appearance.effects.is_empty());
|
||||
let copies = n.children().unwrap();
|
||||
assert_eq!(copies.len(), 3, "the path and its two copies");
|
||||
let xs: Vec<f64> = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect();
|
||||
assert_eq!(xs, vec![100.0, 250.0, 400.0]);
|
||||
for c in copies {
|
||||
assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label());
|
||||
assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!((c.geometric_bounds().unwrap().width() - 100.0).abs() < 1e-9);
|
||||
}
|
||||
let mut ids: Vec<NodeId> = vec![];
|
||||
n.walk(&mut |c| ids.push(c.id));
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), 4, "the group and each copy have ids of their own");
|
||||
// Two Transform effects: three columns, each a group of the column's two copies.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(*s.doc().unwrap().doc, *before);
|
||||
s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index":1,"params":{"moveV":150,"copies":1},"ids":[id.0],"item":null})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let columns = node(&s, id).children().unwrap().to_vec();
|
||||
assert_eq!(columns.len(), 3);
|
||||
for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) {
|
||||
let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label()));
|
||||
let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect();
|
||||
assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]);
|
||||
assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's own effect ids, in order.
|
||||
fn object_effects(s: &Session, id: NodeId) -> Vec<String> {
|
||||
node(s, id).appearance.effects.iter().map(|e| e.id.clone()).collect()
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -20,7 +20,9 @@
|
||||
//! 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 +181,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 +193,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)))
|
||||
|
||||
@@ -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, 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",
|
||||
|
||||
@@ -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,30 @@ 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}");
|
||||
}
|
||||
|
||||
#[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 +311,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 +1079,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]
|
||||
|
||||
@@ -404,6 +404,35 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() {
|
||||
assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err());
|
||||
}
|
||||
|
||||
/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document
|
||||
/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from
|
||||
/// before that opens with the radius converted, drawing the same dots; one saved since opens as
|
||||
/// it was.
|
||||
#[test]
|
||||
fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() {
|
||||
let halftone = |old: bool| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap();
|
||||
let r = super::tests_svgedit::rect(&mut s, 10.0, 10.0);
|
||||
s.execute("effect.apply", &json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 8}, "ids": [r]})).unwrap();
|
||||
if old {
|
||||
// As VectorCraft 0.18 wrote it: the document model's version 1, the radius in points.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).version = 1;
|
||||
}
|
||||
let pdf = b64(&s.execute("document.exportPdf", &json!({})).unwrap());
|
||||
let opened = open(&mut s, "halftone.pdf", &pdf);
|
||||
assert_eq!(opened["restored"], json!(true), "{opened}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.version, vectorcraft_doc::FORMAT_VERSION);
|
||||
let n = d.node(vectorcraft_doc::NodeId(r)).unwrap();
|
||||
n.appearance.effects.iter().find(|e| e.id == "pixelate.colorHalftone").and_then(|e| e.params["maxRadius"].as_f64()).unwrap()
|
||||
};
|
||||
// 8 pt at 300 ppi are 33⅓ px.
|
||||
assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true));
|
||||
assert_eq!(halftone(false), 8.0);
|
||||
}
|
||||
|
||||
/// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded.
|
||||
fn outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
fn walk(nodes: &[std::sync::Arc<vectorcraft_doc::Node>], depth: usize, out: &mut Vec<String>) {
|
||||
@@ -623,3 +652,265 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() {
|
||||
let kinds = see_through_outline(&legacy.doc);
|
||||
assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}");
|
||||
}
|
||||
|
||||
/// The paths and compound paths of `doc`'s art and of its patterns' tiles with their geometric
|
||||
/// bounds (rounded) and fills and strokes, one line each, then its gradient and pattern swatches: a
|
||||
/// gradient by its kind, its swatch link (`-` when it names no gradient swatch of `doc`), its stops
|
||||
/// (place, color, opacity, midpoint, swatch link and tint) and the gradient's place at the corners and
|
||||
/// center of the paint's bounds (rounded to hundredths); a pattern by its name and placement.
|
||||
fn paint_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
|
||||
let link = |name: &Option<String>| match name.as_deref().and_then(|n| doc.swatch(n)) {
|
||||
Some(sw) if matches!(sw.paint, Paint::Gradient(_)) => sw.name.clone(),
|
||||
_ => "-".into(),
|
||||
};
|
||||
let drawn = |p: &Paint, b: vectorcraft_geom::Rect| match p {
|
||||
Paint::Gradient(g) => {
|
||||
let geom = g.resolve(b);
|
||||
let at: Vec<f64> = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1), (b.center().x, b.center().y)]
|
||||
.map(|(x, y)| (geom.param_at(g.gradient.kind, (x, y).into()) * 100.0).round() / 100.0)
|
||||
.to_vec();
|
||||
let stops: Vec<String> = g
|
||||
.gradient
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let rgb = s.color.to_rgb().map(|v| (v * 100.0).round());
|
||||
format!("{:.3} {rgb:?} {:.2} mid {:.2} {:?} {:.2}", s.offset, s.opacity, s.midpoint, s.swatch, s.tint)
|
||||
})
|
||||
.collect();
|
||||
format!("{:?} link {} {stops:?} {at:?}", g.gradient.kind, link(&g.swatch))
|
||||
}
|
||||
Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(|v| (v * 1000.0).round() / 1000.0)),
|
||||
Paint::Solid { color, .. } => format!("{:?}", color.to_rgb().map(|v| (v * 100.0).round())),
|
||||
Paint::None => "none".into(),
|
||||
};
|
||||
// A compound path's paint is its own: its members' paint isn't drawn (Release gives them the
|
||||
// compound path's), so a compound path's line lists only its members' bounds.
|
||||
fn walk(nodes: &[Arc<Node>], f: &mut dyn FnMut(&Node)) {
|
||||
for n in nodes {
|
||||
f(n);
|
||||
if !matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
walk(n.children().map(Vec::as_slice).unwrap_or_default(), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
let lines = |nodes: &[Arc<Node>]| {
|
||||
let mut lines = vec![];
|
||||
walk(nodes, &mut |n| {
|
||||
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(b) = n.geometric_bounds() else { return };
|
||||
let kind = match n.children() {
|
||||
Some(members) => format!("compound of {:?}", members.iter().map(|m| bounds(m)).collect::<Vec<_>>()),
|
||||
None => "path".into(),
|
||||
};
|
||||
let mut line = format!("{kind} {:?}", [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64));
|
||||
for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) {
|
||||
line += &match it {
|
||||
AppearanceItem::Fill(f) => format!(" fill {}", drawn(&f.paint, b)),
|
||||
AppearanceItem::Stroke(st) => format!(" stroke {} {}", st.width, drawn(&st.paint, st.paint_bounds(b))),
|
||||
};
|
||||
}
|
||||
lines.push(line);
|
||||
});
|
||||
lines
|
||||
};
|
||||
let mut out = lines(&doc.layers);
|
||||
for p in doc.patterns.iter() {
|
||||
out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1]));
|
||||
out.extend(lines(&p.art));
|
||||
}
|
||||
for sw in doc.swatches_iter() {
|
||||
match &sw.paint {
|
||||
// A gradient swatch reads back linked to itself.
|
||||
Paint::Gradient(g) => {
|
||||
let own = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g.gradient.clone())));
|
||||
out.push(format!("swatch {} {}", sw.name, drawn(&own, vectorcraft_geom::Rect::ZERO)));
|
||||
}
|
||||
Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", sw.name)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The images of `doc`'s art, one line each: its pixel size, where its corners land (rounded to
|
||||
/// hundredths), its link's path and relative path, and its pixels (RGBA).
|
||||
fn image_outline(doc: &vectorcraft_doc::Document) -> Vec<String> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
let r = vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height));
|
||||
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x0, r.y1)].map(|(x, y)| {
|
||||
let p = im.xf * vectorcraft_geom::Point::new(x, y);
|
||||
((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0)
|
||||
});
|
||||
let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone()));
|
||||
let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw());
|
||||
out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// An embedded image (RGBA, part of it see-through, turned) and a linked one come back from the
|
||||
/// editing copy for other apps alone, pixel for pixel, with every save option that writes the copy;
|
||||
/// the linked image keeps its path and its path relative to the document's folder.
|
||||
#[test]
|
||||
fn images_come_back_from_the_editing_copy() {
|
||||
let dir = tmp("ai-images");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(format!("{dir}/art")).unwrap();
|
||||
let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| {
|
||||
let mut out = vec![];
|
||||
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
};
|
||||
let linked = format!("{dir}/art/linked.png");
|
||||
std::fs::write(&linked, png(5, 4, &|x, y| [(x * 50) as u8, (y * 60) as u8, 90, 255])).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
|
||||
let data = vectorcraft_format::base64_encode(&png(6, 3, &|x, y| [200, (x * 40) as u8, (y * 80) as u8, if x < 2 { 100 } else { 255 }]));
|
||||
s.execute("file.place", &json!({"name": "embedded.png", "dataBase64": data})).unwrap();
|
||||
// The placed image is selected.
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
s.execute("file.place", &json!({"path": linked, "link": true})).unwrap();
|
||||
let path = format!("{dir}/images.ai");
|
||||
s.execute("document.save", &json!({"path": path})).unwrap();
|
||||
let before = image_outline(&s.doc().unwrap().doc);
|
||||
assert_eq!(before.len(), 2, "{before:#?}");
|
||||
assert!(before[1].contains("art/linked.png"), "{before:#?}");
|
||||
for opts in [
|
||||
json!({"format": "ai"}),
|
||||
json!({"format": "ai", "compress": false}),
|
||||
json!({"format": "ai", "embedProfiles": false}),
|
||||
json!({"format": "ai", "includeLinked": true}),
|
||||
json!({"format": "ai", "range": "all"}),
|
||||
json!({"format": "ai", "pdfCompatible": false}),
|
||||
] {
|
||||
let r = s.execute("document.export", &opts).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("image"), "{r}");
|
||||
let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap();
|
||||
assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings);
|
||||
assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings);
|
||||
assert_eq!(image_outline(©.doc), before, "{opts}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of two artboards (the art on the first): a rectangle filled with a linear gradient of
|
||||
/// three stops placed across part of it, an ellipse filled with an elliptical radial gradient whose
|
||||
/// focal point is off its center, a rectangle stroked with a gradient, rectangles filled and
|
||||
/// stroked with the pattern `Dots`, one of them turned, an even-odd compound path filled with a
|
||||
/// gradient of a gray, a CMYK color and the spot color `Ink` at 70%, and the gradient swatch `Dawn`.
|
||||
fn gradient_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap();
|
||||
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
|
||||
let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| {
|
||||
id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
};
|
||||
let three = json!({"kind": "linear", "stops": [
|
||||
{"offset": 0, "color": "#ff0000", "midpoint": 0.3},
|
||||
{"offset": 0.4, "color": "#00ff00", "opacity": 0.5},
|
||||
{"offset": 1, "color": "#0000ff"}
|
||||
], "start": [20, 40], "end": [60, 17]});
|
||||
let a = rect(&mut s, 10.0, 10.0, 80.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "gradient": three})).unwrap();
|
||||
let e = id(s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 80, "height": 40})).unwrap());
|
||||
let glow = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#1a33cc"}],
|
||||
"start": [140, 30], "end": [180, 30], "aspect": 50, "focal": [150, 25]});
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "gradient": glow})).unwrap();
|
||||
let c = rect(&mut s, 190.0, 10.0, 90.0, 40.0);
|
||||
let two = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#000000"}]});
|
||||
s.execute("paint.setStroke", &json!({"ids": [c], "gradient": two, "width": 6})).unwrap();
|
||||
let tile = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [tile], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [tile], "none": true})).unwrap();
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
|
||||
let p = rect(&mut s, 10.0, 70.0, 80.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots", "width": 4})).unwrap();
|
||||
let turned = rect(&mut s, 100.0, 70.0, 80.0, 40.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [turned], "swatch": "Dots"})).unwrap();
|
||||
// Turned 30° and scaled to half about (140, 90).
|
||||
let (c, k) = (30f64.to_radians().cos() * 0.5, 30f64.to_radians().sin() * 0.5);
|
||||
let m = [c, k, -k, c, 140.0 - 140.0 * c + 90.0 * k, 90.0 - 140.0 * k - 90.0 * c];
|
||||
s.execute("pattern.transform", &json!({"ids": [turned], "matrix": m})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff9900", "spot": true})).unwrap();
|
||||
let outer = rect(&mut s, 190.0, 70.0, 90.0, 40.0);
|
||||
let hole = rect(&mut s, 210.0, 80.0, 40.0, 20.0);
|
||||
let ring = id(s.execute("object.compoundPath.make", &json!({"ids": [outer, hole]})).unwrap());
|
||||
let mixed = json!({"kind": "linear", "stops": [
|
||||
{"offset": 0, "color": {"gray": 0.8}},
|
||||
{"offset": 0.5, "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "midpoint": 0.7},
|
||||
{"offset": 1, "swatch": "Ink", "tint": 70}
|
||||
]});
|
||||
s.execute("paint.setFill", &json!({"ids": [ring], "gradient": mixed})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [ring], "none": true})).unwrap();
|
||||
let dawn = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Dawn", "gradient": dawn})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Gradients and patterns come back from the editing copy for other apps alone (the native
|
||||
/// document left out), with every save option that writes the copy; where the file has PDF pages,
|
||||
/// the reader takes the copy only when it draws as its page does. The version 7 `.ai` keeps each
|
||||
/// gradient.
|
||||
#[test]
|
||||
fn gradients_and_patterns_come_back_from_the_editing_copy() {
|
||||
let mut s = gradient_session();
|
||||
let before = (*s.doc().unwrap().doc).clone();
|
||||
let want = paint_outline(&before);
|
||||
assert!(want.iter().filter(|l| l.starts_with("path") && l.contains("pattern Dots")).count() == 2, "{want:#?}");
|
||||
assert!(want.iter().any(|l| l.starts_with("compound") && l.contains("Ink") && l.contains(") 0.70")), "{want:#?}");
|
||||
assert!(want.iter().any(|l| l.contains("mid 0.30")) && want.iter().any(|l| l.starts_with("swatch Dawn")), "{want:#?}");
|
||||
for opts in [
|
||||
json!({"format": "ai"}),
|
||||
json!({"format": "ai", "compress": false}),
|
||||
json!({"format": "ai", "embedProfiles": false}),
|
||||
json!({"format": "ai", "includeLinked": true}),
|
||||
json!({"format": "ai", "range": "all"}),
|
||||
json!({"format": "ai", "pdfCompatible": false}),
|
||||
] {
|
||||
let r = s.execute("document.export", &opts).unwrap();
|
||||
assert!(!r["warnings"].to_string().contains("gradient") && !r["warnings"].to_string().contains("pattern"), "{r}");
|
||||
let copy = editing_copy(&b64(&r));
|
||||
assert_eq!(paint_outline(©), want, "{opts}");
|
||||
}
|
||||
let path = tmp("gradients.ai");
|
||||
let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!(files.len(), 3, "{r}");
|
||||
for f in files.iter().filter(|f| !f.ends_with("-2.ai")) {
|
||||
assert_eq!(paint_outline(&editing_copy(&std::fs::read(f).unwrap())), want, "{f}");
|
||||
}
|
||||
let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap();
|
||||
let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap();
|
||||
// Each gradient the art paints with, by its kind and its stops' places and colors to 5% (version
|
||||
// 7 writes a gradient stroke as its filled outline, so the objects differ, and a spot color's
|
||||
// tint through its CMYK equivalent, 2% off here).
|
||||
let gradients = |doc: &vectorcraft_doc::Document| {
|
||||
let mut all = std::collections::BTreeSet::new();
|
||||
doc.walk(|node| {
|
||||
for it in node.appearance.items.iter() {
|
||||
if let vectorcraft_color::Paint::Gradient(g) = it.paint() {
|
||||
let stops: Vec<String> = g
|
||||
.gradient
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| format!("{:.3} {:?}", s.offset, s.color.to_rgb().map(|v| (v * 20.0).round() * 5.0)))
|
||||
.collect();
|
||||
all.insert(format!("{:?} {stops:?}", g.gradient.kind));
|
||||
}
|
||||
}
|
||||
});
|
||||
all
|
||||
};
|
||||
assert_eq!(gradients(&legacy.doc), gradients(&before));
|
||||
}
|
||||
@@ -32,6 +32,44 @@ fn png_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_export_defaults_to_document_resolution() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 72, "height": 36, "rasterEffectsPpi": 300})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0);
|
||||
for format in ["png", "psd"] {
|
||||
for (options, size, ppi) in [
|
||||
(json!({}), (300, 150), 300.0),
|
||||
(json!({"scale": 1}), (72, 36), 72.0),
|
||||
(json!({"scale": 2}), (144, 72), 144.0),
|
||||
(json!({"ppi": 150, "scale": 2}), (150, 75), 150.0),
|
||||
] {
|
||||
let mut params = options;
|
||||
params["format"] = json!(format);
|
||||
let bytes = b64(&s.execute("document.export", ¶ms).unwrap());
|
||||
assert_eq!(super::ppi::resolution(&bytes), Some((ppi, ppi)), "{params}");
|
||||
let image = super::load::raster_image(&bytes).unwrap();
|
||||
assert_eq!((image.width, image.height), size, "{params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_export_default_uses_the_sanitised_document_resolution() {
|
||||
// A stored resolution that isn't finite or is outside 1–2400 ppi exports at the resolution the
|
||||
// document reports (72 when not finite, else clamped), not at a zero, huge or failed size.
|
||||
for (stored, (width, height), size) in [(f64::NAN, (72, 36), (72, 36)), (0.0, (144, 72), (2, 1)), (1e9, (36, 18), (1200, 600))] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": width, "height": height})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).raster_effects_ppi = stored;
|
||||
for format in ["png", "psd"] {
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": format})).unwrap());
|
||||
let image = super::load::raster_image(&bytes).unwrap();
|
||||
assert_eq!((image.width, image.height), size, "{format} with a stored {stored} ppi");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_options_resolution_background_interlace_and_anti_aliasing() {
|
||||
let mut s = session(40.0, 30.0, 1);
|
||||
@@ -183,7 +221,7 @@ fn formats_list_the_raster_options() {
|
||||
assert!(opts("png").get(k).is_some(), "png lists {k}");
|
||||
}
|
||||
assert_eq!(opts("png")["antiAlias"]["default"], "art");
|
||||
assert_eq!(opts("png")["ppi"]["default"], 72);
|
||||
assert_eq!(opts("png")["ppi"]["default"], Value::Null);
|
||||
assert!(opts("jpg").get("quality").is_some() && opts("jpg").get("interlaced").is_none());
|
||||
assert!(opts("webp").get("antiAlias").is_some() && opts("svg").get("antiAlias").is_none());
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ fn new_id(v: &Value) -> u64 {
|
||||
v["id"].as_u64().or_else(|| v["ids"][0].as_u64()).unwrap_or_else(|| panic!("no id in {v}"))
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
pub(super) fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap())
|
||||
}
|
||||
|
||||
|
||||
@@ -151,11 +151,16 @@ impl FlattenOptions {
|
||||
|
||||
/// Whether colorized image `n`, art of `d`, counts as transparency by itself. With
|
||||
/// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale
|
||||
/// or 1-bit doesn't: the EPS writer draws it in that paint.
|
||||
/// or 1-bit doesn't: the EPS writer draws it in that paint. An image whose pixels don't take
|
||||
/// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized.
|
||||
pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool {
|
||||
let NodeKind::Image(im) = &n.kind else { return true };
|
||||
let blob = d.image_blob(im);
|
||||
if blob.is_some_and(|b| !b.takes_colorize()) {
|
||||
return false;
|
||||
}
|
||||
let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. }));
|
||||
!self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none())
|
||||
!self.keeps_colorize || !solid || blob.is_some_and(|b| b.gray_source().is_none())
|
||||
}
|
||||
|
||||
/// `n` shows an image whose see-through pixels count as transparency.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! another everywhere or in the selection, and selecting the text that uses a font. Also the fonts
|
||||
//! available (the bundled and installed ones) and rescanning the installed fonts.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -64,18 +64,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Text objects in scope: the selection's (and their descendants') or the whole document's.
|
||||
fn scope(s: &Session, selection_only: bool) -> Result<Vec<NodeId>> {
|
||||
fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
let mut v = vec![];
|
||||
let mut seen = HashSet::new();
|
||||
let mut add = |n: &vectorcraft_doc::Node| {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::Text(_)) && !v.contains(&c.id) {
|
||||
if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
})
|
||||
};
|
||||
if selection_only {
|
||||
for id in &st.selection.objects {
|
||||
for id in selected.unwrap_or(&st.selection.objects) {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
add(n);
|
||||
}
|
||||
@@ -97,7 +98,7 @@ fn being_edited(d: &Document, name: &str) -> bool {
|
||||
/// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a
|
||||
/// hidden or locked group of the art. Returned as (all of them, those shown by instances the
|
||||
/// Selection tool can reach: not hidden or locked, as `Document::editable` says).
|
||||
fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
|
||||
fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet<String>, BTreeSet<String>)> {
|
||||
fn open_instances(n: &Node, out: &mut BTreeSet<String>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
@@ -123,7 +124,7 @@ fn selected_symbols(s: &Session) -> Result<(BTreeSet<String>, BTreeSet<String>)>
|
||||
let st = s.doc()?;
|
||||
let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new());
|
||||
let editable = st.doc.editable();
|
||||
for id in &st.selection.objects {
|
||||
for id in selected.unwrap_or(&st.selection.objects) {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
@@ -482,12 +483,66 @@ fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> {
|
||||
}
|
||||
|
||||
fn fonts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let selection_only = bool_or(p, "selectionOnly", false);
|
||||
let ids = scope(s, selection_only)?;
|
||||
if bool_or(p, "selectionOnly", false) {
|
||||
let selected = s.doc()?.selection.objects.clone();
|
||||
font_inventory(s, Some(&selected))
|
||||
} else {
|
||||
font_inventory(s, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// List the fonts in the document, or in the given objects and their symbols.
|
||||
pub fn font_inventory(&self, selected: Option<&[NodeId]>) -> Result<Value> {
|
||||
font_inventory(self, selected)
|
||||
}
|
||||
|
||||
/// List text currently unavailable to a Replace Font request in its original selection.
|
||||
pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result<Vec<NodeId>> {
|
||||
let (family, style) = font_param(params, "from", "text.replaceFont")?;
|
||||
let selection_only = bool_or(params, "selectionOnly", false);
|
||||
let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?;
|
||||
let d = &self.doc()?.doc;
|
||||
let other: Vec<NodeId> = {
|
||||
let editable = d.editable();
|
||||
scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect()
|
||||
};
|
||||
let uses = |t: &TextObject| {
|
||||
t.runs.iter().any(|r| {
|
||||
r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name))
|
||||
})
|
||||
};
|
||||
let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::<Vec<_>>();
|
||||
fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec<NodeId>) {
|
||||
let open = open && n.visible && !n.locked;
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& (!open || closed)
|
||||
&& uses(t)
|
||||
{
|
||||
ids.push(n.id);
|
||||
}
|
||||
for child in n.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
visit(child, open, closed, uses, ids);
|
||||
}
|
||||
}
|
||||
for symbol in d
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name)))
|
||||
{
|
||||
let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name));
|
||||
visit(&symbol.art, true, closed, &uses, &mut ids);
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result<Value> {
|
||||
let ids = scope(s, selected.is_some(), selected)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// The type in the art of the symbols in scope too: all of them, or those the selection shows.
|
||||
let symbols = if selection_only { Some(selected_symbols(s)?.0) } else { None };
|
||||
let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None };
|
||||
let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect();
|
||||
texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t));
|
||||
let mut found: BTreeMap<UsedFont, (usize, usize, String)> = BTreeMap::new();
|
||||
@@ -536,6 +591,21 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option<String>)> {
|
||||
Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string)))
|
||||
}
|
||||
|
||||
fn skipped_font_texts(
|
||||
d: &Document,
|
||||
other: &[NodeId],
|
||||
symbols: &[(&TextObject, bool)],
|
||||
closed: &BTreeSet<String>,
|
||||
uses: &impl Fn(&TextObject) -> bool,
|
||||
) -> usize {
|
||||
let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count();
|
||||
skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
if !closed.is_empty() {
|
||||
skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count();
|
||||
}
|
||||
skipped
|
||||
}
|
||||
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.replaceFont";
|
||||
let (ff, fs) = font_param(p, "from", C)?;
|
||||
@@ -567,7 +637,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// With selectionOnly: the symbols the selection shows; those shown only by hidden or locked
|
||||
// instances keep their type, counted in `skipped`.
|
||||
let (symbols, closed) = if selection_only {
|
||||
let (all, open) = selected_symbols(s)?;
|
||||
let (all, open) = selected_symbols(s, None)?;
|
||||
let closed: BTreeSet<String> = all.difference(&open).cloned().collect();
|
||||
(Some(open), closed)
|
||||
} else {
|
||||
@@ -579,13 +649,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (ids, skipped, in_symbols) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let editable = d.editable();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id));
|
||||
let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count();
|
||||
let (ids, other): (Vec<NodeId>, Vec<NodeId>) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id));
|
||||
let texts = symbol_texts(d, symbols.as_ref());
|
||||
skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count();
|
||||
if !closed.is_empty() {
|
||||
skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count();
|
||||
}
|
||||
let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses);
|
||||
// The text that changes: when none does, the document and its undo history stay as they are.
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect();
|
||||
let in_symbols = texts.iter().any(|(t, open)| *open && changes(t));
|
||||
@@ -646,7 +712,7 @@ const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't
|
||||
fn select_font(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string();
|
||||
let style = str_param(p, "style").map(str::to_string);
|
||||
let ids = scope(s, false)?;
|
||||
let ids = scope(s, false, None)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group
|
||||
// or layer, or on a locked artboard.
|
||||
|
||||
@@ -262,7 +262,59 @@ impl Form {
|
||||
/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists
|
||||
/// images, text, masks and links as unsupported).
|
||||
fn supported(n: &Node) -> bool {
|
||||
n.extras().mask.is_none() && Form::of(n).is_some()
|
||||
n.extras().mask.is_none() && has_form(n)
|
||||
}
|
||||
|
||||
/// Does [`Form::of`] give `n` a form? The same walk and the same box, without collecting the
|
||||
/// points or placing them in a unit box.
|
||||
fn has_form(n: &Node) -> bool {
|
||||
let mut b = None;
|
||||
form_box(n, 0, &mut b).is_some()
|
||||
&& b.is_some_and(|b: Rect| {
|
||||
let side = b.width().max(b.height());
|
||||
side.is_finite() && side > 1e-9
|
||||
})
|
||||
}
|
||||
|
||||
/// [`Form::add`] without the form: `b` grows by each point it would add; `None` when `n` isn't
|
||||
/// supported.
|
||||
fn form_box(n: &Node, depth: usize, b: &mut Option<Rect>) -> Option<()> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, clipping, guide: false, .. } if !*clipping || depth > 0 => grow_by_path(b, path),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
for c in children {
|
||||
grow_by_path(b, c.path_data()?);
|
||||
}
|
||||
}
|
||||
NodeKind::SymbolInstance { xf, .. } => {
|
||||
for p in [*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)] {
|
||||
grow(b, p);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => {
|
||||
for c in children {
|
||||
if c.extras().mask.is_some() {
|
||||
return None;
|
||||
}
|
||||
form_box(c, depth + 1, b)?;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn grow_by_path(b: &mut Option<Rect>, path: &PathData) {
|
||||
for a in path.subpaths.iter().flat_map(|sp| &sp.anchors) {
|
||||
for p in [a.p, a.h_in, a.h_out] {
|
||||
grow(b, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `b` grown to take in `p`, as [`Form::of`] measures its points.
|
||||
fn grow(b: &mut Option<Rect>, p: Point) {
|
||||
*b = Some(b.unwrap_or(Rect::from_points(p, p)).union_pt(p));
|
||||
}
|
||||
|
||||
/// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension,
|
||||
@@ -374,8 +426,9 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
let [id] = st.selection.objects.as_slice() else {
|
||||
return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into());
|
||||
};
|
||||
// A group's contents are checked when Global Edit starts: building its shape here would walk
|
||||
// every object in it each time the menu or the Properties panel asks.
|
||||
// A group's contents are checked when Global Edit starts: measuring them here would walk
|
||||
// every object in it each time the menu or the Properties panel asks. Other objects are
|
||||
// measured ([`supported`]), not reduced to their form: the Control bar asks every frame.
|
||||
match st.doc.node(*id) {
|
||||
Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()),
|
||||
Some(n) if supported(n) => Ok(()),
|
||||
@@ -750,3 +803,195 @@ pub fn highlights(s: &Session) -> Outlines {
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::OpacityMask;
|
||||
use vectorcraft_geom::{Anchor, SubPath};
|
||||
|
||||
/// Global Edit's support as it was decided by building the form.
|
||||
fn by_form(n: &Node) -> bool {
|
||||
n.extras().mask.is_none() && Form::of(n).is_some()
|
||||
}
|
||||
|
||||
/// A small seeded generator (xorshift64*), so that a failure repeats.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
|
||||
}
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
fn unit(&mut self) -> f64 {
|
||||
(self.next() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
/// A spread for the points of one object: none, below and around the smallest size a form
|
||||
/// takes, ordinary, or past every bound.
|
||||
fn spread(&mut self) -> f64 {
|
||||
[0.0, 1e-10, 5e-10, 1e-9, 2e-9, 1.0, 1.0, 100.0, 100.0, 100.0, f64::INFINITY, f64::NAN][self.below(12) as usize]
|
||||
}
|
||||
fn point(&mut self, base: Point, spread: f64) -> Point {
|
||||
let mut c = |b: f64| match self.below(400) {
|
||||
0 => f64::NAN,
|
||||
1 => f64::INFINITY,
|
||||
2 => f64::NEG_INFINITY,
|
||||
_ => b + (self.unit() - 0.5) * spread,
|
||||
};
|
||||
Point::new(c(base.x), c(base.y))
|
||||
}
|
||||
}
|
||||
|
||||
fn path_data(r: &mut Rng) -> PathData {
|
||||
let (base, spread) = (Point::new(r.unit() * 200.0, r.unit() * 200.0), r.spread());
|
||||
let subpaths = (0..r.below(3))
|
||||
.map(|_| {
|
||||
let anchors = (0..r.below(4))
|
||||
.map(|_| Anchor { p: r.point(base, spread), h_in: r.point(base, spread), h_out: r.point(base, spread), ..Anchor::corner(base) })
|
||||
.collect();
|
||||
SubPath::new(anchors, r.below(2) == 0)
|
||||
})
|
||||
.collect();
|
||||
PathData::new(subpaths)
|
||||
}
|
||||
|
||||
/// A random object: paths (clipping paths and guides too), compound paths, symbol instances,
|
||||
/// groups (clip groups, live art, members with an opacity mask), type, blends and intertwined
|
||||
/// objects, any of them with an opacity mask.
|
||||
fn object(r: &mut Rng, d: &mut Document, text: &Node, depth: usize) -> Node {
|
||||
let leaf = depth >= 3;
|
||||
let mut n = match r.below(if leaf { 4 } else { 8 }) {
|
||||
0 | 1 => {
|
||||
let mut n = Node::path(d.alloc_id(), path_data(r), Appearance::default());
|
||||
if let NodeKind::Path { clipping, guide, .. } = &mut n.kind {
|
||||
*clipping = r.below(6) == 0;
|
||||
*guide = r.below(8) == 0;
|
||||
}
|
||||
n
|
||||
}
|
||||
2 => {
|
||||
let xf = match r.below(4) {
|
||||
0 => Affine::scale(0.0),
|
||||
1 => Affine::scale(1e-10),
|
||||
_ => Affine::translate((r.unit() * 100.0, r.unit() * 100.0)) * Affine::scale(r.spread()),
|
||||
};
|
||||
Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf })
|
||||
}
|
||||
3 => {
|
||||
let mut t = text.clone();
|
||||
t.id = d.alloc_id();
|
||||
t
|
||||
}
|
||||
4 => {
|
||||
let children = (0..r.below(4))
|
||||
.map(|_| match r.below(5) {
|
||||
0 => Arc::new(object(r, d, text, depth + 1)),
|
||||
_ => Arc::new(Node::path(d.alloc_id(), path_data(r), Appearance::default())),
|
||||
})
|
||||
.collect();
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::NonZero })
|
||||
}
|
||||
5 => {
|
||||
let children = (0..r.below(3)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect();
|
||||
Node::new(d.alloc_id(), NodeKind::Blend { children, spec: Box::default() })
|
||||
}
|
||||
_ => {
|
||||
let children = (0..r.below(4)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect();
|
||||
let mut g = Node::new(d.alloc_id(), NodeKind::Group { children, clip: r.below(3) == 0 });
|
||||
if r.below(8) == 0 {
|
||||
g.extras_mut().trace = Some(Box::new(Value::Null));
|
||||
}
|
||||
g
|
||||
}
|
||||
};
|
||||
if r.below(10) == 0 {
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::path(d.alloc_id(), path_data(r), Appearance::default()), true)));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// `n` and every object in it.
|
||||
fn every(n: &Node) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |c| out.push(c.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_is_decided_as_building_the_form_decides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
|
||||
let text = s.doc().unwrap().doc.node(t).unwrap().clone();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let (mut checked, mut taken, mut asked) = (0, 0, 0);
|
||||
for seed in 1..=400u64 {
|
||||
let mut r = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1);
|
||||
let n = object(&mut r, Arc::make_mut(&mut s.doc_mut().unwrap().doc), &text, 0);
|
||||
for c in every(&n) {
|
||||
assert_eq!(supported(&c), by_form(&c), "seed {seed}: {c:?}");
|
||||
checked += 1;
|
||||
taken += usize::from(by_form(&c));
|
||||
}
|
||||
// The enabled check of Start Global Edit on it, and Start Global Edit itself.
|
||||
let id = Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, n.clone()).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
if s.doc().unwrap().selection.objects != [id] {
|
||||
continue;
|
||||
}
|
||||
asked += 1;
|
||||
let today = n.extras().mask.is_none() && plain_group(&n) || by_form(&n);
|
||||
assert_eq!(can_toggle(&s).is_ok(), today, "seed {seed}");
|
||||
match s.execute(C, &json!({})) {
|
||||
Ok(_) => {
|
||||
assert!(by_form(&n), "seed {seed}");
|
||||
s.execute(C, &json!({})).unwrap();
|
||||
}
|
||||
Err(e) => assert_eq!(e.to_string().contains(UNSUPPORTED), !by_form(&n), "seed {seed}: {e}"),
|
||||
}
|
||||
}
|
||||
// Both answers came up often, and most objects could be selected alone.
|
||||
assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let corner = |x: f64, y: f64| Anchor::corner(Point::new(x, y));
|
||||
let path = |d: &mut Document, subpaths: Vec<SubPath>| Node::path(d.alloc_id(), PathData::new(subpaths), Appearance::default());
|
||||
let mut cases = vec![
|
||||
path(&mut d, vec![]),
|
||||
path(&mut d, vec![SubPath::new(vec![], true)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(5.0, 5.0)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 1e-9)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 2e-9)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(f64::INFINITY, 0.0)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, 0.0), corner(10.0, 0.0), corner(0.0, 0.0)], false)]),
|
||||
path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, f64::NAN)], false)]),
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children: vec![], rule: Default::default() }),
|
||||
Node::group(d.alloc_id(), vec![]),
|
||||
Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::scale(0.0) }),
|
||||
Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }),
|
||||
];
|
||||
// A group as deep as the walk goes, and one level deeper.
|
||||
let mut deep = path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(10.0, 10.0)], false)]);
|
||||
for _ in 0..=vectorcraft_doc::MAX_DEPTH {
|
||||
deep = Node::group(d.alloc_id(), vec![Arc::new(deep)]);
|
||||
cases.push(deep.clone());
|
||||
}
|
||||
let expected = [false, false, false, false, true, false, true, false, false, false, false, true];
|
||||
for (i, n) in cases.iter().enumerate() {
|
||||
assert_eq!(supported(n), by_form(n), "case {i}: {n:?}");
|
||||
if let Some(e) = expected.get(i) {
|
||||
assert_eq!(supported(n), *e, "case {i}");
|
||||
}
|
||||
}
|
||||
assert!(supported(&cases[cases.len() - 2]) && !supported(&cases[cases.len() - 1]));
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,8 @@ pub(crate) fn with_stored_stops<'a>(g: &'a Value, old: &Paint, stored: &StopColo
|
||||
/// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid
|
||||
/// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the
|
||||
/// diamond's range; `swatch` and `tint` (%) keep a stop's link as given (resolve them first with
|
||||
/// [`link_stops`]). The result is sorted by offset.
|
||||
/// [`link_stops`]), and `plates` (C, M, Y, K, 0..1) the process inks a linked stop prints with its
|
||||
/// spot ink. The result is sorted by offset.
|
||||
pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
let arr = v.as_array().ok_or("`stops` must be an array")?;
|
||||
if arr.len() < 2 {
|
||||
@@ -213,6 +214,10 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
let opacity = num("opacity")?.map(|o| if o > 1.0 { o / 100.0 } else { o }).unwrap_or(1.0);
|
||||
let swatch = str_param(st, "swatch").map(str::to_string);
|
||||
let tint = num("tint")?.filter(|_| swatch.is_some()).map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32);
|
||||
let plates = match st.get("plates").filter(|_| swatch.is_some()) {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(p) => Some(plates_param(p).ok_or_else(|| format!("stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K)"))?),
|
||||
};
|
||||
Ok(GradientStop {
|
||||
offset: offset.clamp(0.0, 1.0) as f32,
|
||||
color,
|
||||
@@ -220,6 +225,7 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
midpoint: num("midpoint")?.unwrap_or(0.5).clamp(0.13, 0.87) as f32,
|
||||
swatch,
|
||||
tint,
|
||||
plates,
|
||||
})
|
||||
})
|
||||
.collect::<Parsed<Vec<_>>>()?;
|
||||
@@ -227,6 +233,17 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A stop's `plates` param: the process inks (C, M, Y, K, 0..1) printed with its spot swatch.
|
||||
fn plates_param(v: &Value) -> Option<[f32; 4]> {
|
||||
let a = v.as_array().filter(|a| a.len() == 4)?;
|
||||
let mut out = [0.0f32; 4];
|
||||
for (o, x) in out.iter_mut().zip(a) {
|
||||
let x = x.as_f64().filter(|x| x.is_finite())?;
|
||||
*o = x.clamp(0.0, 1.0) as f32;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parse a gradient paint object (the `gradient` param of `paint.setFill`). Lossless for everything
|
||||
/// `vectorcraft_tools::params::gradient_params` writes.
|
||||
pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
//!
|
||||
//! An overlap area is a face of the planar arrangement of what the members paint (their fills and
|
||||
//! strokes, type outlined; other objects by their bounds): the part where two or more of them
|
||||
//! overlap, split wherever a member's edge crosses it.
|
||||
//! overlap, split wherever a member's edge crosses it. The area a member is raised in is that
|
||||
//! face grown a little ([`SEAM`]) into the parts where only that member paints ([`raised_area`]),
|
||||
//! so its edge does not lie on the edge of the member it passes over: there, both edges would be
|
||||
//! anti-aliased and the member below would show through as a hairline (#5337).
|
||||
//!
|
||||
//! Behaviour: <https://helpx.adobe.com/illustrator/using/intertwine-objects.html> (Make,
|
||||
//! Release, clicking or drawing around an overlap, Bring to Front, Bring Forward, Send Backward
|
||||
@@ -23,7 +26,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces, faces_in, is_intertwine, nonempty};
|
||||
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::Beside;
|
||||
@@ -302,13 +305,46 @@ fn tiers(order: &[usize]) -> Vec<(usize, usize)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How far (pt) the area a member is raised in reaches past its overlap face, into the parts only
|
||||
/// that member paints ([`raised_area`]).
|
||||
const SEAM: f64 = 2.0;
|
||||
|
||||
/// The area member `i` is raised in for `face`: the face, and the parts within [`SEAM`] of it
|
||||
/// where only `i` paints (`areas`: what each member paints, [`painted_areas`]). Drawing `i` again
|
||||
/// there changes nothing, and the edge of the area then lies inside `i`, not on the edge of a
|
||||
/// member it passes over (where the anti-aliased edges of both would let that member show
|
||||
/// through as a hairline).
|
||||
fn raised_area(face: &PathData, i: usize, areas: &[Option<PathData>]) -> PathData {
|
||||
let Some(own) = areas.get(i).and_then(Option::as_ref) else { return face.clone() };
|
||||
let ring = po::offset_path(face, SEAM, po::Join::Round, 4.0);
|
||||
let Some(near) = ring.bounds() else { return face.clone() };
|
||||
let mut paths = vec![(&ring, FillRule::NonZero), (own, FillRule::NonZero)];
|
||||
paths.extend(
|
||||
areas
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(k, _)| *k != i)
|
||||
.filter_map(|(_, a)| a.as_ref())
|
||||
.filter(|a| a.bounds().is_some_and(|b| b.overlaps(near)))
|
||||
.map(|a| (a, FillRule::NonZero)),
|
||||
);
|
||||
let only = po::boolean_n(&paths, |inside| inside.first() == Some(&true) && inside.get(1) == Some(&true) && !inside.iter().skip(2).any(|b| *b));
|
||||
if only.is_empty() {
|
||||
return face.clone();
|
||||
}
|
||||
nonempty(po::boolean(face, FillRule::NonZero, &only, FillRule::NonZero, po::BoolOp::Union)).unwrap_or_else(|| face.clone())
|
||||
}
|
||||
|
||||
/// Draw the members of `face` in `order` there (bottom first), leaving the other areas as they
|
||||
/// are.
|
||||
fn arrange_face(children: &mut [Arc<Node>], face: &Face, order: &[usize]) {
|
||||
/// are (`areas`: what each member paints, [`painted_areas`]).
|
||||
fn arrange_face(children: &mut [Arc<Node>], face: &Face, order: &[usize], areas: &[Option<PathData>]) {
|
||||
for (i, tier) in tiers(order) {
|
||||
if let Some(c) = children.get_mut(i) {
|
||||
set_tier(Arc::make_mut(c), &face.path, tier);
|
||||
let Some(c) = children.get_mut(i) else { continue };
|
||||
// A member drawn in its own order there with no areas has nothing to change.
|
||||
if tier == 0 && c.extras().intertwine.is_none() && c.extras().intertwine_tiers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
set_tier(Arc::make_mut(c), &raised_area(&face.path, i, areas), tier);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,7 +415,8 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(m) => Some(children.iter().position(|c| c.id == m).ok_or_else(|| bad(C, format!("object {} is not in this Intertwine group", m.0)))?),
|
||||
None => None,
|
||||
};
|
||||
let all = faces(&children);
|
||||
let painted = painted_areas(&children);
|
||||
let all = faces_of(&painted);
|
||||
let found = match (at, &lasso) {
|
||||
(Some(p), _) => face_at(&all, p).into_iter().collect(),
|
||||
(None, Some(l)) => faces_in(&all, l),
|
||||
@@ -423,7 +460,7 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = d.node_mut(group).ok_or(EngineError::NoNode(group))?;
|
||||
let NodeKind::Intertwine { children } = &mut n.kind else { return Err(EngineError::NoNode(group)) };
|
||||
for (face, new) in &plans {
|
||||
arrange_face(children, face, new);
|
||||
arrange_face(children, face, new, &painted);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -100,7 +100,31 @@ pub enum ItemKind {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct LibraryColor {
|
||||
pub name: String,
|
||||
/// The colour; a spot colour's full-strength ink (its swatch's colour), without the tint.
|
||||
pub color: Color,
|
||||
/// A spot colour's ink (its swatch's name): using it adds the document's spot swatch of that
|
||||
/// name and links the paint to it (#5812). Files written before spot colours have none.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub spot: Option<String>,
|
||||
/// A spot colour's tint (0..1; 1 for a process colour).
|
||||
#[serde(default = "full_tint", skip_serializing_if = "is_full_tint")]
|
||||
pub tint: f32,
|
||||
}
|
||||
|
||||
fn full_tint() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn is_full_tint(t: &f32) -> bool {
|
||||
*t >= 1.0
|
||||
}
|
||||
|
||||
/// A library colour as `library.add` reads it from the selection or params.
|
||||
struct NewColor {
|
||||
name: String,
|
||||
color: Color,
|
||||
spot: Option<String>,
|
||||
tint: f32,
|
||||
}
|
||||
|
||||
/// A graphic: the art as a native document (its own resources included) and its thumbnail.
|
||||
@@ -369,6 +393,13 @@ impl Library {
|
||||
fn sanitize(&mut self) {
|
||||
clip(&mut self.name);
|
||||
self.colors.truncate(MAX_ITEMS);
|
||||
for c in &mut self.colors {
|
||||
if let Some(ink) = &mut c.spot {
|
||||
clip(ink);
|
||||
}
|
||||
c.spot = c.spot.take().filter(|ink| !ink.trim().is_empty());
|
||||
c.tint = if c.spot.is_some() && c.tint.is_finite() { c.tint.clamp(0.0, 1.0) } else { 1.0 };
|
||||
}
|
||||
self.gradients.retain_mut(|g| clean_gradient(&mut g.gradient));
|
||||
self.gradients.truncate(MAX_ITEMS);
|
||||
self.patterns.truncate(MAX_ITEMS);
|
||||
@@ -598,7 +629,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
|
||||
"{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color, spot: ink name or null, tint: 0..1}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}",
|
||||
always,
|
||||
get
|
||||
),
|
||||
@@ -643,7 +674,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add to Library",
|
||||
[],
|
||||
None,
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
"{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint; with `color`, the spot swatch it is, kept as a spot colour), tint?: 0..100 (with `color` and a spot `swatch`: its %), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke), a colour linked to a spot swatch kept as a spot colour (the swatch's name, its colour and the tint); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
@@ -652,7 +683,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Use Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
@@ -782,7 +813,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"id": id,
|
||||
"name": lib.name,
|
||||
"graphics": lib.graphics.iter().map(|g| json!({"id": g.id, "name": g.name, "width": g.width, "height": g.height, "thumbnail": g.thumbnail})).collect::<Vec<_>>(),
|
||||
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color})).collect::<Vec<_>>(),
|
||||
"colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color, "spot": c.spot, "tint": c.tint})).collect::<Vec<_>>(),
|
||||
"gradients": lib.gradients.iter().map(|g| json!({"name": g.name, "gradient": g.gradient})).collect::<Vec<_>>(),
|
||||
"patterns": lib.patterns.iter().map(|p| json!({"name": p.name, "pattern": p.pattern, "thumbnail": p.thumbnail})).collect::<Vec<_>>(),
|
||||
"charStyles": lib.char_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::<Vec<_>>(),
|
||||
@@ -856,13 +887,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
lib.graphics.push(g);
|
||||
placed(lib, &place, ItemRef { kind: item_kind, item: key }, v)?
|
||||
}
|
||||
Item::Color((name, color)) => {
|
||||
Item::Color(NewColor { name, color, spot, tint }) => {
|
||||
full(lib.colors.len())?;
|
||||
if let Some(old) = lib.colors.iter().find(|o| o.color == color) {
|
||||
// A spot colour is its ink: one of another ink (or a process colour) is another item.
|
||||
if let Some(old) = lib.colors.iter().find(|o| o.color == color && o.spot == spot && o.tint == tint) {
|
||||
return Ok(json!({ "name": old.name, "existing": true }));
|
||||
}
|
||||
let name = unique(&given.clone().unwrap_or(name), |n| lib.colors.iter().any(|o| o.name == n));
|
||||
lib.colors.push(LibraryColor { name: name.clone(), color });
|
||||
lib.colors.push(LibraryColor { name: name.clone(), color, spot, tint });
|
||||
placed(lib, &place, ItemRef { kind: item_kind, item: name.clone() }, json!({ "name": name, "existing": false }))?
|
||||
}
|
||||
Item::Gradient(mut g) => {
|
||||
@@ -925,7 +957,7 @@ fn placed(lib: &mut Library, place: &Placement, r: ItemRef, mut v: Value) -> Res
|
||||
|
||||
enum Item {
|
||||
Graphic(LibraryGraphic),
|
||||
Color((String, Color)),
|
||||
Color(NewColor),
|
||||
Gradient(LibraryGradient),
|
||||
Pattern(LibraryPattern),
|
||||
Style(bool, Map<String, Value>),
|
||||
@@ -942,7 +974,7 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result<LibraryGraphic> {
|
||||
if roots.is_empty() {
|
||||
return Err(bad(cmd, "select the art to add first"));
|
||||
}
|
||||
let clip = Clipboard::copy(st, &roots);
|
||||
let clip = Clipboard::copy(st, &roots, false);
|
||||
let bounds = clip.bounds().ok_or_else(|| bad(cmd, "the selection draws nothing"))?;
|
||||
let mut doc = clip.to_document();
|
||||
let board = bounds.inflate(1.0, 1.0);
|
||||
@@ -963,23 +995,38 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result<LibraryGraphic> {
|
||||
}
|
||||
|
||||
/// The first selected object's solid fill (`stroke`: stroke) colour, else the default one, with a
|
||||
/// name: its swatch's, else its hex.
|
||||
fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<(String, Color)> {
|
||||
// A colour given (a swatch dropped on the panel).
|
||||
/// name: its swatch's, else its hex. A colour linked to a spot swatch keeps the ink (the swatch's
|
||||
/// name and full-strength colour) and its tint.
|
||||
fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<NewColor> {
|
||||
// A colour given (a swatch dropped on the panel), with its spot swatch's name when it has one.
|
||||
if let Some(c) = p.get("color").filter(|v| !v.is_null()) {
|
||||
let color = color_value(c).ok_or_else(|| bad(cmd, "bad colour"))?;
|
||||
return Ok((color.to_hex(), color));
|
||||
let swatch = str_param(p, "swatch").map(str::to_string);
|
||||
let tint = super::paint::tint_param(p, cmd)?.unwrap_or(1.0);
|
||||
let given = NewColor { name: color.to_hex(), color, spot: None, tint: 1.0 };
|
||||
return Ok(spot_color(s, given, swatch, tint));
|
||||
}
|
||||
match selected_paint(s, p, stroke)? {
|
||||
Paint::Solid { color, swatch, .. } => {
|
||||
let name = swatch.filter(|n| !n.is_empty()).unwrap_or_else(|| color.to_hex());
|
||||
Ok((name, color))
|
||||
Paint::Solid { color, swatch, tint } => {
|
||||
let swatch = swatch.filter(|n| !n.is_empty());
|
||||
let name = swatch.clone().unwrap_or_else(|| color.to_hex());
|
||||
Ok(spot_color(s, NewColor { name, color, spot: None, tint: 1.0 }, swatch, tint))
|
||||
}
|
||||
Paint::None => Err(bad(cmd, if stroke { "the selection has no stroke colour" } else { "the selection has no fill colour" })),
|
||||
_ => Err(bad(cmd, "only solid colours can be added (not gradients or patterns)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the spot colour of the active document's spot swatch `swatch` at `tint` (0..1), when
|
||||
/// there is one: named after it, with its full-strength colour; else `c` as it is.
|
||||
fn spot_color(s: &Session, c: NewColor, swatch: Option<String>, tint: f32) -> NewColor {
|
||||
let Some(doc) = s.active().map(|st| &st.doc) else { return c };
|
||||
let Some(name) = swatch else { return c };
|
||||
let Some(ink) = doc.swatch(&name).filter(|w| w.spot).and_then(|w| w.paint.color()) else { return c };
|
||||
let tint = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 1.0 };
|
||||
NewColor { name: name.clone(), color: ink, spot: Some(name), tint }
|
||||
}
|
||||
|
||||
/// The first selected object's (or `ids`') fill (`stroke`: stroke) paint (type's: its first
|
||||
/// character's, as the proxy shows it), else the default one.
|
||||
fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result<Paint> {
|
||||
@@ -989,11 +1036,13 @@ fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result<Paint> {
|
||||
None => st.selection.objects.clone(),
|
||||
};
|
||||
let from_art = ids.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| {
|
||||
let (paint, to_doc, _) = n.proxy_paint(stroke, None)?;
|
||||
let (paint, to_doc, bounds) = n.proxy_paint(stroke, None)?;
|
||||
// Type's characters paint in its own space: a gradient there takes its placement in the
|
||||
// document, so that it keeps the direction it shows.
|
||||
match (paint, n.proxy_gradient(stroke, None)) {
|
||||
(Paint::Gradient(g), Some((_, geom))) if to_doc != vectorcraft_geom::Affine::IDENTITY => {
|
||||
match paint {
|
||||
Paint::Gradient(g) if to_doc != vectorcraft_geom::Affine::IDENTITY => {
|
||||
let mut geom = g.resolve(bounds);
|
||||
geom.transform(to_doc, g.gradient.kind);
|
||||
Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })))
|
||||
}
|
||||
_ => Some(paint.clone()),
|
||||
@@ -1100,7 +1149,10 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Kind::FillColor | Kind::StrokeColor => {
|
||||
let c = lib.colors.iter().find(|c| c.name == item).ok_or_else(missing)?;
|
||||
json!({ "color": c.color })
|
||||
match &c.spot {
|
||||
Some(ink) => json!({ "color": c.color, "spot": ink, "tint": c.tint }),
|
||||
None => json!({ "color": c.color }),
|
||||
}
|
||||
}
|
||||
Kind::FillGradient | Kind::StrokeGradient => {
|
||||
let g = lib.gradients.iter().find(|g| g.name == item).ok_or_else(missing)?;
|
||||
@@ -1143,7 +1195,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Kind::FillColor | Kind::StrokeColor => {
|
||||
let stroke = to_stroke(p, kind)?;
|
||||
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
|
||||
s.execute(if stroke { "paint.setStroke" } else { "paint.setFill" }, &json!({ "color": color }))?;
|
||||
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
|
||||
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(ink) => use_spot(s, set, ink, &color, &data)?,
|
||||
None => {
|
||||
s.execute(set, &json!({ "color": color }))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } }))
|
||||
}
|
||||
Kind::FillGradient | Kind::StrokeGradient => {
|
||||
@@ -1185,6 +1243,32 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its
|
||||
/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of
|
||||
/// that name: the one it has when it is the same colour, else a new one (a name taken by another
|
||||
/// colour gets a number), one undo step (#5812).
|
||||
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> {
|
||||
const C: &str = "library.use";
|
||||
let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?;
|
||||
let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0));
|
||||
let doc = &s.doc()?.doc;
|
||||
let have = doc.swatch(ink).is_some_and(|w| w.spot && w.paint.color() == Some(c));
|
||||
in_one_step(s, |s| {
|
||||
let swatch = if have {
|
||||
ink.to_string()
|
||||
} else {
|
||||
let r = s.execute("swatch.new", &json!({ "name": ink, "color": color, "spot": true, "keepModel": true }))?;
|
||||
r.get("name").and_then(Value::as_str).ok_or_else(|| bad(C, "the spot colour couldn't be added"))?.to_string()
|
||||
};
|
||||
let mut p = json!({ "swatch": swatch });
|
||||
if tint < 1.0 {
|
||||
p["tint"] = json!(tint * 100.0);
|
||||
}
|
||||
s.execute(set, &p)?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// The `to` param of `library.use`: whether the item paints the stroke (default: the kind's).
|
||||
fn to_stroke(p: &Value, kind: Kind) -> Result<bool> {
|
||||
match str_param(p, "to") {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! subfolders (`links.findFiles`, searched on separate threads: [`super::findfiles`]). A file with
|
||||
//! a linked file's name, in any letter case, is ranked by what the link saved
|
||||
//! ([`vectorcraft_doc::LinkInfo`]): the same file (its size and hash), the same size (when the link
|
||||
//! saved no hash, or the file is larger than 1 GB and isn't hashed), or the name only.
|
||||
//! saved no hash, or the file is larger than 1 GiB and isn't hashed), or the name only.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Find Linked Files",
|
||||
[],
|
||||
None,
|
||||
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
|
||||
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
|
||||
always,
|
||||
find
|
||||
)]
|
||||
@@ -176,10 +176,29 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// How many folder names the file at `found` has in common with the saved path `saved` (whichever
|
||||
/// system's separators it uses), counted from the innermost out up to the first that differs,
|
||||
/// compared in lowercase.
|
||||
/// system's separators it uses, [`vectorcraft_doc::links::path_separators`]), counted from the
|
||||
/// innermost out up to the first that differs, compared in lowercase. The saved path's parent
|
||||
/// components are resolved first: `..` in a `/` or `\` path, and each colon after the first in a
|
||||
/// run of colons in a classic Mac OS path (`Disk:Projects:Art::photo.png` is in `Projects`).
|
||||
fn shared_folders(saved: &str, found: &Path) -> usize {
|
||||
let saved = saved.rsplit(['/', '\\']).skip(1).filter(|c| !c.is_empty());
|
||||
let separators = vectorcraft_doc::links::path_separators(saved);
|
||||
let classic = separators == [':'];
|
||||
let mut up = 0usize;
|
||||
let saved = saved.rsplit(separators).skip(1).filter(move |c| {
|
||||
let parent = if classic { c.is_empty() } else { *c == ".." };
|
||||
if parent {
|
||||
up += 1;
|
||||
return false;
|
||||
}
|
||||
if c.is_empty() || *c == "." && !classic {
|
||||
return false;
|
||||
}
|
||||
if up > 0 {
|
||||
up -= 1;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
let found = found.parent().into_iter().flat_map(|p| p.components().rev()).map_while(|c| match c {
|
||||
Component::Normal(n) => n.to_str(),
|
||||
_ => None,
|
||||
|
||||
@@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
|
||||
/// Per linked image in the layers of `st`: its file's status, where it was found when away from
|
||||
/// its path, and whether the image shows its preview (each file probed once).
|
||||
fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap<NodeId, (Status, Option<String>, bool)> {
|
||||
let mut out = BTreeMap::new();
|
||||
for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) {
|
||||
let (status, found) = probe(g, st.path.as_deref());
|
||||
@@ -1349,12 +1349,11 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va
|
||||
let doc_path = st.path.as_deref();
|
||||
let path = fileio::document_path(&l.path, doc_path).ok();
|
||||
let stamp = path.as_deref().and_then(file_stamp);
|
||||
let folder_len = l.path.len().saturating_sub(l.name().len());
|
||||
out["status"] = json!(status.as_str());
|
||||
note_refused(out, l, doc_path);
|
||||
out["path"] = json!(l.path);
|
||||
out["fileName"] = json!(l.name());
|
||||
out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\']));
|
||||
out["location"] = json!(l.folder());
|
||||
for (k, v) in [
|
||||
("page", l.page.map(u64::from)),
|
||||
("fileSize", stamp.map(|s| s.0).or(l.size)),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::common::{
|
||||
DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of,
|
||||
spacing_param, starts_param, wrap,
|
||||
@@ -180,6 +182,17 @@ fn finite_point(p: &Value, cmd: &str) -> Result<Point> {
|
||||
if q.x.is_finite() && q.y.is_finite() && q.x.abs() < 1e9 && q.y.abs() < 1e9 { Ok(q) } else { Err(bad(cmd, "x and y must be finite")) }
|
||||
}
|
||||
|
||||
/// Most spine points `with` names.
|
||||
const MAX_SPINE_POINTS: usize = 10_000;
|
||||
|
||||
/// The optional `with` list of spine point indexes (empty when absent).
|
||||
fn spine_points_param(p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
let Some(v) = p.get("with").filter(|v| !v.is_null()) else { return Ok(vec![]) };
|
||||
let wrong = || bad(cmd, "`with` must be a list of at most 10000 spine point indexes");
|
||||
let list = v.as_array().filter(|l| l.len() <= MAX_SPINE_POINTS).ok_or_else(wrong)?;
|
||||
list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect()
|
||||
}
|
||||
|
||||
pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.spine.moveAnchor";
|
||||
let index = index_param(p, "anchor", C)?;
|
||||
@@ -191,6 +204,11 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad(C, "handle must be in or out")),
|
||||
};
|
||||
let independent = switch_or(p, "independent", false, C)?;
|
||||
let with = spine_points_param(p, C)?;
|
||||
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
|
||||
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "`with` moves points, not a handle"));
|
||||
}
|
||||
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
|
||||
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
|
||||
if let Some(out) = handle {
|
||||
@@ -198,9 +216,13 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(());
|
||||
}
|
||||
let delta = q - a.p;
|
||||
a.translate(delta);
|
||||
// The key objects on the point move with it.
|
||||
for (k, _) in anchors.iter().enumerate().filter(|(_, a)| **a == index) {
|
||||
// The other points selected with it (#5285) move as far.
|
||||
let moved: BTreeSet<usize> = with.iter().copied().chain([index]).collect();
|
||||
for &i in &moved {
|
||||
sp.anchors.get_mut(i).ok_or_else(|| bad(C, "no such spine point"))?.translate(delta);
|
||||
}
|
||||
// The key objects on the points move with them.
|
||||
for (k, _) in anchors.iter().enumerate().filter(|(_, a)| moved.contains(*a)) {
|
||||
if let Some(key) = keys.get_mut(k) {
|
||||
Arc::make_mut(key).transform(Affine::translate(delta), false);
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Spine Point",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the selected blend), anchor: index, x, y, handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on the point moves with it. The first edit turns the straight spine into a path",
|
||||
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
|
||||
has_doc,
|
||||
spine_move_anchor
|
||||
),
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, MaskEdit, Node, NodeId, NodeKind, Selection};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, switch_or};
|
||||
|
||||
/// Name of the temporary mask-editing layer.
|
||||
pub const MASK_EDIT_LAYER: &str = "Opacity Mask Editing";
|
||||
@@ -138,7 +138,7 @@ fn view_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "transparency.viewOpacityMask";
|
||||
let st = s.doc()?;
|
||||
let editing = st.doc.mask_edit.map(|m| m.object);
|
||||
if !p.get("on").and_then(Value::as_bool).unwrap_or(st.shown_mask().is_none()) {
|
||||
if !switch_or(p, "on", st.shown_mask().is_none(), C)? {
|
||||
let st = s.doc_mut()?;
|
||||
let id = st.mask_view.take();
|
||||
st.revision += 1;
|
||||
|
||||
Loaded 100 of 449 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user