Merge remote-tracking branch 'upstream/main' into pencil-redraw-extend

# Conflicts:
#	docs/target-app-parity.md
#	docs/ui-parity.md
This commit is contained in:
ncic committed 2026-11-06 22:04:24 +01:00
commit b7c923921e
189 files changed
+14806 -554

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
name: House rules
on:
push:
branches: [main]
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
pull_request:
paths:
- AGENTS.md
- CLAUDE.md
- .github/workflows/house-rules.yml
workflow_dispatch:
permissions:
contents: read
concurrency:
group: house-rules-${{ github.ref }}
cancel-in-progress: true
jobs:
house-rules:
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
with:
rust: true
+56 -5
View File
@@ -1,3 +1,56 @@
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
10. **Keep secrets and personal details out** of the repository, logs and requests.
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
<!-- craft-house-rules:end -->
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
## Licence allowlist
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
- `ISC`
- `MIT`
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
- `CC0-1.0`
- `CC-BY-4.0`
- `CC-BY-SA-4.0`
- `LicenseRef-Public-Domain`
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
<!-- craft-house-rules:end -->
# VectorCraft — instructions for agents
VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions.
@@ -6,10 +59,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
2. `plan/` is an optional gitignored notebook. Behaviour notes may be in `plan/illustrator/*.md`. Do not ask for it and do not stop when it is absent. Orient, implement, test, verify, then record in the public docs.
## Non-negotiables
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
@@ -45,7 +95,6 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
@@ -88,3 +137,5 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
+1 -76
View File
@@ -1,76 +1 @@
# VectorCraft — instructions for agents
VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions.
Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format": "drawcraft"` headers still open (`vectorcraft_format::LEGACY_EXTENSION`), and preferences migrate from the old config folder. Keep those paths working; use the new name everywhere else.
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
## Non-negotiables
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
- Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones.
- Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles).
- Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS).
- Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names.
- If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications.
- Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).**
- Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it.
- Every image, icon, font or other asset must be one of:
- original work created for VectorCraft by a contributor (who licenses it MIT OR Apache-2.0);
- OSI open source;
- public domain / CC0;
- Creative Commons with redistribution allowed.
- **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`.
- `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts.
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input.
- Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort.
- Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible.
- New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare `#![forbid(unsafe_code)]` before modules or other crate items; crate-level `//!` documentation may precede it.
- Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them.
- Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why.
- Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that.
- `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net.
- Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, cover it in `cursor_icon` (`crates/ui-egui/src/canvas.rs`), draw it in `crates/ui-egui/src/cursors.rs` or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`.
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise).
- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`).
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`).
## Roadmap and progress docs
The progress docs:
- [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log.
- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships).
- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus.
- Checklists: [`ui-parity.md`](docs/ui-parity.md), [`file-format-parity.md`](docs/file-format-parity.md), [`hardware-parity.md`](docs/hardware-parity.md), [`localization-parity.md`](docs/localization-parity.md), [`effects-parity.md`](docs/effects-parity.md), [`type-parity.md`](docs/type-parity.md); [`architecture.md`](docs/architecture.md).
When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history.
- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated.
- Keep the README's Status section in step with the ROADMAP headline.
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
@AGENTS.md
Generated
+1
View File
@@ -6471,6 +6471,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-testkit",
"vectorcraft-text",
]
+3 -2
View File
@@ -14,7 +14,7 @@
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (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)
> **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
@@ -107,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% |
@@ -223,6 +223,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. |
+4
View File
@@ -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
+77 -2
View File
@@ -6,9 +6,10 @@ use std::rc::Rc;
use std::sync::{Arc, OnceLock};
use vectorcraft_geom::hit::{fill_contains, stroke_contains};
use vectorcraft_geom::{BezPath, FillRule, Point, Rect};
use vectorcraft_geom::kurbo::ParamCurveNearest;
use vectorcraft_geom::{BezPath, FillRule, PathData, PathSeg, Point, Rect};
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, SymbolBoxes};
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeAlign, SymbolBoxes};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HitKind {
@@ -724,6 +725,43 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom::
stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline)
}
/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a
/// miter or square cap, so the caller falls back to the full stroke check there.
fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> {
if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 {
return None;
}
let radius_sq = radius * radius;
let decoration_sq = decoration_reach * decoration_reach;
let mut near_decoration = false;
for sp in &path.subpaths {
for i in 0..sp.segment_count() {
let c = sp.segment(i);
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
near_decoration = true;
}
let controls = [c.p0, c.p1, c.p2, c.p3];
if controls.iter().all(|q| q.x < p.x - radius)
|| controls.iter().all(|q| q.x > p.x + radius)
|| controls.iter().all(|q| q.y < p.y - radius)
|| controls.iter().all(|q| q.y > p.y + radius)
{
continue;
}
let seg = if sp.segment_is_line(i) { PathSeg::Line(vectorcraft_geom::kurbo::Line::new(c.p0, c.p3)) } else { PathSeg::Cubic(c) };
if seg.nearest(p, 1e-9).distance_sq <= radius_sq {
if vectorcraft_geom::bez::has_length(&seg) {
return Some((true, near_decoration));
}
// A zero-length segment can still hit as an outline, though a painted stroke
// needs a segment with direction. Let the existing check decide its hit kind.
near_decoration = true;
}
}
}
Some((false, near_decoration))
}
#[cfg(test)]
thread_local! {
/// How many objects [`hit_leaf`] tested on this thread.
@@ -735,6 +773,43 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
LEAVES_TESTED.with(|c| c.set(c.get() + 1));
match &n.kind {
NodeKind::Path { path, rule, .. } => {
if opt.outline
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
{
if hit {
return Some(HitKind::Outline);
}
if !needs_full_check {
return None;
}
}
let mut strokes = n.appearance.painted_strokes();
if !opt.outline
&& n.appearance.fill().is_none_or(|f| f.paint.is_none())
&& let Some(s) = strokes.next()
&& strokes.next().is_none()
&& s.align == StrokeAlign::Center
&& s.width.is_finite()
&& s.width > 0.0
&& s.dash.as_ref().is_none_or(|d| !d.is_dashed())
&& s.profile.is_none()
&& s.start_arrow.is_none()
&& s.end_arrow.is_none()
&& s.brush.is_none()
&& let Some((hit, near_decoration)) = near_path_body(
path,
p,
s.width / 2.0 + opt.tol,
if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 },
)
{
if hit {
return Some(HitKind::Stroke);
}
if !near_decoration {
return None;
}
}
let bp = path.to_bezpath();
if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) {
return Some(k);
+33
View File
@@ -38,6 +38,39 @@ fn unfilled_interior_misses() {
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
}
#[test]
fn long_plain_stroke_hits_its_middle_and_curved_end() {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let mut sp = vectorcraft_geom::SubPath::polyline(&(0..=4097).map(|i| Point::new(i as f64 * 10.0, 0.0)).collect::<Vec<_>>(), false);
sp.anchors[4096].h_out = Point::new(40960.0, 100.0);
sp.anchors[4097].h_in = Point::new(40970.0, 100.0);
sp.anchors.push(vectorcraft_geom::Anchor::corner(Point::new(40970.0, 100.0)));
sp.anchors.push(vectorcraft_geom::Anchor::corner(Point::new(0.0, 100.0)));
let path = vectorcraft_geom::PathData::single(sp);
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(Some(l), 0, Node::path(id, path, look)).unwrap();
let outline = HitOptions { outline: true, ..Default::default() };
for point in [Point::new(20485.0, 0.0), Point::new(40965.0, 75.0)] {
assert_eq!(hit_test(&d, point, HitOptions::default()).map(|h| h.kind), Some(HitKind::Stroke));
assert_eq!(hit_test(&d, point, outline).map(|h| h.kind), Some(HitKind::Outline));
}
assert!(hit_test(&d, Point::new(20485.0, 50.0), HitOptions::default()).is_none());
}
#[test]
fn coincident_anchors_remain_hittable_as_an_outline() {
let mut d = Document::new(200.0, 200.0);
let id = d.alloc_id();
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(50.0, 50.0); 2], false));
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
d.insert(d.layers.first().map(|l| l.id), 0, Node::path(id, path, look)).unwrap();
let at = Point::new(50.0, 50.0);
assert_eq!(hit_test(&d, at, HitOptions::default()).map(|h| h.kind), Some(HitKind::Outline));
assert_eq!(hit_test(&d, at, HitOptions { outline: true, ..Default::default() }).map(|h| h.kind), Some(HitKind::Outline));
}
/// #1103: a marquee drawn over a background picks what is on it, not the background, whose
/// outline it doesn't touch.
#[test]
+7 -1
View File
@@ -307,7 +307,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
),
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})),
r(
"blur.gaussian",
"Gaussian Blur…",
BLUR,
"{radius: pt (5), linear?: bool (false; blurs the colours in linear light, as an SVG filter with color-interpolation-filters=\"linearRGB\" does)}",
json!({"radius": 5.0}),
),
r(
"artistic.coloredPencil",
"Colored Pencil…",
+41
View File
@@ -1079,6 +1079,47 @@ pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) {
}
}
/// [`gaussian_rgba`] with the colours mixed in linear light: decoded from sRGB before the blur
/// and encoded again after it (Filter Effects 1 §16, `color-interpolation-filters: linearRGB`,
/// <https://www.w3.org/TR/filter-effects-1/#ColorInterpolationFiltersProperty>). The blur runs on
/// 16-bit values, so dark linear tones keep their steps.
pub fn gaussian_rgba_linear(data: &mut [u8], w: usize, h: usize, sigma: f64) {
use vectorcraft_doc::color::cms::lab::{linear_to_srgb, srgb_to_linear};
if let Some(px) = pixels(data, w, h)
&& sigma >= 0.2
{
// Each colour is unpremultiplied, decoded (by table) and premultiplied again.
let decode: Vec<f32> = (0..=255u8).map(|v| srgb_to_linear(f32::from(v) / 255.0)).collect();
let mut wide: Vec<Px16> = px
.iter()
.map(|p| {
let a = f32::from(p[3]) / 255.0;
let lin = |v: u8| {
if p[3] == 0 {
return 0;
}
let straight = (f32::from(v) / f32::from(p[3]) * 255.0).round().clamp(0.0, 255.0) as usize;
(decode.get(straight).copied().unwrap_or(0.0) * a * 65535.0).round().clamp(0.0, 65535.0) as u16
};
[lin(p[0]), lin(p[1]), lin(p[2]), u16::from(p[3]) * 257]
})
.collect();
gaussian(&mut wide, w, sigma);
for (p, q) in px.iter_mut().zip(&wide) {
let a = to8(q[3]);
let alpha = f32::from(q[3]) / 65535.0;
let enc = |v: u16| {
if alpha <= 0.0 {
return 0;
}
let straight = (f32::from(v) / 65535.0 / alpha).clamp(0.0, 1.0);
(linear_to_srgb(straight) * f32::from(a)).round().clamp(0.0, f32::from(a)) as u8
};
*p = [enc(q[0]), enc(q[1]), enc(q[2]), a];
}
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
+22
View File
@@ -887,6 +887,28 @@ fn gaussian_and_plane_blurs_keep_their_mass() {
assert!((plane.iter().sum::<f32>() - 100.0).abs() < 0.5 && plane[15 * w + 13] > 0.0 && plane[13 * w + 15] > 0.0);
}
/// Blurred in linear light, black beside white meets at about 188/255 (half the light, encoded),
/// where the plain blur meets at about 128; flat areas and alpha stay as they are (#5877).
#[test]
fn linear_light_blur_mixes_light_not_values() {
// Large enough that the transparency past the edges doesn't reach the middle.
let (w, h) = (120, 60);
let src = image(w, h, |x, _| if x < 60 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
let (mut plain, mut linear) = (src.clone(), src.clone());
gaussian_rgba(&mut plain, w, h, 3.0);
gaussian_rgba_linear(&mut linear, w, h, 3.0);
let mid = |d: &[u8]| (f32::from(at(d, w, 59, 30)[0]) + f32::from(at(d, w, 60, 30)[0])) / 2.0;
assert!((mid(&plain) - 128.0).abs() < 6.0, "{}", mid(&plain));
assert!((mid(&linear) - 188.0).abs() < 6.0, "{}", mid(&linear));
assert_eq!((at(&linear, w, 30, 30), at(&linear, w, 90, 30)), ([0, 0, 0, 255], [255, 255, 255, 255]));
// Premultiplied input: a half-transparent white square blurs to white at any alpha.
let mut soft = image(30, 30, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [128, 128, 128, 128] } else { [0, 0, 0, 0] });
gaussian_rgba_linear(&mut soft, 30, 30, 2.0);
for p in soft.as_chunks::<4>().0 {
assert!(p[0] <= p[3] && p[3] <= 128 && (p[3] < 8 || p[0] + 2 >= p[3]), "{p:?}");
}
}
/// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored
/// --nocapture pixel_timings`).
#[test]
+5 -3
View File
@@ -48,9 +48,11 @@ pub enum RasterFx {
Feather {
radius: f64,
},
/// Blur the whole object (σ = radius / 2).
/// Blur the whole object (σ = radius / 2): its colours mixed as they are, or in linear light
/// (`linear`, as an SVG filter asks with `color-interpolation-filters="linearRGB"`).
GaussianBlur {
radius: f64,
linear: bool,
},
/// A Photoshop-style filter over the object's pixels (Radial Blur, Unsharp Mask…).
Pixel(PixelFx),
@@ -77,7 +79,7 @@ impl RasterFx {
RasterFx::DropShadow { dx, dy, blur, .. } => dx.abs().max(dy.abs()) + 1.5 * blur,
RasterFx::OuterGlow { blur, .. } => 1.5 * blur,
RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => 0.0,
RasterFx::GaussianBlur { radius } => 1.5 * radius,
RasterFx::GaussianBlur { radius, .. } => 1.5 * radius,
RasterFx::Pixel(p) => p.outset(bounds),
RasterFx::Rasterize(r) => r.outset(),
}
@@ -416,7 +418,7 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
center: text(&p, "source", "edge").eq_ignore_ascii_case("center"),
},
"stylize.feather" => RasterFx::Feather { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0) },
"blur.gaussian" => RasterFx::GaussianBlur { radius: num(&p, "radius", 5.0).clamp(0.0, 1000.0), linear: flag(&p, "linear", false) },
RASTERIZE => RasterFx::Rasterize(Rasterize::parse(&p)),
id => RasterFx::Pixel(pixel::parse(id, &p)?),
})
+10 -1
View File
@@ -19,7 +19,7 @@ mod width;
use std::borrow::Cow;
use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Shape};
use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Rect, Shape};
use vectorcraft_doc::{LineCap, LineJoin, StrokeAlign, StrokeLayer};
pub(crate) use vectorcraft_geom::bez::{kink, segments, subpaths, tangent, unit};
@@ -120,6 +120,15 @@ pub fn line_outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> B
}
}
/// The variable-width outline near `near`, with its profile positions measured on the whole
/// undashed line. Returns `None` when no segment is omitted or the stroke is dashed.
pub fn line_outline_profile_near(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64, near: Rect) -> Option<BezPath> {
if st.dash.is_some() || line.elements().is_empty() || width <= 0.0 || !width.is_finite() {
return None;
}
width::width_outline_near(line, width, st.profile.as_ref()?, st, tol, near)
}
/// [`line_outline`] of a dashed line without a width profile, made of only the dashes and dots on
/// the segments of `line` that `keep` accepts ([`dash_kept`]). `None` when `st` has no dash
/// pattern or has a width profile, or when its pattern draws the line solid.
+65 -1
View File
@@ -10,7 +10,7 @@
use std::f64::consts::PI;
use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Vec2};
use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Rect, Vec2};
use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile};
use super::{kink, segments, subpaths, unit};
@@ -21,6 +21,70 @@ pub fn width_outline(bp: &BezPath, width: f64, profile: &WidthProfile, st: &Stro
outline_spans(bp, &[], width, profile, st, tol)
}
/// Outline only flattened segments near `near`, retaining each run's original fractions of its
/// whole subpath for the width profile. `None` means no segments could be omitted.
pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64, near: Rect) -> Option<BezPath> {
let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) };
let mut out = BezPath::new();
let mut cut = false;
for (r, closed) in subpaths(bp) {
if closed {
return None;
}
let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol);
let n = pts.len();
if n < 2 {
continue;
}
let count = n - 1;
let mut lengths = Vec::with_capacity(count);
let mut kept = Vec::with_capacity(count);
let mut total = 0.0;
for i in 0..count {
let (a, b) = (pts[i], pts[i + 1]);
let len = a.distance(b);
if !len.is_finite() {
return None;
}
total += len;
lengths.push(len);
kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1));
}
if kept.iter().all(|v| *v) {
ctx.subpath(&mut out, &pts, &corner, closed, (0.0, 1.0));
continue;
}
cut = true;
if total <= 1e-12 {
continue;
}
let mut walked = 0.0;
let mut run = Vec::new();
let mut run_corner = Vec::new();
let mut from = 0.0;
for i in 0..count {
if kept[i] {
if run.is_empty() {
from = walked / total;
run.push(pts[i]);
run_corner.push(corner[i]);
}
run.push(pts[i + 1]);
run_corner.push(corner[i + 1]);
} else if run.len() > 1 {
ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total));
run.clear();
run_corner.clear();
}
walked += lengths[i];
}
if run.len() > 1 {
ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total));
}
}
cut.then_some(out)
}
/// [`width_outline`] of pieces of longer subpaths: subpath `i` of `bp` covers the fractions
/// `spans[i]` of the subpath it was cut from (see [`Dashed::spans`](super::Dashed::spans));
/// subpaths without a span are whole.
+11 -9
View File
@@ -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() {
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Attributes",
[],
None,
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG export links the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
"{overprintFill?: bool, overprintStroke?: bool (aimed as object.setOverprint's fill and stroke, item? too), showCenter?: bool (the canvas shows the selected object's centre point), imageMap?: \"none\"|\"rectangle\"|\"polygon\", url?: string (\"\" removes it; SVG, PDF and .ai export link the object), note?: string, ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} set the Attributes panel's values on ids or the selection, as one undo step; a URL given joins the recent URLs (attributes.info) → {changed: objects}",
has_doc,
set
),
+1
View File
@@ -37,6 +37,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
use symbols::selected_instances;
pub(crate) use symbols::{
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
stored_natural_size,
};
use symbols::{
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
+6 -5
View File
@@ -8,11 +8,12 @@ use super::{
// ---------- symbols ----------
pub(crate) fn natural_size(d: &Document, name: &str) -> (f64, f64) {
d.unknown
.get(SIZES_KEY)
.and_then(|m| m.get(name))
.and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)))
.unwrap_or((2.0 * HALF, 2.0 * HALF))
stored_natural_size(d, name).unwrap_or((2.0 * HALF, 2.0 * HALF))
}
/// The natural size `d` records for symbol `name` (`None` when it records none).
pub(crate) fn stored_natural_size(d: &Document, name: &str) -> Option<(f64, f64)> {
d.unknown.get(SIZES_KEY).and_then(|m| m.get(name)).and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)))
}
pub(crate) fn set_natural_size(d: &mut Document, name: &str, size: Option<(f64, f64)>) {
+3 -1
View File
@@ -24,7 +24,7 @@ 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
+62 -5
View File
@@ -20,7 +20,12 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, TextStyleDef};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration,
TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
use super::super::patterncmds::add_pattern;
use super::super::{Result, bad, unique_name};
@@ -628,6 +633,38 @@ fn shows_definitions(b: &Brush) -> bool {
found
}
/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and
/// given to it under the name pasting adds it as.
#[derive(Clone, Debug, PartialEq)]
pub struct SymbolOptions {
/// Natural size `(w, h)` (`None`: the document records none).
pub size: Option<(f64, f64)>,
pub registration: SymbolRegistration,
pub export_type: SymbolExportType,
/// 9-slice guides (`None`: 9-slice scaling off).
pub nine_slice: Option<SymbolNineSlice>,
}
impl SymbolOptions {
/// The options `d` keeps for symbol `name`.
fn of(d: &Document, name: &str) -> Self {
Self {
size: stored_natural_size(d, name),
registration: d.symbol_registration(name),
export_type: d.symbol_export_type(name),
nine_slice: d.symbol_nine_slice(name),
}
}
/// Make them the options of `d`'s symbol `name`.
fn give(&self, d: &mut Document, name: &str) {
set_natural_size(d, name, self.size);
d.set_symbol_registration(name, self.registration);
d.set_symbol_export_type(name, self.export_type);
d.set_symbol_nine_slice(name, self.nine_slice);
}
}
/// What pasting did to the document's resources (part of the paste result).
#[derive(Debug, Default)]
pub(crate) struct Imported {
@@ -671,6 +708,12 @@ impl Clipboard {
Self {
images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(),
symbols: src.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).cloned().collect(),
symbol_options: src
.symbols
.iter()
.filter(|s| used.has(Res::Symbol, &s.name))
.map(|s| (s.name.clone(), SymbolOptions::of(src, &s.name)))
.collect(),
patterns: src.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).cloned().collect(),
swatches: src.swatches_iter().filter(|w| used.carries(w)).cloned().collect(),
graphic_styles: src.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)).cloned().collect(),
@@ -725,13 +768,27 @@ impl Clipboard {
out.placed(r, &def.name, &p);
}
}
// Symbols and patterns, compared once relinked. Those added are relinked at the end, when
// every new name and graphic style id is known.
// Symbols and patterns, compared once relinked (symbols with their options too). Those
// added are relinked at the end, when every new name and graphic style id is known.
let mut added_symbols = HashSet::new();
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
let options = self.symbol_options.get(&def.name);
let theirs: HashMap<String, SymbolOptions> = match options {
Some(_) => {
d.symbols.iter().filter(|s| copy_of(&def.name, &s.name)).map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))).collect()
}
None => HashMap::new(),
};
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)));
added_symbols.extend(p.new_name(&def.name));
let p = place(&mut d.symbols, def, same_doc, |a, b| {
options.is_none_or(|o| theirs.get(&a.name) == Some(o)) && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
o.give(d, &name);
}
added_symbols.insert(name);
}
out.placed(Res::Symbol, &def.name, &p);
}
let mut added_patterns = HashSet::new();
+1 -1
View File
@@ -721,7 +721,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
if rotation != 0.0 {
t.xf *= vectorcraft_geom::rotate_deg(rotation);
}
t.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false);
t.vertical = switch_or(p, "vertical", false, "text.create")?;
t.para = new_type_para();
new_type_alignment(s, p, "text.create", &mut t)?;
if let Some(a) = p.get("area") {
+2 -2
View File
@@ -14,7 +14,7 @@ use super::pathops::Beside;
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
use super::{
CommandSpec, EngineError, Point, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ok,
str_param,
str_param, switch_or,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -716,7 +716,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
}
fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("locked").and_then(Value::as_bool).unwrap_or(!s.menu.guides_locked);
let v = switch_or(p, "locked", !s.menu.guides_locked, "view.guides.lock")?;
s.menu.guides_locked = v;
// Locked guides can't stay selected, ruler guides or guide paths, in any open document
// ([`Session::select`] lets those go in the active one).
+1 -1
View File
@@ -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
),
+114 -2
View File
@@ -1,4 +1,6 @@
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, target_paths};
use vectorcraft_pathops::addons::pathtools as pt;
use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths};
use super::{
Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Result, Session, SimplifyOptions, SubPath, Value, json,
number_or, po,
@@ -179,11 +181,121 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Join tool ----------
/// Most open subpaths the Join tool compares pairwise for crossings before it only joins ends.
const MAX_TRIM_SUBPATHS: usize = 64;
/// One end of an open subpath that runs on past where it crosses another: the part kept, which
/// ends at the crossing, and the part past it.
struct Overhang {
kept: SubPath,
cut: SubPath,
}
impl Overhang {
fn at(&self) -> Option<Point> {
self.kept.anchors.last().map(|a| a.p)
}
}
/// The overhangs of `sp` at its first and last crossing (`places`: subpath, segment, t, in order).
/// A crossing on an end anchor leaves no overhang there.
fn overhangs(sp: &SubPath, places: &[(usize, usize, f64)]) -> Vec<Overhang> {
let mut out = vec![];
for (place, at_start) in [(places.first(), true), (places.last(), false)] {
let Some(&(_, seg, t)) = place else { continue };
let (split, marks) = pt::insert_at(sp, &[(seg, t)]);
let Ok([first, second]) = <[SubPath; 2]>::try_from(split.cut_at(&marks)) else { continue };
let (mut kept, cut) = if at_start { (second, first) } else { (first, second) };
if at_start {
kept.reverse();
}
out.push(Overhang { kept, cut });
}
out
}
/// Does the scrub `pts` (`scrub` as a path) cross `cut` or pass within `tol` of it?
fn scrubbed(cut: &SubPath, pts: &[Point], scrub: &PathData, tol: f64) -> bool {
let pd = PathData::single(cut.clone());
pt::crossings(&[&pd, scrub], false).is_some_and(|c| c.first().is_some_and(|v| !v.is_empty()))
|| cut.anchors.iter().any(|a| dist_to_polyline(pts, a.p) <= tol)
|| pts.iter().any(|q| pd.nearest(*q).is_some_and(|n| n.4 <= tol))
}
/// Two crossing open subpaths, each `(path, subpath)`, trimmed and joined at the crossing.
struct TrimJoin {
a: (NodeId, usize),
b: (NodeId, usize),
joined: SubPath,
}
/// #5844: two open subpaths among `ids` that cross, where the scrub runs over the part of each
/// that overhangs the crossing, trimmed at the crossing and joined there with a corner. When
/// several pairs or ends qualify, the one trimming the least wins.
fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: f64) -> Result<Option<TrimJoin>> {
let mut open = vec![];
for &id in ids {
let (pd, _) = path_of(d, id)?;
open.extend(pd.subpaths.into_iter().enumerate().filter(|(_, sp)| !sp.closed && sp.anchors.len() >= 2).map(|(si, sp)| (id, si, sp)));
}
if open.len() > MAX_TRIM_SUBPATHS {
return Ok(None);
}
let scrub = PathData::single(SubPath::polyline(pts, false));
let mut best: Option<(f64, TrimJoin)> = None;
for (i, (ida, sa, a)) in open.iter().enumerate() {
for (idb, sb, b) in open.iter().skip(i + 1) {
let (pa, pb) = (PathData::single(a.clone()), PathData::single(b.clone()));
let Some(places) = pt::crossings(&[&pa, &pb], false) else { continue };
let (Some(on_a), Some(on_b)) = (places.first(), places.get(1)) else { continue };
let (oa, ob) = (overhangs(a, on_a), overhangs(b, on_b));
for x in oa.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) {
for y in ob.iter().filter(|o| scrubbed(&o.cut, pts, &scrub, tol)) {
let (Some(xa), Some(ya)) = (x.at(), y.at()) else { continue };
let trimmed = subpath_len(&x.cut) + subpath_len(&y.cut);
if xa.distance(ya) > 1e-2 || best.as_ref().is_some_and(|b| b.0 <= trimmed) {
continue;
}
// `x` ends at the crossing; `y`, reversed, starts there: one corner anchor.
let mut joined = x.kept.clone();
let mut rest = y.kept.clone();
rest.reverse();
let (Some(last), Some(first)) = (joined.anchors.last_mut(), rest.anchors.first()) else { continue };
*last =
Anchor { p: last.p, h_in: last.h_in, h_out: first.h_out + (last.p - first.p), kind: vectorcraft_geom::AnchorKind::Corner };
joined.anchors.extend(rest.anchors.into_iter().skip(1));
best = Some((trimmed, TrimJoin { a: (*ida, *sa), b: (*idb, *sb), joined }));
}
}
}
}
Ok(best.map(|(_, t)| t))
}
pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.joinScrub";
let pts = points_param(p, "points", C)?;
let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0);
let st = s.doc()?;
let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol));
// Paths that cross with their ends scrubbed are trimmed there and joined (#5844).
if let Some(TrimJoin { a: (ida, sa), b: (idb, sb), joined }) = trim_join(&st.doc, &targets, &pts, tol)? {
s.edit("Join", |d, sel| {
let missing = || crate::EngineError::Other("Join: a subpath went missing".into());
*path_mut(d, ida)?.subpaths.get_mut(sa).ok_or_else(missing)? = joined;
let pbm = path_mut(d, idb)?;
if sb >= pbm.subpaths.len() {
return Err(missing());
}
pbm.subpaths.remove(sb);
if ida != idb && pbm.is_empty() {
d.remove(idb)?;
}
sel.set([ida]);
Ok(())
})?;
return Ok(json!({ "id": ida.0 }));
}
// Open endpoints near the scrub, ordered along it: (order, id, subpath, at_start).
let poly = {
let mut bp = BezPath::new();
@@ -202,7 +314,7 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
};
let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied());
let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![];
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) {
for id in targets {
let (pd, _) = path_of(&st.doc, id)?;
for (si, sp) in pd.subpaths.iter().enumerate() {
if sp.closed || sp.anchors.len() < 2 {
+3 -2
View File
@@ -11,7 +11,7 @@ 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};
@@ -817,6 +817,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
}
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() || !s.doc()?.selection.segments.is_empty()) {
@@ -829,7 +830,7 @@ 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
+6 -4
View File
@@ -16,7 +16,7 @@ use vectorcraft_render::effects;
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
use super::expand::has_seeded;
use super::rasterfx;
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or};
/// The effect commands of the Effect menu and the Appearance panel.
pub fn specs() -> Vec<CommandSpec> {
@@ -116,12 +116,13 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us
// Whether `item` names an item in the stack it is a row of (else the edit is object-level there).
let anchor = roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a));
let anchor_level = anchor.map(|a| item.effects_item(&a.appearance, cmd)).transpose()?.flatten();
let aligned = aligned(p, cmd)?;
let mut out = Vec::with_capacity(roots.len());
for (id, item) in roots.iter().zip(per) {
let (Some(item), Some(n)) = (item, d.node(*id)) else { continue };
let at = item.effects_item(&n.appearance, cmd)?;
// An object-level effect this target shares with the first is where it is in this target.
let index = match (first.filter(|_| aligned(p)), at, anchor_level) {
let index = match (first.filter(|_| aligned), at, anchor_level) {
(Some(f), None, None) => SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1).unwrap_or(index),
_ => index,
};
@@ -236,6 +237,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let effect = effects::new_effect(id, &params).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?;
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
aligned(p, C)?;
if let Some(loose) = loose_for_pathfinder(s, p, id)? {
let gid = s.edit(&label, |d, sel| {
let gid = super::object::group_nodes(d, &loose)?;
@@ -375,10 +377,10 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
let to = index_param(p, "to", C)?;
let src = item_target_at(s, p, "fromItem", C)?;
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false);
let copy = switch_or(p, "copy", false, C)?;
let roots = appearance_targets(s, p)?;
// Where an aligned effect would go in each of several different stacks isn't one place.
if aligned(p) && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
}
// Where the effect landed in each object it moved in, in the order of `ids`.
+8 -5
View File
@@ -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)))
+1 -1
View File
@@ -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",
+45 -8
View File
@@ -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(())
})?;
+25 -3
View File
@@ -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);
}
+1 -1
View File
@@ -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
),
+2 -2
View File
@@ -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;
+2 -2
View File
@@ -16,7 +16,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node,
use vectorcraft_tools::PaintDefaults;
use super::gradient::unplaced;
use super::{CommandSpec, Result, Session, always, cmd};
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -216,7 +216,7 @@ impl Session {
}
fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
let on = p.get("on").and_then(Value::as_bool).unwrap_or(!s.prefs.new_art_basic);
let on = switch_or(p, "on", !s.prefs.new_art_basic, "appearance.setNewArtBasic")?;
s.prefs.new_art_basic = on;
Ok(json!({ "on": on }))
}
+8 -3
View File
@@ -117,8 +117,12 @@ fn apply_transform_moving_guides(
// A transform of ids that name no object, or an identity transform without a copy, moves
// nothing: the document and its undo history stay as they are, and Transform Again repeats it.
// With a copy, the reply lists the copies, and there are none.
// An edit normally preserves the tree positions already found here. Settling an active
// typing session can change the document before the edit closure runs, so look up again then.
let reindex = copy || (!s.previewing && crate::cmd::typing_in_progress(s));
let d = &s.doc()?.doc;
let none = d.index_paths(ids.iter().copied()).is_empty() && !has_guides;
let paths = d.index_paths(ids.iter().copied());
let none = paths.is_empty() && !has_guides;
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
if xf != Affine::IDENTITY {
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
@@ -154,8 +158,9 @@ fn apply_transform_moving_guides(
}
None => ids.clone(),
};
// Transforms don't move nodes in the tree, so the paths found up front stay right.
let paths = d.index_paths(targets.iter().copied());
// Transforms don't move nodes in the tree, so reuse the paths found for the no-copy
// case; copies and a settled typing session need paths from the edited document.
let paths = if reindex { d.index_paths(targets.iter().copied()) } else { paths };
for id in &targets {
if let Some(n) = paths.get(id).and_then(|p| d.node_mut_at(p))
&& !(objects && areas && resize_type_area(n, xf))
+1 -1
View File
@@ -1191,7 +1191,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
let with_guides = p.get("guides").and_then(Value::as_bool).unwrap_or(false);
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
let st = s.doc()?;
let sel = st.selection.anchors.clone();
let segments = st.selection.segments.clone();
+4 -3
View File
@@ -20,7 +20,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_plugins::{Budget, Kind, Plugin, effect, export, objects, registry};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
@@ -288,12 +288,13 @@ fn load_given(c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
/// `plugin.list` entry.
fn install(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "plugin.install";
let (replace, allow_heavy) = (switch_or(p, "replace", true, C)?, switch_or(p, "allowHeavy", false, C)?);
let (plugin, bytes) = load_given(C, p)?;
if !p.get("replace").and_then(Value::as_bool).unwrap_or(true) && registry::get(plugin.id()).is_some() {
if !replace && registry::get(plugin.id()).is_some() {
return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())));
}
// A heavy plug-in is installed once the user agrees: whoever installs it asks them first.
if plugin.manifest().budget == Budget::Heavy && !p.get("allowHeavy").and_then(Value::as_bool).unwrap_or(false) {
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
let (minutes, times) = vectorcraft_plugins::heavy_terms();
return Err(bad(
C,
+2 -2
View File
@@ -10,7 +10,7 @@ use vectorcraft_pdf::{TileOrigin, TilingPage};
use super::fileio::pdf::pdf_error;
use super::print::{settings, to_json};
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc, index};
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc, index, switch_or};
const SET: &str = "print.tiling.set";
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
fn show(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc_mut()?;
st.print_tiling = p.get("on").and_then(Value::as_bool).unwrap_or(!st.print_tiling);
st.print_tiling = switch_or(p, "on", !st.print_tiling, "view.printTiling")?;
Ok(json!({ "on": st.print_tiling }))
}
+4 -4
View File
@@ -14,7 +14,7 @@ use vectorcraft_geom::{Rect, shapes};
use super::{
CommandSpec, EngineError, NodeId, Result, Session, bad, bool_or, cmd, f64_or, f64_req, has_doc, has_selection, id_param, ids_param, index,
targets,
switch_or, targets,
};
/// The most slices one Divide Slices makes.
@@ -593,7 +593,7 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
}
fn clip_to_artboard(s: &mut Session, p: &Value) -> Result<Value> {
let on = p.get("on").and_then(Value::as_bool).unwrap_or(!s.doc()?.doc.slices_clip_to_artboard);
let on = switch_or(p, "on", !s.doc()?.doc.slices_clip_to_artboard, "object.slice.clipToArtboard")?;
if on != s.doc()?.doc.slices_clip_to_artboard {
s.edit("Clip to Artboard", |d, _| {
d.slices_clip_to_artboard = on;
@@ -604,7 +604,7 @@ fn clip_to_artboard(s: &mut Session, p: &Value) -> Result<Value> {
}
fn hide(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("hidden").and_then(Value::as_bool).unwrap_or(!s.menu.slices_hidden);
let v = switch_or(p, "hidden", !s.menu.slices_hidden, "view.slices.hide")?;
s.menu.slices_hidden = v;
if v {
deselect_in_every_document(s);
@@ -613,7 +613,7 @@ fn hide(s: &mut Session, p: &Value) -> Result<Value> {
}
fn lock(s: &mut Session, p: &Value) -> Result<Value> {
let v = p.get("locked").and_then(Value::as_bool).unwrap_or(!s.menu.slices_locked);
let v = switch_or(p, "locked", !s.menu.slices_locked, "view.slices.lock")?;
s.menu.slices_locked = v;
if v {
deselect_in_every_document(s);
+93
View File
@@ -24,6 +24,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
stroke_set
),
cmd!(
"stroke.weightUp",
"Stroke Weight Up",
[],
Some("Cmd+Alt+."),
"{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn → {objects}",
has_doc,
|s, p| stroke_step(s, p, true)
),
cmd!(
"stroke.weightDown",
"Stroke Weight Down",
[],
Some("Cmd+Alt+,"),
"{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}",
has_doc,
|s, p| stroke_step(s, p, false)
),
cmd!(
"stroke.setAdvanced",
"Stroke Options",
@@ -261,6 +279,61 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
}
/// `w` (pt) one step up or down in `unit` (Units › Stroke): a quarter unit up to one unit,
/// whole units above it, from 0.25 unit to 1000 pt. A weight between steps goes to the next step
/// in that direction (0.6 pt up is 0.75 pt); a weight below a quarter unit doesn't go down.
pub(crate) fn step_weight(w: f64, unit: Unit, up: bool) -> f64 {
const EPS: f64 = 1e-9;
let k = Some(unit.to_pt(1.0)).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0);
let w = if w.is_finite() { w.max(0.0) } else { 0.0 };
let v = w / k;
let next = if up {
if v < 1.0 - EPS { ((v * 4.0 + EPS).floor() + 1.0) / 4.0 } else { (v + EPS).floor() + 1.0 }
} else if v <= 1.0 + EPS {
(((v * 4.0 - EPS).ceil() - 1.0) / 4.0).max(0.25)
} else {
(v - EPS).ceil() - 1.0
};
let r = (next * k).min(1000.0);
// Never a step the wrong way: past 1000 pt up stays, below a quarter unit down stays.
if up { r.max(w) } else { r.min(w) }
}
/// `stroke.weightUp` / `stroke.weightDown`: each target stroke stepped from its own weight.
fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
let c = if up { "stroke.weightUp" } else { "stroke.weightDown" };
let unit = s.stroke_unit();
let item = item_target(s, p, c)?.of_kind(s, false);
let ids = item.targets(s, p)?;
if no_targets(&ids, p) {
let w = step_weight(s.paint.stroke_width, unit, up);
s.paint.stroke_width = w;
if let Some(st) = s.new_art_stroke_mut() {
st.width = w;
}
return Ok(json!({"objects": 0}));
}
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
edit_items(s, &ids, item, c, label, false, |n, index| {
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
// Character strokes are drawn in text space, scaled by the type's transform.
let k = Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0);
for r in t.runs.iter_mut().filter(|r| !matches!(r.style.stroke, Paint::None)) {
let change = StrokeChange { weight: Some(step_weight(r.style.stroke_width * k, unit, up)), ..StrokeChange::default() };
change.apply_char_scaled(&mut r.style, k);
}
return Ok(());
}
if let Some(st) = n.appearance.stroke_at_mut(index) {
st.width = step_weight(st.width, unit, up);
}
Ok(())
})?;
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
}
impl Session {
/// Units > Stroke (Preferences): the unit stroke weights and dash lengths show in.
pub fn stroke_unit(&self) -> Unit {
@@ -514,3 +587,23 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> {
let current = s.shown_stroke().map(|st| s.profile_entry(st.profile.as_ref()).map_or("custom", |e| e.id).to_string());
Ok(json!({ "profiles": profiles, "current": current }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn weight_steps_follow_units_and_stop_at_their_bounds() {
assert_eq!(step_weight(0.6, Unit::Points, true), 0.75);
assert_eq!(step_weight(0.6, Unit::Points, false), 0.5);
assert_eq!(step_weight(2.5, Unit::Points, true), 3.0);
assert_eq!(step_weight(2.5, Unit::Points, false), 2.0);
assert_eq!(step_weight(0.1, Unit::Points, false), 0.1, "below a quarter point a step down keeps it");
assert_eq!(step_weight(1000.0, Unit::Points, true), 1000.0);
assert_eq!(step_weight(2000.0, Unit::Points, true), 2000.0, "a step up never lowers a weight");
assert_eq!(step_weight(f64::NAN, Unit::Points, true), 0.25);
let mm = Unit::Millimeters.to_pt(1.0);
assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9);
assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9);
}
}
+22 -1
View File
@@ -211,7 +211,28 @@ impl<L: LibraryFile> Libraries<L> {
.user_dir()
.ok_or_else(|| bad(cmd, "no user library folder here (save with a path, or without one to get the data)"))?
.to_string();
let file = library_file_name(name, ext);
let mut file = library_file_name(name, ext);
// `COM¹` is saved as `COM¹-`, which can be another library's own name, and a library put
// under a numbered name holds a file another name can ask for: such a file is kept.
self.rescan();
let device = crate::file_access::is_device_name;
let id = format!("user/{file}").to_lowercase();
let fallback = |other: &str| library_file_name(other, ext).to_lowercase() != file.to_lowercase();
if self
.extra
.iter()
.any(|e| e.info.id.to_lowercase() == id && e.lib.name() != name && (device(name) || device(e.lib.name()) || fallback(e.lib.name())))
{
// Saved again, it goes back to the file it was given the first time.
let own = self.extra.iter().find(|e| e.info.category == "user" && e.lib.name() == name && extension(&e.info.id) == extension(&file));
file = match own.and_then(|e| e.info.id.strip_prefix("user/")) {
Some(own) => own.to_string(),
None => {
let mut taken: HashSet<String> = library_files(&dir, L::EXTS).iter().map(|p| file_name(p).to_lowercase()).collect();
free_name(&file, &mut taken)
}
};
}
let path = std::path::Path::new(&dir).join(&file).to_string_lossy().to_string();
// The app's own folder, under a name made safe: no root applies.
crate::file_access::unconfined(|| create_dir(&dir).and_then(|()| write_file(&path, bytes)))?;
+27 -4
View File
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Tab Stops",
["Window", "Tabs"],
None,
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches)",
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty",
has_selection,
set
),
@@ -44,15 +44,31 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
if !(0.0..=100_000.0).contains(&position) {
return Err(bad(C, "positions must be between 0 and 100000 pt"));
}
let align = match s.get("align").and_then(Value::as_str).unwrap_or("left").to_ascii_lowercase().as_str() {
let align = match s.get("align") {
None | Some(Value::Null) => "left",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(C, "`align` must be a string")),
};
let align = match align.to_ascii_lowercase().as_str() {
"left" => TabAlign::Left,
"center" | "centre" => TabAlign::Center,
"right" => TabAlign::Right,
"decimal" => TabAlign::Decimal,
other => return Err(bad(C, format!("unknown align `{other}`"))),
};
let leader = s.get("leader").and_then(Value::as_str).unwrap_or("").chars().take(8).collect();
let align_on = s.get("alignOn").and_then(Value::as_str).and_then(|a| a.chars().next()).unwrap_or('.');
let leader = match s.get("leader") {
None | Some(Value::Null) => "",
Some(Value::String(value)) => value.as_str(),
Some(_) => return Err(bad(C, "`leader` must be a string")),
}
.chars()
.take(8)
.collect();
let align_on = match s.get("alignOn") {
None | Some(Value::Null) => '.',
Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?,
Some(_) => return Err(bad(C, "`alignOn` must be a string")),
};
stops.push(TabStop { position, align, leader, align_on });
}
stops.sort_by(|a, b| a.position.total_cmp(&b.position));
@@ -116,6 +132,13 @@ mod tests {
use crate::Session;
#[test]
fn supplied_tab_stop_fields_require_strings() {
for stop in [json!({"position": 40, "align": false}), json!({"position": 40, "leader": 1}), json!({"position": 40, "alignOn": ""})] {
assert!(super::parse_stops(&json!({"stops": [stop.clone()]})).is_err(), "accepted {stop}");
}
}
#[test]
fn set_get_clear_tabs() {
let mut s = Session::new();
+1 -1
View File
@@ -1585,7 +1585,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
};
let kind = if on_path { TextKind::OnPath { path: path.clone(), start, end: None } } else { TextKind::Area { frame: path.clone() } };
let mut t = TextObject {
vertical: p.get("vertical").and_then(Value::as_bool).unwrap_or(false),
vertical: switch_or(p, "vertical", false, C)?,
kind,
xf: Affine::IDENTITY,
runs: vec![TextRun { text, style, inline: None }],
+40
View File
@@ -20,6 +20,46 @@ fn text(s: &Session, id: u64) -> String {
}
}
#[test]
fn empty_later_frames_keep_the_first_frames_edited_paragraph_style() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
let a =
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "First", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
let c = s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
assert_eq!([text(&s, a), text(&s, b), text(&s, c)], ["First", "", ""]);
s.execute("text.setFormat", &json!({"ids": [a], "hyphenate": true})).unwrap();
let hyphenates = |id| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.para_at(0).hyphenate,
_ => panic!("not text"),
};
assert_eq!([hyphenates(a), hyphenates(b), hyphenates(c)], [true, true, true]);
}
#[test]
fn a_restyled_empty_frame_keeps_its_style_before_an_unedited_empty_frame() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "First\n", "area": {"width": 150, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
let c = s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
assert_eq!([text(&s, a), text(&s, b), text(&s, c)], ["First\n", "", ""]);
s.execute("text.setFormat", &json!({"ids": [b], "hyphenate": true})).unwrap();
let hyphenates = |id, para| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.para_at(para).hyphenate,
_ => panic!("not text"),
};
// The empty paragraph after the break takes the style; the paragraph "First" keeps its own.
assert_eq!([hyphenates(a, 0), hyphenates(a, 1), hyphenates(b, 0), hyphenates(c, 0)], [false, true, true, true]);
}
#[test]
fn thread_flows_reflows_on_edit_and_survives_delete() {
let (mut s, a, b) = setup();
+1 -1
View File
@@ -856,7 +856,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Variable Library…",
["Window", "Variables"],
None,
"{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every variable of the document is deleted with its bindings and values, and every data set is deleted; then variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}",
"{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every data set is deleted, and every variable of the document is deleted with its bindings and values except a text variable the library also declares, which keeps its bindings; then the library's other variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}",
has_doc,
load_library
),
+16 -7
View File
@@ -258,24 +258,33 @@ fn parse_library(xml: &str, cmd: &str) -> Result<Library> {
/// Load Variable Library: replace the document's variables and data sets with a variable library's
/// ([`parse_library`]) in one undo step, or none when the document already holds what the library
/// gives. Every variable of the document is deleted with its bindings
/// and values, and every data set is deleted. The library's text variables are then defined,
/// unbound, and its data sets are added. The library's variables of other kinds are left out, named
/// in `skipped` and in a warning.
/// gives. Every data set is deleted, and every variable of the document is deleted with its
/// bindings and values, except a text variable the library also declares: it stays bound to its
/// objects, so the library's data sets change them (#4136; a template's bound variables take a
/// library of the same names:
/// <https://community.adobe.com/questions-652/illustrator-error-with-csv-files-812184>). The
/// library's other text variables are then defined, unbound, and its data sets are added. The
/// library's variables of other kinds are left out, named in `skipped` and in a warning.
pub(super) fn load_library(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "variable.loadLibrary";
let bytes = library_bytes(p, C)?;
let xml = std::str::from_utf8(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes)).map_err(|_| bad(C, "the variable library is not UTF-8"))?;
let lib = parse_library(xml, C)?;
let vars = &s.doc()?.doc.variables;
let deleted: Vec<String> = vars.variables.iter().map(|v| v.name.clone()).collect();
let kept = |v: &Variable| v.kind == VariableKind::Text && lib.text.contains(&v.name);
let deleted: Vec<String> = vars.variables.iter().filter(|v| !kept(v)).map(|v| v.name.clone()).collect();
let deleted_sets: Vec<String> = vars.datasets.iter().map(|d| d.name.clone()).collect();
let added: Vec<Variable> = lib
.text
.iter()
.filter(|n| !vars.variables.iter().any(|v| kept(v) && &v.name == *n))
.map(|n| Variable { name: n.clone(), kind: VariableKind::Text })
.collect();
// Lock Variables refuses New Variable and Delete Variable, so the load is refused when it would
// delete or define a variable.
if !deleted.is_empty() || !lib.text.is_empty() {
if !deleted.is_empty() || !added.is_empty() {
variables_unlocked(s).map_err(|why| EngineError::Disabled(C.into(), why))?;
}
let added: Vec<Variable> = lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect();
let names: Vec<String> = lib.datasets.iter().map(|d| d.name.clone()).collect();
// A load that leaves the variables and data sets as they were adds no undo step.
super::edit_variables(s, "Load Variable Library", |vars| {
+2 -2
View File
@@ -5,7 +5,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::SavedView;
use vectorcraft_geom::Point;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param, switch_or};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -64,7 +64,7 @@ fn caps_lock(s: &mut Session, p: &Value) -> Result<Value> {
fn transparency_grid(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc_mut()?;
st.transparency_grid = p.get("on").and_then(Value::as_bool).unwrap_or(!st.transparency_grid);
st.transparency_grid = switch_or(p, "on", !st.transparency_grid, "view.transparencyGrid")?;
Ok(json!({ "on": st.transparency_grid }))
}
+9 -6
View File
@@ -11,7 +11,7 @@
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - The result must lie inside one of the roots of its kind, compared by whole components
//! (`/work2` isn't inside `/work`), without regard to case on Windows.
//! (`/work2` isn't inside `/work`), exactly apart from the case of a Windows drive or share prefix.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
@@ -260,7 +260,7 @@ fn resolve(path: &str) -> Result<PathBuf, String> {
}
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case in a
/// Windows drive prefix only: resolved folder names have their real case, and a folder that differs
/// Windows drive or share prefix only: resolved folder names have their real case, and a folder that differs
/// in case alone may be another, on a case-sensitive Windows folder)?
fn inside(path: &Path, root: &Path) -> bool {
let mut path = path.components();
@@ -280,10 +280,11 @@ fn same_component(a: Component, b: Component) -> bool {
}
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension), which names no file.
pub(crate) fn is_device_name(component: &str) -> bool {
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
let numbered =
|prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"));
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
}
@@ -499,6 +500,8 @@ mod tests {
let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err());
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
assert!(e.contains("reserved device names"), "{e}");
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
let _ = std::fs::remove_dir_all(base);
}
@@ -527,10 +530,10 @@ mod tests {
#[test]
fn device_names() {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] {
assert!(is_device_name(d), "{d}");
}
for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x"] {
for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x", "COM⁴", "com¹0", "lpt¹x"] {
assert!(!is_device_name(f), "{f}");
}
}
+33
View File
@@ -981,3 +981,36 @@ fn removing_shared_and_unshared_rows_removes_only_the_shared_ones_elsewhere() {
assert!(node(&s, a).appearance.items.is_empty(), "a loses both");
assert_eq!(node(&s, b).appearance.items, fills_b, "b loses only its stroke, keeping both fills");
}
#[test]
fn invalid_aligned_flags_leave_the_appearance_alone() {
let mut s = session();
let id = rect(&mut s, 100.0);
run(&mut s, "effect.apply", json!({"effect": "distort.twist"}));
let before = node(&s, id);
let before_undo = s.doc().unwrap().history.undo.len();
for (command, params) in [
("appearance.setItem", json!({"index": 0, "opacity": 50, "aligned": "true"})),
("appearance.removeItem", json!({"index": 0, "aligned": 1})),
("appearance.duplicateItem", json!({"index": 0, "aligned": "false"})),
("appearance.moveItem", json!({"from": 0, "to": 1, "aligned": 0})),
("stroke.set", json!({"item": 1, "weight": 5, "aligned": "true"})),
("stroke.set", json!({"weight": 5, "aligned": "true"})),
("transparency.set", json!({"item": 0, "opacity": 50, "aligned": "true"})),
("effect.apply", json!({"effect": "distort.roughen", "item": 0, "aligned": "true"})),
("effect.remove", json!({"index": 0, "aligned": "true"})),
] {
assert!(s.execute(command, &params).is_err(), "{command} accepted {params}");
assert_eq!(node(&s, id), before, "{command} changed the object");
assert_eq!(s.doc().unwrap().history.undo.len(), before_undo, "{command} recorded an undo step");
}
// Null, as for every command, is the same as leaving `aligned` out.
run(&mut s, "appearance.removeItem", json!({"index": 0, "aligned": null}));
assert_eq!(node(&s, id).appearance.items.len(), before.appearance.items.len() - 1);
// A Pathfinder effect on loose objects groups them first: the flag is checked before that.
let other = rect(&mut s, 250.0);
run(&mut s, "select.set", json!({"ids": [id.0, other.0]}));
let before_undo = s.doc().unwrap().history.undo.len();
assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.add", "aligned": "true"})).is_err());
assert_eq!(s.doc().unwrap().history.undo.len(), before_undo, "grouped the objects");
}
+29
View File
@@ -66,6 +66,35 @@ fn a_spine_point_added_and_moved_bends_the_blend() {
assert!(center(&steps(&s, g)[1]).distance(Point::new(55.0, 5.0)) < 1e-6);
}
/// #5285: `with` moves other spine points by as much as the one dragged, and the key objects on
/// them along, in one undo step; it can't go with a handle or name a point the spine lacks.
#[test]
fn spine_points_move_together() {
let mut s = session();
let (a, b, g) = blend(&mut s);
s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap();
let before = spec(&s, g);
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [9]})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2], "handle": "in"})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [], "handle": "in"})).is_err());
assert!(s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": "2"})).is_err());
assert_eq!(spec(&s, g), before, "refused requests change nothing");
s.execute("object.blend.spine.moveAnchor", &json!({"anchor": 1, "x": 55, "y": 45, "with": [2, 1]})).unwrap();
let sp = spec(&s, g).spine.unwrap();
let pts: Vec<Point> = sp.subpaths[0].anchors.iter().map(|x| x.p).collect();
let want = [Point::new(5.0, 5.0), Point::new(55.0, 45.0), Point::new(105.0, 45.0)];
assert!(pts.len() == 3 && pts.iter().zip(want).all(|(p, w)| p.distance(w) < 1e-9), "{pts:?}");
let keys = match node(&s, g).kind {
NodeKind::Blend { children, .. } => children,
_ => panic!("not a blend"),
};
let at = |id: NodeId| keys.iter().find(|k| k.id == id).map(|k| center(k)).unwrap();
assert!(at(b).distance(Point::new(105.0, 45.0)) < 1e-9, "the key on the point went along: {:?}", at(b));
assert!(at(a).distance(Point::new(5.0, 5.0)) < 1e-9, "the other stayed: {:?}", at(a));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, g), before, "one undo step");
}
/// #2544: an Anchor Point drag on a blend spine must create two symmetric
/// handles, not bend the adjacent segment and leave one handle behind.
#[test]
+91
View File
@@ -850,3 +850,94 @@ fn artwork_drop_uses_the_current_layer_even_when_paste_remembers_hidden_or_locke
assert!(doc(&s).paste_remembers_layers, "the preference still applies to ordinary Paste");
}
}
/// Two touching rectangles made into 9-slice symbol `Audit`, its instance scaled 150% × 75% and
/// copied (#5902).
fn copied_nine_slice_instance(s: &mut Session) -> Document {
let red = rect(s, 30.0, 30.0, 80.0, 60.0);
s.execute("paint.setFill", &json!({"ids": [red.0], "color": "#ff0000"})).unwrap();
let blue = rect(s, 110.0, 90.0, 40.0, 30.0);
s.execute("paint.setFill", &json!({"ids": [blue.0], "color": "#0000ff"})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Audit", "nineSlice": true, "registration": 0, "exportType": "graphic"})).unwrap();
s.execute("object.scale", &json!({"sx": 150, "sy": 75})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
doc(s).clone()
}
/// The symbol options pasted symbol `to` should have: those of `from` in `src`.
fn assert_same_symbol_options(src: &Document, from: &str, d: &Document, to: &str) {
assert!(src.symbol_nine_slice(from).is_some());
assert_eq!(d.symbol_nine_slice(to), src.symbol_nine_slice(from));
assert_eq!(d.symbol_registration(to), src.symbol_registration(from));
assert_eq!(d.symbol_export_type(to), src.symbol_export_type(from));
assert_eq!(d.symbol_natural_xf(to), src.symbol_natural_xf(from));
}
#[test]
fn a_nine_slice_symbol_pasted_into_another_document_keeps_its_options_and_look() {
let mut s = session();
let src = copied_nine_slice_instance(&mut s);
let before = render(&s);
new_doc(&mut s);
s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert_same_symbol_options(&src, "Audit", doc(&s), "Audit");
assert!(before == render(&s), "the pasted instance draws as in the source");
// Pasting again uses the symbol the first paste added.
let v = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert_eq!(v["added"], 0, "{v}");
}
#[test]
fn a_renamed_nine_slice_symbol_keeps_its_options_under_the_new_name() {
let mut s = session();
let src = copied_nine_slice_instance(&mut s);
new_doc(&mut s);
let other = ellipse(&mut s);
sel(&mut s, &[other]);
s.execute("symbol.new", &json!({"name": "Audit"})).unwrap();
let own = doc(&s).clone();
let v = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(renamed(&v).contains(&("symbol".into(), "Audit".into(), "Audit 2".into())), "{v}");
assert_same_symbol_options(&src, "Audit", doc(&s), "Audit 2");
// The document's own symbol keeps its options.
assert_eq!(doc(&s).symbol_nine_slice("Audit"), None);
assert_eq!(doc(&s).symbol_natural_xf("Audit"), own.symbol_natural_xf("Audit"));
}
#[test]
fn a_same_named_symbol_with_other_options_is_not_reused() {
let mut s = session();
let src = copied_nine_slice_instance(&mut s);
new_doc(&mut s);
s.execute("edit.pasteInPlace", &json!({})).unwrap();
// The document's `Audit` has the same art but 9-slice scaling off now.
s.execute("symbol.options", &json!({"name": "Audit", "nineSlice": false})).unwrap();
let v = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(renamed(&v).contains(&("symbol".into(), "Audit".into(), "Audit 2".into())), "{v}");
assert_same_symbol_options(&src, "Audit", doc(&s), "Audit 2");
assert_eq!(doc(&s).symbol_nine_slice("Audit"), None, "the document's own symbol keeps its options");
}
#[test]
fn a_symbol_without_a_recorded_natural_size_is_pasted_without_one() {
let mut s = session();
let r = rect(&mut s, 30.0, 30.0, 80.0, 60.0);
sel(&mut s, &[r]);
s.execute("symbol.new", &json!({"name": "Plain"})).unwrap();
s.edit("Forget size", |d, _| {
if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) {
m.remove("Plain");
}
Ok(())
})
.unwrap();
assert_eq!(doc(&s).unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get("Plain")), None);
s.execute("edit.copy", &json!({})).unwrap();
let before = render(&s);
new_doc(&mut s);
s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(doc(&s).symbols.iter().any(|x| x.name == "Plain"));
assert_eq!(doc(&s).unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get("Plain")), None, "no size is made up for it");
assert!(before == render(&s), "the pasted instance draws as in the source");
}
+9 -1
View File
@@ -370,13 +370,21 @@ fn colorized_gray_image_is_flattened_for_pdf_x_1a() {
assert!(!String::from_utf8_lossy(&bytes).contains("/SMask"), "PDF/X-1a has no soft mask");
}
/// A colorized image with a gray pixel is left out; one of black and white pixels is written as an
/// image mask and kept.
#[test]
fn colorized_gray_image_is_omitted_from_legacy_ai_when_requested() {
let mut s = session();
let mid = png(image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 128]).unwrap()));
let id = image(&mut s, "mid", mid);
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
let out = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "omit"})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
let mut s = session();
let id = image(&mut s, "gray", gray(false));
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
let out = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": "omit"})).unwrap();
assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
assert!(!out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("are left out")), "{}", out["warnings"]);
}
#[test]
+84
View File
@@ -1351,6 +1351,54 @@ fn join_tool_joins_endpoints_near_the_scrub_ends() {
assert_eq!(p.subpaths[0].anchors[1].p, Point::new(202.5, 100.0));
}
/// #5844: scrubbing over the ends of two crossing open paths that run past the crossing trims
/// those ends and joins the paths there with a corner, rather than drawing a segment between the
/// ends.
#[test]
fn join_tool_trims_crossing_paths_and_joins_them_at_the_crossing() {
let mut s = session();
let a = line(&mut s, 100.0, 300.0, 400.0, 300.0);
let b = line(&mut s, 300.0, 100.0, 300.0, 380.0);
s.execute("select.all", &json!({})).unwrap();
drag(&mut s, "join", &[(380.0, 285.0), (285.0, 365.0)], Mods::default());
let ps = paths(&s);
assert_eq!(ps.len(), 1, "one path is left: {ps:?}");
let (id, p) = &ps[0];
assert!(*id == a || *id == b);
assert_eq!(p.subpaths.len(), 1);
let mut got: Vec<Point> = p.subpaths[0].anchors.iter().map(|x| x.p).collect();
if got.first() != Some(&Point::new(100.0, 300.0)) {
got.reverse();
}
let near = |q: Point, r: Point| q.distance(r) < 1e-6;
assert_eq!(got.len(), 3, "{got:?}");
assert!(near(got[0], Point::new(100.0, 300.0)) && near(got[1], Point::new(300.0, 300.0)) && near(got[2], Point::new(300.0, 100.0)), "{got:?}");
assert!(!p.subpaths[0].closed);
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
}
/// #5844: a curve with a hook past a straight line (the report's case) is trimmed at the crossing
/// and joined to the line's kept part; nothing of either overhang is left.
#[test]
fn join_tool_trims_a_curve_hooking_past_a_line() {
let mut s = session();
line(&mut s, 0.0, 300.0, 480.0, 300.0);
s.execute("path.create", &json!({"anchors": [{"x": 260, "y": 0, "out": [290, 150]}, {"x": 378, "y": 368, "in": [310, 380]}]})).unwrap();
s.execute("select.all", &json!({})).unwrap();
drag(&mut s, "join", &[(470.0, 280.0), (420.0, 330.0), (370.0, 380.0)], Mods::default());
let ps = paths(&s);
assert_eq!(ps.len(), 1, "{ps:?}");
let sp = &ps[0].1.subpaths[0];
assert!(!sp.closed);
// Every anchor is on the kept sides: the line left of the crossing, the curve above it.
let joint = sp.anchors.iter().find(|x| (x.p.y - 300.0).abs() < 1e-6 && x.p.x > 100.0).expect("an anchor at the crossing");
for x in &sp.anchors {
assert!(x.p.y <= 300.0 + 1e-6 && x.p.x <= joint.p.x + 1e-6, "{x:?} is past the crossing at {joint:?}");
}
let bounds = ps[0].1.bounds().unwrap();
assert!(bounds.y1 <= 300.0 + 1e-6 && bounds.x1 <= joint.p.x + 1e-6, "{bounds:?}");
}
#[test]
fn line_family_tools_draw_and_click_asks_dialog() {
let mut s = session();
@@ -2717,6 +2765,42 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() {
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap();
}
#[test]
fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() {
// #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor,
// and its bounding box's handles scale the object; Direct Selection is back on the release.
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
let v = view();
let mut s = session();
let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]);
let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
s.select_tool("directSelection", v).unwrap();
assert_eq!(s.lent_tool_id(&none), None);
assert_eq!(s.lent_tool_id(&cmd), Some("selection"));
// The path selected whole: the bottom-right handle scales it.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
assert_eq!(s.cursor(Point::new(200.0, 200.0), cmd, v), vectorcraft_tools::Cursor::ResizeNwSe);
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
for at in [250.0, 300.0] {
s.pointer(&PointerEvent::new(PointerKind::Drag, at, at).with_mods(cmd), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 300.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "{b:?}");
// An anchor selected: a Cmd drag inside moves the whole path and the anchor stays selected.
gesture(&mut s, &[(300.0, 300.0)], none);
let picked = s.doc().unwrap().selection.anchors.clone();
assert!(!picked.is_empty(), "Direct Selection picked the anchor");
let before: Vec<_> = path(&s, id).subpaths[0].anchors.iter().map(|a| a.p).collect();
gesture(&mut s, &[(150.0, 150.0), (160.0, 160.0), (170.0, 150.0)], cmd);
let after: Vec<_> = path(&s, id).subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(after, before.iter().map(|p| *p + kurbo::Vec2::new(20.0, 0.0)).collect::<Vec<_>>());
assert_eq!(s.doc().unwrap().selection.anchors, picked, "the anchor is still selected");
assert_eq!(s.tool_id(), "directSelection");
}
#[test]
fn the_pen_drops_the_new_path_asterisk_once_a_path_is_started() {
// The Pen's asterisk means a click starts a new path: it shows until the first anchor is
+23
View File
@@ -70,6 +70,29 @@ fn effects_move_and_copy_between_the_object_and_its_items() {
assert!(s.execute("effect.move", &json!({"from": 0, "fromItem": 1, "to": 0, "toItem": 7})).is_err());
}
#[test]
fn invalid_effect_move_flags_leave_the_effects_alone() {
let (mut s, id) = session_with_rect();
run(&mut s, "effect.apply", json!({"effect": "distort.twist"}));
let before_undo = s.doc().unwrap().history.undo.len();
let to_fill = json!({"from": 0, "fromItem": null, "to": 0, "toItem": 0});
for (key, value) in [("copy", json!("true")), ("copy", json!(1)), ("aligned", json!("false"))] {
let mut params = to_fill.clone();
params[key] = value;
assert!(s.execute("effect.move", &params).is_err(), "accepted {params}");
assert_eq!(fx(&s, id, None), ["distort.twist"], "moved the effect for {params}");
assert!(fx(&s, id, Some(0)).is_empty(), "copied the effect for {params}");
assert_eq!(s.doc().unwrap().history.undo.len(), before_undo, "recorded undo for {params}");
}
// Null, as for every command, is the same as leaving the flag out: a move.
let mut params = to_fill;
params["copy"] = Value::Null;
params["aligned"] = Value::Null;
run(&mut s, "effect.move", params);
assert!(fx(&s, id, None).is_empty());
assert_eq!(fx(&s, id, Some(0)), ["distort.twist"]);
}
/// `effect.duplicate` copies a fill's effect right after it.
#[test]
fn duplicate_selected_works_for_effects() {
+22
View File
@@ -82,6 +82,28 @@ fn clicking_an_overlap_brings_the_object_below_to_the_front_there_only() {
assert_eq!(hit(&s, 50.0, 70.0), Some(b));
}
/// #5337: where A is brought over B, the edges of B that cross A leave no blue hairline in A.
#[test]
fn the_object_brought_over_shows_no_seam_of_the_one_below() {
let mut s = session();
intertwined(&mut s);
arrange(&mut s, json!({"at": [50, 30]}));
let zoom = 8.0;
let r = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 800, 800, Affine::scale(zoom), &Default::default());
let mut worst = 0;
for y in 160..360 {
for x in 320..480 {
let (px, py) = ((x as f64 + 0.5) / zoom, (y as f64 + 0.5) / zoom);
// Well inside ring A's 8 pt stroke (radius 21 to 29), A covers every pixel.
let d = ((px - 35.0).powi(2) + (py - 50.0).powi(2)).sqrt();
if (22.0..28.0).contains(&d) {
worst = worst.max(r.pixel(x, y)[2]);
}
}
}
assert!(worst < 8, "blue shows through ring A at the top crossing (blue {worst})");
}
#[test]
fn clicking_the_same_overlap_again_swaps_back() {
let mut s = session();
+96 -1
View File
@@ -447,6 +447,100 @@ fn transparent_images_can_be_left_out_and_opacity_makes_one_transparent() {
assert_eq!(v["options"]["transparentImages"]["value"], "flatten", "{v}");
}
/// A red square (10–50 × 10–50) half under a 4 × 2 black-and-white image (30–70 × 10–30) that the
/// spot color `Ink` colorizes. Returns the session and the image's pixels.
fn colorized_bitmap_over_square() -> (Session, Vec<u8>) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let gray = vec![0, 255, 0, 255, 255, 0, 255, 0];
let mut bytes = vec![];
image::GrayImage::from_raw(4, 2, gray.clone()).unwrap().write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let p = json!({"name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 40, 20]});
s.execute("file.place", &p).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
(s, gray)
}
/// An image's pixels' coverage and its colorize paint.
type Colorized = (Option<(u32, u32, Vec<u8>)>, Option<vectorcraft_color::Paint>);
/// The colorized image of each image node of `d`, with its pixels' coverage.
fn colorized(d: &vectorcraft_doc::Document) -> Vec<Colorized> {
let mut out = vec![];
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
out.push((d.image_blob(im).and_then(vectorcraft_doc::ImageBlob::coverage), n.extras().colorize.as_deref().cloned()));
}
});
out
}
/// A colorized image of black and white pixels is neither flattened nor left out: it is written as
/// a 1-bit image mask in its color, with either setting of `transparentImages`, and opens again
/// colorized with that color, its white pixels clear over the square, and the square as it was.
#[test]
fn a_colorized_black_and_white_image_is_written_as_an_image_mask() {
let (mut s, gray) = colorized_bitmap_over_square();
let before = colorized(&s.doc().unwrap().doc);
let want: Vec<u8> = gray.iter().map(|v| 255 - v).collect();
assert!(matches!(before.as_slice(), [(Some((4, 2, c)), Some(_))] if *c == want), "{before:?}");
for mode in ["flatten", "omit"] {
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": mode})).unwrap();
assert!(!warnings(&r).iter().any(|w| w.contains("transparent images") || w.contains("flattened")), "{mode}: {r}");
let mut t = Session::new();
t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let d = &t.doc().unwrap().doc;
let after = colorized(d);
assert_eq!(after.len(), 1, "{mode}: {after:?}");
assert_eq!(after[0].0, before[0].0, "{mode}");
let (Some(a), Some(b)) = (&after[0].1, &before[0].1) else { panic!("{mode}: {after:?}") };
let rgb = |p: &vectorcraft_color::Paint| p.color().map(|c| c.to_rgb()).unwrap();
assert!(rgb(a).iter().zip(rgb(b)).all(|(x, y)| (x - y).abs() < 0.01), "{mode}: {a:?} {b:?}");
assert_eq!(images(d), (1, 0), "{mode}");
// The first row draws as before: black (the color) and white (clear) over the square, then
// black and white (clear) over the page.
let src = &s.doc().unwrap().doc;
for x in [35.0, 45.0, 55.0, 65.0] {
let (now, was) = (colour_at(d, x, 15.0), colour_at(src, x, 15.0));
assert!(now.iter().zip(was).all(|(a, b)| a.abs_diff(b) <= 3), "{mode} at {x}: {now:?} {was:?}");
}
assert_ne!(colour_at(src, 35.0, 15.0), colour_at(src, 45.0, 15.0), "{mode}");
assert_ne!(colour_at(src, 55.0, 15.0), colour_at(src, 65.0, 15.0), "{mode}");
}
}
/// A colorized image of black and clear pixels is written as an image mask too, its clear pixels
/// clear, instead of being flattened or left out for its see-through pixels.
#[test]
fn a_colorized_image_of_black_and_clear_pixels_is_written_as_an_image_mask() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
let mut bytes = vec![];
image::GrayAlphaImage::from_raw(2, 1, vec![0, 255, 0, 0])
.unwrap()
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
let p = json!({"name": "c.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "rect": [30, 10, 20, 10]});
s.execute("file.place", &p).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
let before = colorized(&s.doc().unwrap().doc);
assert!(matches!(before.as_slice(), [(Some((2, 1, c)), Some(_))] if *c == [255, 0]), "{before:?}");
for mode in ["flatten", "omit"] {
let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7", "transparentImages": mode})).unwrap();
assert!(!warnings(&r).iter().any(|w| w.contains("transparent images") || w.contains("flattened")), "{mode}: {r}");
let mut t = Session::new();
t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap();
let after = colorized(&t.doc().unwrap().doc);
assert_eq!(after.len(), 1, "{mode}: {after:?}");
assert_eq!(after[0].0, before[0].0, "{mode}");
assert!(after[0].1.is_some(), "{mode}: {after:?}");
}
}
/// #2692's file, an image clipped to a circle inside a circle's stroke, and #2830's, an image with
/// see-through pixels (which the save flattens into an image inside a clipping group), each with
/// an orange square on the next layer.
@@ -639,7 +733,8 @@ fn colorized_grayscale_image_pattern_keeps_its_colors_in_legacy_ai() {
for (a, b) in before.iter().zip(&after) {
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 3), "before {before:?} after {after:?}");
}
assert!(saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}");
// The tile's pixels are black or white: its images are written as image masks, not flattened.
assert!(!saved_warnings.iter().any(|w| w.contains("flattened with the art under them")), "{saved_warnings:?}");
}
/// #3666: a pattern fill whose tile is an image, under opacity, is flattened with the art under it
+20
View File
@@ -69,3 +69,23 @@ fn view_opacity_mask_shows_its_luminance_and_hides_the_artwork() {
assert!(s.execute("transparency.viewOpacityMask", &json!({"on": true, "id": other.0})).is_err());
assert!(s.doc().unwrap().mask_view.is_none());
}
#[test]
fn invalid_view_opacity_mask_parameters_leave_the_view_unchanged() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
let obj = rect(&mut s, 0.0, 200.0, "#ff0000");
let m = rect(&mut s, 0.0, 100.0, "#00ff00");
s.execute("select.set", &json!({"ids": [obj.0, m.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let undo = s.doc().unwrap().history.undo.len();
for params in [json!({"on": "true"}), json!({"on": 1})] {
assert!(s.execute("transparency.viewOpacityMask", &params).is_err(), "accepted {params}");
let st = s.doc().unwrap();
assert!(st.doc.mask_edit.is_none() && st.shown_mask().is_none(), "showed the mask for {params}");
assert_eq!(st.history.undo.len(), undo, "recorded undo for {params}");
}
// Left out, or null as for every command, it toggles.
assert_eq!(s.execute("transparency.viewOpacityMask", &json!(null)).unwrap(), json!({"on": true, "id": obj.0}));
assert_eq!(s.execute("transparency.viewOpacityMask", &json!({"on": null})).unwrap(), json!({"on": false, "id": obj.0}));
}
+41
View File
@@ -3539,6 +3539,23 @@ fn ruler_guides_and_lock() {
assert!(s.execute("guide.remove", &json!({"index": 0})).is_err());
}
#[test]
fn invalid_guide_lock_parameters_keep_guides_selected() {
let mut s = session();
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
let before_undo = s.doc().unwrap().history.undo.len();
for params in [json!({"locked": "false"}), json!({"locked": 1})] {
assert!(s.execute("view.guides.lock", &params).is_err(), "accepted {params}");
assert!(!s.guides_locked(), "locked guides for {params}");
assert_eq!(s.doc().unwrap().selection.guides, vec![0], "cleared selection for {params}");
assert_eq!(s.doc().unwrap().history.undo.len(), before_undo, "recorded undo for {params}");
}
// Left out, or null as for every command, it toggles.
assert_eq!(s.execute("view.guides.lock", &json!(null)).unwrap(), json!({"locked": true}));
assert_eq!(s.execute("view.guides.lock", &json!({"locked": null})).unwrap(), json!({"locked": false}));
}
/// #1534: Lock Guides locks the paths made into guides too: they can't be selected (so neither
/// moved, reshaped nor deleted), by a click, a marquee or Select All, and locking lets them go.
#[test]
@@ -3810,6 +3827,30 @@ fn guides_and_art_are_shift_selected_together() {
assert_eq!(guides(&s).len(), 2);
}
#[test]
fn invalid_clear_guides_parameters_delete_nothing() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 40.0, 20.0);
s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap();
sel(&mut s, &[a]);
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
let n = undo_len(&s);
for params in [json!({"ids": [a.0], "guides": "true"}), json!({"guides": 1})] {
assert!(s.execute("edit.clear", &params).is_err(), "accepted {params}");
assert!(s.doc().unwrap().doc.node(a).is_some(), "deleted the art for {params}");
assert_eq!((guides(&s).len(), undo_len(&s)), (1, n), "changed the document for {params}");
}
// Direct-selected anchors take the same check.
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
assert!(s.execute("edit.clear", &json!({"guides": "false"})).is_err());
assert!(!s.doc().unwrap().selection.anchors.is_empty());
assert_eq!(undo_len(&s), n);
// Null, as for every command, is the same as leaving `guides` out: with ids, the guides stay.
s.execute("edit.clear", &json!({"ids": [a.0], "guides": null})).unwrap();
assert!(s.doc().unwrap().doc.node(a).is_none());
assert_eq!(guides(&s).len(), 1);
}
/// When ruler guides and art are selected together, moving the art moves the guides as well;
/// copy leaves both in place and moves the copies; single undo reverts both.
#[test]
+14
View File
@@ -29,6 +29,20 @@ fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn invalid_new_art_basic_parameters_keep_the_preference_unchanged() {
let mut s = session();
let undo = undo_len(&s);
for params in [json!({"on": "false"}), json!({"on": 1})] {
assert!(s.execute("appearance.setNewArtBasic", &params).is_err(), "accepted {params}");
assert!(s.prefs.new_art_basic, "changed the preference for {params}");
assert_eq!(undo_len(&s), undo, "recorded undo for {params}");
}
// Left out, or null as for every command, it toggles.
assert_eq!(s.execute("appearance.setNewArtBasic", &json!(null)).unwrap(), json!({"on": false}));
assert_eq!(s.execute("appearance.setNewArtBasic", &json!({"on": null})).unwrap(), json!({"on": true}));
}
#[test]
fn stroke_options_set_with_nothing_selected_carry_to_the_next_object() {
let mut s = session();
+1 -1
View File
@@ -126,7 +126,7 @@ fn effect_params_are_the_effects_own() {
check_effect_params("effect.apply", e.id, &e.defaults).unwrap_or_else(|why| panic!("{}'s defaults: {why}", e.id));
}
let apply = |effect: &str, params| json!({"effect": effect, "params": params});
assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius");
assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius, linear");
assert_eq!(
refusal("appearance.addEffect", apply("stylize.dropShadow", json!({"opacty": 50}))),
"unknown parameter `opacty`; did you mean `opacity`?"
+30
View File
@@ -493,6 +493,36 @@ fn a_heavy_filter_installs_once_the_user_agrees() {
assert!(install(&mut s, DESATURATE).get("budget").is_none());
}
#[test]
fn invalid_install_flags_are_refused() {
let mut s = session();
let id = "test.engine.heavy.flags";
let data = vectorcraft_format::base64_encode(&heavy(id, 1));
for allow in [json!("true"), json!(1)] {
let e = s.execute("plugin.install", &json!({"dataBase64": data, "allowHeavy": allow})).unwrap_err().to_string();
assert!(e.contains("`allowHeavy` must be true or false"), "allowHeavy {allow}: {e}");
assert!(vectorcraft_plugins::registry::get(id).is_none(), "installed with allowHeavy {allow}");
}
// Null, as for every command, is the same as leaving the flag out.
let e = s.execute("plugin.install", &json!({"dataBase64": data, "allowHeavy": null})).unwrap_err().to_string();
assert!(e.contains("heavy budget"), "{e}");
run(&mut s, "plugin.install", json!({"dataBase64": data, "allowHeavy": true}));
for replace in [json!("false"), json!(0)] {
let e = s.execute("plugin.install", &json!({"dataBase64": data, "allowHeavy": true, "replace": replace})).unwrap_err().to_string();
assert!(e.contains("`replace` must be true or false"), "replace {replace}: {e}");
}
run(&mut s, "plugin.install", json!({"dataBase64": data, "allowHeavy": true, "replace": null}));
assert!(vectorcraft_plugins::registry::get(id).is_some());
// A plug-in with the usual budget is refused too.
let light = "test.engine.light.flags";
let manifest = format!(r#"{{"id":"{light}","name":"Test {light}","version":"1","kind":"filter"}}"#);
let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]});
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::spinning(&manifest, 1, &output.to_string())).unwrap());
let e = s.execute("plugin.install", &json!({"dataBase64": data, "allowHeavy": "false"})).unwrap_err().to_string();
assert!(e.contains("`allowHeavy` must be true or false"), "{e}");
assert!(vectorcraft_plugins::registry::get(light).is_none());
}
/// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next
/// start without asking, with its budget.
#[test]
+15
View File
@@ -182,3 +182,18 @@ fn settings_saved_before_the_tile_origin_still_load() {
assert_eq!((set["copies"].clone(), set["tileOrigin"]["placed"].clone()), (json!(2), json!(false)));
assert_eq!(tiling(&mut s, json!({}))["pages"].as_array().unwrap().len(), 1);
}
#[test]
fn invalid_print_tiling_parameters_leave_the_view_unchanged() {
let mut s = session();
let undo = s.doc().unwrap().history.undo.len();
for params in [json!({"on": "true"}), json!({"on": 1})] {
assert!(s.execute("view.printTiling", &params).is_err(), "accepted {params}");
let st = s.doc().unwrap();
assert!(!st.print_tiling, "showed the tiling for {params}");
assert_eq!(st.history.undo.len(), undo, "recorded undo for {params}");
}
// Left out, or null as for every command, it toggles.
assert_eq!(s.execute("view.printTiling", &json!(null)).unwrap(), json!({"on": true}));
assert_eq!(s.execute("view.printTiling", &json!({"on": null})).unwrap(), json!({"on": false}));
}
+24
View File
@@ -593,3 +593,27 @@ fn slice_commands_check_their_params() {
assert!(s.doc().unwrap().doc.node(NodeId(a)).is_some(), "deleting an object slice keeps its object");
assert_eq!(run(&mut s, "object.slice.select", json!({}))["selected"], json!([]));
}
#[test]
fn invalid_slice_toggle_flags_do_not_change_state_or_selection() {
for (command, params) in [
("object.slice.clipToArtboard", json!({"on": "false"})),
("view.slices.hide", json!({"hidden": 0})),
("view.slices.lock", json!({"locked": 1})),
] {
let mut s = session();
let id = user_slice(&mut s, [10.0, 10.0, 20.0, 20.0]);
run(&mut s, "select.object.slices", json!({}));
let before_undo = s.doc().unwrap().history.undo.len();
assert!(s.execute(command, &params).is_err(), "{command} accepted {params}");
assert!(s.doc().unwrap().doc.slices_clip_to_artboard, "{command} changed the document");
assert!(!s.slices_hidden(), "{command} hid slices");
assert!(!s.slices_locked(), "{command} locked slices");
assert_eq!(s.doc().unwrap().selection.slices, vec![NodeId(id)], "{command} cleared the selection");
assert_eq!(s.doc().unwrap().history.undo.len(), before_undo, "{command} recorded an undo step");
}
// Left out, or null as for every command, the flag toggles.
let mut s = session();
assert_eq!(run(&mut s, "view.slices.hide", Value::Null)["hidden"], true);
assert_eq!(run(&mut s, "view.slices.hide", json!({"hidden": null}))["hidden"], false);
}
+46
View File
@@ -111,3 +111,49 @@ fn inspect_reports_stroke_options() {
let text = doc["layers"][0]["children"].as_array().unwrap().iter().find(|c| c["kind"] == "Text" || c.get("text").is_some()).unwrap().clone();
assert_eq!(text["strokeOptions"]["join"], "round", "{text}");
}
/// Stroke Weight Up and Down (Cmd/Ctrl+Alt+. and ,) step each selected stroke from its own
/// weight, a quarter point at a time below 1 pt and whole points above, in one undo step each.
#[test]
fn stroke_weight_up_and_down_step_each_selected_stroke() {
let mut s = session();
let (a, b, bare) = (rect(&mut s, 10.0), rect(&mut s, 60.0), rect(&mut s, 110.0));
select(&mut s, &[a]);
run(&mut s, "stroke.set", json!({"weight": 0.6}));
select(&mut s, &[b]);
run(&mut s, "stroke.set", json!({"weight": 3}));
select(&mut s, &[bare]);
run(&mut s, "paint.setStroke", json!({"none": true}));
let has_stroke = |s: &Session| {
s.doc().unwrap().doc.node(bare).unwrap().appearance.stroke().is_some_and(|st| !matches!(st.paint, vectorcraft_color::Paint::None))
};
let bare_before = has_stroke(&s);
let w = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
select(&mut s, &[a, b, bare]);
run(&mut s, "stroke.weightUp", json!({}));
assert_eq!((w(&s, a), w(&s, b)), (0.75, 4.0));
run(&mut s, "stroke.weightUp", json!({}));
assert_eq!((w(&s, a), w(&s, b)), (1.0, 5.0));
assert_eq!(has_stroke(&s), bare_before, "an object without a stroke takes none");
for _ in 0..6 {
run(&mut s, "stroke.weightDown", json!({}));
}
// 1 → 0.75 → 0.5 → 0.25, where it stays; 5 → 4 → 3 → 2 → 1 → 0.75 → 0.5.
assert_eq!((w(&s, a), w(&s, b)), (0.25, 0.5));
run(&mut s, "edit.undo", json!({}));
assert_eq!((w(&s, a), w(&s, b)), (0.25, 0.75), "one undo step per press");
}
/// With nothing selected the next object drawn takes the stepped weight.
#[test]
fn stroke_weight_up_with_nothing_selected_sets_up_new_art() {
let mut s = session();
run(&mut s, "select.none", json!({}));
run(&mut s, "stroke.set", json!({"weight": 2}));
run(&mut s, "stroke.weightUp", json!({}));
assert_eq!(s.paint.stroke_width, 3.0);
let r = rect(&mut s, 10.0);
assert_eq!(s.doc().unwrap().doc.node(r).unwrap().appearance.stroke_width(), 3.0);
assert_eq!(crate::cmd::find_command("stroke.weightUp").unwrap().shortcut, Some("Cmd+Alt+."));
assert_eq!(crate::cmd::find_command("stroke.weightDown").unwrap().shortcut, Some("Cmd+Alt+,"));
}
+38 -3
View File
@@ -765,13 +765,48 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() {
assert_eq!(back.swatch("Checkerboard").map(|w| &w.paint), doc(&s).swatch("Checkerboard").map(|w| &w.paint));
}
/// A device name is saved with a `-` after it, which can be another library's own name: neither
/// library replaces the other, and saving either again replaces only itself.
#[test]
fn a_library_named_like_a_device_keeps_the_library_with_its_file_name() {
for (first, second) in [("COM¹", "COM¹-"), ("COM¹-", "COM¹"), ("com¹", "COM¹-")] {
let dir = temp_dir("device-collision");
let mut s = session();
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let save =
|s: &mut Session, name: &str| run(s, "swatch.library.save", json!({"user": true, "name": name}))["library"].as_str().unwrap().to_string();
let a = save(&mut s, first);
let b = save(&mut s, second);
assert_ne!(a, b);
assert_eq!(save(&mut s, first), a, "saving {first} again replaces {first}");
assert_eq!(save(&mut s, second), b, "saving {second} again replaces {second}");
assert_eq!(s.swatch_libraries.get(&a).unwrap().1.name, first);
assert_eq!(s.swatch_libraries.get(&b).unwrap().1.name, second);
// The name of the numbered file the second one got is a third library's own name.
let third = b.strip_prefix("user/").unwrap().strip_suffix(".vcswatches").unwrap().to_string();
let c = save(&mut s, &third);
assert!(c != a && c != b, "{third}: {c}");
assert_eq!(save(&mut s, &third), c, "saving {third} again replaces {third}");
assert_eq!(s.swatch_libraries.get(&b).unwrap().1.name, second);
let _ = std::fs::remove_dir_all(&dir);
}
}
/// #3602: a library titled with a Windows device name is saved under a name that is not one.
#[test]
fn a_library_file_name_is_never_a_windows_device_name() {
use crate::cmd::swatchlib::library_file_name;
for (title, ext) in
[("CON", "json"), ("nul", "json"), ("Com1", "acb"), ("LPT9", "ase"), ("aux.", "json"), ("CON.txt", "json"), ("nul.tar.gz", "acb")]
{
for (title, ext) in [
("CON", "json"),
("nul", "json"),
("Com1", "acb"),
("LPT9", "ase"),
("aux.", "json"),
("CON.txt", "json"),
("nul.tar.gz", "acb"),
("COM¹", "json"),
("lpt³.x", "ase"),
] {
let file = library_file_name(title, ext);
assert!(!crate::file_access::is_device_name(&file), "{title}: {file}");
assert!(
@@ -26,3 +26,18 @@ fn transparency_grid_is_per_document_view_state() {
s.execute("document.activate", &json!({"index": 1})).unwrap();
assert!(!grid(&s));
}
#[test]
fn invalid_transparency_grid_parameters_leave_the_view_unchanged() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
for params in [json!({"on": "false"}), json!({"on": 1})] {
assert!(s.execute("view.transparencyGrid", &params).is_err(), "accepted {params}");
let st = s.doc().unwrap();
assert!(!st.transparency_grid, "changed the grid for {params}");
assert!(st.history.undo.is_empty() && !st.is_dirty(), "recorded an edit for {params}");
}
// Left out, or null as for every command, it toggles.
assert_eq!(s.execute("view.transparencyGrid", &json!(null)).unwrap(), json!({"on": true}));
assert_eq!(s.execute("view.transparencyGrid", &json!({"on": null})).unwrap(), json!({"on": false}));
}
+31 -13
View File
@@ -2060,14 +2060,17 @@ fn a_variable_library_defines_text_variables_and_data_sets() {
assert_eq!(from_file["names"], json!(["Row 1", "Row 2"]));
let bom = [b"\xEF\xBB\xBF".as_slice(), xml.as_bytes()].concat();
let from_base64 = s.execute("variable.loadLibrary", &json!({"dataBase64": vectorcraft_format::base64_encode(&bom)})).unwrap();
assert_eq!((from_base64["deleted"].clone(), from_base64["deletedDataSets"].clone()), (json!(["Name", "Note"]), json!(["Row 1", "Row 2"])));
// The library declares the document's text variables: they stay, and only the data sets go.
assert_eq!((from_base64["deleted"].clone(), from_base64["deletedDataSets"].clone()), (json!([]), json!(["Row 1", "Row 2"])));
assert_eq!(s.doc().unwrap().doc.variables.datasets.len(), 2);
}
/// Load Variable Library replaces the document's variables and data sets: every variable goes with
/// its bindings and values, a text variable of the same name included, and every data set goes,
/// the active one included. The highlight of a variable that went highlights nothing. Undo brings
/// back the variables, bindings, data sets and active data set as they were.
/// its bindings and values, a variable of another kind with a library variable's name included,
/// and every data set goes, the active one included. A text variable the library also declares
/// stays bound (#4136), and the library's data sets then change its text. The highlight of a
/// variable that went highlights nothing. Undo brings back the variables, bindings, data sets and
/// active data set as they were.
#[test]
fn a_variable_library_replaces_every_variable_and_data_set() {
let mut s = session();
@@ -2085,17 +2088,22 @@ fn a_variable_library_replaces_every_variable_and_data_set() {
let xml = library(&[("Name", "textcontent"), ("Title", "textcontent")], &[("A", &[("Name", &["New"]), ("Title", &["Heading"])])]);
let loaded = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!(loaded["deleted"], json!(["Name", "Title", "Kept"]));
assert_eq!(loaded["deleted"], json!(["Title", "Kept"]));
assert_eq!((loaded["deletedDataSets"].clone(), loaded["names"].clone()), (json!(["A", "Other"]), json!(["A"])));
let listed = s.execute("variable.list", &json!({})).unwrap();
assert_eq!(listed["variables"], json!([{"name": "Name", "kind": "text", "bindings": 0}, {"name": "Title", "kind": "text", "bindings": 0}]));
assert_eq!(listed["variables"], json!([{"name": "Name", "kind": "text", "bindings": 1}, {"name": "Title", "kind": "text", "bindings": 0}]));
let sets = s.execute("dataset.list", &json!({})).unwrap();
assert_eq!(sets["datasets"].as_array().map(Vec::len), Some(1));
assert_eq!(sets["datasets"][0]["values"], json!({"Name": {"text": "New"}, "Title": {"text": "Heading"}}));
assert_eq!(sets["active"], Value::Null);
assert!(s.doc().unwrap().doc.variables.bindings.is_empty(), "the bindings went with the variables");
let bindings = &s.doc().unwrap().doc.variables.bindings;
assert_eq!(bindings.len(), 1, "the bindings went with the variables, but for Name's");
assert_eq!(bindings.get(&t).map(|v| v.len()), Some(1));
assert!(s.doc().unwrap().variables_highlight.is_none(), "the highlighted variable went");
assert_eq!(plain(&s, t), "Stays", "loading applies nothing");
s.execute("dataset.select", &json!({"name": "A"})).unwrap();
assert_eq!(plain(&s, t), "New", "the library's data set changes the text bound to Name");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.variables, before, "one undo step brings everything back");
@@ -2133,11 +2141,17 @@ fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() {
let before = super::history(&s);
let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!((super::history(&s), r["names"].clone()), (before, json!(["A", "B"])));
// Binding the variable makes the next load a change: it deletes the binding.
// A bound variable the library declares keeps its binding: loading it again changes nothing.
s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap();
super::select_with_a_step_to_redo(&mut s, &[t]);
let undo = super::history(&s).0;
let before = super::history(&s);
s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
assert_eq!(super::history(&s), before);
assert_eq!(s.execute("variable.list", &json!({})).unwrap()["variables"][0]["bindings"], json!(1));
// A library of other variables is a change: it deletes Name with its binding.
let other = library(&[("Note", "textcontent")], &[("A", &[("Note", &["Hi"])])]);
let undo = super::history(&s).0;
s.execute("variable.loadLibrary", &json!({"xml": other})).unwrap();
assert_eq!(super::history(&s), (undo + 1, 0, true));
// While the variables are locked, a library without text variables still loads its data sets,
@@ -2492,9 +2506,10 @@ fn a_saved_variable_library_near_the_size_cap_loads_back() {
/// While the variables are locked, a library that would delete or define a variable is refused, as
/// Delete Variable and New Variable are, and the document keeps its variables and data sets. That
/// covers a library whose only variable is a text variable the document already has, and one
/// without text variables loaded into a document with variables. A library without text variables
/// loads into a document without variables, replacing its data sets.
/// covers a library without text variables loaded into a document with variables, and one that
/// adds a text variable to the document's. A library of the document's own text variables, and
/// one without text variables loaded into a document without variables, delete and define none:
/// they load, replacing the data sets.
#[test]
fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
let mut s = session();
@@ -2502,11 +2517,14 @@ fn locked_variables_refuse_a_library_that_deletes_or_defines_variables() {
s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Old"}})).unwrap();
s.execute("variable.lock", &json!({"locked": true})).unwrap();
let before = s.doc().unwrap().doc.variables.clone();
for vars in [&[("Name", "textcontent")][..], &[("Shown", "other")][..]] {
for vars in [&[("Shown", "other")][..], &[("Name", "textcontent"), ("Note", "textcontent")][..]] {
let e = s.execute("variable.loadLibrary", &json!({"xml": library(vars, &[("B", &[])])})).unwrap_err();
assert!(matches!(&e, EngineError::Disabled(cmd, why) if cmd == "variable.loadLibrary" && why == "variables are locked"), "{e}");
assert_eq!(s.doc().unwrap().doc.variables, before);
}
// A library of the document's own text variable deletes and defines none: it loads its data sets.
let r = s.execute("variable.loadLibrary", &json!({"xml": library(&[("Name", "textcontent")], &[("B", &[])])})).unwrap();
assert_eq!((r["deleted"].clone(), r["deletedDataSets"].clone()), (json!([]), json!(["A"])));
let mut s = session();
s.execute("dataset.new", &json!({"name": "A"})).unwrap();
+14 -2
View File
@@ -154,6 +154,8 @@ impl Session {
/// Direct Selection to the tools that edit anchors (the Pen) and Selection to the others.
/// Cmd+Alt lends Group Selection while Direct Selection is active. Cmd still lends the last
/// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract).
/// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the
/// object (#3901; <https://community.adobe.com/t5/illustrator-discussions/handles-disappar-on-shape-with-direct-selection-tool/m-p/14848662>).
/// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane.
/// None for the other selection tools and the view tools.
fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> {
@@ -161,8 +163,8 @@ impl Session {
if matches!(id, "hand" | "zoom" | "rotateView") {
return None;
}
if id == "directSelection" && mods.cmd && mods.alt {
return Some("groupSelection");
if id == "directSelection" && mods.cmd {
return Some(if mods.alt { "groupSelection" } else { "selection" });
}
if id == "perspectiveSelection" && mods.cmd && mods.alt {
return None;
@@ -173,6 +175,16 @@ impl Session {
Some(self.last_selection_tool.unwrap_or(if edits_anchors(id) { "directSelection" } else { "selection" }))
}
/// The selection tool a press with `mods` would borrow from the active tool
/// ([`Self::lend_selection_tool`]), as [`Self::cursor`] shows it: the canvas also shows what
/// that tool shows (Direct Selection with Cmd held shows the bounding box).
pub fn lent_tool_id(&self, mods: &Mods) -> Option<&'static str> {
if !mods.cmd || self.lender.is_some() {
return None;
}
self.lent_tool(self.tool.id(), mods)
}
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
/// not Select Behind). The tool lent to stays as it was, unaware, until the release.
+108 -11
View File
@@ -30,6 +30,13 @@ const MAX_FONTS: usize = 4096;
const MAX_TABS: usize = 1024;
/// Largest tab stop position read (points), as `text.tabs.set` takes it.
const MAX_TAB_POSITION: f64 = 100_000.0;
/// Most tab stops copied in one text object into its runs of paragraphs with the same attributes
/// while it is read, and again, counted apart, into each of its paragraphs when it has more than one
/// run and into the frames of its linked areas after the first. The runs, paragraphs and frames past
/// it take the default stops, with a warning.
const MAX_STORY_TABS: usize = 1 << 20;
/// The warning when [`MAX_STORY_TABS`] leaves tab stops out.
const TABS_LEFT_OUT: &str = "tab stops past VectorCraft's limits were left out";
/// Most values read before one operator in a re-encoding section.
const MAX_ENCODING_VALUES: usize = 1024;
/// Most text paths read in one text object (its linked areas); the frames of others are left out,
@@ -56,6 +63,17 @@ struct TextPath {
path: Option<(BezPath, Vec<AnchorKind>)>,
}
/// Paragraphs in a row that start with the same attributes.
#[derive(Debug)]
struct ParaRun {
/// The attributes, as they were at the first character of each paragraph.
style: ParaStyle,
/// How many paragraphs.
count: usize,
/// [`TypeState::tabs_version`] when the last of them started.
tabs_version: u64,
}
/// A text object being read.
#[derive(Debug, Default)]
pub(super) struct LegacyText {
@@ -69,8 +87,13 @@ pub(super) struct LegacyText {
past_limit: bool,
/// The story: the characters after every text path, in file order.
runs: Vec<TextRun>,
/// Each paragraph's attributes, as they were at its first character.
paras: Vec<ParaStyle>,
/// The paragraphs' attributes, as they were at the first character of each, by runs of
/// paragraphs with the same attributes.
paras: Vec<ParaRun>,
/// The tab stops that the runs in `paras` hold.
tab_stops: usize,
/// [`MAX_STORY_TABS`] left tab stops out.
tabs_left_out: bool,
/// The current paragraph's attributes are in `paras`.
para_taken: bool,
/// An overflow paragraph break (`(\r) TX`) not yet followed by type: the story's end.
@@ -83,11 +106,74 @@ pub(super) struct LegacyText {
hidden: bool,
}
impl LegacyText {
/// A paragraph starts, with the attributes `para` at [`TypeState::tabs_version`]
/// `tabs_version`. When they are those of the paragraph before it, it joins that paragraph's
/// run; else a new run starts, with the tab stops that [`MAX_STORY_TABS`] leaves room for.
fn begin_para(&mut self, para: &mut ParaStyle, tabs_version: u64) {
if let Some(run) = self.paras.last_mut() {
// No tab definition since the run's last paragraph started: the stops are the same.
let same = if run.tabs_version == tabs_version { same_but_tabs(&mut run.style, para) } else { run.style == *para };
if same {
run.count += 1;
run.tabs_version = tabs_version;
return;
}
}
let style = within_tabs(para, &mut self.tab_stops, &mut self.tabs_left_out);
self.paras.push(ParaRun { style, count: 1, tabs_version });
}
}
/// Are `a` and `b` the same, leaving their tab stops out?
fn same_but_tabs(a: &mut ParaStyle, b: &mut ParaStyle) -> bool {
let (a_tabs, b_tabs) = (std::mem::take(&mut a.tabs), std::mem::take(&mut b.tabs));
let same = a == b;
(a.tabs, b.tabs) = (a_tabs, b_tabs);
same
}
/// A copy of `para`, with its tab stops when `copied` (the tab stops copied so far) has room for
/// them within [`MAX_STORY_TABS`], else with the default stops and `left_out` set.
fn within_tabs(para: &ParaStyle, copied: &mut usize, left_out: &mut bool) -> ParaStyle {
let mut style = para.clone();
if MAX_STORY_TABS.saturating_sub(*copied) >= style.tabs.len() {
*copied += style.tabs.len();
} else {
*left_out = true;
style.tabs = Vec::new();
}
style
}
/// The attributes of each paragraph of the runs `runs`, in order. A paragraph keeps its tab stops
/// while `copied` (the tab stops copied so far) has room for them within [`MAX_STORY_TABS`]; the
/// paragraphs past it take the default stops, and `left_out` is set.
fn each_paragraph(runs: Vec<ParaRun>, copied: &mut usize, left_out: &mut bool) -> Vec<ParaStyle> {
let mut each = Vec::with_capacity(runs.iter().map(|r| r.count).sum());
for run in runs {
let stops = run.style.tabs.len();
let room = MAX_STORY_TABS.saturating_sub(*copied);
let kept = room.checked_div(stops).map_or(run.count, |n| run.count.min(n));
*copied += kept * stops;
let bare = (kept < run.count).then(|| ParaStyle { tabs: Vec::new(), ..run.style.clone() });
each.extend(std::iter::repeat_n(run.style, kept));
if let Some(bare) = bare {
*left_out = true;
each.extend(std::iter::repeat_n(bare, run.count - kept));
}
}
each
}
/// The modal type attributes of the legacy format, which last from one text object to the next.
#[derive(Debug)]
pub(super) struct TypeState {
style: CharStyle,
para: ParaStyle,
/// How many tab definitions set `para`'s tab stops: paragraphs that start at the same count
/// start with the same stops.
tabs_version: u64,
/// `Tr`.
render: i64,
/// The encoding strings are in, by code (`TE`); None where it says nothing.
@@ -109,6 +195,7 @@ impl Default for TypeState {
Self {
style: CharStyle::default(),
para: ParaStyle::default(),
tabs_version: 0,
render: 0,
encoding: vec![None; 256],
fonts: vec![],
@@ -488,6 +575,7 @@ impl Reader<'_> {
tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
st.para.tabs = tabs;
st.tabs_version = st.tabs_version.wrapping_add(1);
}
}
_ => {}
@@ -538,13 +626,13 @@ impl Reader<'_> {
}
for c in decoded.chars() {
if c != '\n' && !t.para_taken {
t.paras.push(st.para.clone());
t.begin_para(&mut st.para, st.tabs_version);
t.para_taken = true;
}
text.push(c);
if c == '\n' {
if !t.para_taken {
t.paras.push(st.para.clone());
t.begin_para(&mut st.para, st.tabs_version);
}
t.para_taken = false;
}
@@ -562,7 +650,7 @@ impl Reader<'_> {
/// Point type is read at its first text path; area type and type on a path at the first one
/// that has a frame or path (else at the first one, as point type).
pub(super) fn end_text(&mut self, hidden: bool) -> Result<(), String> {
let Some(t) = self.text.take() else { return Ok(()) };
let Some(mut t) = self.text.take() else { return Ok(()) };
if t.runs.is_empty() {
return Ok(());
}
@@ -581,13 +669,15 @@ impl Reader<'_> {
if t.kind == 1 && (t.past_limit || all_areas > placed.len()) {
self.warn(LINKED_AREAS_LEFT_OUT);
}
let mut paras = t.paras;
let mut paras = std::mem::take(&mut t.paras);
if paras.is_empty() {
paras.push(self.type_state.para.clone());
paras.push(ParaRun { style: self.type_state.para.clone(), count: 1, tabs_version: 0 });
}
let last_para = paras.last().cloned().unwrap_or_default();
let last_para = paras.last().map(|r| r.style.clone()).unwrap_or_default();
let last_style = t.runs.last().map(|r| r.style.clone()).unwrap_or_default();
let mut story = Some((t.runs, paras));
let mut story = Some((std::mem::take(&mut t.runs), paras));
// The tab stops copied into the paragraphs and frames.
let mut copied = 0;
let mut nodes = Vec::with_capacity(placed.len());
for (m, kind) in placed {
let mut obj = TextObject::point(kurbo::Point::ZERO, "", last_style.clone());
@@ -596,12 +686,19 @@ impl Reader<'_> {
match story.take() {
Some((runs, paras)) => {
obj.runs = runs;
obj.set_paragraph_styles(paras);
// Paragraphs that all have the same attributes share one copy of them.
match <[ParaRun; 1]>::try_from(paras) {
Ok([one]) => obj.set_all_paras(one.style),
Err(paras) => obj.set_paragraph_styles(each_paragraph(paras, &mut copied, &mut t.tabs_left_out)),
}
}
None => obj.set_paragraph_styles(vec![last_para.clone()]),
None => obj.set_all_paras(within_tabs(&last_para, &mut copied, &mut t.tabs_left_out)),
}
nodes.push(self.new_node(NodeKind::Text(Box::new(obj)), &t.gs));
}
if t.tabs_left_out {
self.warn(TABS_LEFT_OUT);
}
let frames: Vec<NodeId> = nodes.iter().map(|n| n.id).collect();
// Type used as a mask clips the objects of its clipping group, as a `W` path does. A
// clipping path is one object, and wraparound text and compound paths don't clip their
@@ -377,7 +377,9 @@ impl<'a> Reader<'a> {
sub.global_names = std::mem::take(&mut self.global_names);
sub.nodes = self.nodes;
sub.template = self.template;
self.lend_budgets(&mut sub);
let read = sub.open(Kind::Group, false).and_then(|()| sub.run());
self.take_back_budgets(&mut sub);
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
@@ -402,6 +404,7 @@ impl<'a> Reader<'a> {
sub.global_names = std::mem::take(&mut self.global_names);
sub.nodes = self.nodes;
sub.template = self.template;
self.lend_budgets(&mut sub);
let mut read = sub.open(Kind::Group, false);
for layer in &def.layers {
if read.is_err() {
@@ -409,6 +412,7 @@ impl<'a> Reader<'a> {
}
read = sub.pattern_layer(layer, def.tile);
}
self.take_back_budgets(&mut sub);
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
@@ -543,7 +547,9 @@ impl<'a> Reader<'a> {
sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles);
sub.v7_patterns.clone_from(&self.v7_patterns);
sub.nodes = self.nodes;
self.lend_budgets(&mut sub);
let read = sub.open(Kind::Group, false).and_then(|()| sub.run());
self.take_back_budgets(&mut sub);
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
@@ -723,7 +729,9 @@ impl<'a> Reader<'a> {
sub.global_names = std::mem::take(&mut self.global_names);
sub.nodes = self.nodes;
sub.template = self.template;
self.lend_budgets(&mut sub);
let read = sub.open(Kind::Group, false).and_then(|()| sub.run());
self.take_back_budgets(&mut sub);
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
@@ -749,6 +757,21 @@ impl<'a> Reader<'a> {
self.brush_art.insert(name, node);
}
/// Lend `sub`, a reader of a definition, what this import may still spend on laying out blends
/// and checking envelopes ([`Reader::take_back_budgets`] takes back what is left).
fn lend_budgets(&mut self, sub: &mut Reader<'_>) {
sub.blend_budget = self.blend_budget;
sub.envelope_checks = self.envelope_checks;
sub.envelope_spent = std::mem::take(&mut self.envelope_spent);
}
/// Take back from `sub` what [`Self::lend_budgets`] lent it, less what it spent.
fn take_back_budgets(&mut self, sub: &mut Reader<'_>) {
self.blend_budget = sub.blend_budget;
self.envelope_checks = sub.envelope_checks;
self.envelope_spent = std::mem::take(&mut sub.envelope_spent);
}
/// In a pattern's definition, the operands of its first operator start with its head,
/// `(name) llx lly urx ury`: taken off them.
pub(super) fn take_head(&mut self, mut vals: Vec<V>) -> Vec<V> {
@@ -1107,4 +1130,66 @@ mod tests {
assert!(reader.brush_art.is_empty(), "{placed:?}");
}
}
/// A blend of two keys along a straight spine, with its drawn steps and its record.
fn blend() -> String {
use crate::import::ai::tests::{blend_file, blend_record};
blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B']))
}
/// A symbol's definition named `name` whose art is `art`.
fn symbol_section(name: &str, art: &str) -> String {
format!("({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n")
}
/// Whether `n` or an object in it is a live blend.
fn holds_blend(n: &Node) -> bool {
matches!(n.kind, NodeKind::Blend { .. }) || n.children().is_some_and(|c| c.iter().any(|k| holds_blend(k)))
}
/// Blends in symbols' definitions lay out their objects from the import's one budget: once a
/// definition has spent it, the next definition's blend keeps its drawn steps.
#[test]
fn blends_in_symbol_definitions_spend_the_imports_budget() {
let mut reader = Reader::new(b"");
reader.define_symbol(symbol_section("One", &blend()).as_bytes());
let one = super::super::types::BLEND_BUDGET - reader.blend_budget;
assert!(one > 0, "the definition's blend spends from the reader's budget");
let mut reader = Reader::new(b"");
reader.blend_budget = one;
reader.define_symbol(symbol_section("One", &blend()).as_bytes());
reader.define_symbol(symbol_section("Two", &blend()).as_bytes());
assert_eq!(reader.blend_budget, 0);
let live: Vec<bool> = reader.doc.symbols.iter().map(|s| holds_blend(&s.art)).collect();
assert_eq!(live, [true, false]);
}
/// Blends in patterns' and brushes' art spend from the same budget.
#[test]
fn blends_in_pattern_and_brush_art_spend_the_imports_budget() {
let mut reader = Reader::new(b"");
reader.define_pattern(format!("(P) 0 0 200 100\n0 A\n0 Xw\n0 Ae\n{}E\n", blend()).as_bytes());
assert!(reader.blend_budget < super::super::types::BLEND_BUDGET, "a pattern's blend");
let mut reader = Reader::new(b"");
reader.define_brush_art(format!("(A)\n0 A\n{}", blend()).as_bytes());
assert!(reader.blend_budget < super::super::types::BLEND_BUDGET, "a brush's blend");
}
/// Envelopes in symbols' definitions are checked within the import's one count of checks.
#[test]
fn envelopes_in_symbol_definitions_spend_the_imports_checks() {
use crate::import::ai::tests::{drawn_content, envelope_content, envelope_of, straight_mesh, warp_keys};
use vectorcraft_doc::live::EnvelopeKind;
let want = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true };
let envelope =
envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), &warp_keys(1, 0.5, 0.0, 0.0, 0), &envelope_content(), 1, &drawn_content(&want));
let mut reader = Reader::new(b"");
reader.define_symbol(symbol_section("One", &envelope).as_bytes());
assert_eq!(reader.envelope_checks, crate::import::ai::envelope::MAX_CHECKED - 1);
let mut reader = Reader::new(b"");
reader.envelope_checks = 1;
reader.define_symbol(symbol_section("One", &envelope).as_bytes());
reader.define_symbol(symbol_section("Two", &envelope).as_bytes());
assert_eq!(reader.envelope_checks, 0);
}
}
+107 -30
View File
@@ -22,6 +22,19 @@ fn ruler_unit(v: u8) -> Option<Unit> {
})
}
/// `base`, or the first of "base 2", "base 3"… not in `taken`, as [`Document::free_swatch_name`]
/// gives it when `taken` holds the document's swatch and colour group names; `taken` takes the
/// name returned.
fn free_swatch_name(taken: &mut std::collections::HashSet<String>, base: &str) -> String {
let name = if taken.contains(base) {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n)).unwrap_or_else(|| base.to_string())
} else {
base.to_string()
};
taken.insert(name.clone());
name
}
/// An artboard of the `/Document`'s `ArtboardArray`: its name, its rect in art space and its
/// display options.
#[derive(Clone, Debug)]
@@ -820,6 +833,86 @@ impl<'a> Reader<'a> {
Some((swatches, groups))
}
/// The swatches of the file's named colors and patterns, added to `doc`'s, and the new name of
/// each color that took a numbered one.
///
/// The colour operators' definitions come first: a gradient, defined before the art, names a
/// global process colour as a stop and would otherwise make it an ink (#1771). The header's
/// custom colors follow. The first definition of a name makes its swatch, and takes the place
/// of a default swatch of that name when the file has no palette of its own (`own_palette`; a
/// reserved name in brackets, such as `[None]`, keeps its swatch). Then each pattern gets a
/// swatch. A color whose name a gradient or pattern swatch of the palette has, and a pattern
/// whose name another swatch has, take the first free "Name 2", "Name 3"…
/// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches;
/// a pattern a swatch already paints with gets no other.
fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap<String, String> {
let mut defined = std::collections::HashSet::new();
let mut clashes = vec![];
// The swatch names there are, looked up rather than scanned for each name a file defines
// (`Document::swatch` also knows the registration colour).
let mut have: std::collections::HashSet<String> = doc.swatches_iter().map(|s| s.name.clone()).collect();
have.insert(vectorcraft_color::swatch::REGISTRATION.to_string());
// The names a swatch of another kind than a gradient or pattern has.
let mut solid: std::collections::HashSet<String> =
doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect();
let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
for (n, spot) in colors {
let first = defined.insert(n.name.clone());
let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot };
let reserved = n.name.starts_with('[') && n.name.ends_with(']');
if have.insert(n.name.clone()) {
solid.insert(n.name.clone());
doc.swatches.push(swatch);
} else if first && !reserved {
if !own_palette && let Some(default) = doc.swatch_mut(&n.name) {
*default = swatch;
solid.insert(n.name.clone());
} else if !solid.contains(&n.name) {
clashes.push(swatch);
}
}
}
let mut unnamed = vec![];
for pattern in doc.patterns.iter().map(|p| p.name.clone()).collect::<Vec<_>>() {
if have.insert(pattern.clone()) {
doc.swatches.push(Swatch {
paint: Paint::Pattern { pattern: pattern.clone(), xf: Affine::IDENTITY },
name: pattern,
global: false,
spot: false,
});
} else {
unnamed.push(pattern);
}
}
// Every color and pattern name now has a swatch, so a numbered name takes none of them. The
// names taken and the patterns painted with are looked up rather than scanned for each one.
let mut taken: std::collections::HashSet<String> = doc.swatches_iter().map(|s| s.name.clone()).collect();
taken.extend(doc.swatch_groups.iter().map(|g| g.name.clone()));
taken.insert(vectorcraft_color::swatch::REGISTRATION.to_string());
let mut painted: std::collections::HashSet<String> = doc
.swatches_iter()
.filter_map(|s| match &s.paint {
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
_ => None,
})
.collect();
let mut renamed = HashMap::new();
for swatch in clashes {
let name = free_swatch_name(&mut taken, &swatch.name);
renamed.insert(swatch.name.clone(), name.clone());
doc.swatches.push(Swatch { name, ..swatch });
}
for pattern in unnamed {
if !painted.insert(pattern.clone()) {
continue;
}
let name = free_swatch_name(&mut taken, &pattern);
doc.swatches.push(Swatch { paint: Paint::Pattern { pattern, xf: Affine::IDENTITY }, name, global: false, spot: false });
}
renamed
}
/// The brushes read ([`brush::finish_brushes`]) and how many weren't; `None` when the file has
/// no brush objects (the document keeps the default brushes).
fn brush_library(&mut self) -> Option<(Vec<vectorcraft_brush::Brush>, usize)> {
@@ -957,39 +1050,11 @@ impl<'a> Reader<'a> {
}
None => false,
};
// The colour operators' definitions first: a gradient, defined before the art, names a
// global process colour as a stop and would otherwise make it an ink (#1771). The header's
// custom colors follow. The first definition of a name makes its swatch, and takes the place
// of a default swatch of that name when the file has no palette of its own (a reserved name
// in brackets, such as `[None]`, keeps its swatch).
let mut defined = std::collections::HashSet::new();
// The swatch names there are, looked up rather than scanned for each name a file defines
// (`Document::swatch` also knows the registration colour).
let mut have: std::collections::HashSet<String> = doc.swatches_iter().map(|s| s.name.clone()).collect();
have.insert(vectorcraft_color::swatch::REGISTRATION.to_string());
let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
for (n, spot) in colors {
let first = defined.insert(n.name.clone());
let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot };
if have.insert(n.name.clone()) {
doc.swatches.push(swatch);
} else if first
&& !own_palette
&& !(n.name.starts_with('[') && n.name.ends_with(']'))
&& let Some(default) = doc.swatch_mut(&n.name)
{
*default = swatch;
}
}
let renamed = self.file_swatches(&mut doc, own_palette);
if let Some(author) = self.author.take() {
doc.metadata.author = author;
}
for name in doc.patterns.iter().map(|p| p.name.clone()).collect::<Vec<_>>() {
if have.insert(name.clone()) {
doc.swatches.push(Swatch { paint: Paint::Pattern { pattern: name.clone(), xf: Affine::IDENTITY }, name, global: false, spot: false });
}
}
let brushes = self.brush_library();
let mut brushes = self.brush_library();
// The file's graphic styles in place of the defaults, and the objects linked to them.
let (styles, ids) = self.graphic_styles();
let styles_read = !styles.is_empty();
@@ -1003,6 +1068,18 @@ impl<'a> Reader<'a> {
}
doc.graphic_styles = styles.into();
}
// The colors linked to a color that took a free name follow it.
if !renamed.is_empty() {
let mut follow = |_: &mut vectorcraft_color::Color, link: &mut Option<String>, _: &mut f32| {
let Some(new) = link.as_ref().and_then(|l| renamed.get(l)) else { return false };
*link = Some(new.clone());
true
};
doc.map_solid_paints(&mut follow);
for a in brushes.iter_mut().flat_map(|(lib, _)| lib.iter_mut().flat_map(|b| b.art_mut())) {
vectorcraft_doc::swatches::map_node_solid_paints(a, &mut follow);
}
}
let mut warnings = self.warnings;
if let Some((lib, unread)) = brushes {
vectorcraft_brush::store(&mut doc, &lib);
+127 -7
View File
@@ -818,6 +818,71 @@ fn pattern_names_are_numbered_around_the_documents_swatches() {
assert_eq!(names(&d), ["Sea 2"]);
}
/// A pattern whose name has no newline keeps it, and its swatch takes the first free "Name 2" when
/// another swatch has the name: a default swatch, a named color the art uses, or a color of the
/// palette. A pattern a swatch already paints with gets no other.
#[test]
fn a_pattern_swatch_named_as_another_swatch_is_numbered() {
let def = |name: &str| DOTS.replace("(Dots)", &format!("({name})"));
let filled = |name: &str| format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(10.0, 20.0, 70.0, 80.0));
let ink = format!("0 1 1 0 (Ink) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0));
let paints = |d: &Document, name: &str| d.swatches_iter().find(|s| s.name == name).map(|s| s.paint.clone());
let doc = read_ok(&format!("{}{}{}", def("White"), def("Ink"), layer(&format!("{}{}{ink}", filled("White"), filled("Ink"))))).doc;
assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["White", "Ink"]);
for name in ["White", "Ink"] {
assert!(matches!(paints(&doc, name), Some(Paint::Solid { .. })), "{name}");
let numbered = format!("{name} 2");
assert!(matches!(paints(&doc, &numbered), Some(Paint::Pattern { pattern, .. }) if pattern == name), "{numbered}");
}
let fills: Vec<_> = art(&doc).iter().map(|n| fill(n)).collect();
assert!(matches!(&fills[..2], [Paint::Pattern { pattern: a, .. }, Paint::Pattern { pattern: b, .. }] if a == "White" && b == "Ink"));
// A pattern defined later under the numbered name keeps its swatch's name.
let doc = read_ok(&format!("{}{}{}", def("White"), def("White 2"), layer(&filled("White")))).doc;
assert!(matches!(paints(&doc, "White 2"), Some(Paint::Pattern { pattern, .. }) if pattern == "White 2"));
assert!(matches!(paints(&doc, "White 3"), Some(Paint::Pattern { pattern, .. }) if pattern == "White"));
// A color of the palette.
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\nPB\n%AI5_EndPalette\n";
let doc = read_ok(&format!("{}{palette}{}", def("Mist"), layer(&filled("Mist")))).doc;
assert!(matches!(paints(&doc, "Mist"), Some(Paint::Solid { .. })));
assert!(matches!(paints(&doc, "Mist 2"), Some(Paint::Pattern { pattern, .. }) if pattern == "Mist"));
// A palette swatch under another name already paints with the pattern.
let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\n(Mist) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Fog)\nPc\nPB\n%AI5_EndPalette\n";
let doc = read_ok(&format!("{}{palette}{}", def("Mist"), layer(&filled("Mist")))).doc;
let names: Vec<&str> = doc.swatches_iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["[None]", "Mist", "Fog"]);
}
/// A named color whose name a gradient or pattern swatch of the palette has takes the first free
/// "Name 2", and the fills and gradient stops linked to it follow it.
#[test]
fn a_color_named_as_a_palette_gradient_or_pattern_is_numbered() {
let gradient = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n\
%_0 1 1 0 (Brand) 0 0 5 1 6 50 0 Bs\n%_0 0 0 0 1 0 0 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let palette = "%AI5_BeginPalette\n0 0 Pb\nBb\n2 (Brand) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Brand)\nPc\n\
(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Ink)\nPc\nPB\n%AI5_EndPalette\n";
let colored = |name: &str| format!("0 1 1 0 ({name}) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0));
let doc = read_ok(&format!("{gradient}{DOTS}{palette}{}", layer(&format!("{}{}", colored("Brand"), colored("Ink"))))).doc;
let paints = |name: &str| doc.swatches_iter().find(|s| s.name == name).map(|s| s.paint.clone());
assert!(matches!(paints("Brand"), Some(Paint::Gradient(_))));
assert!(matches!(paints("Ink"), Some(Paint::Pattern { .. })));
for name in ["Brand 2", "Ink 2"] {
let sw = doc.swatches_iter().find(|s| s.name == name).unwrap_or_else(|| panic!("{name}"));
assert!(matches!(sw.paint, Paint::Solid { .. }) && sw.global && sw.spot, "{sw:?}");
}
let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Solid { swatch, .. } = fill(n) { swatch } else { None }).collect();
assert_eq!(links, [Some("Brand 2".to_string()), Some("Ink 2".to_string())]);
let Some(Paint::Gradient(g)) = paints("Brand") else { panic!() };
assert_eq!(g.gradient.stops[0].swatch.as_deref(), Some("Brand 2"), "the stop's link");
// A color defined later under the numbered name keeps it and its links.
let later = format!("0 0 1 0 (Brand 2) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0));
let doc = read_ok(&format!("{gradient}{DOTS}{palette}{}", layer(&format!("{}{later}", colored("Brand"))))).doc;
let color = |name: &str| doc.swatches_iter().find(|s| s.name == name).and_then(|s| s.paint.color());
assert_eq!(color("Brand 2"), Some(Color::cmyk(0.0, 0.0, 1.0, 0.0)));
assert_eq!(color("Brand 3"), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)));
let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Solid { swatch, .. } = fill(n) { swatch } else { None }).collect();
assert_eq!(links, [Some("Brand 3".to_string()), Some("Brand 2".to_string())]);
}
/// A palette's pattern swatch named by its pattern takes the name the pattern is shown with.
#[test]
fn a_palette_pattern_swatch_takes_its_patterns_shown_name() {
@@ -3313,6 +3378,44 @@ fn legacy_tab_definitions_skipped_capped_and_left_open() {
assert!(texts[1].para_at(0).tabs.is_empty(), "the next object's `To` ends the open definition");
}
/// Point type whose 1024 tab stops are followed by 2048 paragraph breaks, each after `attrs(i)`.
fn paragraphs_after_many_tabs(attrs: impl Fn(usize) -> String) -> String {
let many: String = (0..1024).map(|i| format!("0 0 1 {i} Xe\n")).collect();
let breaks: String = (0..2048).map(|i| format!("{}(x\\r) Tx\n", attrs(i))).collect();
point_type(&format!("36 1024 Xb\n{many}XB"), "A").replace("TO\n", &format!("{breaks}TO\n"))
}
/// Paragraphs that start with the same attributes all keep the same tab stops, however many
/// there are, also when an attribute is set again to the value it has.
#[test]
fn legacy_tab_stops_last_through_many_paragraphs() {
for again in ["", "0 Ta\n"] {
let r = legacy_read(&paragraphs_after_many_tabs(|_| again.to_string()));
let texts = art_texts(&r.doc);
let [t] = texts.as_slice() else { panic!("{texts:?}") };
assert_eq!(t.paragraph_count(), 2049);
assert!((0..2049).all(|i| t.para_at(i).tabs.len() == 1024), "{again}");
assert!(r.warnings.is_empty(), "{again}: {:?}", r.warnings);
}
}
/// Each paragraph whose attributes differ from the paragraph before it holds its own copy of its
/// tab stops, and a text object's paragraphs hold no more than 1,048,576 stops: the paragraphs
/// past them take the default stops and keep their other attributes, with a warning.
#[test]
fn legacy_tab_stops_copied_into_paragraphs_are_capped() {
let r = legacy_read(&paragraphs_after_many_tabs(|i| format!("{} Ta\n", i % 2)));
let texts = art_texts(&r.doc);
let [t] = texts.as_slice() else { panic!("{texts:?}") };
let paras = t.paragraph_styles();
assert_eq!(paras.len(), 2049);
assert_eq!(paras.iter().map(|p| p.tabs.len()).sum::<usize>(), 1 << 20);
assert!(paras[..1024].iter().all(|p| p.tabs.len() == 1024));
assert!(paras[1024..].iter().all(|p| p.tabs.is_empty()));
assert_eq!((paras[2046].justify, paras[2047].justify), (vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Center));
assert_eq!(r.warnings, ["tab stops past VectorCraft's limits were left out"]);
}
/// `Te` (end render, §22.6) reads in a text object with no operands and with four, inside a tab
/// definition too, and keeps nothing; so does `TM` (pop text matrix, §22.6).
#[test]
@@ -3625,6 +3728,23 @@ fn legacy_area_type_reads_up_to_its_limit_of_linked_areas() {
assert_eq!(r.warnings, [LINKED_AREAS_LEFT_OUT]);
}
/// The frames of linked areas after the first copy the story's last paragraph attributes, and
/// those copies hold no more than 1,048,576 tab stops: the frames past them take the default
/// stops, with a warning.
#[test]
fn legacy_linked_area_frames_cap_their_copied_tab_stops() {
let many: String = (0..1024).map(|i| format!("0 0 1 {i} Xe\n")).collect();
let area = format!("1 0 0 1 0 0 0 Tp\n{}n\nTP\n", rect_path(0.0, 0.0, 50.0, 40.0));
let text = format!("1 To\n{}0 Tr\n36 1024 Xb\n{many}XB\n(a) Tx\nTO\n", area.repeat(4096));
let r = legacy_read(&text);
let frames = art_frames(&r.doc);
assert_eq!(frames.len(), 4096);
let stops: Vec<usize> = frames.iter().map(|(_, f)| f.para_at(0).tabs.len()).collect();
assert_eq!(stops.iter().filter(|&&n| n == 1024).count(), 1025);
assert_eq!(stops.iter().filter(|&&n| n == 0).count(), 3071);
assert_eq!(r.warnings, ["tab stops past VectorCraft's limits were left out"]);
}
/// The warning when linked areas are left out.
const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out";
@@ -5495,7 +5615,7 @@ fn envelope_parts(before: &str, keys: &str, block: &str, kind: u32, drawn: &str)
/// An envelope of `content` (in the plain group the editing data puts round it) shaped by the mesh
/// `shape`.
fn envelope_of(shape: &str, keys: &str, content: &str, kind: u32, drawn: &str) -> String {
pub(super) fn envelope_of(shape: &str, keys: &str, content: &str, kind: u32, drawn: &str) -> String {
envelope_parts(shape, keys, &format!("u\n{content}U\n9 () XW\n"), kind, drawn)
}
@@ -5527,7 +5647,7 @@ fn mesh_text(cols: usize, rows: usize, at: MeshAt<'_>, handle: MeshHandle<'_>, a
}
/// A grid in art space, its points `step` apart from (40, 20), handles a third of the way.
fn straight_mesh(cols: usize, rows: usize, step: (f64, f64)) -> String {
pub(super) fn straight_mesh(cols: usize, rows: usize, step: (f64, f64)) -> String {
let at = move |(i, j): (usize, usize)| (40.0 + i as f64 * step.0, 20.0 + j as f64 * step.1);
let third = move |p: (usize, usize), q: (usize, usize)| {
let ((x, y), (u, v)) = (at(p), at(q));
@@ -5537,13 +5657,13 @@ fn straight_mesh(cols: usize, rows: usize, step: (f64, f64)) -> String {
}
/// The red rectangle 40 20 160 80 in art space, which is the same box in the document's.
fn envelope_content() -> String {
pub(super) fn envelope_content() -> String {
format!("{RED}{}f\n", rect_path(40.0, 20.0, 160.0, 80.0))
}
/// What envelope `kind` draws of [`envelope_content`]: the rectangle's edges, many points to a
/// side, mapped as VectorCraft maps them, as a red path in art space.
fn drawn_content(kind: &vectorcraft_doc::live::EnvelopeKind) -> String {
pub(super) fn drawn_content(kind: &vectorcraft_doc::live::EnvelopeKind) -> String {
let rect = Rect::new(40.0, 20.0, 160.0, 80.0);
let map = vectorcraft_doc::live::envelope_mapper(kind, rect);
let corners = [Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(160.0, 80.0), Point::new(40.0, 80.0)];
@@ -5571,7 +5691,7 @@ fn live_envelope(n: &Node) -> (&[Arc<Node>], &vectorcraft_doc::live::EnvelopeKin
/// A warp's dictionary keys: style number `style`, bend, horizontal and vertical distortion as
/// fractions, and the orientation (vertical with `rotate` 1).
fn warp_keys(style: u32, bend: f64, h: f64, v: f64, rotate: u32) -> String {
pub(super) fn warp_keys(style: u32, bend: f64, h: f64, v: f64, rotate: u32) -> String {
format!(
"{ENVELOPE_KEYS}{style} /Int (DeformStyle) ,\n{h} /Real (DeformHoriz) ,\n{bend} /Real (DeformValue) ,\n{v} /Real (DeformVert) ,\n{rotate} /Bool (Rotate) ,\n(Warp) /UnicodeString (DisplayString) ,\n"
)
@@ -6209,7 +6329,7 @@ fn layer_options_of_nine_to_twelve_operands() {
/// A blend's record as the editing data writes it after `(Adobe Path Blends) 1 0 n XP`: `DCBA`,
/// Specified Steps, then (as far as the reader reads it) the number of keys at word 10 and a record
/// of six words per key starting with its id. Hand-written; the other words are zero.
fn blend_record(ids: &[char]) -> String {
pub(super) fn blend_record(ids: &[char]) -> String {
blend_record_spaced(ids, 1, 0.0, 0)
}
@@ -6241,7 +6361,7 @@ fn blend_part(kind: &str, id: Option<&str>) -> String {
/// A blend of two 20 pt squares, red on the left (key `A`) and blue on the right (`B`), along
/// `spine` (path operators, `%_` lines), with its drawn steps (three between the keys) and the
/// record `record`.
fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String {
pub(super) fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String {
blend_file_colored(spine, ids, record, [1.0, 0.0, 0.0], [0.0, 0.0, 1.0])
}
+1 -1
View File
@@ -816,7 +816,7 @@ impl<'a> Interp<'a> {
},
Bitshift => {
let (s, v) = (self.pop_int()?, self.pop_int()?);
let r = if s >= 0 { v.checked_shl(s.min(63) as u32) } else { v.checked_shr((-s).min(63) as u32) };
let r = if s >= 0 { v.checked_shl(s.min(63) as u32) } else { v.checked_shr(s.saturating_neg().min(63) as u32) };
self.push(Obj::Int(r.unwrap_or(0)))?;
}
True => self.push(Obj::Bool(true))?,
+15 -3
View File
@@ -103,7 +103,8 @@ fn layer_tree(nodes: &[Arc<Node>]) -> Vec<Arc<Node>> {
/// data was decompressed but its layers can't be read, and its swatches, brushes, graphic styles and
/// variables those of the editing data's palette ([`use_palette`]), brushes ([`use_brushes`]), styles
/// ([`use_styles`]) and variable library ([`use_variables`]) when it was decompressed: a graphic
/// style library, which has no layers, opens with its styles. `outlined`: the PDF part's type was
/// style library, which has no layers, opens with its styles, and editing data with no layers opens
/// on the page of its active artboard under the checks of `place_pages`. `outlined`: the PDF part's type was
/// read as outlines (a file whose type shows then comes in as its PDF part).
/// `trust`: layers that draw differently from the PDF part are used all the same, with a warning.
/// `unit`: the size in points of a unit of the PDF part's user space, its first page's `UserUnit`,
@@ -134,10 +135,14 @@ pub fn layered_ai_from(
};
if !has_layers(&data) {
let (mut visible, mut warnings) = (visible, warnings);
let (boards, active) = ai::artboards(&data);
if board_scale(&boards, &visible, unit).is_some() {
visible.opened_artboard = active_page(active, &visible);
}
let have = visible.patterns.len();
use_palette(&data, &mut visible);
use_brushes(&data, &mut visible, have, &mut warnings);
use_styles(&data, &mut visible, false, unit, None);
use_styles(&data, &mut visible, false, unit, Some(&boards));
use_variables(&data, &mut visible, &mut warnings);
return (visible, warnings, false);
}
@@ -347,7 +352,7 @@ fn place_pages(boards: &[(String, Rect)], active: Option<usize>, doc: &mut Docum
for ((name, _), a) in boards.iter().zip(&mut doc.artboards) {
a.name.clone_from(name);
}
doc.opened_artboard = active.filter(|i| *i > 0).and_then(|i| doc.artboards.get(i)).map(|a| a.id);
doc.opened_artboard = active_page(active, doc);
let [(_, first), _, ..] = boards else { return };
// Art space (y up) → the document, the first artboard's top left at the origin, as `read` has it,
// `k` points a unit.
@@ -362,6 +367,13 @@ fn place_pages(boards: &[(String, Rect)], active: Option<usize>, doc: &mut Docum
}
}
/// The id of the page of `doc` (a `.ai` read as its PDF part: a page per artboard) for the artboard
/// at `active` among those of its editing data, to open the file on: `None` for the first, which a
/// file opens on anyway, or when `doc` has no such page.
fn active_page(active: Option<usize>, doc: &Document) -> Option<u32> {
active.filter(|i| *i > 0).and_then(|i| doc.artboards.get(i)).map(|a| a.id)
}
/// The objects in `layer` (and its sublayers) moved by the move of the page they are on.
fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) {
let Some(children) = layer.children_mut() else { return };
+7
View File
@@ -1400,3 +1400,10 @@ fn stored_graphics_states_use_up_the_memory_budget() {
assert!(r.warnings.iter().any(|w| w.contains("uses too much memory")), "{body}: {:?}", r.warnings);
}
}
/// `bitshift` by the most negative integer shifts right by everything, not a negation overflow.
#[test]
fn bitshift_by_the_most_negative_integer_does_not_panic() {
let r = read("0 0 10 10 rectfill 1 -9223372036854775808 bitshift pop -1 -9223372036854775808 bitshift pop");
assert_eq!(objects(&r.document).len(), 1, "{:?}", r.warnings);
}
+43
View File
@@ -2335,6 +2335,49 @@ fn an_ai_file_read_as_its_pdf_part_keeps_its_active_artboard() {
assert_eq!(d.opened_artboard, Some(2));
}
/// A `.ai` whose editing data has artboards and no layers comes in as its PDF part, open on the
/// page of the artboard the editing data names as the active one when there is a page per artboard
/// of its size.
#[test]
fn an_ai_file_with_no_layers_keeps_its_active_artboard() {
let board = |x0: i32| {
format!(
"%_/Dictionary :\n%_{x0} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n",
x0 + 100
)
};
let no_layers = |active: &str| {
native(&format!(
"%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n{active}%_; /NotRecorded ,\n%_;\n",
board(0),
board(120)
))
};
let mut pdf = pdf_part(10.0, 10.0);
let mut page = pdf.artboards[0].clone();
(page.id, page.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0));
pdf.artboards.push(page.clone());
let opened = |pdf: &Document, active: &str| {
let data = no_layers(active);
assert!(!data.contains("%AI5_BeginLayer"));
let (d, w, read) = crate::layered_ai(&private(&data), pdf.clone(), vec![], false, false, 1.0);
assert!(!read && !w.iter().any(|w| w.contains("layers weren't read")), "{w:?}");
assert_eq!(d.artboards.iter().map(|a| a.rect).collect::<Vec<_>>(), pdf.artboards.iter().map(|a| a.rect).collect::<Vec<_>>());
d.opened_artboard
};
assert_eq!(opened(&pdf, "%_1 /Int (CropAreaActive) ,\n"), Some(2));
assert_eq!(opened(&pdf, "%_0 /Int (CropAreaActive) ,\n"), None);
assert_eq!(opened(&pdf, ""), None);
// Not a page per artboard, or a page of another size: the pages aren't the artboards.
let mut three = pdf.clone();
(page.id, page.rect) = (3, vectorcraft_geom::Rect::new(240.0, 0.0, 340.0, 100.0));
three.artboards.push(page);
assert_eq!(opened(&three, "%_1 /Int (CropAreaActive) ,\n"), None);
let mut other_size = pdf.clone();
other_size.artboards[1].rect = vectorcraft_geom::Rect::new(120.0, 0.0, 320.0, 100.0);
assert_eq!(opened(&other_size, "%_1 /Int (CropAreaActive) ,\n"), None);
}
#[test]
fn art_moved_with_its_page_moves_its_pattern_tile() {
// Two 100-point artboards, the second 50 below the first; an operator this doesn't know, so
+21
View File
@@ -150,6 +150,27 @@ pub struct LegacyAiOutput {
pub warnings: Vec<String>,
}
/// Whether image node `n` of `doc` is written as a 1-bit image mask in its colorize color
/// (ImageMask 1, §8.1) that draws as the document does: it is colorized with a solid color, its
/// pixels take the color and are all black or white (or clear), it has no opacity mask turned on,
/// and it has no more pixels than the writer writes. Such an image keeps its clear pixels in the file.
pub fn writes_image_mask(doc: &Document, n: &Node) -> bool {
let NodeKind::Image(im) = &n.kind else { return false };
// The size from the file's header, before any pixels are decoded.
let fits = |bytes: &[u8]| {
image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.ok()
.and_then(|r| r.into_dimensions().ok())
.is_some_and(|(w, h)| w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS)
};
matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. }))
&& !n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
&& doc
.image_blob(im)
.is_some_and(|b| b.takes_colorize() && fits(&b.bytes) && b.coverage().is_some_and(|(_, _, c)| c.iter().all(|&v| v == 0 || v == 255)))
}
/// Write `doc`'s first artboard and every layer (all its art, on the artboard or not) as a
/// legacy `.ai` file of version 7. Art space is y up, its origin at the artboard's left edge and
/// just under its bottom edge: the artboard's top is on a whole point, where readers that place
+5 -3
View File
@@ -36,7 +36,7 @@ pub(crate) const PROCSET: &str = "VectorCraft_Legacy 1 0";
/// application's procedure set): paths and their painting with the fill and stroke colours,
/// compound paths painted as one path, clipping groups, guides that don't print, layers that are
/// hidden or don't print marking nothing, and images drawn from the samples on the comment lines
/// that follow `XI`. Gradients fill with the colour set before them (the writer sets the first
/// that follow `XI` (an image mask's 0 bits in the fill color). Gradients fill with the colour set before them (the writer sets the first
/// stop's), and type marks nothing: apps that read the format draw both. The page trailer's
/// `annotatepage` (§3, Script Setup: `gsave annotatepage grestore showpage`) marks nothing.
pub(super) const PROLOG: &str = "%%BeginResource: procset VectorCraft_Legacy 1 0
@@ -96,9 +96,11 @@ VCLegacy begin
/_l 256 string def /_s 128 string def
/_row {{currentfile _l readline not {exit} if dup length 1 gt {exit} if pop} loop
dup length 1 gt {dup length 1 sub 1 exch getinterval /ASCIIHexDecode filter _s readstring pop} {pop ()} ifelse} bd
/XI {pop pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop
% An image mask (ImageMask 1) paints its 0 bits in the fill color.
/XI {1 eq /_im exch def pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop
[1 0 0 -1 0 0] exch matrix concatmatrix
_on {gsave concat _iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage grestore} {pop} ifelse} bd
_on {gsave concat _im {_fc _iw _ih false [1 0 0 1 0 0] /_row load imagemask}
{_iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage} ifelse grestore} {pop} ifelse} bd
% Type (15) is set by the app that reads the file: its operators take their operands and mark
% nothing; encodings (3.3) are skipped.
/TE {cleartomark} bd /TZ {cleartomark} bd
+88
View File
@@ -442,6 +442,94 @@ fn empty_images_get_the_size_note_and_undecodable_ones_the_decode_note() {
assert_eq!(notes(b"not an image".to_vec()), [UNDECODED]);
}
/// A gray image of `doc`, `w` × `h` pixels of `gray`, colorized `paint`, placed 10 pt a pixel
/// at (`x`, `y`).
fn colorized_image(doc: &mut Document, (w, h): (u32, u32), gray: Vec<u8>, paint: &Paint, (x, y): (f64, f64)) -> Node {
let mut png = vec![];
image::GrayImage::from_raw(w, h, gray).unwrap().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let blob = ImageBlob::new("image/png", png);
let key = blob.content_key();
doc.images.insert(key.clone(), blob);
let xf = Affine::new([10.0, 0.0, 0.0, 10.0, x, y]);
let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
n.extras_mut().colorize = Some(Box::new(paint.clone()));
n
}
/// A colorized image whose pixels are black or white is written as a 1-bit image mask
/// (ImageMask 1) after its color as the fill: its black pixels are 0 bits, which take the color, and its
/// white pixels 1 bits, which are clear. It prints in its color over the square behind it and
/// reads back colorized with that color and with the same clear pixels. A colorized image with
/// gray pixels is written with its color in its pixels, over white, with the note for
/// transparent pixels.
#[test]
fn colorized_images_keep_their_color() {
let mut doc = Document::new(200.0, 100.0);
doc.layers.clear();
let layer = doc.add_layer(Some("Art"));
let square = shape(&mut doc, shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 30.0)), red(), Paint::None);
doc.insert(Some(layer), usize::MAX, square).unwrap();
let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
// 1 0 0 1 0 1 1 0 / 0 1 1 0 1 0 0 1 in black (1) and white (0).
let mask: Vec<u8> = "1001011001101001".bytes().map(|b| if b == b'1' { 0 } else { 255 }).collect();
let bitmap = colorized_image(&mut doc, (8, 2), mask.clone(), &paint, (10.0, 10.0));
doc.insert(Some(layer), usize::MAX, bitmap).unwrap();
let out = write(&doc);
let text = String::from_utf8(out.bytes.clone()).unwrap();
let images = rasters(&text);
assert_eq!(images.len(), 1, "{text}");
let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) };
assert!(xi.ends_with(" ] 0 0 8 2 8 2 1 1 0 0 0 1 XI"), "{xi}");
// Each row is a byte: the black pixels are 0 bits.
assert_eq!(data, &["%6996"], "{text}");
let at = text.find("%AI5_File:\n").unwrap();
assert!(text[..at].ends_with("0 0.5 1 0 k\n"), "{text}");
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let read = crate::import(&out.bytes).unwrap().document;
let mut found = vec![];
read.walk(|n| {
if let NodeKind::Image(im) = &n.kind {
found.push((read.image_blob(im).and_then(ImageBlob::coverage), n.extras().colorize.as_deref().cloned()));
}
});
let want: Vec<u8> = mask.iter().map(|&v| 255 - v).collect();
assert_eq!(found, [(Some((8, 2, want)), Some(paint.clone()))]);
// Gray pixels: the color at each pixel's strength, over white.
let mut doc = Document::new(200.0, 100.0);
doc.layers.clear();
let layer = doc.add_layer(Some("Art"));
let tint = colorized_image(&mut doc, (2, 1), vec![0, 128], &Paint::solid(Color::rgb(1.0, 0.0, 0.0)), (10.0, 10.0));
doc.insert(Some(layer), usize::MAX, tint).unwrap();
let out = write(&doc);
let text = String::from_utf8(out.bytes.clone()).unwrap();
let images = rasters(&text);
let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) };
assert!(xi.ends_with(" ] 0 0 2 1 2 1 8 3 0 0 0 0 XI"), "{xi}");
assert_eq!(data, &["%FF0000FF8080"], "{text}");
assert_eq!(out.warnings, [IMAGE_ALPHA]);
}
/// An image mask is only for a colorized image the writer draws as the document does: not one
/// with an opacity mask turned on, and not one with more pixels than the writer writes.
#[test]
fn image_masks_are_for_images_the_writer_draws_as_they_are() {
let mut doc = Document::new(200.0, 100.0);
let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
let mut n = colorized_image(&mut doc, (2, 1), vec![0, 255], &paint, (10.0, 10.0));
assert!(writes_image_mask(&doc, &n));
let art = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::gray(1.0)), Paint::None);
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, false)));
assert!(!writes_image_mask(&doc, &n));
if let Some(m) = n.extras_mut().mask.as_mut() {
m.disabled = true;
}
assert!(writes_image_mask(&doc, &n));
let big = colorized_image(&mut doc, (8193, 8193), vec![255; 8193 * 8193], &paint, (10.0, 10.0));
assert!(!writes_image_mask(&doc, &big));
}
#[test]
fn a_gradient_fill_and_its_stroke_are_one_object() {
let mut doc = Document::new(100.0, 100.0);
+61 -20
View File
@@ -272,7 +272,11 @@ impl<'a> Writer<'a> {
}
NodeKind::Image(im) => {
self.lock(locked);
self.image(self.doc.image_blob(im), im.width, im.height, im.xf);
let blob = self.doc.image_blob(im);
// A colorize color the renderer draws the image in.
let colorize =
n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize));
self.image(blob, im.width, im.height, im.xf, colorize);
}
NodeKind::SymbolInstance { symbol, xf } => {
self.warn(LIVE);
@@ -835,7 +839,7 @@ impl<'a> Writer<'a> {
// Colour bitmap glyphs (emoji): their images, which the runs' paint doesn't paint.
for g in &layout.glyphs {
if let Some((image, to_text)) = g.placed_image() {
self.image(Some(&image.blob), image.width, image.height, t.xf * to_text);
self.image(Some(&image.blob), image.width, image.height, t.xf * to_text, None);
}
// COLR glyphs: their layers, as art.
if let Some(art) = g.placed_colour(t.xf) {
@@ -853,8 +857,12 @@ impl<'a> Writer<'a> {
/// `%AI5_EndRaster`, then `F`. §8.4's examples have no `F`; without it, an app reading the file
/// can leave out an image in a clipping group and the art after it. No path is open there, so
/// the `F` paints nothing. `blob` holds the pixels, placed as a grid of `width` × `height`
/// by `xf`.
fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine) {
/// by `xf`, and `colorize` is the solid color the image is colorized with. A colorized image
/// whose pixels are all black or white is written as an image mask (ImageMask 1, §8.1): its
/// color as the fill, then 1-bit samples, a 0 bit for each black pixel, which takes the color,
/// and a 1 bit for each white pixel, which is clear. Another colorized image is written with
/// its color in its pixels.
fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<&Paint>) {
let flip = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
let m = self.to_art * xf * flip;
if !invertible(m) {
@@ -876,25 +884,61 @@ impl<'a> Writer<'a> {
// The object places the image's own pixel grid (its width × height) wherever the file's is.
let fit = Affine::scale_non_uniform(f64::from(width.max(1)) / f64::from(w), f64::from(height.max(1)) / f64::from(h));
let m = self.to_art * xf * fit * flip;
// Over white.
let over = |c: u8, a: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8;
if let Some(paint) = colorize {
let Some((_, _, coverage)) = blob.and_then(ImageBlob::coverage).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else {
self.warn(UNDECODED);
return;
};
if coverage.iter().all(|&v| v == 0 || v == 255) {
let stride = (w as usize).div_ceil(8);
let mut bits = vec![0xFF; stride.saturating_mul(h as usize)];
for (i, _) in coverage.iter().enumerate().filter(|(_, v)| **v == 255) {
let (x, y) = (i % w as usize, i / w as usize);
if let Some(byte) = bits.get_mut(y * stride + x / 8) {
*byte &= !(0x80 >> (x % 8));
}
}
self.color(paint, false);
self.raster(m, &format!("0 0 {w} {h} {w} {h} 1 1 0 0 0 1"), &bits);
return;
}
let rgb = paint.color().map_or([0; 3], |c| c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8));
let samples: Vec<u8> = coverage.iter().flat_map(|&a| rgb.map(|c| over(c, a))).collect();
self.warn(IMAGE_ALPHA);
self.raster(m, &format!("0 0 {w} {h} {w} {h} 8 3 0 0 0 0"), &samples);
return;
}
let rgba = img.to_rgba8();
let mut hex = String::with_capacity(rgba.len() / 4 * 7);
hex.push('%');
let mut on_line = 0;
let mut samples = Vec::with_capacity(rgba.len() / 4 * 3);
let mut see_through = false;
for px in rgba.pixels() {
let [r, g, b, a] = px.0;
if a < 255 {
see_through = true;
}
// Over white.
let over = |c: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8;
for c in [over(r), over(g), over(b)] {
let _ = write!(hex, "{c:02X}");
on_line += 2;
if on_line >= HEX_LINE {
hex.push_str("\n%");
on_line = 0;
}
samples.extend([over(r, a), over(g, a), over(b, a)]);
}
if see_through {
self.warn(IMAGE_ALPHA);
}
self.raster(m, &format!("0 0 {w} {h} {w} {h} 8 3 0 0 0 0"), &samples);
}
/// An image's lines (§8.4): `%AI5_File:`, `%AI5_BeginRaster`, matrix `m` as `[ a b c d tx ty ]`
/// and the numbers `operands` with `XI`, `samples` in hex on comment lines of [`HEX_LINE`]
/// digits, `%AI5_EndRaster`, then `F`.
fn raster(&mut self, m: Affine, operands: &str, samples: &[u8]) {
let mut hex = String::with_capacity(samples.len() * 2 + samples.len() / HEX_LINE * 2 + 2);
hex.push('%');
let mut on_line = 0;
for c in samples {
let _ = write!(hex, "{c:02X}");
on_line += 2;
if on_line >= HEX_LINE {
hex.push_str("\n%");
on_line = 0;
}
}
if hex.ends_with('%') {
@@ -902,14 +946,11 @@ impl<'a> Writer<'a> {
} else {
hex.push('\n');
}
if see_through {
self.warn(IMAGE_ALPHA);
}
let [a, b, c, d, e, f] = m.as_coeffs();
let s = &mut self.body;
s.push_str("%AI5_File:\n%AI5_BeginRaster\n[ ");
ps::push_nums(s, &[a, b, c, d, e, f]);
let _ = writeln!(s, "] 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 XI");
let _ = writeln!(s, "] {operands} XI");
s.push_str(&hex);
s.push_str("%AI5_EndRaster\nF\n");
}
+1 -1
View File
@@ -47,7 +47,7 @@ pub use import::{
AiLayers, Imported, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_layers_alone, family_style, import, import_trusting, import_with, is_loss,
layered_ai, layered_ai_from, page,
};
pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai};
pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask};
pub use print::{PrintJob, PrintPage, print};
use vectorcraft_doc::Document;
+1
View File
@@ -33,6 +33,7 @@ use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard};
mod entry;
mod exporter;
mod images;
mod links;
mod nodes;
mod paint;
mod text;
+11
View File
@@ -79,6 +79,16 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
// In PDF 1.6 and later files that aren't PDF/X files, a page with a side longer than
// [`MAX_PAGE_SIDE`] is written in larger units; other files have every page in points.
let scales = set.compatibility.has_user_unit() && !set.standard.is_pdfx();
// PDF/X files have no annotations over the art (ISO 15930: only printer's mark and trap
// network annotations, outside the bleed box): objects' URLs aren't written as links there.
let links = !set.standard.is_pdfx();
let mut linked = false;
for layer in doc.layers.iter().filter(|_| !links) {
layer.walk(&mut |n| linked |= n.url().is_some());
}
if linked {
warnings.push(format!("{} files have no links: the objects' URLs aren't clickable", set.standard.label()));
}
let mut units = Vec::with_capacity(pages.len());
let total = pages.len() as u64;
for (written, (i, boxes)) in pages.into_iter().enumerate() {
@@ -107,6 +117,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
clip: m != r,
marks: art.as_ref(),
negative: false,
links,
};
w.page(&mut ex, &sheet).map_err(|_| PdfError::BadArtboard(i))?;
}
+121
View File
@@ -0,0 +1,121 @@
//! The objects' URLs (Window › Attributes) as link annotations: a rectangle over each linked
//! object's bounds on the page that opens its URL (ISO 32000-1 §12.5.6.5 Link Annotations, with a
//! URI action, §12.6.4.7).
use super::{Affine, Exporter, Node, NodeKind, Rect, krilla};
/// Most links written on one page: the rest are left out with a warning.
pub(super) const MAX_LINKS: usize = 10_000;
/// The warning for the links left out past [`MAX_LINKS`].
pub(super) const TOO_MANY_LINKS: &str = "a page has more linked objects than a PDF page keeps links for: the rest aren't clickable";
/// Does a link open `uri`? Web and mail URLs only, the ones the app's Browser button opens: a URL
/// can come from an imported file, and a `javascript:` or `file:` one has no place in a PDF.
fn opens(uri: &str) -> bool {
let scheme = uri.trim().split_once(':').map_or("", |(s, _)| s);
["http", "https", "mailto"].iter().any(|k| scheme.eq_ignore_ascii_case(k))
}
/// A link to write: the URI it opens, and the area it covers in page space (y down).
pub(super) struct Link {
pub uri: String,
pub rect: Rect,
}
impl Exporter<'_> {
/// The links of the art drawn on a page: each linked object that shows (on a layer that
/// prints, or any layer when non-printing layers are written; not on a template layer), over
/// its bounds within the clipping groups it is in and within `area` (document space, the art
/// drawn), mapped onto the page by `to_page`. A group's link comes before its objects', so an
/// object's own link lies over it. The second value: links were left out past [`MAX_LINKS`].
pub(super) fn links(&self, area: Rect, to_page: Affine) -> (Vec<Link>, bool) {
let mut links = vec![];
let mut more = false;
for layer in &self.doc.layers {
self.link_node(layer, area, to_page, &mut links, &mut more);
}
(links, more)
}
fn link_node(&self, n: &Node, within: Rect, to_page: Affine, links: &mut Vec<Link>, more: &mut bool) {
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return;
}
if let NodeKind::Layer { template, printable, .. } = n.kind
&& (template || !(printable || self.non_printing))
{
return;
}
let bounds = n.visual_bounds_with(&self.symbols).filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()));
if let (Some(uri), Some(b)) = (n.url().filter(|u| opens(u)), bounds) {
let shown = b.intersect(within);
if shown.width() > 0.0 && shown.height() > 0.0 {
let rect = to_page.transform_rect_bbox(shown);
if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| !v.is_finite()) {
// Off any page a reader can show: no link.
} else if links.len() < MAX_LINKS {
links.push(Link { uri: uri_bytes(uri), rect });
} else {
*more = true;
}
}
}
// What a clipping group holds shows only inside its clipping path's bounds.
let within = match bounds {
Some(b) if n.clips() => b.intersect(within),
None if n.clips() => return,
_ => within,
};
if within.width() <= 0.0 || within.height() <= 0.0 {
return;
}
for child in n.children().into_iter().flatten() {
self.link_node(child, within, to_page, links, more);
}
}
}
/// `uri` as a PDF URI (ISO 32000-1 §12.6.4.7: 7-bit ASCII): spaces, control characters and
/// non-ASCII bytes percent-encoded (RFC 3986 §2.1), leading and trailing spaces dropped.
fn uri_bytes(uri: &str) -> String {
let mut out = String::with_capacity(uri.len());
for b in uri.trim().bytes() {
if b.is_ascii_graphic() {
out.push(char::from(b));
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
/// The annotation of `link`: a borderless rectangle that opens its URI.
pub(super) fn annotation(link: Link) -> Option<krilla::annotation::Annotation> {
let r = link.rect;
let rect = krilla::geom::Rect::from_ltrb(r.x0 as f32, r.y0 as f32, r.x1 as f32, r.y1 as f32)?;
let target = krilla::annotation::Target::Action(krilla::action::LinkAction::new(link.uri.clone()).into());
Some(krilla::annotation::Annotation::new_link(krilla::annotation::LinkAnnotation::new(rect, target), Some(link.uri)))
}
#[cfg(test)]
mod tests {
use super::{opens, uri_bytes};
#[test]
fn only_web_and_mail_urls_become_links() {
for ok in ["https://example.com/a", "HTTP://example.com", "mailto:someone@example.com", " https://example.com "] {
assert!(opens(ok), "{ok}");
}
for refused in ["javascript:alert(1)", "file:///etc/passwd", "smb://host/share", "ms-settings:", "example.com", ""] {
assert!(!opens(refused), "{refused}");
}
}
#[test]
fn uris_are_written_in_ascii() {
assert_eq!(uri_bytes(" https://example.com/a b "), "https://example.com/a%20b");
assert_eq!(uri_bytes("https://example.com/café"), "https://example.com/caf%C3%A9");
assert_eq!(uri_bytes("mailto:a@b.c?subject=x\ny"), "mailto:a@b.c?subject=x%0Ay");
}
}
+11
View File
@@ -51,6 +51,8 @@ pub(crate) struct Sheet<'a> {
pub marks: Option<&'a Node>,
/// Invert the page: paper black, ink clear (a film negative).
pub negative: bool,
/// The objects' URLs are written as links over them ([`super::links`]).
pub links: bool,
}
impl Writer {
@@ -190,6 +192,15 @@ impl Writer {
s.pop();
}
s.finish();
if fits && sheet.links {
let (links, more) = ex.links(r, sheet.view * sheet.place);
for annotation in links.into_iter().filter_map(super::links::annotation) {
page.add_annotation(annotation);
}
if more {
ex.warn(super::links::TOO_MANY_LINKS);
}
}
page.finish();
Ok(())
}
+2
View File
@@ -338,6 +338,8 @@ impl PlannedSheet {
clip: true,
marks: self.marks.as_ref(),
negative: self.negative,
// A printed sheet has no links to click.
links: false,
}
}
}
+1
View File
@@ -27,6 +27,7 @@ mod import_lines;
mod import_options;
mod import_overprint;
mod layers;
mod links;
pub(super) mod live_text;
mod marks;
mod mesh_export;
+119
View File
@@ -0,0 +1,119 @@
//! Objects with a URL (Window › Attributes) export as link annotations over their bounds that
//! open it; hidden ones and PDF/X files have none.
use std::sync::Arc;
use craft_pdf::syntax::Pdf;
use craft_pdf::syntax::object::{Array, Dict, Name};
use vectorcraft_color::Color;
use vectorcraft_doc::{Document, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
use super::{add, doc, rect_node};
use crate::*;
/// A rectangle over `r` linking to `url`.
fn linked(r: Rect, url: &str) -> Node {
let mut n = rect_node(r, Color::rgb(1.0, 0.0, 0.0));
n.edit_attrs(|a| a.url = url.into());
n
}
/// Each link annotation of each page: its URI and its rectangle (PDF space, y up).
fn links(pdf: &[u8]) -> Vec<Vec<(String, [f32; 4])>> {
let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap();
file.pages()
.iter()
.map(|page| {
let Some(annots) = page.raw().get::<Array<'_>>(b"Annots") else { return vec![] };
annots
.iter::<Dict<'_>>()
.filter(|a| a.get::<Name<'_>>(b"Subtype").is_some_and(|s| s.as_ref() == b"Link"))
.map(|a| {
let action = a.get::<Dict<'_>>(b"A").unwrap();
assert_eq!(action.get::<Name<'_>>(b"S").unwrap().as_ref(), b"URI");
let uri = action.get::<craft_pdf::syntax::object::String<'_>>(b"URI").unwrap().as_bytes().to_vec();
let r: Vec<f32> = a.get::<Array<'_>>(b"Rect").unwrap().iter::<f32>().collect();
(String::from_utf8(uri).unwrap(), [r[0], r[1], r[2], r[3]])
})
.collect()
})
.collect()
}
fn near(a: [f32; 4], b: [f32; 4]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01)
}
#[test]
fn a_linked_object_exports_a_link_over_its_bounds() {
let mut d = doc(200.0, 100.0);
add(&mut d, rect_node(Rect::new(0.0, 0.0, 5.0, 5.0), Color::rgb(0.0, 0.0, 1.0)));
add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/a b"));
for bytes in [export(&d, &PdfOptions::default()).unwrap(), export(&d, &PdfOptions::uncompressed()).unwrap()] {
let pages = links(&bytes);
assert_eq!(pages.len(), 1);
let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") };
// In ASCII, as a PDF URI is (the space percent-encoded).
assert_eq!(uri, "https://example.com/a%20b");
// y up from the page's bottom edge: 100 − 30 to 100 − 10.
assert!(near(*rect, [10.0, 70.0, 50.0, 90.0]), "{rect:?}");
}
}
#[test]
fn hidden_and_unprinted_objects_have_no_links_and_clipping_trims_them() {
let mut d = doc(200.0, 100.0);
let mut hidden = linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/hidden");
hidden.visible = false;
add(&mut d, hidden);
// Clipped to x 20…40: the link covers only what shows.
let clip = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 0.0, 40.0, 100.0)), Default::default());
let mut group = Node::group(NodeId(0), vec![Arc::new(clip), Arc::new(linked(Rect::new(0.0, 40.0, 200.0, 60.0), "https://example.com/clipped"))]);
group.set_clips(true);
let group = d.reid(&group);
add(&mut d, group);
// Off the artboard: nothing to click.
add(&mut d, linked(Rect::new(300.0, 10.0, 350.0, 30.0), "https://example.com/off"));
let pages = links(&export(&d, &PdfOptions::default()).unwrap());
let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") };
assert_eq!(uri, "https://example.com/clipped");
assert!(near(*rect, [20.0, 40.0, 40.0, 60.0]), "{rect:?}");
// A layer that doesn't print leaves its links out with its art.
let mut d = doc(200.0, 100.0);
add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/"));
if let vectorcraft_doc::NodeKind::Layer { printable, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
*printable = false;
}
assert_eq!(links(&export(&d, &PdfOptions::default()).unwrap()), vec![Vec::<(String, [f32; 4])>::new()]);
}
#[test]
fn each_page_links_its_own_artboard_objects() {
let mut d = doc(200.0, 100.0);
let mut second = d.artboards[0].clone();
second.id = 2;
second.rect = Rect::new(300.0, 0.0, 400.0, 100.0);
d.artboards.push(second);
add(&mut d, linked(Rect::new(310.0, 20.0, 330.0, 40.0), "mailto:a@example.com"));
let pages = links(&export(&d, &PdfOptions::default()).unwrap());
assert_eq!(pages[0], vec![]);
let [(uri, rect)] = pages[1].as_slice() else { panic!("one link: {pages:?}") };
assert_eq!(uri, "mailto:a@example.com");
assert!(near(*rect, [10.0, 60.0, 30.0, 80.0]), "{rect:?}");
}
#[test]
fn pdfx_files_have_no_links() {
let mut d: Document = doc(200.0, 100.0);
add(&mut d, linked(Rect::new(10.0, 10.0, 50.0, 30.0), "https://example.com/"));
let mut o = PdfOptions::default();
(o.settings.standard, o.settings.compatibility) = (Standard::PdfX4, Standard::PdfX4.version());
o.created = Some(1_700_000_000);
let report = export_with_report(&d, &o).unwrap();
assert_eq!(links(&report.bytes), vec![Vec::<(String, [f32; 4])>::new()]);
assert!(report.warnings.iter().any(|w| w.contains("URLs aren't clickable")), "{:?}", report.warnings);
// Without links, no such warning.
assert!(!export_with_report(&doc(200.0, 100.0), &o).unwrap().warnings.iter().any(|w| w.contains("URLs")));
}
+1
View File
@@ -21,6 +21,7 @@ pub(crate) fn blob_key(blob: &vectorcraft_doc::ImageBlob) -> (images::ImageKey,
luts: (lut.as_ref().map_or(0, |l| l.1), 0),
plates: 0,
mip: 0,
tile: None,
};
(key, lut.map(|l| l.0), id.size)
}
+4 -1
View File
@@ -236,7 +236,10 @@ impl Renderer {
bounds = fx.spread(before, space.line);
let outline = image_outline.as_ref().map(|g| (g, FillRule::NonZero)).or(content.outline);
match fx {
RasterFx::GaussianBlur { radius } => effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px),
RasterFx::GaussianBlur { radius, linear } => {
let blur = if *linear { effects::pixel::gaussian_rgba_linear } else { effects::pixel::gaussian_rgba };
blur(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px)
}
RasterFx::Feather { radius } => {
effects::pixel::gaussian_rgba(pm.data_as_u8_slice_mut(), wz, hz, radius / 2.0 / px);
if let Some((g, rule)) = outline {
+1 -1
View File
@@ -74,7 +74,7 @@ pub(super) fn hard_edged(chain: &[&RasterFx], px: f64) -> bool {
/// document's raster grid lines `line` apart; `None` when anywhere in the object.
pub(super) fn looks_around(fx: &RasterFx, line: f64) -> Option<f64> {
match fx {
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius),
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => Some(1.5 * radius),
RasterFx::Pixel(p) => p.reach(line),
RasterFx::Rasterize(r) => Some(r.reach()),
_ => Some(0.0),
+39 -2
View File
@@ -691,17 +691,54 @@ impl Renderer {
// The content itself (blurred / feathered / filtered), on its pixels: a filter layer's blur
// works on a coarser grid tied to the canvas, so the blurred art shifted by up to a pixel
// and looked blocky as the view moved by parts of a pixel (#755).
let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } if *radius > 0.0));
let blurs = rfx.iter().any(|fx| matches!(fx, RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } if *radius > 0.0));
if blurs || rfx.iter().any(|fx| matches!(fx, RasterFx::Pixel(_) | RasterFx::Rasterize(_))) {
self.pixel_content(ctx, f, content, rfx, paint);
} else {
paint(self, ctx, f);
}
// Above the content: inner glows, clipped to its outline.
// Above the content: inner glows, clipped to its outline. An image's glow follows its
// visible pixels, not its frame (#5308).
let Some((g, rule)) = content.outline else { return };
let pixels = matches!(content.node.kind, NodeKind::Image(_));
for fx in rfx {
let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue };
let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color));
if pixels {
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
if let Some((m, o)) = comp {
c.set_transform(Affine::IDENTITY);
c.push_layer(None, Some(blend_mode(m)), Some(o), None, None);
}
c.set_transform(fr.view);
c.set_fill_rule(fill_rule(rule));
c.push_clip_layer(g);
c.push_layer(None, None, None, None, Some(filter));
if !*center {
// Everything around the visible pixels, so the glow bleeds in from their edges.
let pad = blur * 2.0 + 4.0 * fr.px;
c.set_transform(fr.view);
c.set_paint(peniko::Color::BLACK);
c.fill_rect(&g.bounding_box().inflate(pad, pad));
c.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestOut)), None, None, None);
}
// The glow is cast by the pixels' alpha alone (the filter takes no color from them).
paint(r, c, fr);
if !*center {
c.pop_layer();
}
c.pop_layer();
// Only where the image shows, as much as it shows.
c.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestIn)), None, None, None);
paint(r, c, fr);
c.pop_layer();
c.pop_layer();
if comp.is_some() {
c.pop_layer();
}
});
continue;
}
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
// The blend layer goes outside the clip: a clip layer is isolated, so a blend
// inside it would mix with nothing instead of the content below.
+41
View File
@@ -1076,3 +1076,44 @@ fn photoshop_filters_on_content_larger_than_the_budget() {
assert!(lum(img.pixel(190, 100)) >= WHITE - 3 * 25, "{id}: outside {:?}", img.pixel(190, 100));
}
}
/// #5308: an image's Inner Glow follows its visible pixels, not its frame. A 40 × 40 image whose
/// left half is transparent and right half opaque black, on a black page, with a white glow from
/// the edges: the transparent half stays black, and the glow lights the opaque half's left edge
/// (inside the frame), on the single-threaded and the multithreaded renderer alike.
#[test]
fn an_image_inner_glow_follows_its_visible_pixels() {
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
let rgba: Vec<u8> = (0..40 * 40).flat_map(|i| if i % 40 < 20 { [0, 0, 0, 0] } else { [0, 0, 0, 255] }).collect();
let png = crate::encode::png::encode(&rgba, 40, 40, &Default::default()).unwrap();
let mut d = Document::new(100.0, 100.0);
d.images.insert("half".into(), ImageBlob::new("image/png", png));
let im = ImageObject {
key: "half".into(),
width: 40,
height: 40,
xf: Affine::translate((30.0, 30.0)),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
n.appearance.effects = vec![Effect {
id: "stylize.innerGlow".into(),
params: json!({"color": "#ffffff", "mode": "normal", "opacity": 100, "blur": 4}),
visible: true,
}];
d.insert(Some(d.layers[0].id), 0, n).unwrap();
let opts = RenderOptions { background: Some([0, 0, 0, 255]), ..Default::default() };
for threads in [0, 3] {
let mut r = Renderer::new();
r.threads = threads;
let img = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
for (x, y) in [(31, 50), (40, 31), (45, 50)] {
assert!(lum(img.pixel(x, y)) < 10, "threads {threads}: no glow on the transparent pixels at ({x}, {y}): {:?}", img.pixel(x, y));
}
assert!(lum(img.pixel(51, 50)) > 60, "threads {threads}: the glow lights the visible pixels' edge: {:?}", img.pixel(51, 50));
assert!(lum(img.pixel(68, 50)) > 60, "threads {threads}: and the frame's edge where the pixels reach it: {:?}", img.pixel(68, 50));
assert!(lum(img.pixel(60, 50)) < lum(img.pixel(51, 50)), "threads {threads}: fading inward");
}
}
+33 -1
View File
@@ -108,6 +108,8 @@ pub(crate) struct ImageKey {
pub plates: u64,
/// Halved this many times ([`half`]).
pub mip: u8,
/// A [`TILE`]-pixel square of the pixels (column, row), when only part of them is made.
pub tile: Option<(u16, u16)>,
}
/// A blob's content key and whether it holds CMYK inks, worked out once per blob allocation, and
@@ -413,6 +415,36 @@ fn mean(v: [u8; 4]) -> u8 {
((v.iter().map(|&c| u32::from(c)).sum::<u32>() + 2) / 4) as u8
}
/// The side of the squares whose colours are made one by one when only part of an image's
/// pixels show ([`ImageKey::tile`]): a large photo zoomed in on is separated, colorized or proofed
/// only where it shows.
pub(crate) const TILE: u32 = 1024;
/// The `w`×`h` pixels of `pm` from (`x`, `y`). `None` unless they lie inside `pm`.
pub(crate) fn crop(pm: &Pixmap, x: u32, y: u32, w: u32, h: u32) -> Option<Pixmap> {
let (pw, ph) = (u32::from(pm.width()), u32::from(pm.height()));
if w == 0 || h == 0 || x.checked_add(w)? > pw || y.checked_add(h)? > ph {
return None;
}
let (stride, x, w) = (pw as usize, x as usize, w as usize);
let rows = pm.data().chunks_exact(stride).skip(y as usize).take(h as usize);
let data: Vec<PremulRgba8> = rows.flat_map(|row| row.get(x..x + w).unwrap_or_default().iter().copied()).collect();
(data.len() == w * h as usize).then(|| Pixmap::from_parts(data, w as u16, h as u16))
}
/// `src` copied into `dst` with its top left at (`x`, `y`), as far as `dst` reaches.
pub(crate) fn paste(dst: &mut Pixmap, src: &Pixmap, x: usize, y: usize) {
let (dw, sw) = (usize::from(dst.width()), usize::from(src.width()));
let dst_rows = dst.data_mut().chunks_exact_mut(dw).skip(y);
for (to, from) in dst_rows.zip(src.data().chunks_exact(sw)) {
let row = to.get_mut(x..).unwrap_or_default();
let n = row.len().min(from.len());
if let (Some(to), Some(from)) = (row.get_mut(..n), from.get(..n)) {
to.copy_from_slice(from);
}
}
}
/// Pixels `pm` colorized with `rgb`: each pixel takes the color, as opaque as the pixel is dark
/// (255 less its Rec. 709 luma) times its alpha, so white pixels are transparent.
pub(crate) fn colorized(pm: &Pixmap, [r, g, b]: [u8; 3]) -> Pixmap {
@@ -448,7 +480,7 @@ mod tests {
use super::*;
fn key(content: &str) -> ImageKey {
ImageKey { content: content.into(), adjust: None, grey: false, tint: None, ink: Ink::Display, luts: (0, 0), plates: 0, mip: 0 }
ImageKey { content: content.into(), adjust: None, grey: false, tint: None, ink: Ink::Display, luts: (0, 0), plates: 0, mip: 0, tile: None }
}
#[test]
+8 -1
View File
@@ -395,11 +395,17 @@ pub(crate) fn cmyk_pixmap(blob: &ImageBlob, lut: &InkLut) -> Option<Pixmap> {
inks_pixmap(&blob.cmyk()?, lut)
}
/// Whether image pixels `key` are a CMYK image's inks as shown (not adjusted or greyscale), so
/// they paint those inks ([`key_inks`]).
pub(crate) fn shows_own_inks(key: &ImageKey) -> bool {
key.luts.0 != 0 && key.adjust.is_none() && !key.grey
}
/// The ink amounts behind image pixels `key` when they are CMYK image `blob`'s inks as shown (not
/// adjusted or greyscale): its own inks, halved as its pixels are to `key`'s mip
/// ([`images::half_inks`]). `None` for other pixels.
pub(crate) fn key_inks(key: &ImageKey, blob: Option<&ImageBlob>) -> Option<Inks> {
if key.luts.0 == 0 || key.adjust.is_some() || key.grey {
if !shows_own_inks(key) {
return None;
}
(0..key.mip).try_fold(blob?.cmyk()?, |inks, _| images::half_inks(&inks))
@@ -538,6 +544,7 @@ mod tests {
luts: (0, 0),
plates: 0,
mip: 0,
tile: None,
};
let pm =
Arc::new(Pixmap::from_parts(vec![PremulRgba8 { r: 204, g: 102, b: 51, a: 255 }, PremulRgba8 { r: 102, g: 51, b: 26, a: 128 }], 2, 1));
+3
View File
@@ -53,6 +53,9 @@ pub use vello_cpu;
pub struct Renderer {
/// Glyph geometry per text object, keyed by `Arc` identity like `geom` (see [`Self::text_geom_of`]).
texts: FrameCache<usize, (Arc<Node>, Arc<TextGeom>)>,
/// The latest cached glyph geometry for each text object id. A move changes the node's Arc
/// but not its glyphs in text space, so the old geometry can still be used after comparison.
text_ids: PtrMap<NodeId, usize>,
/// The [`vectorcraft_text::FontDb::generation`] `texts` was laid out with: type lays out
/// again when fonts are added or rescanned.
text_fonts: u64,
+27 -1
View File
@@ -101,6 +101,33 @@ impl<K: Hash + Eq + Clone, V, S: BuildHasher + Default> FrameCache<K, V, S> {
Some(&s.value)
}
/// Read an entry only when it matches `accept`; rejected entries keep their previous age so
/// another document's object with the same id cannot prevent their eviction.
pub(crate) fn get_if<Q>(&mut self, k: &Q, stamp: u64, accept: impl FnOnce(&V) -> bool) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let s = self.map.get_mut(k)?;
if !accept(&s.value) {
return None;
}
self.clock += 1;
(s.stamp, s.used) = (stamp, self.clock);
Some(&s.value)
}
/// Drop the entry for `k`.
pub(crate) fn remove<Q>(&mut self, k: &Q)
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
if let Some(s) = self.map.remove(k) {
self.bytes -= s.bytes;
}
}
/// Keep `value` (about `bytes` bytes) as `k`, used in frame `stamp`, replacing any entry for
/// `k`. Least recently used entries of earlier frames make room; returns false when they can't
/// (the value isn't kept then).
@@ -196,7 +223,6 @@ impl<K: Hash + Eq + Clone, V, S: BuildHasher + Default> FrameCache<K, V, S> {
self.bytes
}
#[cfg(test)]
pub(crate) fn contains_key<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
+2
View File
@@ -33,6 +33,7 @@ impl Renderer {
pub fn new() -> Self {
Self {
texts: FrameCache::new(lru::TEXT_BUDGET, 1024),
text_ids: PtrMap::default(),
text_fonts: 0,
clips: FrameCache::new(lru::CLIP_BUDGET, 256),
threads: default_threads(),
@@ -208,6 +209,7 @@ impl Renderer {
// Filtered rasters are large: only those of the last frame stay.
self.pixel_fx.retain(|_, e| e.stamp == g);
self.texts.sweep(g);
self.text_ids.retain(|_, key| self.texts.contains_key(key));
self.char_strokes.sweep(g);
self.clips.sweep(g);
self.clip_paints.sweep(g);
+132 -18
View File
@@ -71,45 +71,48 @@ impl Renderer {
}
}
}
kept
kept.map(Shown::whole)
} else if let Some(pm) = mips.then(|| self.kept_mip(f, &im.key, im.pixels.as_deref(), outline, tint, unit)).flatten() {
Some(pm)
Some(Shown::whole(pm))
} else {
self.image_pixmap(f.doc, &im.key, im.pixels.as_deref(), outline, !mips).map(|(key, pm)| {
// Shrunk first, so what is made of the pixels below is made of the ones drawn: a
// 141-megapixel photo is separated at the size it shows, not at its own (#4155).
let (key, pm) = if mips { image_mip(key, pm, unit) } else { (key, pm) };
let blob = f.doc.image_blob(im);
let (key, pm) = match tint {
Some(rgb) => colorized_pixmap(key, &pm, rgb),
None => (key, pm),
};
// A colorized image is already in the frame's ink ([`image_tint`]), and with
// Separations Preview its color is already the visible plates' (`proof::prepare`).
let (key, pm) = if outline || tint.is_some() { (key, pm) } else { ink::ink_image(&key, &pm, f.ink, blob, true) };
match f.plates.filter(|_| !outline && tint.is_none()) {
Some(lut) => proof::plate_image(lut, &key, &pm, blob, true).1,
None => pm,
// Zoomed in on it, only the tiles in view.
if let Some(window) = in_view(f, im, &key, &pm, outline, tint) {
return window_pixmap(f, &key, &pm, window, outline, tint, blob);
}
Shown::whole(shown_pixmap(f, key, pm, outline, tint, blob))
})
};
if let Some(pm) = shown {
let sx = im.width as f64 / pm.width().max(1) as f64;
let sy = im.height as f64 / pm.height().max(1) as f64;
if let Some(Shown { pm, level: (lw, lh), at: (ax, ay) }) = shown {
// The pixels drawn are `pm`, from (`ax`, `ay`) of the `lw`×`lh` pixels of the level.
let sx = im.width as f64 / f64::from(lw.max(1));
let sy = im.height as f64 / f64::from(lh.max(1));
let drawn = Affine::scale_non_uniform(sx, sy) * Affine::translate((f64::from(ax), f64::from(ay)));
let part = Rect::new(
f64::from(ax) * sx,
f64::from(ay) * sy,
f64::from(ax + u32::from(pm.width())) * sx,
f64::from(ay + u32::from(pm.height())) * sy,
)
.intersect(rect);
let quality = if f.opts.smooth_images && !pixelated { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low };
let sampler = peniko::ImageSampler { quality, ..Default::default() };
ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(pm), sampler });
match area {
Some((bp, rule)) => {
ctx.set_transform(f.view);
ctx.set_paint_transform(im.xf * Affine::scale_non_uniform(sx, sy));
ctx.set_paint_transform(im.xf * drawn);
ctx.set_fill_rule(fill_rule(*rule));
ctx.fill_path(bp);
}
None => {
ctx.set_transform(f.view * im.xf);
ctx.set_paint_transform(Affine::scale_non_uniform(sx, sy));
ctx.fill_rect(&rect);
ctx.set_paint_transform(drawn);
ctx.fill_rect(&part);
}
}
ctx.reset_paint_transform();
@@ -307,6 +310,117 @@ impl Renderer {
}
}
/// Image pixels [`Renderer::draw_image_in`] draws: `pm`, from (`at`) of the `level` pixels of the
/// mip drawn (all of them, or the tiles in view).
struct Shown {
pm: Arc<Pixmap>,
level: (u32, u32),
at: (u32, u32),
}
impl Shown {
/// All of the pixels of a level.
fn whole(pm: Arc<Pixmap>) -> Self {
let level = (u32::from(pm.width()), u32::from(pm.height()));
Self { pm, level, at: (0, 0) }
}
}
/// Image pixels `pm` (kept as `key`) as [`Renderer::draw_image_in`] draws them: in greyscale with
/// `grey` (the outline view's) or colorized with `tint` as they are, else painted with the frame's
/// ink and shown through its Separations Preview plates. Kept with the images under
/// [`shown_key`], and marked used there.
fn shown_pixmap(
f: &Frame,
key: images::ImageKey,
pm: Arc<Pixmap>,
grey: bool,
tint: Option<[u8; 3]>,
blob: Option<&vectorcraft_doc::ImageBlob>,
) -> Arc<Pixmap> {
let (key, pm) = match tint {
Some(rgb) => colorized_pixmap(key, &pm, rgb),
None => (key, pm),
};
// A colorized image is already in the frame's ink ([`image_tint`]), and with Separations
// Preview its color is already the visible plates' (`proof::prepare`).
if grey || tint.is_some() {
return pm;
}
let (key, pm) = ink::ink_image(&key, &pm, f.ink, blob, true);
match f.plates {
Some(lut) => proof::plate_image(lut, &key, &pm, blob, true).1,
None => pm,
}
}
/// The tiles of image pixels `pm` (kept as `key`, the level of image `im` drawn) in the frame's
/// view, as a range of columns and rows, when the pixels' colours are made again
/// ([`shown_pixmap`]: colorized, separated or proofed), more than one tile of them is made, and
/// some are out of view. `None` otherwise: all the pixels are made, as they are for a CMYK image's
/// own inks (made from the whole image's).
fn in_view(
f: &Frame,
im: &vectorcraft_doc::ImageObject,
key: &images::ImageKey,
pm: &Pixmap,
grey: bool,
tint: Option<[u8; 3]>,
) -> Option<([u32; 2], [u32; 2])> {
let made = !grey && (tint.is_some() || ink::ink_key(key, f.ink) != *key || f.plates.is_some());
let (w, h) = (u32::from(pm.width()), u32::from(pm.height()));
if !made || (w <= images::TILE && h <= images::TILE) || ink::shows_own_inks(key) {
return None;
}
// The view in the level's pixels, a couple wider for smoothing at its edge.
let to_level = (im.xf * Affine::scale_non_uniform(im.width as f64 / f64::from(w), im.height as f64 / f64::from(h))).inverse();
let v = f.visible;
let corners = [(v.x0, v.y0), (v.x1, v.y0), (v.x1, v.y1), (v.x0, v.y1)].map(|c| to_level * vectorcraft_geom::Point::from(c));
let (x0, x1) = corners.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| (a.min(p.x), b.max(p.x)));
let (y0, y1) = corners.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| (a.min(p.y), b.max(p.y)));
if ![x0, x1, y0, y1].iter().all(|v| v.is_finite()) {
return None;
}
let tiles = |lo: f64, hi: f64, n: u32| {
let last = n.saturating_sub(1) / images::TILE;
let at = |v: f64| ((v.clamp(0.0, f64::from(n.saturating_sub(1))) as u32) / images::TILE).min(last);
([at(lo - 2.0), at(hi + 2.0)], last)
};
let ((cols, last_col), (rows, last_row)) = (tiles(x0, x1, w), tiles(y0, y1, h));
// All of them in view: made whole, as without tiles.
(cols != [0, last_col] || rows != [0, last_row]).then_some((cols, rows))
}
/// The tiles `cols` × `rows` of image pixels `pm` (kept as `key`) as [`shown_pixmap`] makes them,
/// each made and kept on its own ([`images::ImageKey::tile`]), in one pixmap.
fn window_pixmap(
f: &Frame,
key: &images::ImageKey,
pm: &Pixmap,
(cols, rows): ([u32; 2], [u32; 2]),
grey: bool,
tint: Option<[u8; 3]>,
blob: Option<&vectorcraft_doc::ImageBlob>,
) -> Shown {
let (w, h) = (u32::from(pm.width()), u32::from(pm.height()));
let t = images::TILE;
let at = (cols[0] * t, rows[0] * t);
let size = (((cols[1] + 1) * t).min(w) - at.0, ((rows[1] + 1) * t).min(h) - at.1);
let mut window = Pixmap::new(size.0 as u16, size.1 as u16);
for (col, row) in (rows[0]..=rows[1]).flat_map(|r| (cols[0]..=cols[1]).map(move |c| (c, r))) {
let tile_key = images::ImageKey { tile: Some((col as u16, row as u16)), ..key.clone() };
let (x, y) = (col * t, row * t);
let made = lookup(&shown_key(f, tile_key.clone(), grey, tint), true).or_else(|| {
let part = images::crop(pm, x, y, t.min(w - x), t.min(h - y))?;
Some(shown_pixmap(f, tile_key, Arc::new(part), grey, tint, blob))
});
if let Some(made) = made {
images::paste(&mut window, &made, (x - at.0) as usize, (y - at.1) as usize);
}
}
Shown { pm: Arc::new(window), level: (w, h), at }
}
/// The key [`Renderer::draw_image_in`] gives the pixels it draws of image pixels `key`: in
/// greyscale with `grey` (the outline view's) or colorized with `tint` as they are, else painted
/// with the frame's ink and shown through its Separations Preview plates.
+17 -3
View File
@@ -313,11 +313,25 @@ impl Renderer {
}
#[cfg(test)]
STROKES_OUTLINED.with(|n| n.set(n.get() + 1));
// A long stroke without a width profile is outlined only in and around the view, with a
// margin of the view's own size on each side ([`crop_dashed`] for a dashed one,
// [`crop_line`] otherwise).
// A long stroke is outlined only in and around the view, with a margin of the view's
// own size on each side. Width profiles keep their positions on the whole path.
let region = v.inflate(v.width(), v.height());
let tol = 2f64.powi(level);
if crops()
&& line.elements().len() > CROP_ELEMENTS
&& st.dash.is_none()
&& width >= tol * 4.0
&& let Some(profile) = &st.profile
&& profile.points.iter().all(|(t, l, r)| t.is_finite() && l.is_finite() && r.is_finite())
{
let side = profile.points.iter().flat_map(|&(_, l, r)| [l, r]).fold(1.0_f64, f64::max);
let reach = crop_reach(st, width * side, f.px, tol);
if let Some(outline) = effects::stroke::line_outline_profile_near(line, st, width, tol, region.inflate(reach, reach)) {
let outline = Arc::new(outline);
self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), own }, moved);
return Some(outline);
}
}
if crops()
&& line.elements().len() > CROP_ELEMENTS
&& st.dash.is_some()
+37 -4
View File
@@ -151,20 +151,53 @@ impl Renderer {
let fonts = vectorcraft_text::FontDb::global().generation();
if fonts != self.text_fonts {
self.texts.clear();
self.text_ids.clear();
self.char_strokes.clear();
self.text_fonts = fonts;
}
let key = Arc::as_ptr(a) as usize;
if let Some((node, g)) = self.texts.get(&key, self.stamp)
&& Arc::ptr_eq(node, a)
{
if let Some((_, g)) = self.texts.get_if(&key, self.stamp, |(node, _)| Arc::ptr_eq(node, a)) {
return (g.clone(), true);
}
if let Some(&previous) = self.text_ids.get(&a.id)
&& let Some(g) = self
.texts
.get_if(&previous, self.stamp, |(node, _)| {
let NodeKind::Text(old) = &node.kind else { return false };
// Shrink Text to Fit searches document-point sizes, so a scale change can
// alter layout. Translation leaves the glyphs in text space unchanged.
if old.xf.as_coeffs()[..4] != t.xf.as_coeffs()[..4] {
return false;
}
let mut comparable = (**old).clone();
comparable.xf = t.xf;
comparable == *t
})
.map(|(_, g)| g.clone())
{
// Kept under this node from here on: the next frames find it without comparing.
self.texts.remove(&previous);
let kept = self.keep_text(a, g.clone());
return (g, kept);
}
let g = Arc::new(text_geom(t));
let kept = self.texts.insert(key, (a.clone(), g.clone()), g.bytes(), self.stamp);
let kept = self.keep_text(a, g.clone());
(g, kept)
}
/// Keep glyph geometry `g` of text node `a`, as the latest of its id. Whether it was kept.
fn keep_text(&mut self, a: &Arc<Node>, g: Arc<TextGeom>) -> bool {
let key = Arc::as_ptr(a) as usize;
let bytes = g.bytes();
let kept = self.texts.insert(key, (a.clone(), g), bytes, self.stamp);
if kept {
self.text_ids.insert(a.id, key);
} else {
self.text_ids.remove(&a.id);
}
kept
}
/// Draw type `n` (`t`, laid out in `g`). The outlines of its character strokes are cached
/// when `g` is kept in `texts` (`kept`).
pub(super) fn draw_text_geom(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc<TextGeom>, kept: bool) {
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff. Show more