diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 0000000000..de64ad3ee4 --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 0d33612d5c..58ab2d6d27 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ + +## 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. + + +## 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. + + # 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. diff --git a/ASSETS.md b/ASSETS.md index e4a17c7640..b6f5fa007f 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/CLAUDE.md b/CLAUDE.md index 17783d9a1f..43c994c2d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/Cargo.lock b/Cargo.lock index 0d3c1f19e0..5135ab569c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6100,6 +6100,7 @@ dependencies = [ "serde_json", "smithay-clipboard", "socket2", + "tempfile", "vectorcraft-engine", "vectorcraft-render", "vectorcraft-text", @@ -6163,6 +6164,7 @@ dependencies = [ "objc2-core-foundation", "objc2-core-text", "serde_json", + "tempfile", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-engine", @@ -6469,6 +6471,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-geom", + "vectorcraft-pathops", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/ROADMAP.md b/ROADMAP.md index 16bd8b1dab..74909b123a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,8 @@ # VectorCraft Roadmap +- Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. +- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. + - Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. - PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. @@ -11,7 +14,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -104,7 +107,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta | English | `en` | full | 100% | | Simplified Chinese | `zh-hans` | partial (messages in English) | 85% | | Spanish | `es` | full | 100% | -| Hindi | `hi` | none | 0% | +| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner | | Arabic | `ar` | none (no right-to-left interface) | 0% | | French | `fr` | full | 100% | | Portuguese (Brazil) | `pt-br` | full | 100% | @@ -131,6 +134,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). @@ -219,6 +223,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | +| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | | 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | | 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. | | 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. | diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 8f39e3b58d..f7faf7a924 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -45,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features = objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] } [dev-dependencies] +tempfile = "3" vectorcraft-testkit = { workspace = true } serde_json = { workspace = true } diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b7334586ca..2d8df45926 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -2,9 +2,9 @@ //! //! ```text //! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] //! vectorcraft-cli commands -//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] +//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] //! vectorcraft-cli info FILE //! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5] //! vectorcraft-cli perf [--paths 50000] [--deep] @@ -81,11 +81,12 @@ USAGE: allowed, and a kind left out grants none of its access. They imply --headless: a running app enforces its own (vectorcraft --control PORT --automation-read-root DIR …). - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE - is a template, written as file.saveAsTemplate writes it). --scale sizes raster exports - (pixels per point, default 1); other formats leave it out. Prints one JSON result per step. + is a template, written as file.saveAsTemplate writes it). Raster exports use the document's + raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins + over --scale) is given; other formats leave them out. Prints one JSON result per step. --commands reads steps from FILE, or from standard input for -, where it stands among the --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. @@ -94,10 +95,10 @@ USAGE: vectorcraft-cli commands Print the command catalogue as JSON. - vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] + vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] Open IN (any readable format) and export OUT in the format its extension picks (see Writable - formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it - out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard + formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects + resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard unless one of them is given, EPS the bounds of the art, the other formats the first artboard. A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with --artboard or --range). @@ -279,13 +280,15 @@ fn commands() -> Result<(), String> { } fn convert(args: &[String]) -> Result<(), String> { - let valued = ["--scale", "-s", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"]; + let valued = + ["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"]; if help_requested(args, &valued) { return help(); } let mut files = vec![]; let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = - (1.0f64, None::, None::, false, false, false, false); + (None::, None::, None::, false, false, false, false); + let mut ppi = None::; let mut decimals = None::; // Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`, // `transparentImages`); the engine checks their values. @@ -293,7 +296,15 @@ fn convert(args: &[String]) -> Result<(), String> { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { - "--scale" | "-s" => scale = it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?, + "--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), + "--ppi" => { + ppi = Some( + it.next() + .and_then(|v| v.parse().ok()) + .filter(|n: &f64| n.is_finite() && *n > 0.0) + .ok_or("--ppi needs a positive finite number")?, + ); + } "--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?), "--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?), "--outline-text" => outline_text = true, @@ -326,7 +337,7 @@ fn convert(args: &[String]) -> Result<(), String> { // A conversion keeps hidden layers and objects, written hidden, where the format can (SVG, // PSD). let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy}); - let mut params = with_pixel_scale(params, &output, scale); + let mut params = with_pixel_scale(params, &output, scale, ppi); if let Some(decimals) = decimals { params["decimals"] = json!(decimals); } @@ -372,12 +383,17 @@ fn is_template(path: &str) -> bool { vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait") } -/// The export `params` for `path`, with `--scale` (pixels per point) when its format is raster. +/// The export `params` for `path`, with explicit raster resolution options only for raster formats. /// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave /// its units unset. -fn with_pixel_scale(mut params: Value, path: &str, scale: f64) -> Value { +fn with_pixel_scale(mut params: Value, path: &str, scale: Option, ppi: Option) -> Value { if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) { - params["scale"] = json!(scale); + if let Some(scale) = scale { + params["scale"] = json!(scale); + } + if let Some(ppi) = ppi { + params["ppi"] = json!(ppi); + } } params } @@ -485,7 +501,7 @@ fn command_step(v: Value) -> Result { } fn run(args: &[String]) -> Result<(), String> { - let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s"]; + let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"]; if help_requested(args, &valued) { return help(); } @@ -494,7 +510,8 @@ fn run(args: &[String]) -> Result<(), String> { // The step of the `--cmd` just given, which a `--params` sets. let mut params_for: Option = None; let mut stdin_read = false; - let mut scale = 1.0; + let mut scale = None::; + let mut ppi = None::; let mut it = args.iter(); while let Some(a) = it.next() { let mut val = |what: &str| it.next().cloned().ok_or_else(|| format!("{a} needs {what}")); @@ -531,7 +548,16 @@ fn run(args: &[String]) -> Result<(), String> { } "--scale" | "-s" => { let raw = val("a number")?; - scale = raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?; + scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); + } + "--ppi" => { + let raw = val("a number")?; + ppi = Some( + raw.parse::() + .ok() + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?, + ); } other => return Err(format!("unknown run option `{other}`")), } @@ -576,7 +602,7 @@ fn run(args: &[String]) -> Result<(), String> { let r = if is_template(&path) { h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}})) } else { - h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale)) + h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi)) }; let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs index 33815fbf36..3ff82512d8 100644 --- a/apps/vectorcraft-cli/src/perf.rs +++ b/apps/vectorcraft-cli/src/perf.rs @@ -187,6 +187,48 @@ fn budget_row(name: &str, ms: f64, budget: f64, ok: bool) -> String { format!(" {name:<42} {ms:>8.2} ms {budget:>7.0} ms {}", if ok { "ok" } else { "OVER" }) } +/// Tracked rows for pointing at things in an n-path document: what hovering, clicking, marquee +/// selection and snapping cost when nothing narrows the search. +fn pointing(n: usize, rows: &mut Vec<(String, f64)>) -> Result<(), String> { + use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; + let err = |e: vectorcraft_engine::EngineError| e.to_string(); + let mut s = vectorcraft_engine::Session::new(); + s.add_document(synthetic(n)?, None); + let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() }; + s.select_tool("selection", view).map_err(err)?; + // Off the art (nothing under the pointer), the case every hover over empty canvas pays. + let off = Point::new(-200.0, -200.0); + let hover = |s: &mut vectorcraft_engine::Session| { + let _ = s.pointer(&PointerEvent::new(PointerKind::Move, off.x, off.y), view); + let _ = s.cursor(off, Mods::default(), view); + }; + rows.push((format!("hover over empty canvas ({n} paths)"), median_ms(5, || hover(&mut s)))); + s.execute("select.all", &json!({})).map_err(err)?; + rows.push((format!("hover over empty canvas, all selected ({n} paths)"), median_ms(5, || hover(&mut s)))); + let doc = s.doc().map_err(err)?.doc.clone(); + rows.push((format!("hit test, a miss ({n} paths)"), median_ms(5, || drop(hit::hit_test(&doc, off, hit::HitOptions::default()))))); + let r = Rect::new(600.0, 450.0, 1000.0, 750.0); + rows.push((format!("marquee 400×300 ({n} paths)"), median_ms(5, || drop(hit::marquee(&doc, r, None, false))))); + let view_rect = Rect::new(0.0, 0.0, 1600.0, 1200.0); + rows.push(( + format!("smart guide targets in view ({n} paths)"), + median_ms(5, || drop(vectorcraft_engine::tools::guides::Targets::collect(&doc, &[], Some(view_rect)))), + )); + // Adding one more object to a selection of half the document: the command a shift-click ends + // in, without the pointer handling and hit test before it. + let ids: Vec = doc.layers[0].children().map(|c| c.iter().map(|n| n.id.0).collect()).unwrap_or_default(); + s.execute("select.set", &json!({"ids": ids[..ids.len() / 2]})).map_err(err)?; + let mut k = ids.len() / 2; + rows.push(( + format!("select.toggle in a {}-object selection", ids.len() / 2), + median_ms(5, || { + k += 1; + let _ = s.execute("select.toggle", &json!({"id": ids[k % ids.len()]})); + }), + )); + Ok(()) +} + /// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole /// selection, live effects, every Pathfinder operation, typing in a long story, and memory, with /// the peak so far where `rss_mb` reads one. @@ -282,6 +324,8 @@ fn deep(n: usize) -> Result<(), String> { }), )); note("after typing"); + pointing(n, &mut rows)?; + note("after pointing"); // Four embedded 24 MP photos drawn at fit page by three renderers, as the app's canvas, render // worker and a panel each draw them. { diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 1423b78b42..c60357b5f8 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -105,6 +105,38 @@ fn images_open_at_their_pixel_size() { assert_eq!(&std::fs::read(&png).unwrap()[16..24], [0, 0, 0, 6, 0, 0, 0, 4], "IHDR 6×4"); } +#[test] +fn raster_exports_use_document_resolution_unless_overridden() { + let source = tmp("resolution.vectorcraft"); + ok(&["run", "--cmd", "file.new", "--params", r#"{"width":72,"height":36,"rasterEffectsPpi":300}"#, "--export", &source]); + for (flags, width, height) in [(vec![], 300u32, 150u32), (vec!["--scale", "1"], 72, 36), (vec!["--ppi", "150", "--scale", "2"], 150, 75)] { + for mode in ["run", "convert"] { + for format in ["png", "psd"] { + let path = tmp(&format!("resolution-{mode}-{width}.{format}")); + let mut args = if mode == "run" { vec!["run", "--in", &source, "--export", &path] } else { vec!["convert", &source, &path] }; + args.extend_from_slice(&flags); + ok(&args); + let bytes = std::fs::read(&path).unwrap(); + let dimensions = if format == "png" { &bytes[16..24] } else { &bytes[14..22] }; + let expected = + if format == "png" { [width.to_be_bytes(), height.to_be_bytes()] } else { [height.to_be_bytes(), width.to_be_bytes()] }; + assert_eq!(dimensions, expected.concat(), "{args:?}"); + } + } + } +} + +#[test] +fn raster_export_rejects_invalid_ppi() { + for ppi in ["0", "-150", "NaN", "inf", "high"] { + for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] { + let out = Command::new(BIN).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}"); + } + } +} + #[test] fn help_lists_readable_formats() { let out = ok(&["--help"]); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index f462132317..170a7e5c73 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -119,6 +119,7 @@ zbus = "=5.19.0" winresource = "0.1" [dev-dependencies] +tempfile = "3" # Bound socket buffers in real loopback transport deadline regressions. socket2 = { workspace = true } # src/portal_save.rs's tests build and read the portal's D-Bus values on every system. diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 1c0b4cd3c8..b9be306898 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -978,10 +978,17 @@ mod tests { use super::*; - fn dir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id())); - std::fs::create_dir_all(&d).unwrap(); - d + fn dir(name: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("vectorcraft-clipboard-{name}-")).tempdir().unwrap() + } + + #[test] + fn test_directory_is_removed_when_its_handle_is_dropped() { + let dir = dir("cleanup"); + let path = dir.path().to_path_buf(); + assert!(path.exists()); + drop(dir); + assert!(!path.exists()); } fn png(w: u32, h: u32) -> Vec { @@ -993,12 +1000,12 @@ mod tests { #[test] fn the_first_copied_file_that_is_art_pastes() { let d = dir("art"); - let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg")); + let (notes, red, art) = (d.path().join("notes.txt"), d.path().join("red image.png"), d.path().join("art.svg")); std::fs::write(¬es, "not art").unwrap(); std::fs::write(&red, png(3, 2)).unwrap(); std::fs::write(&art, "").unwrap(); // Missing files, folders and text are skipped. - let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap(); + let f = copied_file(vec![d.path().join("gone.png"), d.path().to_path_buf(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap(); assert_eq!((f.mime, f.data), (PNG, png(3, 2))); assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG)); // Only what Paste asks for. @@ -1032,7 +1039,8 @@ mod tests { /// An .eps file copied in a file manager pastes as EPS. #[test] fn a_copied_eps_file_pastes() { - let eps = dir("eps").join("equation.eps"); + let d = dir("eps"); + let eps = d.path().join("equation.eps"); std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap(); assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS)); assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none()); @@ -1040,7 +1048,8 @@ mod tests { #[test] fn a_crlf_left_by_the_uri_list_is_ignored() { - let red = dir("crlf").join("red.png"); + let d = dir("crlf"); + let red = d.path().join("red.png"); std::fs::write(&red, png(2, 2)).unwrap(); let with_cr = PathBuf::from(format!("{}\r", red.display())); assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG)); diff --git a/apps/vectorcraft/src/compositor_gpu.rs b/apps/vectorcraft/src/compositor_gpu.rs index 90e675b7f0..a5d6ae85e8 100644 --- a/apps/vectorcraft/src/compositor_gpu.rs +++ b/apps/vectorcraft/src/compositor_gpu.rs @@ -150,18 +150,16 @@ mod tests { #[cfg(target_os = "linux")] #[test] fn the_gpu_behind_a_device_number_comes_from_sysfs() -> std::io::Result<()> { - let dir = std::env::temp_dir().join(format!("vectorcraft-dev-char-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = tempfile::Builder::new().prefix("vectorcraft-dev-char-").tempdir()?; // /sys/dev/char/226:128 links to the render node, whose `device` is the PCI GPU. - std::fs::create_dir_all(dir.join("226:128/device"))?; - std::fs::write(dir.join("226:128/device/vendor"), "0x10de\n")?; - std::fs::write(dir.join("226:128/device/device"), "0x25ac\n")?; + std::fs::create_dir_all(dir.path().join("226:128/device"))?; + std::fs::write(dir.path().join("226:128/device/vendor"), "0x10de\n")?; + std::fs::write(dir.path().join("226:128/device/device"), "0x25ac\n")?; // A device that isn't a PCI GPU (a virtual one) has no ids. - std::fs::create_dir_all(dir.join("226:0/device"))?; - let render = super::pci_ids(&dir, makedev(226, 128)); - let virtual_gpu = super::pci_ids(&dir, makedev(226, 0)); - let missing = super::pci_ids(&dir, makedev(226, 1)); - std::fs::remove_dir_all(&dir)?; + std::fs::create_dir_all(dir.path().join("226:0/device"))?; + let render = super::pci_ids(dir.path(), makedev(226, 128)); + let virtual_gpu = super::pci_ids(dir.path(), makedev(226, 0)); + let missing = super::pci_ids(dir.path(), makedev(226, 1)); assert_eq!(render, Some((0x10de, 0x25ac))); assert_eq!(virtual_gpu, None); assert_eq!(missing, None); diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 40d84934f3..40e6a555c5 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -242,8 +242,8 @@ fn internal_panels_are_edp_lvds_and_dsi_connectors() { /// PCI ids. Each GPU is listed once, the one with the panel as primary. #[test] fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> { - let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let temp = tempfile::Builder::new().prefix("vectorcraft-drm-").tempdir()?; + let dir = temp.path(); let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> { std::fs::create_dir_all(dir.join(name).join("device"))?; std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?; @@ -262,11 +262,11 @@ fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<() connector("card1-DP-2", "connected")?; connector("card2-Virtual-1", "connected")?; std::fs::write(dir.join("renderD128"), "")?; - let mut gpus = linux_display_gpus(&dir); + let mut gpus = linux_display_gpus(dir); gpus.sort_by_key(|g| g.pci); assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]); assert!(linux_display_gpus(&dir.join("no such dir")).is_empty()); - std::fs::remove_dir_all(&dir) + Ok(()) } #[test] @@ -616,11 +616,26 @@ fn a_normal_exit_or_another_failure_does_not_restart() { /// A log folder of its own for each test, and the guard that keeps other tests from starting a /// program while it runs: the test releases the start file's lock and takes it again, and a child /// starting meanwhile would keep it held (`crate::no_spawns`). -fn start_dir(tag: &str) -> (std::path::PathBuf, std::sync::RwLockReadGuard<'static, ()>) { +struct TestDir(tempfile::TempDir); + +impl std::ops::Deref for TestDir { + type Target = std::path::Path; + + fn deref(&self) -> &Self::Target { + self.0.path() + } +} + +impl AsRef for TestDir { + fn as_ref(&self) -> &std::path::Path { + self.0.path() + } +} + +fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) { let spawns = crate::no_spawns(); - let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - (d, spawns) + let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap(); + (TestDir(dir), spawns) } /// What a start in `dir` leaves out; it then ends without crashing. @@ -670,7 +685,6 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept"); assert_eq!(left_out.crash, None, "the note is shown once"); third.ended(); - let _ = std::fs::remove_dir_all(&dir); } /// A start whose first frame reached the screen, or that ended without crashing (a normal exit, @@ -693,7 +707,6 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { assert!(finish(Ok(Ok(())), &first).is_ok()); drop(first); assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); } /// The process ended while the adapters were being listed (wgpu's DX12 backend creates a @@ -721,7 +734,6 @@ fn a_crash_while_listing_lists_opengl_alone() { second.none_left(); second.ended(); assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); } /// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that @@ -742,7 +754,6 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() { explicit.picked(&c[0].key, &c[0].name, true); explicit.presented(); assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window"); - let _ = std::fs::remove_dir_all(&dir); } /// A damaged record, a file that can't be opened and one another starting copy of the app holds @@ -777,10 +788,9 @@ fn a_damaged_or_unreadable_start_file_is_ignored() { assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]); // A folder in the file's place. - let _ = std::fs::remove_dir_all(&dir); + std::fs::remove_file(dir.join(START_FILE)).unwrap(); std::fs::create_dir_all(dir.join(START_FILE)).unwrap(); assert_eq!(next_start(&dir, false), LeftOut::default()); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 2ca282d74c..978308b9e5 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -198,6 +198,30 @@ fn read_file_refuses_what_is_not_a_regular_file() { assert!(read_file("/dev/zero").is_err()); } +/// Read the first `max` bytes of a file (all of it when it is shorter), and nothing past them. Only +/// a regular file is read. +fn read_file_head(path: &str, max: usize) -> Result, String> { + use std::io::Read; + if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() { + return Err(format!("{path}: not a file")); + } + let mut out = vec![]; + std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| e.to_string())?; + Ok(out) +} + +#[cfg(test)] +#[test] +fn read_file_head_reads_no_more_than_it_is_asked_for() { + use std::io::Write as _; + let mut f = tempfile::Builder::new().prefix("vectorcraft-read-head-").tempfile().unwrap(); + f.write_all(b"0123456789").unwrap(); + let p = f.path().to_string_lossy(); + assert_eq!(read_file_head(&p, 4).unwrap(), b"0123"); + assert_eq!(read_file_head(&p, 20).unwrap(), b"0123456789", "a shorter file is read whole"); + assert!(read_file_head(&std::env::temp_dir().to_string_lossy(), 4).is_err(), "a folder is not read"); +} + /// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]). fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) @@ -325,6 +349,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { #[cfg(windows)] stylus: Some(windows_stylus::start()), read: Some(Box::new(read_file)), + // Load Actions… refuses a file over its size limit without reading all of it. + read_head: Some(Box::new(read_file_head)), write: Some(Box::new(write_file)), exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())), // Background Save and Export write from a worker thread. @@ -569,22 +595,20 @@ mod open_with_tests { use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates}; /// A fresh, empty folder under the system's temporary folder. - fn scratch(name: &str) -> std::path::PathBuf { - let d = std::env::temp_dir().join(format!("vc-open-with-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d + fn scratch(name: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap() } /// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing /// path. #[test] fn only_applications_are_started() { - let d = scratch("check"); + let temp = scratch("check"); + let d = temp.path(); let doc = d.join("notes.txt"); std::fs::write(&doc, "hi").unwrap(); assert!(check_app(&doc).is_err(), "a document"); - assert!(check_app(&d).is_err(), "a folder"); + assert!(check_app(d).is_err(), "a folder"); assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path"); if cfg!(target_os = "macos") { let app = d.join("Editor.app"); @@ -600,19 +624,19 @@ mod open_with_tests { std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); assert!(check_app(&tool).is_ok(), "an executable file"); } - let _ = std::fs::remove_dir_all(&d); } /// PhotoCraft is looked for only where it installs. #[test] fn photocraft_is_found_where_it_installs() { - let d = scratch("find"); + let temp = scratch("find"); + let d = temp.path(); if cfg!(target_os = "macos") { - let candidates = photocraft_candidates(Some(&d), None); + let candidates = photocraft_candidates(Some(d), None); assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app")); assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}"); std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap(); - assert!(find_photocraft(Some(&d), None).unwrap().ends_with("PhotoCraft.app")); + assert!(find_photocraft(Some(d), None).unwrap().ends_with("PhotoCraft.app")); } else { let bin = d.join("bin"); std::fs::create_dir_all(&bin).unwrap(); @@ -636,7 +660,6 @@ mod open_with_tests { assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe)); } } - let _ = std::fs::remove_dir_all(&d); } /// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it diff --git a/apps/vectorcraft/src/logging/tests.rs b/apps/vectorcraft/src/logging/tests.rs index a1b54b353a..78b08a67b3 100644 --- a/apps/vectorcraft/src/logging/tests.rs +++ b/apps/vectorcraft/src/logging/tests.rs @@ -1,12 +1,29 @@ use super::*; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, UNIX_EPOCH}; -fn temp_dir(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - d +struct TestPath { + _parent: tempfile::TempDir, + path: PathBuf, +} + +impl std::ops::Deref for TestPath { + type Target = Path; + + fn deref(&self) -> &Self::Target { + &self.path + } +} + +impl AsRef for TestPath { + fn as_ref(&self) -> &Path { + &self.path + } +} + +fn temp_dir(tag: &str) -> TestPath { + let parent = tempfile::Builder::new().prefix(&format!("vectorcraft-logging-{tag}-")).tempdir().unwrap(); + let path = parent.path().join("log"); + TestPath { _parent: parent, path } } fn read(path: &Path) -> String { diff --git a/apps/vectorcraft/src/mac_fonts.rs b/apps/vectorcraft/src/mac_fonts.rs index a1b5b193c5..36223c559f 100644 --- a/apps/vectorcraft/src/mac_fonts.rs +++ b/apps/vectorcraft/src/mac_fonts.rs @@ -63,11 +63,10 @@ mod tests { /// fonts, is listed while it is registered. #[test] fn fonts_registered_from_other_folders_are_listed() { - let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap(); // A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS // installs. - let file = dir.join("Registered Font.ttf"); + let file = dir.path().join("Registered Font.ttf"); std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap(); let want = std::fs::canonicalize(&file).unwrap(); let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want)); @@ -78,7 +77,6 @@ mod tests { let registered = listed(); // SAFETY: as above. unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) }; - std::fs::remove_dir_all(&dir).unwrap(); assert!(registered); } } diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index a6daacb83a..f03572ebb2 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -335,13 +335,11 @@ mod tests { #[test] fn a_kept_preferences_copy_is_owner_only() { use std::os::unix::fs::PermissionsExt as _; - let dir = std::env::temp_dir().join(format!("vc-prefs-copy-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap(); + let dir = temp.path(); super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable"); let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 8ef0355831..0048323f03 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -192,7 +192,22 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) { #[cfg(test)] mod tests { use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + + struct TestDir(tempfile::TempDir); + + impl std::ops::Deref for TestDir { + type Target = Path; + + fn deref(&self) -> &Self::Target { + self.0.path() + } + } + + impl AsRef for TestDir { + fn as_ref(&self) -> &Path { + self.0.path() + } + } fn environment(key: &str) -> Option { match key { @@ -287,12 +302,8 @@ mod tests { assert_eq!(install_dir("macos", mounted, &appimage), Some("/tmp/.mount_vc/usr/bin".into())); } - fn temp(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("vectorcraft-profile-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d + fn temp(tag: &str) -> TestDir { + TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-profile-{tag}-")).tempdir().unwrap()) } #[test] diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index f7026131c9..5ced4aef33 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -263,15 +263,23 @@ mod tests { use super::*; + struct TestDir(tempfile::TempDir); + + impl std::ops::Deref for TestDir { + type Target = Path; + + fn deref(&self) -> &Self::Target { + self.0.path() + } + } + /// A fresh folder for one test, with an existing file in it. - fn folder(name: &str) -> (PathBuf, PathBuf, String) { - let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - let file = dir.join("a b.svg"); + fn folder(name: &str) -> (PathBuf, TestDir, String) { + let dir = tempfile::Builder::new().prefix(&format!("vc-single-instance-{name}-")).tempdir().unwrap(); + let file = dir.path().join("a b.svg"); fs::write(&file, "").unwrap(); let file = file.to_string_lossy().into_owned(); - (dir.join(FILE_NAME), dir, file) + (dir.path().join(FILE_NAME), TestDir(dir), file) } fn primary(path: &Path) -> (Primary, mpsc::Receiver>) { @@ -303,12 +311,11 @@ mod tests { assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); drop(primary); assert!(!path.exists(), "the endpoint file goes with the app"); - let _ = fs::remove_dir_all(dir); } #[test] fn a_wrong_token_garbage_and_oversized_messages_are_refused() { - let (path, dir, file) = folder("refused"); + let (path, _dir, file) = folder("refused"); let (_primary, rx) = primary(&path); let token = read_endpoint(&path).unwrap().token; let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] })); @@ -323,12 +330,11 @@ mod tests { // The listener still serves a launch with the right token. forward(&path, std::slice::from_ref(&file)).unwrap(); assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); - let _ = fs::remove_dir_all(dir); } #[test] fn a_stale_endpoint_file_is_ignored_and_replaced() { - let (path, dir, file) = folder("stale"); + let (path, _dir, file) = folder("stale"); // The recorded app is gone: whatever holds the port closes without a greeting. (A freed // port can be taken by another test's listener meanwhile, which would then accept this // connection in place of its own client's.) @@ -357,18 +363,16 @@ mod tests { let (_primary, rx) = primary(&path); forward(&path, std::slice::from_ref(&file)).unwrap(); assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]); - let _ = fs::remove_dir_all(dir); } #[test] fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() { - let (path, dir, _) = folder("replaced"); + let (path, _dir, _) = folder("replaced"); let (first, _rx1) = primary(&path); let (_second, _rx2) = primary(&path); let second_token = read_endpoint(&path).unwrap().token; drop(first); assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token)); - let _ = fs::remove_dir_all(dir); } #[test] @@ -383,9 +387,8 @@ mod tests { #[test] fn the_endpoint_file_is_the_users_alone() { use std::os::unix::fs::PermissionsExt as _; - let (path, dir, _) = folder("mode"); + let (path, _dir, _) = folder("mode"); let _primary = primary(&path); assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); - let _ = fs::remove_dir_all(dir); } } diff --git a/apps/vectorcraft/src/system_fonts.rs b/apps/vectorcraft/src/system_fonts.rs index 67bbf7843a..fe9df48ca4 100644 --- a/apps/vectorcraft/src/system_fonts.rs +++ b/apps/vectorcraft/src/system_fonts.rs @@ -284,8 +284,8 @@ mod tests { #[test] fn fonts_only_gdi_has_loaded_are_listed_by_their_files() { use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW}; - let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let temp = tempfile::Builder::new().prefix("vc-gdi-fonts-").tempdir().unwrap(); + let dir = temp.path(); let file = dir.join("29457"); let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf"); let mut data = std::fs::read(source).unwrap(); @@ -303,7 +303,6 @@ mod tests { assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1); let files = super::font_files(); let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) }; - let _ = std::fs::remove_dir_all(&dir); let wanted = file.to_string_lossy().to_lowercase(); assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len()); } diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index e6096c54a7..116651fc8d 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -99,9 +99,8 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() { #[test] fn an_unreadable_ui_json_is_kept_beside_it() { - let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); - let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id())); - std::fs::create_dir(&dir).unwrap(); + let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap(); + let dir = temp.path(); let path = dir.join("ui.json"); super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable"); super::keep_prefs_copy(&path, b"not json", "ui.unreadable"); @@ -109,7 +108,6 @@ fn an_unreadable_ui_json_is_kept_beside_it() { let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap(); let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap(); let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap(); - let _ = std::fs::remove_dir_all(&dir); assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced"); assert_eq!(second, b"not json"); assert_eq!(before, b"{}"); diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index b18bcddaee..5e996c4bdd 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -16,6 +16,14 @@ //! mouse message that Windows did not make from a pen or a touch //! () //! clears the feed. +//! +//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a +//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen +//! reports it (): +//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and +//! `rotation` in degrees 0..359 clockwise +//! (). +//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come. #![cfg_attr(not(windows), allow(dead_code))] use std::cell::RefCell; @@ -37,6 +45,11 @@ const PEN_FLAG_INVERTED: u32 = 0x0002; const PEN_FLAG_ERASER: u32 = 0x0004; /// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure. const PEN_MASK_PRESSURE: u32 = 0x0001; +/// `PEN_MASK_ROTATION`, `PEN_MASK_TILT_X` and `PEN_MASK_TILT_Y` (`winuser.h`): the pen reports its +/// barrel rotation, its tilt along x and its tilt along y. +const PEN_MASK_ROTATION: u32 = 0x0002; +const PEN_MASK_TILT_X: u32 = 0x0004; +const PEN_MASK_TILT_Y: u32 = 0x0008; /// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows /// made from a pen or a touch. const MI_WP_SIGNATURE: u32 = 0xFF51_5700; @@ -94,7 +107,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { // pointer that is not a pen. unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; - Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact)) + let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); + Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) }; // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); @@ -106,15 +120,25 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { /// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags` /// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen -/// in contact that reports none; and the eraser end while it is inverted or its eraser button is -/// pressed. -fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample { +/// in contact that reports none; the eraser end while it is inverted or its eraser button is +/// pressed; and how it is held, `pose` ([`pen_pose`]). +fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample { let pressure = match pressure { 1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0, _ if in_contact => 1.0, _ => 0.0, }; - PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose: PenPose::default() } + PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose } +} + +/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is +/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the +/// rotation when it reports one, each kept within [`PenPose`]'s ranges. +fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { + let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; + let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); + let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); + PenPose { tilt, rotation }.sanitized() } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -390,7 +414,7 @@ mod tests { #[test] fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() { - let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser; + let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser; assert!(!eraser(0), "the tip"); assert!(!eraser(PEN_FLAG_BARREL), "the barrel button"); assert!(eraser(PEN_FLAG_INVERTED), "turned over"); @@ -399,19 +423,32 @@ mod tests { assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL)); } + #[test] + fn a_pens_tilt_and_rotation_come_where_it_reports_them() { + let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; + assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) }); + assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel"); + let wild = pen_pose(all, 400, i32::MIN, 720); + assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges"); + let pose = pen_pose(all, 10, 20, 180); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { - assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5); - assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5); + assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0); assert_eq!( - pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false), + pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()), PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() }, "hovering" ); - assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); - assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one"); - assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0"); - assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0); + assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully"); + assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one"); + assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0"); + assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0); } #[test] diff --git a/assets/icons/dc-contour.svg b/assets/icons/dc-contour.svg new file mode 100644 index 0000000000..61c1f2ed82 --- /dev/null +++ b/assets/icons/dc-contour.svg @@ -0,0 +1 @@ + diff --git a/contributors/people.toml b/contributors/people.toml index 405c471a23..fe8e4ddb17 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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 diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 794f92aeea..8e947c1436 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -151,16 +151,23 @@ pub struct GradientStop { /// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint. #[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")] pub tint: f32, + /// Process inks (C, M, Y, K, 0..1) printed together with the linked spot swatch's tint: a + /// DeviceN colour of a file that mixes a spot ink with process plates. `color` is how the mix + /// looks; separations print the spot ink at `tint` and these plates. `None`: the ink alone. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plates: Option<[f32; 4]>, } impl GradientStop { /// An opaque, unlinked stop of `color` at `offset` with a centred midpoint. pub fn new(offset: f32, color: Color) -> Self { - Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 } + Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0, plates: None } } - /// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked. + /// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked, without + /// process plates. pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) { self.color = color; + self.plates = None; (self.swatch, self.tint) = match link { Some((n, t)) => (Some(n), t), None => (None, 1.0), diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 3915b239ed..e487226d4f 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -195,6 +195,24 @@ impl ImageBlob { jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16))) } + /// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8 + /// bits? Reads only its header. + pub fn is_cmyk16(&self) -> bool { + tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16))) + } + + /// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header. + pub fn header_size(&self) -> Option<(u32, u32)> { + let bytes = self.bytes.as_slice(); + if bytes.starts_with(&[0xFF, 0xD8]) { + let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default()); + d.decode_headers().ok()?; + let (w, h) = d.dimensions()?; + return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?)); + } + tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok()) + } + /// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded /// or are larger than [`MAX_CMYK_PIXELS`]. pub fn cmyk(&self) -> Option { @@ -633,6 +651,38 @@ mod tests { assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]); } + #[test] + fn a_header_gives_the_size_without_the_samples() { + assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2))); + // A CMYK TIFF of 6000 × 6000 pixels whose samples aren't there. + let mut t = b"II*\0\x08\0\0\0\x07\0".to_vec(); + // Bits per sample: four values, after the entries (8 + 2 + 7 × 12 + 4 = 98). + let entries = [ + (256u16, 4u16, 1u32, 6000u32), + (257, 4, 1, 6000), + (258, 3, 4, 98), + (262, 3, 1, 5), + (273, 4, 1, 106), + (277, 3, 1, 4), + (279, 4, 1, 144_000_000), + ]; + for (tag, kind, count, value) in entries { + t.extend_from_slice(&tag.to_le_bytes()); + t.extend_from_slice(&kind.to_le_bytes()); + t.extend_from_slice(&count.to_le_bytes()); + t.extend_from_slice(&value.to_le_bytes()); + } + t.extend_from_slice(&0u32.to_le_bytes()); + t.extend_from_slice(&[8, 0, 8, 0, 8, 0, 8, 0]); + let big = ImageBlob::new("image/tiff", t); + assert!(big.is_cmyk()); + assert_eq!(big.header_size(), Some((6000, 6000))); + assert_eq!(big.cmyk(), None); + let mut png = Vec::new(); + image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF"); + } + #[test] fn a_cmyk_image_samples_its_ink_amounts() { let b = ImageBlob::cmyk_tiff(&inks()).unwrap(); diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 976d48485f..102caf53db 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -72,6 +72,7 @@ impl Document { new_art, dimensions, retired_artboard_id: _, + opened_artboard: _, index: _, } = self; *version == other.version @@ -248,6 +249,7 @@ impl Document { new_art: Default::default(), dimensions: false, retired_artboard_id: Default::default(), + opened_artboard: None, index: Default::default(), }; let id = d.alloc_id(); diff --git a/crates/doc/src/halftone_radii.rs b/crates/doc/src/halftone_radii.rs new file mode 100644 index 0000000000..a96707c48e --- /dev/null +++ b/crates/doc/src/halftone_radii.rs @@ -0,0 +1,277 @@ +//! Color Halftone's Max Radius was a distance in points until documents of version 3; since then +//! it is in pixels of the Document Raster Effects resolution, as public documentation gives it +//! (#3260). [`Document::migrate_halftone_radii`] converts the radii of older documents, and +//! [`Document::halftone_radii_to_points`] converts them back for a file saved for an older app. + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::limits::FORMAT_VERSION; +use crate::{Appearance, Document, Effect, Node}; + +/// The first document version whose Color Halftone radii are in pixels. +const PIXEL_RADII_SINCE: u32 = 3; +const HALFTONE: &str = "pixelate.colorHalftone"; +const RADIUS: &str = "maxRadius"; +/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s +/// `DOC_KEY`), whose art can carry effects. +const BRUSHES: &str = "brushes"; +/// The radius (points) an older document's halftone without one drew with. +const OLD_DEFAULT: f64 = 8.0; +/// The range the radius was kept within in points, and is kept within in pixels. +const RANGE: std::ops::RangeInclusive = 4.0..=127.0; + +impl Document { + /// Saved before version 3: each Color Halftone's Max Radius in points becomes the pixels of + /// the document's raster effects resolution that draw the same dots, within the 4 to 127 px + /// the effect takes (a radius over 127 px, from a large radius at a high resolution, draws + /// smaller dots than before). In the art, symbols, patterns, graph designs, opacity masks and + /// graphic styles. + pub fn migrate_halftone_radii(&mut self) { + if self.version >= PIXEL_RADII_SINCE { + return; + } + self.version = FORMAT_VERSION; + let k = self.raster_ppi() / 72.0; + self.each_halftone(&mut |e| rescale(e, k)); + } + + /// For a file saved for an app before version 3 (every native file version before today's): + /// each Color Halftone's Max Radius in pixels becomes the points that draw the same dots, + /// within the 4 to 127 pt that app takes (a radius under 4 pt, from a fine screen at a high + /// resolution, draws bigger dots there), and the document becomes version 2, so reopening the + /// file here converts them back. + pub fn halftone_radii_to_points(&mut self) { + if self.version < PIXEL_RADII_SINCE { + return; + } + self.version = PIXEL_RADII_SINCE - 1; + let k = 72.0 / self.raster_ppi(); + self.each_halftone(&mut |e| rescale(e, k)); + } + + /// `fix` each effect in the art, symbols, patterns (and the one being edited as it was), graph + /// designs, opacity masks, Shaper edits, graphic styles and brush definitions that use a Color + /// Halftone. + fn each_halftone(&mut self, fix: &mut dyn FnMut(&mut Effect)) { + for l in &mut self.layers { + node(l, fix); + } + for s in &mut self.symbols { + node(&mut s.art, fix); + } + // Pattern editing is saved with the pattern as it was, which Cancel puts back. + for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) { + for a in &mut p.art { + node(a, fix); + } + } + for g in &mut self.graph_designs { + node(&mut g.art, fix); + } + if self.graphic_styles.iter().any(|s| has_halftone(&s.appearance)) { + for s in self.graphic_styles.iter_mut() { + appearance(&mut s.appearance, fix); + } + } + if let Some(b) = self.unknown.get_mut(BRUSHES) { + brushes(b, fix); + } + } +} + +/// `fix` each Color Halftone in JSON `v` (brush definitions): every object whose `id` is +/// [`HALFTONE`] is a serialized [`Effect`] (object ids are numbers). +fn brushes(v: &mut Value, fix: &mut dyn FnMut(&mut Effect)) { + match v { + Value::Object(m) if m.get("id").and_then(Value::as_str) == Some(HALFTONE) => { + let params = m.get("params").cloned().unwrap_or(Value::Null); + let mut e = Effect { id: HALFTONE.into(), params, visible: true }; + fix(&mut e); + m.insert("params".into(), e.params); + } + Value::Object(m) => m.values_mut().for_each(|v| brushes(v, fix)), + Value::Array(a) => a.iter_mut().for_each(|v| brushes(v, fix)), + _ => {} + } +} + +/// `e`'s radius times `k` (pixels a point, or points a pixel), within the effect's range, when it +/// is a Color Halftone. Its default is 8 in either unit. +fn rescale(e: &mut Effect, k: f64) { + if e.id != HALFTONE { + return; + } + let pt = e.params.get(RADIUS).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(OLD_DEFAULT); + let px = pt.clamp(*RANGE.start(), *RANGE.end()) * k; + if !e.params.is_object() { + e.params = Value::Object(Default::default()); + } + e.params[RADIUS] = json!(px.clamp(*RANGE.start(), *RANGE.end())); +} + +fn has_halftone(a: &Appearance) -> bool { + a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).any(|e| e.id == HALFTONE) +} + +fn appearance(a: &mut Appearance, fix: &mut dyn FnMut(&mut Effect)) { + for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { + fix(e); + } +} + +/// Fix the effects of `n`'s subtree, its opacity masks and its Shaper edits (copying only what +/// changes). +fn node(n: &mut Arc, fix: &mut dyn FnMut(&mut Effect)) { + let n = Arc::make_mut(n); + if has_halftone(&n.appearance) { + appearance(&mut n.appearance, fix); + } + if let Some(x) = n.extras_if_any() { + if let Some(m) = x.mask.as_mut() { + node(&mut m.art, fix); + } + // A Shaper Group's face and edge edits paint with appearances of their own. + if let Some(s) = x.shaper.as_mut() { + let faces = s.faces.iter_mut().filter_map(|f| f.paint.as_mut()); + for p in faces.chain(s.edges.iter_mut().filter_map(|e| e.paint.as_mut())) { + appearance(p, fix); + } + } + } + if let Some(ch) = n.children_mut() { + for c in ch { + node(c, fix); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn halftone(radius: Option) -> Effect { + let params = radius.map_or_else(|| json!({"channel1": 108.0}), |r| json!({"maxRadius": r, "channel1": 108.0})); + Effect { id: HALFTONE.into(), params, visible: true } + } + + fn radius(e: &Effect) -> f64 { + e.params[RADIUS].as_f64().unwrap() + } + + #[test] + fn older_radii_become_the_pixels_that_draw_the_same_dots() { + for (ppi, pt, px) in [(72.0, 8.0, 8.0), (300.0, 8.0, 33.333333333333336), (300.0, 4.0, 16.666666666666668), (150.0, 127.0, 127.0)] { + let mut e = halftone(Some(pt)); + rescale(&mut e, ppi / 72.0); + assert!((radius(&e) - px).abs() < 1e-9, "{pt} pt at {ppi} ppi: {}", radius(&e)); + assert_eq!(e.params["channel1"], json!(108.0), "the angles stay"); + } + // A radius left out drew at the old default, 8 pt. + let mut e = halftone(None); + rescale(&mut e, 300.0 / 72.0); + assert!((radius(&e) - 33.333333333333336).abs() < 1e-9); + // Other effects keep their parameters. + let mut blur = Effect { id: "blur.gaussian".into(), params: json!({"radius": 8.0}), visible: true }; + rescale(&mut blur, 300.0 / 72.0); + assert_eq!(blur.params, json!({"radius": 8.0})); + } + + #[test] + fn only_documents_before_version_3_are_converted_once() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let mut style = d.graphic_styles.first().cloned().unwrap(); + style.appearance.effects.push(halftone(Some(8.0))); + d.graphic_styles.push(style); + let fresh = d.clone(); + d.migrate_halftone_radii(); + assert_eq!(d, fresh, "a new document's radii are already pixels"); + d.version = 1; + d.migrate_halftone_radii(); + assert_eq!(d.version, FORMAT_VERSION); + let r = d.graphic_styles.last().map(|s| radius(&s.appearance.effects[0])).unwrap(); + assert!((r - 33.333333333333336).abs() < 1e-9, "{r}"); + let once = d.clone(); + d.migrate_halftone_radii(); + assert_eq!(d, once, "converted documents are left alone"); + } + + #[test] + fn radii_go_back_to_points_for_an_older_app_and_return_unchanged() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let mut style = d.graphic_styles.first().cloned().unwrap(); + style.appearance.effects.push(halftone(Some(100.0))); + style.appearance.effects.push(halftone(Some(4.0))); + d.graphic_styles.push(style); + let r = |d: &Document, i: usize| d.graphic_styles.last().map(|s| radius(&s.appearance.effects[i])).unwrap(); + d.halftone_radii_to_points(); + assert_eq!(d.version, 2, "reopened here, it converts back"); + assert!((r(&d, 0) - 24.0).abs() < 1e-9, "100 px at 300 ppi is 24 pt: {}", r(&d, 0)); + assert_eq!(r(&d, 1), 4.0, "0.96 pt is under the 4 pt the older app takes"); + let points = d.clone(); + d.halftone_radii_to_points(); + assert_eq!(d, points, "already in points"); + d.migrate_halftone_radii(); + assert!((r(&d, 0) - 100.0).abs() < 1e-9, "{}", r(&d, 0)); + } + + /// Shaper face and edge edits paint with appearances of their own, and brush definitions keep + /// their art as JSON: their radii convert both ways too. + #[test] + fn shaper_edits_and_brushes_are_converted_both_ways() { + use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec}; + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + d.version = 1; + let mut look = Appearance::default_art(); + look.effects = vec![halftone(Some(8.0))]; + let face = FaceEdit { + selector: FaceSelector { sources: vec![0], anchor: vectorcraft_geom::Point::ZERO }, + erase: false, + erase_edges: false, + paint_source: None, + merge: None, + paint: Some(look), + }; + let mut shaper = Node::group(d.alloc_id(), vec![]); + shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] })); + let l = d.layers[0].id; + d.insert(Some(l), 0, shaper).unwrap(); + let effect = serde_json::to_value(halftone(Some(8.0))).unwrap(); + d.unknown.insert(BRUSHES.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [effect]}}}])); + let radii = |d: &Document| { + let shaper = d.layers[0].children().and_then(|c| c.first()).cloned().unwrap(); + let paint = shaper.extras().shaper.as_ref().and_then(|s| s.faces[0].paint.clone()).unwrap(); + let brush = d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"][RADIUS].as_f64().unwrap(); + (radius(&paint.effects[0]), brush) + }; + d.migrate_halftone_radii(); + let (face, brush) = radii(&d); + assert!((face - 33.333333333333336).abs() < 1e-9, "the face edit: {face}"); + assert!((brush - 33.333333333333336).abs() < 1e-9, "the brush: {brush}"); + assert_eq!(d.unknown[BRUSHES][0]["art"]["appearance"]["effects"][0]["params"]["channel1"], json!(108.0)); + d.halftone_radii_to_points(); + let (face, brush) = radii(&d); + assert!((face - 8.0).abs() < 1e-9 && (brush - 8.0).abs() < 1e-9, "back in points: {face}, {brush}"); + } + + #[test] + fn the_pattern_being_edited_is_converted_as_it_was() { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = 300.0; + let id = d.alloc_id(); + let mut look = Appearance::default_art(); + look.effects = vec![halftone(Some(8.0))]; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let tile = Arc::new(Node::path(id, square, look)); + let original = Some(crate::PatternDef::new("Tile", vec![tile])); + d.pattern_edit = Some(crate::PatternEdit { pattern: "Tile".into(), layer: crate::NodeId(0), original }); + d.version = 1; + d.migrate_halftone_radii(); + let art = &d.pattern_edit.as_ref().unwrap().original.as_ref().unwrap().art[0]; + assert!((radius(&art.appearance.effects[0]) - 33.333333333333336).abs() < 1e-9, "the tile Cancel puts back"); + } +} diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index cb972b94f8..b3b4394a2f 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -6,9 +6,10 @@ use std::rc::Rc; use std::sync::{Arc, OnceLock}; use vectorcraft_geom::hit::{fill_contains, stroke_contains}; -use vectorcraft_geom::{BezPath, FillRule, Point, Rect}; +use vectorcraft_geom::kurbo::ParamCurveNearest; +use vectorcraft_geom::{BezPath, FillRule, PathData, PathSeg, Point, Rect}; -use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, SymbolBoxes}; +use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeAlign, SymbolBoxes}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HitKind { @@ -508,8 +509,9 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && let Some(isolated) = doc.node(scope) && let Some(mut chain) = doc.ancestry(scope) { - // Isolated before its artboard was locked: nothing in it hits. - if locks.holds_id(scope) { + // Isolated before its artboard, or its layer or a group around it, was locked or hidden: + // nothing in it hits (#5309). + if !doc.is_editable_with(&locks, scope) { return None; } if isolated.is_container() { @@ -723,6 +725,43 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } +/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a +/// miter or square cap, so the caller falls back to the full stroke check there. +fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> { + if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 { + return None; + } + let radius_sq = radius * radius; + let decoration_sq = decoration_reach * decoration_reach; + let mut near_decoration = false; + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + let c = sp.segment(i); + if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) { + near_decoration = true; + } + let controls = [c.p0, c.p1, c.p2, c.p3]; + if controls.iter().all(|q| q.x < p.x - radius) + || controls.iter().all(|q| q.x > p.x + radius) + || controls.iter().all(|q| q.y < p.y - radius) + || controls.iter().all(|q| q.y > p.y + radius) + { + continue; + } + let seg = if sp.segment_is_line(i) { PathSeg::Line(vectorcraft_geom::kurbo::Line::new(c.p0, c.p3)) } else { PathSeg::Cubic(c) }; + if seg.nearest(p, 1e-9).distance_sq <= radius_sq { + if vectorcraft_geom::bez::has_length(&seg) { + return Some((true, near_decoration)); + } + // A zero-length segment can still hit as an outline, though a painted stroke + // needs a segment with direction. Let the existing check decide its hit kind. + near_decoration = true; + } + } + } + Some((false, near_decoration)) +} + #[cfg(test)] thread_local! { /// How many objects [`hit_leaf`] tested on this thread. @@ -734,6 +773,43 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio LEAVES_TESTED.with(|c| c.set(c.get() + 1)); match &n.kind { NodeKind::Path { path, rule, .. } => { + if opt.outline + && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) + { + if hit { + return Some(HitKind::Outline); + } + if !needs_full_check { + return None; + } + } + let mut strokes = n.appearance.painted_strokes(); + if !opt.outline + && n.appearance.fill().is_none_or(|f| f.paint.is_none()) + && let Some(s) = strokes.next() + && strokes.next().is_none() + && s.align == StrokeAlign::Center + && s.width.is_finite() + && s.width > 0.0 + && s.dash.as_ref().is_none_or(|d| !d.is_dashed()) + && s.profile.is_none() + && s.start_arrow.is_none() + && s.end_arrow.is_none() + && s.brush.is_none() + && let Some((hit, near_decoration)) = near_path_body( + path, + p, + s.width / 2.0 + opt.tol, + if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 }, + ) + { + if hit { + return Some(HitKind::Stroke); + } + if !near_decoration { + return None; + } + } let bp = path.to_bezpath(); if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { return Some(k); @@ -893,6 +969,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh let mut out = Vec::new(); // `tops` pairs each object with the part of `r` in which the marquee can touch it. let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the + // marquee touches none of it, as clicks don't (#5309). + Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match (s.children(), marquee_in(s, r)) { (Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), (Some(_), None) => vec![], diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 452055a8f2..9a5c404781 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -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::>(), 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] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2a51b662b3..988df4c511 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -16,6 +16,7 @@ pub mod corners; pub mod depth; pub mod dimension; pub mod graph; +mod halftone_radii; pub mod hit; mod id_index; pub mod inks; @@ -324,6 +325,11 @@ pub struct Document { /// Never saved. #[serde(skip)] pub retired_artboard_id: RetiredArtboardId, + /// The id of the artboard an imported file names as its active one (a `.ai` file's + /// `CropAreaActive`): the document opens with that artboard active. `None`: the first. Never + /// saved. + #[serde(skip)] + pub opened_artboard: Option, /// Some object is a dimension (the Dimension tool): edits refresh dimensions only while this /// is set, so documents without any pay nothing for them. #[serde(default, skip_serializing_if = "std::ops::Not::not")] diff --git a/crates/doc/src/limits.rs b/crates/doc/src/limits.rs index 86c2e802a7..240672cca7 100644 --- a/crates/doc/src/limits.rs +++ b/crates/doc/src/limits.rs @@ -14,8 +14,10 @@ pub enum DocError { } /// The document version new documents get. Version 2: a positive Twist angle turns clockwise -/// ([`crate::twist`]). -pub const FORMAT_VERSION: u32 = 2; +/// ([`crate::twist`]). Version 3: Color Halftone's Max Radius is in pixels of the raster effects +/// resolution (older documents are converted on opening, +/// [`crate::Document::migrate_halftone_radii`]). +pub const FORMAT_VERSION: u32 = 3; /// Node, slice and asset ids are handed out below this: no document gets near it by counting, so /// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718). diff --git a/crates/doc/src/links.rs b/crates/doc/src/links.rs index 2330e95ac9..781e61e685 100644 --- a/crates/doc/src/links.rs +++ b/crates/doc/src/links.rs @@ -46,10 +46,26 @@ impl LinkInfo { Self { path: path.into(), ..Self::default() } } - /// The file name: the path's last component, whichever system's separators it uses. + /// The file name: the path's last component, whichever system's separators it uses + /// ([`path_separators`]). pub fn name(&self) -> &str { - self.path.rsplit(['/', '\\']).next().unwrap_or(&self.path) + self.path.rsplit(path_separators(&self.path)).next().unwrap_or(&self.path) } + + /// The folder the file is in: the path without its name and the separators before it. + pub fn folder(&self) -> &str { + let folder = self.path.get(..self.path.len().saturating_sub(self.name().len())).unwrap_or_default(); + folder.trim_end_matches(path_separators(&self.path)) + } +} + +/// The characters that separate the folders of `path`. A path with a colon and no `/` or `\` is a +/// classic Mac OS path (`Disk:Folder:file.tif`, as older documents store links), whose folders are +/// separated by colons. Any other path is separated by `/` and `\`: its file name may hold a colon +/// (`/Users/a/x:y.png`) and never holds a `/` or `\`. +pub fn path_separators(path: &str) -> &'static [char] { + const SLASHES: &[char] = &['/', '\\']; + if path.contains(':') && !path.contains(SLASHES) { &[':'] } else { SLASHES } } impl From<&str> for LinkInfo { @@ -164,6 +180,31 @@ impl ImageBlob { pub fn is_proxy(&self) -> bool { self.proxy.as_ref().is_some_and(|p| Arc::ptr_eq(p, &self.bytes)) } + + /// Does a colorize paint ([`crate::NodeExtras::colorize`]) show on these bytes? Not while + /// they are a preview whose pixels aren't grayscale, such as [`missing_placeholder`]: until + /// the file is relinked the image shows the preview as it is, and keeps the paint. + pub fn takes_colorize(&self) -> bool { + !self.is_proxy() || self.gray_source().is_some() + } +} + +/// The side of [`missing_placeholder`]'s image, in pixels. +pub const MISSING_SIDE: u32 = 64; + +/// What a linked image shows when an importer has no pixels for it (its file is missing or isn't +/// in the data): a light tile, crossed out, [`MISSING_SIDE`] pixels a side, as a PNG. `None` when +/// it can't be encoded. +pub fn missing_placeholder() -> Option> { + let last = MISSING_SIDE - 1; + let img = image::RgbaImage::from_fn(MISSING_SIDE, MISSING_SIDE, |x, y| { + let edge = x == 0 || y == 0 || x == last || y == last; + let cross = x.abs_diff(y) <= 1 || (x + y).abs_diff(last) <= 1; + image::Rgba(if edge || cross { [200, 60, 60, 255] } else { [236, 236, 236, 255] }) + }); + let mut png = Vec::new(); + img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(png) } /// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or @@ -445,6 +486,12 @@ mod tests { .unwrap() } + #[test] + fn the_placeholder_is_a_png() { + let png = missing_placeholder().unwrap(); + assert_eq!(image::load_from_memory(&png).unwrap().width(), MISSING_SIDE); + } + #[test] fn a_path_string_from_older_files_reads_as_a_link() { let old: ImageObject = serde_json::from_str(r#"{"key":"k","width":2,"height":1,"xf":[1,0,0,1,0,0],"link":"C:\\art\\photo.png"}"#).unwrap(); @@ -460,6 +507,35 @@ mod tests { assert_eq!(v["link"], serde_json::json!({"path": "/a/b.png", "size": 9, "page": 2})); } + /// A classic Mac OS path is named by its last colon-separated component, and its folder is + /// what comes before; other paths keep their `/` and `\` separators, and a name never holds + /// one. + #[test] + fn a_classic_mac_path_is_named_by_its_last_component() { + let parts = |path: &str| { + let l = LinkInfo::new(path); + (l.name().to_string(), l.folder().to_string()) + }; + assert_eq!(parts("Macintosh HD:Images:photo.tif"), ("photo.tif".into(), "Macintosh HD:Images".into())); + assert_eq!(parts("Disk:photo.tif"), ("photo.tif".into(), "Disk".into())); + assert_eq!(parts("Disk:Art/2024:a\\b.tif"), ("b.tif".into(), "Disk:Art/2024:a".into())); + assert_eq!(parts("Disk:Images:../other.png"), ("other.png".into(), "Disk:Images:..".into()), "a name reaches no other folder"); + assert_eq!(parts("C:\\art\\photo.png"), ("photo.png".into(), "C:\\art".into())); + assert_eq!(parts("c:/art/photo.png"), ("photo.png".into(), "c:/art".into())); + assert_eq!(parts("/Users/a/x:y.png"), ("x:y.png".into(), "/Users/a".into()), "a POSIX name may hold a colon"); + assert_eq!(parts("./art/x:y.png"), ("x:y.png".into(), "./art".into())); + assert_eq!(parts("..\\art\\x:y.png"), ("x:y.png".into(), "..\\art".into())); + assert_eq!(parts("\\\\?\\C:\\art\\photo.png"), ("photo.png".into(), "\\\\?\\C:\\art".into())); + assert_eq!(parts("file:///art/photo.png"), ("photo.png".into(), "file:///art".into())); + assert_eq!(parts("file:/art/photo.png"), ("photo.png".into(), "file:/art".into())); + assert_eq!(parts("assets/icon:dark.png"), ("icon:dark.png".into(), "assets".into()), "a relative path with slashes"); + assert_eq!(parts(":Images:photo.tif"), ("photo.tif".into(), ":Images".into()), "a classic path relative to its folder"); + assert_eq!(parts("/Users/a//photo.png").1, "/Users/a", "repeated separators"); + assert_eq!(parts("photo.png"), ("photo.png".into(), String::new())); + assert_eq!(parts("C:photo.png"), ("photo.png".into(), "C".into()), "a drive-relative path has the same shape"); + assert_eq!(LinkInfo::new("Macintosh HD:Images:photo.tif").path, "Macintosh HD:Images:photo.tif", "the stored path is kept"); + } + #[test] fn a_reader_hashes_as_its_bytes_do() { // Several 64 KB reads, and none. diff --git a/crates/doc/src/text/char_style.rs b/crates/doc/src/text/char_style.rs index 731480fed0..67ccb60a44 100644 --- a/crates/doc/src/text/char_style.rs +++ b/crates/doc/src/text/char_style.rs @@ -143,8 +143,11 @@ pub struct CharStyle { pub no_break: bool, /// Language (Character panel): the BCP 47 tag of one of [`crate::setup::LANGUAGES`] these /// characters are shaped in, so that the font uses that language's forms (OpenType `locl`). - /// `None`: the default language, English: USA, shaped without a language. New type takes the - /// document's language (Document Setup). Saved only when set. + /// `None`: the default language, English: USA, shaped without a language, which is what text + /// saved without one reads as. A tag the list doesn't have, from a file, is kept and has no + /// hyphenation. New type takes the document's language (Document Setup), else the default + /// language of Preferences › Hyphenation. Saved only when set. Each run hyphenates in its own + /// language (`vectorcraft_text::hyphen`). #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option, /// Another glyph of the font for the run's first character (Glyphs panel › Show › Alternates diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index bab9ee6ed1..8440639328 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -43,13 +43,25 @@ pub fn is_length(id: &str, key: &str, relative: bool) -> bool { } /// The range in points that distance parameter `key` of effect `id` is kept within, as its -/// parameter documentation gives it (`{maxRadius: pt 4..127 (8), …}`); `None` when it gives none. +/// parameter documentation gives it (`{edgeWidth: pt 1..14 (2), …}`); `None` when it gives none. pub fn length_range(id: &str, key: &str) -> Option> { + documented_range(id, key, "pt") +} + +/// The range of parameter `key` of effect `id` when it is a size in pixels of the Document Raster +/// Effects resolution (`{maxRadius: px 4..127 (8), …}`), which no unit setting changes and which +/// stays in pixels when the resolution does; `None` for other parameters. +pub fn raster_px_range(id: &str, key: &str) -> Option> { + documented_range(id, key, "px") +} + +/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`). +fn documented_range(id: &str, key: &str, unit: &str) -> Option> { let doc = catalog_index().get(id)?.params; let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { let rest = doc.get(at + key.len()..)?; - rest.strip_prefix(": pt ").or_else(|| rest.strip_prefix("?: pt ")) + rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ') })?; let (lo, hi) = rest.split_whitespace().next()?.split_once("..")?; let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches(',').parse::().ok()?); @@ -81,7 +93,6 @@ fn lengths_of(id: &str) -> Lengths { "brushStrokes.spatter" => always(&["sprayRadius"]), "brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]), "brushStrokes.sumiE" => always(&["strokeWidth"]), - "pixelate.colorHalftone" => always(&["maxRadius"]), "pixelate.crystallize" | "pixelate.pointillize" => always(&["cellSize"]), "texture.craquelure" => always(&["crackSpacing"]), "texture.mosaicTiles" => always(&["tileSize"]), @@ -296,7 +307,13 @@ pub fn effect_catalog() -> Vec { json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), ), r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), - r("blur.gaussian", "Gaussian Blur…", BLUR, "{radius: pt (5)}", json!({"radius": 5.0})), + r( + "blur.gaussian", + "Gaussian Blur…", + BLUR, + "{radius: pt (5), linear?: bool (false; blurs the colours in linear light, as an SVG filter with color-interpolation-filters=\"linearRGB\" does)}", + json!({"radius": 5.0}), + ), r( "artistic.coloredPencil", "Colored Pencil…", @@ -633,7 +650,7 @@ pub fn effect_catalog() -> Vec { "pixelate.colorHalftone", "Color Halftone…", PIXELATE, - "{maxRadius: pt 4..127 (8; the radius of a dot at full strength, which fills its square cell), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", + "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), ), r( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index fbbf3b0a90..8835d769f7 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -79,8 +79,8 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects}; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_options, image_paint, - needs_outline, outline_art, outline_text, reshape, + SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options, + image_paint, needs_outline, outline_art, outline_text, reshape, }; pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ @@ -95,7 +95,7 @@ mod catalog; mod geometry; mod params; -pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects}; +pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range}; pub(crate) use geometry::{Budget, apply_one}; pub use geometry::{GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_with}; #[cfg(test)] diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index c8cea82590..fbf22ff6b4 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -95,13 +95,16 @@ pub fn new_effect(id: &str, params: &Value) -> Option { } /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see -/// [`EffectInfo::lengths`]). A distance left at its default is written out scaled; one the -/// effect doesn't have (Outline Stroke's weight following its stroke) stays absent. +/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which +/// keep their share of the object so. A distance left at its default is written out scaled; one +/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. pub fn scale_effect(e: &mut Effect, s: f64) { let Some(info) = catalog_index().get(e.id.as_str()) else { return }; let merged = merged_params(&e.id, &e.params); let relative = util::flag(&merged, "relative", false); - for k in info.lengths.keys(relative) { + let mut keys: Vec<&str> = info.lengths.keys(relative).collect(); + keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some())); + for k in keys { let v = util::num(&merged, k, f64::NAN); if v.is_finite() { if !e.params.is_object() { diff --git a/crates/effects/src/pixel.rs b/crates/effects/src/pixel.rs index 8885c9def4..6be45756b4 100644 --- a/crates/effects/src/pixel.rs +++ b/crates/effects/src/pixel.rs @@ -254,7 +254,8 @@ pub enum PixelFx { /// Stylize › Glowing Edges: bright coloured Sobel outlines on black. GlowingEdges { width: f64, brightness: f64, smoothness: f64 }, /// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels - /// 1 to 4) into dots of up to `max_radius`, whose area follows the channel's strength. + /// 1 to 4) into dots of up to `max_radius` pixels of the Document Raster Effects resolution + /// ([`PixelSpace::line`] each), whose area follows the channel's strength. ColorHalftone { max_radius: f64, angles: [f64; 4] }, /// Pixelate › Crystallize: polygons of solid colour around random points about `cell` apart. Crystallize { cell: f64 }, @@ -668,9 +669,10 @@ impl PixelFx { } } - /// How far (document units) from a pixel the content that decides it lies; `None` when that - /// is anywhere in the object (Radial Blur). - pub fn reach(&self) -> Option { + /// How far (document units) from a pixel the content that decides it lies, with lines of the + /// raster grid `line` apart ([`PixelSpace::line`]); `None` when that is anywhere in the object + /// (Radial Blur). + pub fn reach(&self, line: f64) -> Option { match *self { PixelFx::RadialBlur { .. } => None, PixelFx::SmartBlur { radius, mode: SmartBlurMode::Normal, .. } => Some(radius), @@ -703,7 +705,10 @@ impl PixelFx { PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)), PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)), // The cells around the pixel's, and the cells around theirs. - PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius), + // (Without a usable grid there are no dots: see `pixelate::color_halftone`.) + PixelFx::ColorHalftone { max_radius, .. } => { + Some(3.0 * std::f64::consts::SQRT_2 * max_radius * line).filter(|d| d.is_finite()).or(Some(0.0)) + } PixelFx::Crystallize { cell } => Some(1.5 * cell), PixelFx::ColoredPencil { width, .. } => Some(artistic::colored_pencil_reach(width)), PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH), @@ -1074,6 +1079,47 @@ pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) { } } +/// [`gaussian_rgba`] with the colours mixed in linear light: decoded from sRGB before the blur +/// and encoded again after it (Filter Effects 1 §16, `color-interpolation-filters: linearRGB`, +/// ). 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 = (0..=255u8).map(|v| srgb_to_linear(f32::from(v) / 255.0)).collect(); + let mut wide: Vec = 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)] diff --git a/crates/effects/src/pixel/pixelate.rs b/crates/effects/src/pixel/pixelate.rs index e9997b0cf3..0318eb5f45 100644 --- a/crates/effects/src/pixel/pixelate.rs +++ b/crates/effects/src/pixel/pixelate.rs @@ -436,11 +436,12 @@ impl Screen { } /// Color Halftone: each channel screened at its angle in square cells sized so that a dot of -/// `max_radius` fills one; each cell's dot covers the share of it that is the channel's mean -/// there (white stays white, black black). Coverage stays as it is. +/// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's +/// dot covers the share of it that is the channel's mean there (white stays white, black black). +/// Coverage stays as it is. pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) { let Some(place) = Place::new(space, w, h) else { return }; - let side = max_radius * std::f64::consts::SQRT_2; + let side = max_radius * space.line * std::f64::consts::SQRT_2; // Cells under 3 pixels can't show their dots: on average a screen is the image itself. if !(side.is_finite() && side / place.px >= 3.0) { return; diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index ef4d9d7abf..a1a083f0fe 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -80,7 +80,7 @@ fn film_grain_parameters_are_bounded_and_neutral_settings_preserve_the_art() { neutral.apply(&mut out, w, h, &space(w, h)); assert_eq!(out, src); assert_eq!(neutral.outset(Rect::new(0.0, 0.0, w as f64, h as f64)), 0.0); - assert_eq!(neutral.reach(), Some(0.0)); + assert_eq!(neutral.reach(1.0), Some(0.0)); } #[test] @@ -520,12 +520,12 @@ fn outsets_follow_the_object() { assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9); assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far); assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0); - assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(), Some(4.0)); + assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0)); // The edge modes also read the copy blurred over a wide radius's samples. - assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(), Some(5.0)); + assert_eq!(fx("blur.smart", json!({"radius": 4, "quality": "low", "blurMode": "edgeOnly"})).reach(1.0), Some(5.0)); assert_eq!(fx("sharpen.unsharpMask", json!({})).outset(b), 0.0); - assert_eq!(spin.reach(), None); - assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(), Some(6.0)); + assert_eq!(spin.reach(1.0), None); + assert_eq!(fx("sharpen.unsharpMask", json!({"radius": 2})).reach(1.0), Some(6.0)); } #[test] @@ -887,6 +887,28 @@ fn gaussian_and_plane_blurs_keep_their_mass() { assert!((plane.iter().sum::() - 100.0).abs() < 0.5 && plane[15 * w + 13] > 0.0 && plane[13 * w + 15] > 0.0); } +/// Blurred in linear light, black beside white meets at about 188/255 (half the light, encoded), +/// where the plain blur meets at about 128; flat areas and alpha stay as they are (#5877). +#[test] +fn linear_light_blur_mixes_light_not_values() { + // Large enough that the transparency past the edges doesn't reach the middle. + let (w, h) = (120, 60); + let src = image(w, h, |x, _| if x < 60 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + let (mut plain, mut linear) = (src.clone(), src.clone()); + gaussian_rgba(&mut plain, w, h, 3.0); + gaussian_rgba_linear(&mut linear, w, h, 3.0); + let mid = |d: &[u8]| (f32::from(at(d, w, 59, 30)[0]) + f32::from(at(d, w, 60, 30)[0])) / 2.0; + assert!((mid(&plain) - 128.0).abs() < 6.0, "{}", mid(&plain)); + assert!((mid(&linear) - 188.0).abs() < 6.0, "{}", mid(&linear)); + assert_eq!((at(&linear, w, 30, 30), at(&linear, w, 90, 30)), ([0, 0, 0, 255], [255, 255, 255, 255])); + // Premultiplied input: a half-transparent white square blurs to white at any alpha. + let mut soft = image(30, 30, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [128, 128, 128, 128] } else { [0, 0, 0, 0] }); + gaussian_rgba_linear(&mut soft, 30, 30, 2.0); + for p in soft.as_chunks::<4>().0 { + assert!(p[0] <= p[3] && p[3] <= 128 && (p[3] < 8 || p[0] + 2 >= p[3]), "{p:?}"); + } +} + /// Timings on a 2000 × 2000 raster (`cargo test -p vectorcraft-effects --release -- --ignored /// --nocapture pixel_timings`). #[test] @@ -962,7 +984,7 @@ fn pixelate_params_take_defaults_and_stay_in_range() { assert_eq!(fx("pixelate.crystallize", json!({"cellSize": 20})).outset(b), 30.0); assert_eq!(fx("pixelate.pointillize", json!({"cellSize": 20})).outset(b), 30.0); assert_eq!(fx("pixelate.colorHalftone", json!({})).outset(b), 0.0); - assert_eq!(fx("pixelate.mezzotint", json!({})).reach(), Some(0.0)); + assert_eq!(fx("pixelate.mezzotint", json!({})).reach(1.0), Some(0.0)); } /// Fraction of `d`'s pixels for which `f` holds. @@ -1002,6 +1024,25 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() { assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40)); } +#[test] +fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() { + // Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a + // point apart) are the 8 px of 72 ppi, and draw the same dots. + let (w, h) = (64, 64); + let src = image(w, h, |x, y| [(x * 4) as u8, (y * 4) as u8, 128, 255]); + let run = |radius: f64, line: f64| { + let mut d = src.clone(); + fx("pixelate.colorHalftone", json!({"maxRadius": radius})).apply(&mut d, w, h, &PixelSpace { line, ..space(w, h) }); + d + }; + assert_eq!(run(16.0, 0.5), run(8.0, 1.0)); + assert_ne!(run(8.0, 0.5), run(8.0, 1.0), "the same radius at a finer resolution draws finer dots"); + // It looks as far around a pixel as its cells reach, in document units. + let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8})); + assert_eq!(halftone.reach(0.5), Some(3.0 * std::f64::consts::SQRT_2 * 4.0)); + assert_eq!(halftone.reach(f64::NAN), Some(0.0), "no grid, no dots"); +} + #[test] fn color_halftone_screens_inks_in_cmyk_documents() { let (w, h) = (64, 64); @@ -1241,8 +1282,8 @@ fn texture_params_take_defaults_and_stay_in_range() { for id in ["texture.craquelure", "texture.grain", "texture.mosaicTiles", "texture.texturizer"] { assert_eq!(fx(id, json!({})).outset(b), 0.0, "{id}"); } - assert_eq!(fx("texture.grain", json!({})).reach(), Some(0.0)); - assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(), Some(6.0)); + assert_eq!(fx("texture.grain", json!({})).reach(1.0), Some(0.0)); + assert_eq!(fx("texture.craquelure", json!({"crackSpacing": 12})).reach(1.0), Some(6.0)); } /// The pixels of `d` (`w` wide) in the square `lo..hi` on both axes. @@ -1509,9 +1550,9 @@ fn distort_params_take_defaults_and_stay_in_range() { // Shifted content reaches past the bounds by the longest shift, and comes from as far. let b = Rect::new(0.0, 0.0, 100.0, 50.0); let glass = fx("distort.glass", json!({"distortion": 20})); - assert_eq!((glass.outset(b), glass.reach()), (10.0, Some(10.0))); + assert_eq!((glass.outset(b), glass.reach(1.0)), (10.0, Some(10.0))); let ripple = fx("distort.oceanRipple", json!({})); - assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach() == Some(ripple.outset(b))); + assert!((ripple.outset(b) - 0.03 * 9.0 * 11.0).abs() < 1e-9 && ripple.reach(1.0) == Some(ripple.outset(b))); assert_eq!(fx("distort.diffuseGlow", json!({})).outset(b), 0.0); } @@ -1621,7 +1662,7 @@ fn ocean_ripple_moves_content_no_farther_than_its_magnitude() { fx("distort.oceanRipple", json!({"rippleMagnitude": 0})).apply(&mut d, w, h, &space(w, h)); assert_eq!(d, src, "no magnitude, no ripples"); let f = fx("distort.oceanRipple", json!({"rippleSize": 6, "rippleMagnitude": 20})); - let most = f.reach().unwrap(); + let most = f.reach(1.0).unwrap(); let mut d = src.clone(); f.apply(&mut d, w, h, &space(w, h)); assert_ne!(d, src); @@ -1765,19 +1806,19 @@ fn brush_strokes_outsets() { let reach = brushstrokes::stroke_reach; assert!((reach(20.0) - (0.75 * 20.0 + 1.5 / 15.0 * 20.0 + 1.0)).abs() < 1e-9); assert_eq!(fx("brushStrokes.accentedEdges", json!({})).outset(b), 0.0); - assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0)); + assert_eq!(fx("brushStrokes.accentedEdges", json!({})).reach(1.0), Some(3.0 * (0.35 * 2.0 + 0.5) + 1.0)); assert_eq!(fx("brushStrokes.angledStrokes", json!({})).outset(b), reach(15.0)); assert_eq!(fx("brushStrokes.crosshatch", json!({})).outset(b), reach(9.0) + 0.9); assert_eq!(fx("brushStrokes.darkStrokes", json!({})).outset(b), reach(9.0)); assert_eq!(fx("brushStrokes.inkOutlines", json!({"strokeLength": 50})).outset(b), reach(50.0)); let spatter = fx("brushStrokes.spatter", json!({})); - assert_eq!((spatter.outset(b), spatter.reach()), (4.0, Some(4.0))); + assert_eq!((spatter.outset(b), spatter.reach(1.0)), (4.0, Some(4.0))); assert_eq!(fx("brushStrokes.spatter", json!({"sprayRadius": 0})).outset(b), 0.0); assert_eq!(fx("brushStrokes.sprayedStrokes", json!({})).outset(b), reach(12.0) + 0.3 * 7.0); assert_eq!(fx("brushStrokes.sumiE", json!({})).outset(b), 0.0); for id in brush_strokes() { let f = fx(id, json!({})); - assert!(f.reach().is_some_and(|r| r >= f.outset(b)), "{id}"); + assert!(f.reach(1.0).is_some_and(|r| r >= f.outset(b)), "{id}"); } } @@ -1961,7 +2002,7 @@ fn spatter_scatters_content_no_farther_than_its_radius() { let src = image(w, h, |x, _| if x < 32 { grey(255) } else { [0; 4] }); assert_eq!(run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 0})), src, "no radius, no spatter"); let f = fx("brushStrokes.spatter", json!({"sprayRadius": 15})); - let most = f.reach().unwrap(); + let most = f.reach(1.0).unwrap(); let d = run_fx(&src, w, h, "brushStrokes.spatter", json!({"sprayRadius": 15})); assert_ne!(d, src); let inside = |v: usize, n: usize| (v as f64 + 0.5).min(n as f64 - v as f64 - 0.5) > most + 1.0; @@ -1990,7 +2031,7 @@ fn brush_strokes_look_no_farther_than_their_reach() { ("brushStrokes.sumiE", json!({"strokeWidth": 15})), ]); for (id, p) in cases { - let reach = fx(id, p.clone()).reach().unwrap(); + let reach = fx(id, p.clone()).reach(1.0).unwrap(); // Everything from `cut` on differs; the pixels left of 20 can't tell. let cut = 20 + reach.ceil() as usize + 1; assert!(cut < w, "{id}"); @@ -2047,7 +2088,7 @@ fn chalk_charcoal_params_take_defaults_and_stay_in_range() { assert!(doc.contains("chalkArea") && doc.contains("charcoalArea") && doc.contains("strokePressure"), "{doc}"); let f = fx("sketch.chalkCharcoal", json!({"strokePressure": 5})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert!(f.reach().unwrap() > 0.0); + assert!(f.reach(1.0).unwrap() > 0.0); } #[test] @@ -2108,7 +2149,7 @@ fn graphic_pen_params_take_defaults_and_stay_in_range() { assert!(STROKE_DIRECTIONS.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); let f = fx("sketch.graphicPen", json!({"strokeLength": 15})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), brushstrokes::stroke_reach(15.0)); - assert_eq!(f.reach(), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); + assert_eq!(f.reach(1.0), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); assert_eq!( fx("sketch.graphicPen", json!({"strokeLength": 99})), PixelFx::GraphicPen { length: 15.0, balance: 50.0, direction: StrokeDirection::RightDiagonal } @@ -2148,7 +2189,7 @@ fn halftone_pattern_params_take_defaults_and_stay_in_range() { assert!(HALFTONE_TYPES.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); let f = fx("sketch.halftonePattern", json!({"size": 12})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } #[test] @@ -2162,7 +2203,7 @@ fn note_paper_params_take_defaults_and_stay_in_range() { assert!(doc.contains("imageBalance") && doc.contains("graininess") && doc.contains("relief"), "{doc}"); let f = fx("sketch.notePaper", json!({"relief": 12})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } /// Note Paper embosses a horizontal gradient and graininess adds fibre. @@ -2198,7 +2239,7 @@ fn water_paper_params_take_defaults_and_stay_in_range() { ); let f = fx("sketch.waterPaper", json!({"fiberLength": 40})); assert!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)) > 0.0); - assert!(f.reach().unwrap_or(0.0) > 0.0); + assert!(f.reach(1.0).unwrap_or(0.0) > 0.0); let doc = crate::effect_info("sketch.waterPaper").unwrap().params; assert!(doc.contains("unverified"), "{doc}"); } @@ -2281,7 +2322,7 @@ fn plaster_params_take_defaults_and_stay_in_range() { let doc = crate::effect_info("sketch.plaster").unwrap().params; assert!(doc.contains("\"bottomRight\""), "{doc}"); let f = fx("sketch.plaster", json!({"smoothness": 24})); - assert_eq!(f.reach(), Some(super::sketch::plaster_reach(15.0))); + assert_eq!(f.reach(1.0), Some(super::sketch::plaster_reach(15.0))); } /// Plaster changes the image and different light directions give different results. @@ -2356,8 +2397,8 @@ fn chrome_params_take_defaults_and_stay_in_range() { assert!(doc.contains("detail") && doc.contains("smoothness"), "{doc}"); let f = fx("sketch.chrome", json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(sketch::chrome_reach(4.0))); - assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(), Some(sketch::chrome_reach(10.0))); + assert_eq!(f.reach(1.0), Some(sketch::chrome_reach(4.0))); + assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(1.0), Some(sketch::chrome_reach(10.0))); } /// Chrome redraws in greyscale, keeps coverage, and more detail changes the pattern. @@ -2389,7 +2430,7 @@ fn reticulation_params_take_defaults_and_stay_in_range() { ); let f = fx("sketch.reticulation", json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); - assert_eq!(f.reach(), Some(0.0)); + assert_eq!(f.reach(1.0), Some(0.0)); } #[test] @@ -2431,7 +2472,7 @@ fn torn_edges_params_take_defaults_and_stay_in_range() { for junk in [json!({"imageBalance": "x"}), json!({"smoothness": null})] { assert_eq!(fx("sketch.tornEdges", junk), fx("sketch.tornEdges", json!({}))); } - assert_eq!(fx("sketch.tornEdges", json!({})).reach(), None); + assert_eq!(fx("sketch.tornEdges", json!({})).reach(1.0), None); } #[test] @@ -2496,7 +2537,7 @@ fn artistic_params_take_defaults_and_stay_in_range() { fx("artistic.coloredPencil", json!({"pencilWidth": 0, "strokePressure": 200, "paperBrightness": -5})), PixelFx::ColoredPencil { width: 1.0, pressure: 15.0, paper: 0.0 } ); - assert_eq!(fx("artistic.coloredPencil", json!({})).reach(), Some(artistic::colored_pencil_reach(5.0))); + assert_eq!(fx("artistic.coloredPencil", json!({})).reach(1.0), Some(artistic::colored_pencil_reach(5.0))); assert_eq!(fx("artistic.cutout", json!({})), PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 }); assert_eq!( fx("artistic.cutout", json!({"levels": 1e308, "edgeSimplicity": -5, "edgeFidelity": "NaN"})), @@ -2860,7 +2901,7 @@ fn dry_brush_repaints_and_preserves_coverage() { let before = clear.clone(); fx("artistic.dryBrush", json!({})).apply(&mut clear, w, h, &space(w, h)); assert_eq!(clear, before); - let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(); + let reach = fx("artistic.dryBrush", json!({"brushSize": 10, "brushDetail": 1})).reach(1.0); assert!(reach.is_some_and(|r| r > 0.0)); } diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs index 2f463f52f6..fd467a23ca 100644 --- a/crates/effects/src/pixel/tests_sketch.rs +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -176,7 +176,7 @@ fn sketch_filters_reach_beyond_nothing_they_do_not_paint() { for id in ["sketch.basRelief", "sketch.charcoal", "sketch.conteCrayon", "sketch.photocopy", "sketch.stamp"] { let f = fx(id, json!({})); assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage"); - assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); + assert!(f.reach(1.0).is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); } } diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index a1d8df2d61..cfa51ca2b0 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -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 { 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)?), }) diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index fa77c5702e..38d79c125e 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -39,8 +39,13 @@ pub fn needs_outline(n: &Node) -> bool { /// in a fill or stroke? Such an object is drawn through its art ([`outline_art`]) so that each copy /// paints its gradient by itself ([`copy_leaf`]), as a group's copies do. pub fn has_gradient_copies(n: &Node) -> bool { + (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && has_transform_copies(n) +} + +/// Is `n` a path or compound path with a visible Transform effect that makes copies? Expand +/// Appearance makes each copy an object of its own ([`expand_outlined`]). +pub fn has_transform_copies(n: &Node) -> bool { matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) - && (n.appearance.has_unplaced_gradient() || n.appearance.has_placed_gradient()) && geometry_effects(n) .iter() .any(|e| e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0) @@ -249,11 +254,20 @@ fn with_id(art: &Node, id: NodeId) -> Node { /// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of /// `doc`'s symbols that its instances show toward its instance budget. pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { - outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default()) + outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false) } -/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]). -fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option { +/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with +/// `apart`, also a path or compound path whose Transform effect makes copies +/// ([`has_transform_copies`]), as the one piece the copies are made from. +fn outline_art_with( + doc: Option<&Document>, + n: &Node, + symbol_art: Option<&Node>, + outline: OutlineHook, + nodes: &SymbolNodes, + apart: bool, +) -> Option { let mut art = match &n.kind { NodeKind::Text(_) => outline_text(n)?, NodeKind::SymbolInstance { symbol, xf } => { @@ -268,7 +282,7 @@ fn outline_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, Node::group(n.id, vec![Arc::new(a)]) } // The object as the one piece the copies of its Transform effect are made from. - _ if has_transform_art(n) => { + _ if has_transform_art(n) || (apart && has_transform_copies(n)) => { let mut one = n.clone(); one.opacity = 1.0; one.blend = Default::default(); @@ -429,10 +443,12 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O /// geometry effects, else type with fills or strokes of its own outlined, or an image with fills /// or strokes of its own that paint a shape, in the same form. `None` when it has none of these. pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option { - // A path whose Transform effect copies it with a gradient, or scales its strokes or moves its - // patterns: each copy an object of its own. - if has_transform_art(n) { - return as_art(doc, n, symbol_art); + // A path whose Transform effect copies it, or scales its strokes or moves its patterns: each + // copy an object of its own with the path's fills and strokes, the copies of each Transform + // effect in a group of their own (copies of copies nest), as the reference app expands them + // (#5612). + if has_transform_art(n) || has_transform_copies(n) { + return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true); } let own_paint = match n.kind { NodeKind::Text(_) => !n.appearance.items.is_empty(), @@ -451,6 +467,12 @@ pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node> /// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]). pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option { + as_art_opts(doc, n, symbol_art, outline, nodes, false) +} + +/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an +/// object of its own ([`copy_leaf`]) rather than one path of every copy. +fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option { let fx = geometry_effects(n); let mut art = match &n.kind { NodeKind::Image(im) => { @@ -478,9 +500,12 @@ pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<& Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect()) } } - _ => outline_art_with(doc, n, symbol_art, outline, nodes)?, + _ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?, }; - reshape_leaves(&mut art, &fx); + reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart); + if apart { + hoist_copies(&mut art); + } transform_items(&mut art); // Type and symbols in perspective: the art projected onto their plane. if let Some(h) = n.projection() { @@ -546,6 +571,28 @@ pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) { /// [`reshape_leaves`] whose paths keep to `budget` together, or to what they cost. pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) { + reshape_leaves_apart(art, fx, budget, false); +} + +/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding +/// the group of its copies ([`copy_leaf`]) as its only member: the copies become its members, so +/// the expanded path is one group of its copies rather than a group in a group. +fn hoist_copies(art: &mut Node) { + let id = art.id; + let Some(children) = art.children_mut() else { return }; + let [only] = children.as_slice() else { return }; + if only.id != id || !matches!(only.kind, NodeKind::Group { clip: false, .. }) { + return; + } + let copies = only.children().cloned().unwrap_or_default(); + if !copies.is_empty() { + *children = copies; + } +} + +/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects +/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. +fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) { if fx.is_empty() { return; } @@ -588,14 +635,14 @@ pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budg if let Some((m, copies, options, map)) = transform { // Transform Patterns and Scale Strokes & Effects change each copy's fills and // strokes; a gradient paints each copy by itself, not the one piece the copies - // make together. - let gradient = copies > 0 && (leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); + // make together; and Expand Appearance (`apart`) makes each copy an object. + let separate = copies > 0 && (apart || leaf.appearance.has_unplaced_gradient() || leaf.appearance.has_placed_gradient()); if options.reach_appearance() { let made = transform_leaf(leaf, &path, map, copies, options, room); used = used.minus(before).plus(made); return; } - if gradient { + if separate { let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room); used = used.minus(before).plus(made); return; diff --git a/crates/effects/src/stroke.rs b/crates/effects/src/stroke.rs index 2ae452ed51..6dfcacce2f 100644 --- a/crates/effects/src/stroke.rs +++ b/crates/effects/src/stroke.rs @@ -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 { + 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. diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 44efdb3278..a79b8e0f78 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -501,3 +501,45 @@ fn a_stroke_narrower_than_the_shape_keeps_its_hole() { assert_eq!(moves(&outline), 3, "{join:?}: two contours for the ring, one for the blob"); } } + +/// A subpixel stroke must retain its geometric thickness even when the normal display tolerance +/// is close to its weight. Original uneven circular arcs, independent of any user fixture. +#[test] +fn thin_curved_strokes_keep_their_width_between_notches() { + use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Shape}; + for (radius, degrees) in [(450.0, 47.0_f64), (438.0, 77.0), (450.0, 54.0)] { + let a = degrees.to_radians(); + let k = 4.0 / 3.0 * (a / 4.0).tan(); + let curve = CubicBez::new( + (radius, 0.0), + (radius, k * radius), + (radius * a.cos() + k * radius * a.sin(), radius * a.sin() - k * radius * a.cos()), + (radius * a.cos(), radius * a.sin()), + ); + let mut line = BezPath::new(); + line.move_to(curve.p0); + line.curve_to(curve.p1, curve.p2, curve.p3); + for width in [0.25, 1.0 / 3.0, 0.5, 1.0] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + let outline = line_outline(&line, &st, width, 0.25); + for step in 1..40 { + let t = step as f64 / 40.0; + let p = curve.eval(t); + let tangent = curve.deriv().eval(t).to_vec2().normalize(); + let normal = kurbo::Vec2::new(-tangent.y, tangent.x); + for side in [-1.0, 1.0] { + assert_ne!( + outline.winding(p + normal * (side * width * 0.45)), + 0, + "missing inner band at radius {radius}, {degrees} degrees, width {width}, t {t}" + ); + assert_eq!( + outline.winding(p + normal * (side * width * 0.55)), + 0, + "outside intended band at radius {radius}, {degrees} degrees, width {width}, t {t}" + ); + } + } + } + } +} diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 324fddfac9..6d0a282e8e 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -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 { + 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. diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 611909b964..ea3843f0ee 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1231,14 +1231,29 @@ fn a_repeat_of_a_symbol_whose_art_is_a_repeat_shares_the_instance_budget() { #[test] fn a_distance_parameters_range_comes_from_its_documentation() { - assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert_eq!(length_range("stylize.glowingEdges", "edgeWidth"), Some(1.0..=14.0)); + // A distance documented without a range, and unknown effects and parameters, have none. + assert_eq!(length_range("path.offsetPath", "offset"), None); + assert_eq!(length_range("stylize.glowingEdges", "edgeBrightness"), None); + assert_eq!(length_range("no.such", "edgeWidth"), None); +} + +#[test] +fn color_halftones_radius_is_in_raster_pixels_not_a_distance() { + // Pixels of the Document Raster Effects resolution, as public documentation gives it (#3260): + // no unit setting changes it, so it isn't a distance in points. + assert_eq!(raster_px_range("pixelate.colorHalftone", "maxRadius"), Some(4.0..=127.0)); + assert!(!is_length("pixelate.colorHalftone", "maxRadius", false)); + assert_eq!(length_range("pixelate.colorHalftone", "maxRadius"), None); + assert_eq!(raster_px_range("pixelate.colorHalftone", "channel1"), None); + assert_eq!(raster_px_range("stylize.glowingEdges", "edgeWidth"), None); // The effect applies the range's floor to a radius below it. assert_eq!( crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 1})), crate::pixel::parse("pixelate.colorHalftone", &json!({"maxRadius": 4})) ); - // A distance documented without a range, and unknown effects and parameters, have none. - assert_eq!(length_range("path.offsetPath", "offset"), None); - assert_eq!(length_range("pixelate.colorHalftone", "channel1"), None); - assert_eq!(length_range("no.such", "maxRadius"), None); + // Scale Strokes & Effects scales it with the object, as it does distances. + let mut e = crate::new_effect("pixelate.colorHalftone", &json!({"maxRadius": 10})).unwrap(); + crate::scale_effect(&mut e, 2.0); + assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0))); } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b1b9efd60b..f02d6f6aa6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -168,6 +168,17 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) } } +/// A path is selected, or inside a selected group or compound path: Object › Path's items that +/// work on paths (not on text, images or other objects alone). +pub fn has_selected_path(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + let st = s.active().ok_or("no document open")?; + // Stops at the first path: menus ask this every frame, and a selected group can hold many. + fn holds_path(n: &vectorcraft_doc::Node) -> bool { + matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, .. }) || n.children().is_some_and(|c| c.iter().any(|c| holds_path(c))) + } + if st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(holds_path) { Ok(()) } else { Err("select a path".into()) } +} /// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take). pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) } diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index ac9597cbd8..324d7bde58 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -4,10 +4,12 @@ mod arrange; mod cleanup; mod color; +mod contour; mod document; mod pathtools; mod pen; mod select; +mod shapes; mod typetools; use super::CommandSpec; @@ -17,10 +19,12 @@ pub fn specs() -> Vec { let mut v = arrange::specs(); v.extend(cleanup::specs()); v.extend(color::specs()); + v.extend(contour::specs()); v.extend(document::specs()); v.extend(pathtools::specs()); v.extend(pen::specs()); v.extend(select::specs()); + v.extend(shapes::specs()); v.extend(typetools::specs()); v } diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index 0d279c0f64..4b76562e91 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -13,7 +13,7 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit}; use crate::cmd::fonts::{edit_symbol_texts, symbol_texts}; -use crate::cmd::textedit::editing_range; +use crate::cmd::textedit::{editing_range, editing_story}; use crate::cmd::typecmd::refresh_bounds; use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{EngineError, Result, Session}; @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Remove Breaks", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool, else in all the text of the selected type, as one undo step; a break between two words becomes a space → {ids, removed}", + "{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", has_selection, remove_breaks ), @@ -730,12 +730,11 @@ fn join_text(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "joined": joined, "lines": count })) } -/// Remove the breaks `brk` in bytes `a..b` of `t`: one between two words becomes a space → how many -/// went. -fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { - let text = t.plain_text(); - let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b)); - let Some(range) = text.get(a..b) else { return 0 }; +/// The breaks `brk` in bytes `a..b` of `text`, each with whether it becomes a space (it is between +/// two words). +fn break_cuts(text: &str, a: usize, b: usize, brk: char) -> Vec<(usize, bool)> { + let (a, b) = (edit::floor_char(text, a), edit::floor_char(text, b)); + let Some(range) = text.get(a..b) else { return vec![] }; let mut prev = text.get(..a).and_then(|s| s.chars().next_back()); let mut cuts = vec![]; for (i, c) in range.char_indices() { @@ -753,6 +752,12 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { } cuts.push((at, space)); } + cuts +} + +/// Remove the breaks `brk` at the bytes of `cuts` from `t`, each one that `cuts` marks becoming a +/// space → how many went. +fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize { for &(at, space) in cuts.iter().rev() { let insert = if space { " " } else { "" }; let end = at + brk.len_utf8(); @@ -763,6 +768,30 @@ fn strip_breaks(t: &mut TextObject, a: usize, b: usize, brk: char) -> usize { cuts.len() } +/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or +/// start of a frame between words of the frames on either side becomes a space. Each editable frame +/// comes with its own breaks, at its own bytes. +fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> { + let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect(); + let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect(); + // The breaks in story order, handed to the frames in one pass. + let mut cuts = break_cuts(&joined, 0, joined.len(), brk).into_iter().peekable(); + let mut out = vec![]; + let mut start = 0; + for (id, text) in texts { + let end = start + text.len(); + let mut own = vec![]; + while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) { + own.push((at - start, space)); + } + if d.is_editable(id) { + out.push((id, own)); + } + start = end; + } + out +} + fn remove_breaks(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.cleanup.removeBreaks"; let (brk, label, none) = match text_param(p, "kind", C)? { @@ -771,21 +800,41 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { Some(other) => return Err(bad(C, format!("`kind` must be \"line\" or \"paragraph\", not {other:?}"))), None => return Err(bad(C, "missing `kind`")), }; - // The characters a Type tool has selected, else all the text of the selected type. + // The characters a Type tool has selected (after Select All in threaded text, all the text of + // every frame of the story), else all the text of the selected type. let editing = if p.get("ids").is_some() { None } else { editing_range(s)?.filter(|(_, a, b)| a != b) }; + let story = if editing.is_some() { editing_story(s) } else { vec![] }; let d = &s.doc()?.doc; - let targets: Vec<(NodeId, usize, usize)> = match editing { - Some((id, a, b)) => vec![(id, a.min(b), a.max(b))].into_iter().filter(|(id, ..)| d.is_editable(*id)).collect(), - None => texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().map(|id| (id, 0, usize::MAX)).collect(), + // Each type object with the breaks that go from it. + let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing { + Some(_) if !story.is_empty() => story_cuts(d, &story, brk), + Some((id, a, b)) => vec![(id, a.min(b), a.max(b))] + .into_iter() + .filter(|(id, ..)| d.is_editable(*id)) + .filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk)))) + .collect(), + None => { + let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?; + // A threaded story whose frames are all among them is read as one text, once. + let named: std::collections::HashSet = ids.iter().copied().collect(); + let mut done = std::collections::HashSet::new(); + let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![]; + for &id in &ids { + if !done.insert(id) { + continue; + } + let story = crate::cmd::threads::story_of(d, id); + if !story.is_empty() && story.iter().all(|f| named.contains(f)) { + done.extend(story.iter().copied()); + out.extend(story_cuts(d, &story, brk)); + } else if let Some(t) = text_of(d, id) { + out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk))); + } + } + out + } }; - let count: usize = targets - .iter() - .filter_map(|(id, a, b)| { - let text = text_of(d, *id)?.plain_text(); - let (a, b) = (edit::floor_char(&text, *a), edit::floor_char(&text, *b)); - Some(text.get(a..b)?.matches(brk).count()) - }) - .sum(); + let count: usize = targets.iter().map(|(_, cuts)| cuts.len()).sum(); if count == 0 { return Err(EngineError::Other(none.into())); } @@ -794,9 +843,9 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { } let (removed, ids) = s.edit(label, |d, _| { let (mut removed, mut ids) = (0, vec![]); - for (id, a, b) in targets { + for (id, cuts) in targets { let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue }; - let n = strip_breaks(t, a, b, brk); + let n = apply_cuts(t, &cuts, brk); if n > 0 { refresh_bounds(t); removed += n; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index ac8947cb4a..574003b931 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -3,9 +3,10 @@ //! Filter writes any colour adjustment into the colours themselves, Select by Color Kind selects the //! objects that use spot colours, carry a live colour adjustment, or are images of a colour model, //! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest -//! Swatch ([`nearest`]) matches colours to a swatch library's, and Create Swatch Legend -//! ([`legend`]) draws labelled chips of the document's swatches. Its panel and its submenu, Object › -//! Plug-ins › Color Effects, are the UI's. +//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend +//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply +//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its panel and its submenu, +//! Object › Plug-ins › Color Effects, are the UI's. pub mod legend; mod nearest; @@ -14,13 +15,14 @@ mod print_fixes; mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind}; use vectorcraft_render::effects; use super::super::colorcmds::recolor_links; +use super::super::paint::{restore_unpainted_stroke, set_run_stroke}; use super::super::select::walk_selectable; -use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, text_param}; -use crate::{Result, Session}; +use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, paint_targets, switch_or, text_param}; +use crate::{EngineError, Result, Session}; /// The kinds Select by Color Kind selects (`addon.color.select`). pub const SELECT_KINDS: [&str; 5] = ["spotColors", "colorEffects", "rgbImages", "cmykImages", "grayImages"]; @@ -72,6 +74,24 @@ pub fn specs() -> Vec { has_selection, nearest::apply ), + cmd!( + "addon.color.fillToStroke", + "Apply Fill to Stroke", + ["Object", "Plug-ins", "Color Effects"], + None, + "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's series marks and labels keep the paint when the graph is drawn again. skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", + has_doc, + |s, p| copy_paint(s, p, true) + ), + cmd!( + "addon.color.strokeToFill", + "Apply Stroke to Fill", + ["Object", "Plug-ins", "Color Effects"], + None, + "{ids?|id?, skipNone?: bool} each target's top fill takes its own top stroke's paint, as addon.color.fillToStroke does the other way; the stroke itself is unchanged. The default fill takes the default stroke → {objects}", + has_doc, + |s, p| copy_paint(s, p, false) + ), ] .into_iter() .chain(legend::specs()) @@ -156,3 +176,97 @@ fn filter(s: &mut Session, p: &Value) -> Result { let swatches = |name: &str| kinds.get(name).copied(); recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)) } + +/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own +/// paints onto the other, so a mixed selection keeps each object's colour (#5530). Aimed and +/// undone like Swap Fill and Stroke; characters selected with the Type tool are the only ones that +/// change, as for `paint.setFill`. A graph's series marks and labels give the graph the paint in +/// the same undo step, as `paint.setFill` does, so drawing the graph again keeps it. When nothing +/// changes, the document and its undo history stay as they are. +fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { + let (cmd, label) = + if to_stroke { ("addon.color.fillToStroke", "Apply Fill to Stroke") } else { ("addon.color.strokeToFill", "Apply Stroke to Fill") }; + let skip_none = switch_or(p, "skipNone", false, cmd)?; + // One text style: its stroke takes its fill, or the other way. + let copy_run = |st: &mut CharStyle| { + let from = if to_stroke { st.fill.clone() } else { st.stroke.clone() }; + if (skip_none && from.is_none()) || from == if to_stroke { st.stroke.clone() } else { st.fill.clone() } { + return; + } + if to_stroke { + set_run_stroke(st, from); + } else { + st.fill = from; + } + }; + if p.get("ids").is_none() + && p.get("id").is_none() + && let Some((id, a, b)) = super::super::textedit::editing_range(s)? + && a != b + { + // After Select All in threaded text, every frame's text takes it. + let story = super::super::textedit::editing_story(s); + let ranges: Vec<(NodeId, usize, usize)> = + if story.is_empty() { vec![(id, a, b)] } else { story.iter().map(|f| (*f, 0, usize::MAX)).collect() }; + let ids: Vec = ranges.iter().map(|(f, _, _)| *f).collect(); + let before = s.doc()?.doc.clone(); + let n = super::super::overprint::edit_counted(s, label, |d| { + for &(id, a, b) in &ranges { + let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) }; + vectorcraft_text::edit::style_range(&mut t.runs, a, b, copy_run); + super::super::typecmd::refresh_bounds(t); + } + Ok(super::super::appearance::count_changed(d, &before, &ids)) + })?; + return Ok(json!({"objects": n})); + } + // A graph's series group stands for its marks, as for `paint.setFill`. + let ids = super::super::graph::paint_targets(&s.doc()?.doc, &paint_targets(s, p)?); + let mut objects = 0; + if !ids.is_empty() { + let before = s.doc()?.doc.clone(); + super::super::overprint::edit_counted(s, label, |d| { + for id in &ids { + let Some(node) = d.node_mut(*id) else { continue }; + if let NodeKind::Text(t) = &mut node.kind { + for r in &mut t.runs { + copy_run(&mut r.style); + } + super::super::typecmd::refresh_bounds(t); + continue; + } + let ap = &mut node.appearance; + let (from, to) = if to_stroke { (ap.fill_paint(), ap.stroke_paint()) } else { (ap.stroke_paint(), ap.fill_paint()) }; + // A missing item reads as None: copying None onto it would add an item that + // changes nothing. + if (skip_none && from.is_none()) || from == to { + continue; + } + if to_stroke { + restore_unpainted_stroke(ap, None, &from); + ap.set_stroke(from); + } else { + ap.set_fill(from); + } + } + objects = super::super::appearance::count_changed(d, &before, &ids); + // The graph keeps the paint its series marks and labels now have. + let series = super::super::graph::capture_series_paints(d, &ids, !to_stroke); + let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); + Ok(objects + usize::from(series || labels)) + })?; + } + // The defaults for new art change the same way, as Swap Fill and Stroke changes them. + let from = if to_stroke { s.paint.fill.clone() } else { s.paint.stroke.clone() }; + if !(skip_none && from.is_none()) { + if to_stroke { + if s.paint.stroke.is_none() && !from.is_none() && s.paint.stroke_width == 0.0 { + s.paint.stroke_width = 1.0; + } + s.paint.stroke = from; + } else { + s.paint.fill = from; + } + } + Ok(json!({"objects": objects})) +} diff --git a/crates/engine/src/cmd/addons/contour.rs b/crates/engine/src/cmd/addons/contour.rs new file mode 100644 index 0000000000..46df381edc --- /dev/null +++ b/crates/engine/src/cmd/addons/contour.rs @@ -0,0 +1,85 @@ +//! Contour (`addon.contour.*`), a built-in add-on: the Contour tool's command. A Contour is a copy of a selected shape that +//! carries a live Offset Path effect, so it grows or shrinks the shape without baking anything: its +//! fill, stroke and effect stay editable, and Expand Appearance bakes it into plain paths. The +//! original stays where it is. Running the command on an object that already carries an Offset +//! Path effect (a Contour made earlier) changes that effect instead of nesting another one. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_render::effects; + +use super::super::edit::{copy_above, selected_roots}; +use super::super::pathops::{len_param, num_param}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; + +const C: &str = "addon.contour.set"; +/// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest offset, in points; Offset Path takes the same. +const MAX_OFFSET: f64 = 1e5; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.contour.set", + "Contour", + [], + None, + "{offset: pt (negative insets), corners?: \"sharp\"|\"round\"|\"square\" (default sharp; square cuts each corner off flat), miterLimit?: 1..500 (4; sharp corners only)} make a copy of each selected path or shape directly above it with a live Offset Path effect, or, for a selected object that already has one (a Contour), change that effect: nothing is baked (Expand Appearance bakes it) and the original is kept → {ids, created, updated}", + has_selection, + contour + )] +} + +/// The Offset Path join a Contour corner style stands for. +fn joins_for(corners: Option<&str>) -> Result<&'static str> { + match corners.map(str::to_ascii_lowercase).as_deref() { + None | Some("sharp") => Ok("miter"), + Some("round") => Ok("round"), + Some("square") => Ok("bevel"), + Some(other) => Err(bad(C, format!("`corners` must be sharp, round or square, not `{other}`"))), + } +} + +fn contour(s: &mut Session, p: &Value) -> Result { + let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; + if offset.abs() > MAX_OFFSET { + return Err(bad(C, "offset out of range")); + } + let joins = joins_for(str_param(p, "corners"))?; + let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter})) + .ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?; + let roots = selected_roots(s)?; + let (updated, created) = s.edit("Contour", |d, sel| { + // A shape that already carries Offset Path is a Contour: change it. Any other path or + // shape gets a Contour copy above it. Type, images and the rest are left alone. + let (mut again, mut fresh) = (vec![], vec![]); + for id in roots { + let Some(n) = d.node(id) else { continue }; + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + continue; + } + if n.appearance.effects.iter().any(|e| e.id == EFFECT) { + again.push(id); + } else { + fresh.push(id); + } + } + if again.is_empty() && fresh.is_empty() { + return Err(EngineError::Other("Contour: select paths or shapes".into())); + } + for id in &again { + if let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects.iter_mut().rev().find(|e| e.id == EFFECT)) { + e.params = effect.params.clone(); + } + } + let made = copy_above(d, &fresh, |_, _, copy| copy.appearance.effects.push(effect.clone()))?; + sel.set(again.iter().chain(made.iter()).copied()); + Ok((again, made)) + })?; + let list = |ids: &[NodeId]| ids.iter().map(|i| i.0).collect::>(); + Ok(json!({ "ids": list(&[updated.as_slice(), created.as_slice()].concat()), "created": list(&created), "updated": list(&updated) })) +} diff --git a/crates/engine/src/cmd/addons/contour/tests.rs b/crates/engine/src/cmd/addons/contour/tests.rs new file mode 100644 index 0000000000..900d110d58 --- /dev/null +++ b/crates/engine/src/cmd/addons/contour/tests.rs @@ -0,0 +1,371 @@ +//! Tests for `addon.contour.set`: a live Offset Path copy of a shape that stays editable until baked. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::Rect; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|x| NodeId(x.as_u64().unwrap())).collect() +} + +fn node(s: &Session, id: NodeId) -> vectorcraft_doc::Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn effects_of(s: &Session, id: NodeId) -> Vec<(String, Value)> { + node(s, id).appearance.effects.iter().map(|e| (e.id.clone(), e.params.clone())).collect() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn node_count(s: &Session) -> usize { + s.doc().unwrap().doc.node_count() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +#[test] +fn contour_is_a_live_copy_above_the_original() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let before = bounds(&s, a); + let r = s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(); + let (made, updated) = (ids_of(&r, "created"), ids_of(&r, "updated")); + assert_eq!((made.len(), updated.len()), (1, 0)); + // The original is untouched, the copy is above it and selected, and nothing is baked: the + // copy's own path is still the original's, with the effect on top. + assert!(effects_of(&s, a).is_empty()); + assert_eq!(bounds(&s, a), before); + assert_eq!(s.doc().unwrap().selection.objects, made); + let d = &s.doc().unwrap().doc; + assert!(d.index_path(made[0]).unwrap() > d.index_path(a).unwrap()); + assert_eq!(bounds(&s, made[0]), before); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1); + assert_eq!(fx[0].0, "path.offsetPath"); + assert_eq!(fx[0].1["offset"], json!(10.0)); + assert_eq!(fx[0].1["joins"], json!("miter")); +} + +#[test] +fn baking_a_contour_gives_the_grown_and_the_shrunk_shape() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + for (offset, want) in [(10.0, Rect::new(90.0, 90.0, 160.0, 150.0)), (-5.0, Rect::new(105.0, 105.0, 145.0, 135.0))] { + select(&mut s, &[a]); + s.execute("addon.contour.set", &json!({"offset": offset})).unwrap(); + let baked = ids_of(&s.execute("effect.expandAppearance", &json!({})).unwrap(), "ids"); + let b = bounds(&s, baked[0]); + // The default stroke widens the baked art by its weight; compare the fill's edges. + let fill = baked_fill_bounds(&s, baked[0]); + assert!((fill.x0 - want.x0).abs() < 1e-2 && (fill.y1 - want.y1).abs() < 1e-2, "{offset}: {fill:?} vs {want:?} ({b:?})"); + } +} + +/// The bounds of the fill path inside a baked object (a group of its fill and stroke), or of the +/// object itself when it is one path. +fn baked_fill_bounds(s: &Session, id: NodeId) -> Rect { + match &node(s, id).kind { + NodeKind::Group { children, .. } => children.iter().filter_map(|c| c.geometric_bounds()).next().unwrap(), + _ => bounds(s, id), + } +} + +#[test] +fn a_second_drag_changes_the_contour_instead_of_nesting_one() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 10})).unwrap(), "created"); + let count = node_count(&s); + // The Contour is selected: the next call edits it. + let r = s.execute("addon.contour.set", &json!({"offset": -4, "corners": "round"})).unwrap(); + assert_eq!(ids_of(&r, "updated"), made); + assert!(ids_of(&r, "created").is_empty()); + assert_eq!(node_count(&s), count, "no new object"); + let fx = effects_of(&s, made[0]); + assert_eq!(fx.len(), 1, "one Offset Path, not two"); + assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone()), (json!(-4.0), json!("round"))); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn corner_styles_choose_the_join() { + for (corners, joins) in [("sharp", "miter"), ("round", "round"), ("square", "bevel"), ("Round", "round")] { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 3, "corners": corners})).unwrap(), "created"); + assert_eq!(effects_of(&s, made[0])[0].1["joins"], json!(joins), "{corners}"); + } +} + +#[test] +fn contour_keeps_the_color_and_stroke_editable_on_the_copy() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let made = ids_of(&s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(), "created"); + let original = node(&s, a).appearance.items.clone(); + assert_eq!(node(&s, made[0]).appearance.items, original, "the copy starts with the shape's own paint"); + // Recolouring the Contour (it is the selection) changes its fill only: the live effect stays + // and the original keeps its paint. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_ne!(node(&s, made[0]).appearance.items, original, "the copy took the new fill"); + assert_eq!(node(&s, a).appearance.items, original, "the original is untouched"); + assert_eq!(effects_of(&s, made[0]).len(), 1); +} + +#[test] +fn contour_is_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + s.execute("addon.contour.set", &json!({"offset": 6})).unwrap(); + assert_eq!(node_count(&s), count + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), count); + assert!(effects_of(&s, a).is_empty()); +} + +#[test] +fn contour_refuses_what_it_cannot_offset() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let count = node_count(&s); + for params in [json!({}), json!({"offset": "abc"}), json!({"offset": 1e300}), json!({"offset": 5, "corners": "pointy"})] { + assert!(s.execute("addon.contour.set", ¶ms).is_err(), "{params}"); + } + // Nothing was added by the refused calls. + assert_eq!(node_count(&s), count); + // Type is not a path to offset. + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Hi"})).unwrap(); + let err = s.execute("addon.contour.set", &json!({"offset": 5})).unwrap_err().to_string(); + assert!(err.contains("select paths or shapes"), "{err}"); +} + +/// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then +/// the gap taken out of the border with Minus Front, leaves a ring between the two. +#[test] +fn border_with_a_gap_from_two_contours_and_minus_front() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + // Strip the default stroke so the areas are plain. + s.execute("paint.setStroke", &json!({"none": true})).ok(); + // The gap first (+8), then the border (+20) from the same shape: both land directly above it, + // the later one lower, so the gap ends up in front of the border. + select(&mut s, &[a]); + let gap = ids_of(&s.execute("addon.contour.set", &json!({"offset": 8})).unwrap(), "created")[0]; + select(&mut s, &[a]); + let border = ids_of(&s.execute("addon.contour.set", &json!({"offset": 20})).unwrap(), "created")[0]; + let d = &s.doc().unwrap().doc; + assert!(d.index_path(gap).unwrap() > d.index_path(border).unwrap(), "the gap is in front of the border"); + select(&mut s, &[border, gap]); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let both: Vec = s.doc().unwrap().selection.objects.to_vec(); + assert_eq!(both.len(), 2); + let ring = ids_of(&s.execute("object.pathfinder.minusFront", &json!({})).unwrap(), "ids"); + assert_eq!(ring.len(), 1); + // 90 x 80 outer minus 66 x 56 inner, with sharp corners. + let area = vectorcraft_pathops::area(&ring_path(&s, ring[0]).0, ring_path(&s, ring[0]).1); + assert!((area - (90.0 * 80.0 - 66.0 * 56.0)).abs() < 1.0, "{area}"); +} + +fn ring_path(s: &Session, id: NodeId) -> (vectorcraft_geom::PathData, vectorcraft_geom::FillRule) { + match &node(s, id).kind { + NodeKind::Path { path, rule, .. } => (path.clone(), *rule), + NodeKind::Compound { children, rule } => { + (vectorcraft_geom::PathData::new(children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect()), *rule) + } + NodeKind::Group { children, .. } => children.first().map(|c| ring_path(s, c.id)).unwrap(), + _ => panic!("not a path"), + } +} + +mod tool { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + + use super::*; + use crate::tooling::ViewInfo; + + fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..Default::default() } + } + + fn at(s: &mut Session, kind: PointerKind, x: f64, y: f64, mods: Mods) { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view()).unwrap(); + } + + fn undo_depth(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + /// A 50 x 40 rectangle at (100, 100), selected, with the Contour tool active. + fn ready() -> (Session, NodeId) { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + select(&mut s, &[a]); + s.select_tool("contour", view()).unwrap(); + (s, a) + } + + fn offset_of(s: &Session, id: NodeId) -> f64 { + effects_of(s, id)[0].1["offset"].as_f64().unwrap() + } + + #[test] + fn dragging_out_previews_live_and_commits_one_undo_step() { + let (mut s, a) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + // Press on the right edge and pull 10 pt away from the shape. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + assert!(s.in_interaction(), "the Contour is previewed while the button is down"); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!(undo_depth(&s), before + 1); + assert_eq!(node_count(&s), nodes + 1); + assert_eq!(s.journal.last().map(|j| j.0.as_str()), Some("addon.contour.set")); + let made = s.doc().unwrap().selection.objects.clone(); + assert_eq!(made.len(), 1); + assert_ne!(made[0], a); + assert!((offset_of(&s, made[0]) - 10.0).abs() < 1e-6, "{}", offset_of(&s, made[0])); + assert!(effects_of(&s, a).is_empty(), "the original is kept as it was"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node_count(&s), nodes); + } + + #[test] + fn dragging_in_shrinks_and_a_second_drag_continues_from_where_the_contour_stands() { + let (mut s, _) = ready(); + // From inside, 5 pt toward the middle of the right edge's neighbourhood. + at(&mut s, PointerKind::Down, 145.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 140.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 140.0, 120.0, Mods::default()); + let contour = s.doc().unwrap().selection.objects[0]; + assert!((offset_of(&s, contour) + 5.0).abs() < 1e-6); + // The Contour is selected: pressing at the edge and pulling out 12 pt adds to its -5. + let nodes = node_count(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 162.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 162.0, 120.0, Mods::default()); + assert_eq!(node_count(&s), nodes, "the same Contour changed, none was nested"); + assert_eq!(s.doc().unwrap().selection.objects, vec![contour]); + assert_eq!(effects_of(&s, contour).len(), 1); + assert!((offset_of(&s, contour) - 7.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + } + + #[test] + fn escape_and_a_plain_click_change_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert!(!s.in_interaction()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + // A click with no movement. + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 150.0, 120.0, Mods::default()); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes)); + } + + #[test] + fn shift_rounds_to_whole_points_and_the_corner_option_is_used() { + let (mut s, _) = ready(); + s.set_tool_option("corners", &json!("round")); + let shift = Mods { shift: true, ..Mods::default() }; + at(&mut s, PointerKind::Down, 150.0, 120.0, shift); + at(&mut s, PointerKind::Drag, 160.4, 120.0, shift); + at(&mut s, PointerKind::Up, 160.4, 120.0, shift); + let contour = s.doc().unwrap().selection.objects[0]; + assert_eq!(offset_of(&s, contour), 10.0); + assert_eq!(effects_of(&s, contour)[0].1["joins"], json!("round")); + } + + /// A Contour keeps its own corner style and miter limit when it is dragged again, whatever the + /// tool's options are by then (they said Sharp when the Contour was made Square). + #[test] + fn dragging_a_contour_again_keeps_its_corners_and_miter_limit() { + let (mut s, _) = ready(); + s.execute("addon.contour.set", &json!({"offset": 5, "corners": "square", "miterLimit": 7})).unwrap(); + let contour = s.doc().unwrap().selection.objects[0]; + s.set_tool_option("corners", &json!("sharp")); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 158.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 158.0, 120.0, Mods::default()); + let fx = effects_of(&s, contour); + assert_eq!(fx.len(), 1); + assert!((offset_of(&s, contour) - 13.0).abs() < 1e-6, "{}", offset_of(&s, contour)); + assert_eq!(fx[0].1["joins"], json!("bevel"), "{:?}", fx[0].1); + assert_eq!(fx[0].1["miterLimit"], json!(7.0), "{:?}", fx[0].1); + } + + /// A drag that never moves the distance (along the edge, or rounded back to nothing by Shift) + /// leaves no unchanged copy and no undo step. + #[test] + fn a_drag_along_the_edge_changes_nothing() { + let (mut s, _) = ready(); + let (before, nodes) = (undo_depth(&s), node_count(&s)); + let shift = Mods { shift: true, ..Mods::default() }; + for (mods, to) in [(Mods::default(), (150.0, 135.0)), (shift, (150.3, 120.0))] { + at(&mut s, PointerKind::Down, 150.0, 120.0, mods); + at(&mut s, PointerKind::Drag, to.0, to.1, mods); + at(&mut s, PointerKind::Up, to.0, to.1, mods); + assert_eq!((undo_depth(&s), node_count(&s)), (before, nodes), "{to:?}"); + assert!(!s.in_interaction()); + } + } + + /// The outline a Contour was made from shows as a dashed guide over a solid halo (so it reads + /// over any fill); a shape that is not a Contour yet has none. + #[test] + fn a_selected_contour_shows_the_outline_it_was_made_from() { + use vectorcraft_tools::Overlay; + let (mut s, _) = ready(); + let paths = |s: &mut Session| -> Vec<(bool, f32)> { + s.overlays(view()) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, width, .. } => Some((dashed, width)), + _ => None, + }) + .collect() + }; + assert!(paths(&mut s).is_empty(), "a plain shape has no guide"); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 160.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 160.0, 120.0, Mods::default()); + // The solid halo first, the dashes on top of it. + assert_eq!(paths(&mut s), [(false, 3.0), (true, 1.0)]); + } + + #[test] + fn nothing_selected_does_nothing() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("contour", view()).unwrap(); + let before = undo_depth(&s); + at(&mut s, PointerKind::Down, 150.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Drag, 170.0, 120.0, Mods::default()); + at(&mut s, PointerKind::Up, 170.0, 120.0, Mods::default()); + assert_eq!(undo_depth(&s), before); + } +} diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 52f7f3168e..fafdfc07dc 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Batch Trace Folder", ["Object", "Plug-ins", "Document Tools"], None, - "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", + "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Optional settings use their defaults only when omitted; null and values of the wrong type return an error before any image is opened. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", always, batch_trace::batch_trace_folder ), diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs index 0340fca183..61e59fc54f 100644 --- a/crates/engine/src/cmd/addons/document/batch_trace.rs +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -8,9 +8,9 @@ use serde_json::json; #[cfg(not(target_arch = "wasm32"))] use super::super::super::fileio; -use super::super::super::{Result, Session, bad}; #[cfg(not(target_arch = "wasm32"))] -use super::super::super::{bool_or, str_param}; +use super::super::super::str_param; +use super::super::super::{Result, Session, bad}; /// The command id. pub(super) const ID: &str = "addon.document.batchTraceFolder"; @@ -69,20 +69,39 @@ fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Resu pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result { let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?; let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?; - let format = str_param(p, "format").unwrap_or("vectorcraft"); + let format = match p.get("format") { + None => "vectorcraft", + Some(Value::String(value)) => value.as_str(), + Some(_) => return Err(bad(ID, "`format` must be a string")), + }; + let preset = match p.get("preset") { + None => "Default", + Some(Value::String(value)) => value.as_str(), + Some(_) => return Err(bad(ID, "`preset` must be a string")), + }; + let expand = match p.get("expand") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(ID, "`expand` must be true or false")), + }; + let include_subdirs = match p.get("includeSubdirs") { + None => false, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad(ID, "`includeSubdirs` must be true or false")), + }; if !FORMATS.contains(&format) { return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", ")))); } - let preset = str_param(p, "preset").unwrap_or("Default").to_string(); + let preset = preset.to_string(); let presets = s.execute("imageTrace.presets", &json!({}))?; if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); } - let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + let trace = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; fileio::may_read(&folder)?; fileio::may_write(&dest)?; let mut files = vec![]; - images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?; + images(&folder, include_subdirs, 0, &mut files)?; files.sort(); if files.is_empty() { return Err(bad(ID, "no images in the folder")); diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index a1bc5afff6..b0fbb41422 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -333,6 +333,35 @@ fn batch_trace_folder_traces_and_saves_each_image() { let _ = std::fs::remove_dir_all(&dir); } +/// Batch Trace Folder rejects optional values with the wrong type before opening images. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_rejects_wrong_typed_options() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace-bad-options"); + let src = dir.join("in"); + let out = dir.join("out"); + std::fs::create_dir_all(&src).unwrap(); + let mut s = Session::new(); + for (key, value) in [ + ("format", json!(42)), + ("format", Value::Null), + ("preset", json!(false)), + ("preset", Value::Null), + ("expand", json!("true")), + ("expand", Value::Null), + ("includeSubdirs", json!(1)), + ("includeSubdirs", Value::Null), + ] { + let mut params = json!({"folder": src, "destinationFolder": out}); + params[key] = value; + let error = s.execute(C, ¶ms).unwrap_err(); + assert!(error.to_string().contains(&format!("`{key}`")), "{key}: {error}"); + assert!(!out.exists(), "invalid options must not create a destination folder"); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A folder too big to list in full is refused rather than traced in part. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/engine/src/cmd/addons/pathtools/corners.rs b/crates/engine/src/cmd/addons/pathtools/corners.rs index 464fa032ba..2f035d8ad4 100644 --- a/crates/engine/src/cmd/addons/pathtools/corners.rs +++ b/crates/engine/src/cmd/addons/pathtools/corners.rs @@ -20,7 +20,7 @@ pub(super) fn specs() -> Vec { "Set Corners", [], None, - "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", + "{ids?: [id…] (the selection), anchors?: [index…] (of each path's outline with no corners cut; else its direct-selected anchors, or all of them), items?: [{id, anchors?}…] (instead of ids: each path with its own anchors), radius: pt 0..1000000 (drawn no larger than fits), kind?: \"round\"|\"invertedRound\"|\"chamfer\" (each corner's own), every?: \"all\"|\"odd\"|\"even\" (default all: of those anchors, only the odd- or even-numbered ones, counting each path's anchors from 1), minAngle?: degrees 0..180 (default 0), maxAngle?: degrees 0..180 (default 180; of those anchors, only the corners whose sides meet at an angle in this range: small for a sharp spike, near 180 for a shallow bend)} cut live corners at the anchors that can have one, as one undo step → {ids, corners (how many)}", has_doc, corner_set ), @@ -50,8 +50,108 @@ fn anchors_param(p: &Value, cmd: &str) -> Result>> { .map(Some) } -/// The corners a request names: each path with the corners (anchor indices of its uncut outline). -fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result)>> { +/// Which of the chosen anchors `cornerSet` takes, by their number along the path's uncut outline +/// (the first anchor is number 1). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Every { + All, + /// The 1st, 3rd, 5th… anchors: indices 0, 2, 4…. + Odd, + /// The 2nd, 4th, 6th… anchors: indices 1, 3, 5…. + Even, +} + +impl Every { + /// The `every` of `p` (default: all). + fn of(p: &Value, cmd: &str) -> Result { + match p.get("every").filter(|v| !v.is_null()) { + None => Ok(Self::All), + Some(v) => match v.as_str() { + Some("all") => Ok(Self::All), + Some("odd") => Ok(Self::Odd), + Some("even") => Ok(Self::Even), + _ => Err(bad(cmd, format!("`every` must be \"all\", \"odd\" or \"even\", not {v}"))), + }, + } + } + + /// Does it take the anchor at `index`? Anchors that take no corner still count. + fn takes(self, index: usize) -> bool { + match self { + Self::All => true, + Self::Odd => index.is_multiple_of(2), + Self::Even => !index.is_multiple_of(2), + } + } + + /// Where the corners it takes are, for an error: "" for all of them. + fn at(self) -> &'static str { + match self { + Self::All => "", + Self::Odd => " at an odd-numbered anchor (the 1st, 3rd, 5th…)", + Self::Even => " at an even-numbered anchor (the 2nd, 4th, 6th…)", + } + } +} + +/// How far (degrees) past the ends of the angle range a corner's angle may be, so that a typed 90 +/// takes a rectangle's corners whatever the rounding. +const ANGLE_SLACK: f64 = 1e-6; +/// The error when no anchor named is a corner at all. +const NO_CORNER: &str = "choose anchors where two sides meet at an angle: only those take a corner"; + +/// Which of the chosen corners `cornerSet` takes: by their number (`every`) and by the angle their +/// sides meet at (`minAngle`..`maxAngle`, degrees). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Pick { + every: Every, + min_angle: f64, + max_angle: f64, +} + +impl Pick { + /// Every chosen corner. + const ALL: Self = Self { every: Every::All, min_angle: 0.0, max_angle: 180.0 }; + + /// The `every`, `minAngle` and `maxAngle` of `p`. + fn of(p: &Value, cmd: &str) -> Result { + let every = Every::of(p, cmd)?; + let angle = |key: &str, default: f64| -> Result { + let a = number_or(p, key, default, cmd)?; + if !(a.is_finite() && (0.0..=180.0).contains(&a)) { + return Err(bad(cmd, format!("`{key}` must be from 0 to 180 degrees, not {a}"))); + } + Ok(a) + }; + let (min_angle, max_angle) = (angle("minAngle", 0.0)?, angle("maxAngle", 180.0)?); + if min_angle > max_angle { + return Err(bad(cmd, format!("`minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°)"))); + } + Ok(Self { every, min_angle, max_angle }) + } + + /// Does it take corner `index` of `lc`? + fn takes(&self, lc: &LiveCorners, index: usize) -> bool { + self.every.takes(index) + && lc.corner(index).is_some_and(|c| (self.min_angle - ANGLE_SLACK..=self.max_angle + ANGLE_SLACK).contains(&c.angle_deg())) + } + + /// The error when it takes none of the chosen corners. + fn none(&self) -> String { + let at = self.every.at(); + if self.min_angle > 0.0 || self.max_angle < 180.0 { + format!("none of the chosen corners{at} has an angle from {}° to {}°", self.min_angle, self.max_angle) + } else if at.is_empty() { + NO_CORNER.into() + } else { + format!("none of the chosen corners is{at}") + } + } +} + +/// The corners a request names: each path with the corners (anchor indices of its uncut outline) +/// that `pick` takes. +fn named_corners(s: &Session, p: &Value, cmd: &str, pick: Pick) -> Result)>> { let shared = anchors_param(p, cmd)?; // Each path with its own `anchors`, or sharing the request's. let mut own: Vec>> = vec![]; @@ -71,10 +171,10 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result = match own.get(i).and_then(Option::as_ref).or(shared.as_ref()) { Some(given) => { let n = lc.base.anchor_count(); if let Some(past) = given.iter().find(|k| **k >= n) { @@ -84,12 +184,14 @@ fn named_corners(s: &Session, p: &Value, cmd: &str) -> Result st.selection.partial(*id).filter(|a| !a.is_empty()).map_or_else(|| lc.all(), |a| lc.corners_of(a)), }; + chosen |= !corners.is_empty(); + let corners: BTreeSet = corners.into_iter().filter(|k| pick.takes(&lc, *k)).collect(); if !corners.is_empty() { out.push((*id, corners)); } } if out.is_empty() { - return Err(bad(cmd, "choose anchors where two sides meet at an angle: only those take a corner")); + return Err(bad(cmd, if chosen { pick.none() } else { NO_CORNER.into() })); } Ok(out) } @@ -134,11 +236,12 @@ fn corner_set(s: &mut Session, p: &Value) -> Result { .map_err(|_| bad(C, format!("`kind` must be \"round\", \"invertedRound\" or \"chamfer\", not {v}"))) }) .transpose()?; - let corners = named_corners(s, p, C)?; + let pick = Pick::of(p, C)?; + let corners = named_corners(s, p, C, pick)?; edit_corners(s, "Set Corners", corners, radius, kind) } fn corner_remove(s: &mut Session, p: &Value) -> Result { - let corners = named_corners(s, p, "addon.pathtools.cornerRemove")?; + let corners = named_corners(s, p, "addon.pathtools.cornerRemove", Pick::ALL)?; edit_corners(s, "Remove Corners", corners, 0.0, Some(CornerKind::Round)) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 32bcc0c3b3..e31aadf56e 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -567,6 +567,170 @@ fn corner_commands_refuse_bad_params() { } } +/// A closed five-pointed star about (200, 150): its points at the even indices 0, 2… (the odd +/// numbers counting from 1), its inner corners at the odd ones. +fn star_path(s: &mut Session) -> NodeId { + let pts: Vec<(f64, f64)> = (0..10) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 40.0 }, std::f64::consts::PI * f64::from(i) / 5.0); + (200.0 + r * a.sin(), 150.0 - r * a.cos()) + }) + .collect(); + line(s, &pts, true) +} + +/// The cut corners of `id`: anchor indices of its uncut outline with a radius drawn. +fn cut(s: &Session, id: NodeId) -> Vec { + let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() +} + +#[test] +fn corner_set_every_takes_the_odd_or_even_numbered_anchors_of_each_path() { + let mut s = session(); + let star = star_path(&mut s); + // An open zig-zag: its ends (1st and 5th) take no corner but still count. + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0), (90.0, 250.0)], false); + select(&mut s, &[star, zig]); + let n = steps(&s); + // Odd: the 1st, 3rd, 5th… of each path, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "odd"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(6), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![0, 2, 4, 6, 8], vec![2])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, zig), steps(&s)), (vec![], vec![], n)); + // Even: the 2nd, 4th, 6th…. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 4, "every": "even"})).unwrap(); + assert_eq!((r["corners"].clone(), steps(&s)), (json!(7), n + 1)); + assert_eq!((cut(&s, star), cut(&s, zig)), (vec![1, 3, 5, 7, 9], vec![1, 3])); + // "all" (and no `every`) is every chosen corner, as before. + s.execute("addon.pathtools.cornerSet", &json!({"ids": [zig.0], "radius": 4, "every": "all"})).unwrap(); + assert_eq!(cut(&s, zig), vec![1, 2, 3]); +} + +#[test] +fn corner_set_every_filters_the_named_and_direct_selected_anchors() { + let mut s = session(); + let star = star_path(&mut s); + // Of the named anchors, only the even-numbered ones (indices 1 and 3); numbers stay the path's. + let r = s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "anchors": [1, 2, 3, 4], "radius": 3, "every": "even"})).unwrap(); + assert_eq!(r["corners"], json!(2)); + assert_eq!(cut(&s, star), vec![1, 3]); + // Per path through `items`. + s.execute("addon.pathtools.cornerSet", &json!({"items": [{"id": star.0, "anchors": [5, 6, 7]}], "radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 6]); + // Of the direct-selected anchors. + s.execute("addon.pathtools.cornerRemove", &json!({"ids": [star.0]})).unwrap(); + select_anchors(&mut s, star, &[7, 8, 9]); + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "every": "odd"})).unwrap(); + assert_eq!(cut(&s, star), vec![8]); +} + +#[test] +fn corner_set_every_refuses_bad_values_and_says_when_nothing_is_left() { + let mut s = session(); + let zig = line(&mut s, &[(10.0, 250.0), (30.0, 210.0), (50.0, 250.0), (70.0, 210.0)], false); + select(&mut s, &[zig]); + let i = zig.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "every": "third"}), + json!({"ids": [i], "radius": 5, "every": "Odd"}), + json!({"ids": [i], "radius": 5, "every": 2}), + json!({"ids": [i], "radius": 5, "every": true}), + json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"}), + json!({"ids": [i], "anchors": [0, 1], "radius": 5, "every": "odd"}), + ], + ); + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "radius": 5, "every": "third"})).unwrap_err().to_string(); + assert!(e.contains("`every` must be \"all\", \"odd\" or \"even\""), "{e}"); + // The 2nd anchor is a corner, but not an odd-numbered one. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [1], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("odd-numbered"), "{e}"); + // An open end is no corner at all, whatever `every` says. + let e = s.execute("addon.pathtools.cornerSet", &json!({"ids": [i], "anchors": [0], "radius": 5, "every": "odd"})).unwrap_err().to_string(); + assert!(e.contains("two sides meet"), "{e}"); +} + +/// A closed house: a 100 × 100 square under a roof, its corners 90°, 90°, 135°, 90° and 135°. +fn house(s: &mut Session) -> NodeId { + line(s, &[(250.0, 100.0), (350.0, 100.0), (350.0, 200.0), (300.0, 250.0), (250.0, 200.0)], true) +} + +#[test] +fn corner_set_angle_range_rounds_only_the_corners_in_it_on_each_path() { + let mut s = session(); + // The star's points meet at about 38°, its inner corners at about 110°. + let (star, home) = (star_path(&mut s), house(&mut s)); + select(&mut s, &[star, home]); + let n = steps(&s); + // The sharp spikes only: the house has none, the star five, as one step. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "maxAngle": 60})).unwrap(); + assert_eq!((r["ids"].clone(), r["corners"].clone(), steps(&s)), (json!([star.0]), json!(5), n + 1)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![0, 2, 4, 6, 8], vec![])); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((cut(&s, star), steps(&s)), (vec![], n)); + // Exactly 90°: the house's square corners. + s.execute("addon.pathtools.cornerSet", &json!({"radius": 3, "minAngle": 90, "maxAngle": 90})).unwrap(); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![], vec![0, 1, 3])); + // 100° to 140°: the star's inner corners and the roof's; the square corners stay as they are. + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 2, "minAngle": 100, "maxAngle": 140})).unwrap(); + assert_eq!(r["corners"], json!(7)); + assert_eq!((cut(&s, star), cut(&s, home)), (vec![1, 3, 5, 7, 9], vec![0, 1, 2, 3, 4])); + assert_eq!((drawn(&s, home, 0), drawn(&s, home, 2)), (3.0, 2.0)); + // On top of the named anchors and of `every`. + s.execute("addon.pathtools.cornerRemove", &json!({})).unwrap(); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [home.0], "anchors": [1, 2, 3], "radius": 4, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(cut(&s, home), vec![1, 3]); + s.execute("addon.pathtools.cornerSet", &json!({"ids": [star.0], "radius": 4, "every": "even", "minAngle": 100})).unwrap(); + assert_eq!(cut(&s, star), vec![1, 3, 5, 7, 9]); +} + +#[test] +fn corner_set_angle_range_on_a_three_anchor_path() { + let mut s = session(); + // An open pen path of three anchors: one corner, of 90°. + let id = line(&mut s, &[(10.0, 10.0), (60.0, 60.0), (110.0, 10.0)], false); + select(&mut s, &[id]); + let e = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "maxAngle": 45})).unwrap_err().to_string(); + assert!(e.contains("none of the chosen corners has an angle from 0° to 45°"), "{e}"); + let r = s.execute("addon.pathtools.cornerSet", &json!({"radius": 5, "minAngle": 80, "maxAngle": 100})).unwrap(); + assert_eq!(r["corners"], json!(1)); + assert_eq!(cut(&s, id), vec![1]); +} + +#[test] +fn corner_set_angle_range_refuses_bad_values_and_says_when_nothing_matches() { + let mut s = session(); + let star = star_path(&mut s); + select(&mut s, &[star]); + let i = star.0; + refuses( + &mut s, + "addon.pathtools.cornerSet", + &[ + json!({"ids": [i], "radius": 5, "minAngle": -1}), + json!({"ids": [i], "radius": 5, "maxAngle": 181}), + json!({"ids": [i], "radius": 5, "minAngle": 1e308}), + json!({"ids": [i], "radius": 5, "maxAngle": "sharp"}), + json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60}), + json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100}), + json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100}), + ], + ); + let err = |s: &mut Session, p: Value| s.execute("addon.pathtools.cornerSet", &p).unwrap_err().to_string(); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "maxAngle": 200})); + assert!(e.contains("`maxAngle` must be from 0 to 180 degrees"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 120, "maxAngle": 60})); + assert!(e.contains("`minAngle` (120°) can't be more than `maxAngle` (60°)"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "minAngle": 50, "maxAngle": 100})); + assert!(e.contains("none of the chosen corners has an angle from 50° to 100°"), "{e}"); + let e = err(&mut s, json!({"ids": [i], "radius": 5, "every": "odd", "minAngle": 100})); + assert!(e.contains("none of the chosen corners at an odd-numbered anchor (the 1st, 3rd, 5th…) has an angle from 100° to 180°"), "{e}"); +} + #[test] fn the_corner_tool_clicks_drags_and_removes_in_one_step_each() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index ce2869abca..b2ab59d851 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,33 +1,56 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects -//! overlapping, fully inside or fully outside one or more chosen artboards (#5525). Its submenu -//! (Object › Plug-ins › Selection Tools) and dialog are the UI's. +//! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by +//! Link Status selects the images and placed documents whose file is linked, embedded, missing or +//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins +//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. #[cfg(test)] mod tests; +use std::collections::BTreeSet; + use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; use vectorcraft_geom::Point; -use super::super::select::{on_artboard, selectable}; -use super::super::{CommandSpec, bad, cmd, has_doc, point_indices, text_param}; -use crate::{Result, Session}; +use super::super::links::{Status, statuses}; +use super::super::select::{is_selectable, on_artboard, selectable}; +use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param}; +use crate::{DocState, Result, Session}; /// How Select by Artboards relates an object to the chosen artboards (`relation`). pub const RELATIONS: [&str; 3] = ["overlap", "inside", "outside"]; +/// The link statuses Select by Link Status takes (`status`): a file found unchanged, pixels kept +/// in the document, a file not found, a file changed since it was read. +pub const LINK_STATUSES: [&str; 4] = ["linked", "embedded", "missing", "modified"]; + +/// The add-on's commands: Select by Artboards and Select by Link Status. pub fn specs() -> Vec { - vec![cmd!( - "addon.select.byArtboards", - "Select by Artboards", - ["Object", "Plug-ins", "Selection Tools"], - None, - "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", - has_doc, - by_artboards - )] + vec![ + cmd!( + "addon.select.byArtboards", + "Select by Artboards", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}", + has_doc, + by_artboards + ), + cmd!( + "addon.select.byLinkStatus", + "Select by Link Status", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{status: \"linked\" (its file found unchanged) | \"embedded\" | \"missing\" | \"modified\" (its file changed since it was read) | [several of them] (at least one), ids?: [object ids] (pick only among these; default: every image and placed document in the layers), add?: false (add to the selection instead of replacing it), zoom?: false (then zoom to the selection: the desktop app runs addon.arrange.zoomSelection when something was selected; elsewhere the result's zoom flag asks the caller to)} select the image objects and placed documents whose link has that status, as links.list reports it. Those that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are left out and listed with the reason. Only the selection changes, not the document → {count (how many it selected), selected: [ids] (in stacking order, bottom first), skipped: [{id, reason: hidden|locked|template|isolation}], zoom?: true}", + has_doc, + by_link_status + ), + ] } +/// `addon.select.byArtboards`: select the objects Select All takes that overlap, lie inside or lie +/// outside the chosen artboards. fn by_artboards(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.byArtboards"; let relation = text_param(p, "relation", C)?.unwrap_or("overlap"); @@ -61,3 +84,112 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result { s.select(|_, sel| sel.set(ids))?; Ok(json!({ "count": s.doc()?.selection.objects.len() })) } + +/// The link statuses `p` asks for (`status`: one, or a list of them), each once. +fn link_statuses(p: &Value, cmd: &str) -> Result> { + let given: Vec<&Value> = match p.get("status") { + None | Some(Value::Null) => return Err(bad(cmd, "missing `status`: linked, embedded, missing or modified")), + Some(Value::Array(v)) => v.iter().collect(), + Some(v) => vec![v], + }; + let mut out = vec![]; + for v in given { + let s = v.as_str().ok_or_else(|| bad(cmd, "`status` must be linked, embedded, missing or modified, or a list of them"))?; + let known = + LINK_STATUSES.iter().find(|k| **k == s).ok_or_else(|| bad(cmd, format!("status `{s}`: linked, embedded, missing or modified")))?; + if !out.contains(known) { + out.push(*known); + } + } + if out.is_empty() { + return Err(bad(cmd, "choose at least one status")); + } + Ok(out) +} + +/// The link status of every image object and placed document in the layers of `st`, as +/// `links.list` reports it (`ok` named `linked`), in stacking order (bottom first). Each file is +/// looked at once. +pub(crate) fn link_status_of_objects(st: &DocState) -> Vec<(NodeId, &'static str)> { + let linked = statuses(st); + let mut out = vec![]; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) { + let status = match linked.get(&n.id).map(|(s, ..)| *s) { + Some(Status::Ok) => "linked", + Some(Status::Modified) => "modified", + Some(Status::Missing) => "missing", + None => "embedded", + }; + out.push((n.id, status)); + } + }); + out +} + +/// Why object `id` of `st` can't be selected now ([`is_selectable`]): it is outside the isolated +/// group or layer, on a template layer, hidden (or inside something hidden), or locked (or inside +/// something locked, or on a locked artboard); `None` when it can be. `locks` is the document's +/// [`vectorcraft_doc::Document::locked_artboards`]. +fn skip_reason(st: &DocState, locks: &LockedArtboards, id: NodeId) -> Option<&'static str> { + let d = &st.doc; + if is_selectable(d, st.isolation, locks, id) { + return None; + } + let ancestry = d.ancestry(id).unwrap_or_default(); + // Outside the isolated container, or the isolated container itself (its art is what's taken). + if let Some(c) = st.isolation.and_then(|i| d.node(i)) + && ancestry.iter().position(|i| *i == c.id).is_none_or(|at| at + 1 == ancestry.len() && c.is_container()) + { + return Some("isolation"); + } + let held: Vec<&Node> = ancestry.iter().filter_map(|i| d.node(*i)).collect(); + Some(if held.iter().any(|n| n.is_template()) { + "template" + } else if held.iter().any(|n| !n.visible) { + "hidden" + } else { + // A locked object, group or layer, or the locked artboard that holds it. + "locked" + }) +} + +/// `addon.select.byLinkStatus`: select the images and placed documents whose link has one of the +/// statuses asked for (among `ids` when given), replacing the selection or adding to it, and list +/// those left out with the reason ([`skip_reason`]). +fn by_link_status(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.byLinkStatus"; + let wanted = link_statuses(p, C)?; + let add = switch_or(p, "add", false, C)?; + let zoom = switch_or(p, "zoom", false, C)?; + let only: Option> = match p.get("ids") { + None | Some(Value::Null) => None, + Some(_) => Some(checked_ids_param(s, p, "ids", C)?.into_iter().collect()), + }; + let st = s.doc()?; + let locks = st.doc.locked_artboards(); + let (mut picked, mut skipped) = (vec![], vec![]); + for (id, status) in link_status_of_objects(st) { + if !wanted.contains(&status) || only.as_ref().is_some_and(|o| !o.contains(&id)) { + continue; + } + match skip_reason(st, &locks, id) { + None => picked.push(id), + Some(reason) => skipped.push(json!({ "id": id.0, "reason": reason })), + } + } + s.select(|_, sel| { + if add { + for id in &picked { + sel.add(*id); + } + } else { + sel.set(picked.iter().copied()); + } + })?; + let mut out = json!({ "count": picked.len(), "selected": picked.iter().map(|id| id.0).collect::>(), "skipped": skipped }); + if zoom { + out["zoom"] = json!(true); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index bea05ff9e2..c97b278258 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -126,3 +126,185 @@ fn a_symbol_instance_is_measured_by_its_art() { assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "inside"})), vec![instance]); assert_eq!(pick(&mut s, json!({"artboards": [0], "relation": "outside"})), vec![]); } + +/// Select by Link Status. +mod by_link_status { + use serde_json::{Value, json}; + use vectorcraft_doc::{Document, NodeId}; + + use crate::Session; + use crate::tests_links::{BLUE, Folder, RED, place, png, session, write}; + + const C: &str = "addon.select.byLinkStatus"; + + /// One linked image whose file stays as it is (`ok`), one whose file changes (`modified`), + /// one whose file goes (`missing`), an embedded one, and a placed document whose file goes + /// (missing too), bottom to top. + struct Links { + s: Session, + ok: NodeId, + modified: NodeId, + missing: NodeId, + embedded: NodeId, + document: NodeId, + _dir: Folder, + } + + /// [`Links`] in a fresh folder named after `name`: the files placed, then one changed and two + /// removed. + fn links(name: &str) -> Links { + let dir = Folder::new(name); + let (a, b, c, e, d) = (dir.file("ok.png"), dir.file("changes.png"), dir.file("goes.png"), dir.file("kept.png"), dir.file("page.vectorcraft")); + write(&a, &png(10, 10, RED)); + write(&b, &png(12, 10, RED)); + write(&c, &png(14, 10, BLUE)); + write(&e, &png(16, 10, BLUE)); + write(&d, &vectorcraft_format::save_file(&Document::new(80.0, 50.0))); + let mut s = session(); + let (ok, modified, missing) = (place(&mut s, &a), place(&mut s, &b), place(&mut s, &c)); + let embedded = NodeId(s.execute("file.place", &json!({"path": e, "at": [100, 100], "link": false})).unwrap()["ids"][0].as_u64().unwrap()); + let document = place(&mut s, &d); + write(&b, &png(13, 10, BLUE)); + std::fs::remove_file(&c).unwrap(); + std::fs::remove_file(&d).unwrap(); + Links { s, ok, modified, missing, embedded, document, _dir: dir } + } + + /// Run the command with `p`, which must succeed. + fn run(s: &mut Session, p: Value) -> Value { + s.execute(C, &p).unwrap_or_else(|e| panic!("{p}: {e}")) + } + + /// `v` sorted. + fn sorted(mut v: Vec) -> Vec { + v.sort(); + v + } + + /// The selected objects, sorted. + fn selection(s: &Session) -> Vec { + sorted(s.doc().unwrap().selection.objects.clone()) + } + + /// The ids of a JSON list, sorted. + fn ids(v: &Value) -> Vec { + sorted(v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()) + } + + #[test] + fn each_status_selects_its_images_and_placed_documents() { + let Links { mut s, ok, modified, missing, embedded, document, _dir } = links("select-status"); + // As the Links panel lists them. + let listed = s.execute("links.list", &json!({})).unwrap(); + let status = |id: NodeId| listed["links"].as_array().unwrap().iter().find(|r| r["id"] == id.0).unwrap()["status"].clone(); + assert_eq!([ok, modified, missing, embedded, document].map(status), ["ok", "modified", "missing", "embedded", "missing"].map(|s| json!(s))); + let undo = s.doc().unwrap().history.undo.len(); + for (status, want) in [("linked", vec![ok]), ("modified", vec![modified]), ("missing", vec![missing, document]), ("embedded", vec![embedded])] + { + s.execute("select.none", &json!({})).unwrap(); + let r = run(&mut s, json!({"status": status})); + assert_eq!((ids(&r["selected"]), r["count"].as_u64()), (sorted(want.clone()), Some(want.len() as u64)), "{status}: {r}"); + assert_eq!(selection(&s), sorted(want), "{status}"); + assert_eq!(r["skipped"], json!([])); + assert!(r.get("zoom").is_none()); + } + // Several at once, in stacking order (bottom first); a status listed twice counts once. + let r = run(&mut s, json!({"status": ["missing", "linked", "missing"]})); + assert_eq!(r["selected"], json!([ok.0, missing.0, document.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn ids_add_and_zoom() { + let Links { mut s, ok, modified, embedded, document, _dir, .. } = links("select-options"); + // Only among the ids given; other objects among them (a rectangle) are passed over. + let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap(); + let r = run(&mut s, json!({"status": "missing", "ids": [document.0, ok.0, rect]})); + assert_eq!(r["selected"], json!([document.0])); + assert_eq!(selection(&s), vec![document]); + // Added to the selection. + let r = run(&mut s, json!({"status": "embedded", "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone()), (Some(1), json!([embedded.0]))); + assert_eq!(selection(&s), sorted(vec![document, embedded])); + // Replacing it by default. + run(&mut s, json!({"status": "modified"})); + assert_eq!(selection(&s), vec![modified]); + // Nothing to select: added, the selection stays; replacing, it empties. + let r = run(&mut s, json!({"status": "linked", "ids": [embedded.0], "add": true})); + assert_eq!((r["count"].as_u64(), r["selected"].clone(), r["skipped"].clone()), (Some(0), json!([]), json!([]))); + assert_eq!(selection(&s), vec![modified]); + run(&mut s, json!({"status": "linked", "ids": [embedded.0]})); + assert_eq!(selection(&s), vec![]); + // Zoom is reported for the caller (the desktop app zooms). + assert_eq!(run(&mut s, json!({"status": "linked", "zoom": true}))["zoom"], true); + assert!(run(&mut s, json!({"status": "linked", "zoom": false})).get("zoom").is_none()); + } + + #[test] + fn hidden_locked_template_and_isolated_ones_are_skipped_with_the_reason() { + let dir = Folder::new("select-skipped"); + let files: Vec = (0..6).map(|i| dir.file(&format!("img{i}.png"))).collect(); + for (i, f) in files.iter().enumerate() { + write(f, &png(10 + i as u32, 10, RED)); + } + let mut s = session(); + let [free, hidden, locked, in_group, mate] = [0, 1, 2, 3, 4].map(|i| place(&mut s, &files[i])); + s.execute("object.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"ids": [locked.0], "locked": true})).unwrap(); + // Inside a locked group. + s.execute("select.set", &json!({"ids": [in_group.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + // On a template layer. + let layer = s.execute("layer.new", &json!({"name": "Trace"})).unwrap()["id"].as_u64().unwrap(); + let on_template = place(&mut s, &files[5]); + s.execute("layer.setProps", &json!({"id": layer, "template": true})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(ids(&r["selected"]), sorted(vec![free, mate]), "{r}"); + let mut reasons: Vec<(u64, String)> = + r["skipped"].as_array().unwrap().iter().map(|k| (k["id"].as_u64().unwrap(), k["reason"].as_str().unwrap().to_string())).collect(); + reasons.sort(); + let mut want: Vec<(u64, String)> = [(hidden, "hidden"), (locked, "locked"), (in_group, "locked"), (on_template, "template")] + .into_iter() + .map(|(id, why)| (id.0, why.to_string())) + .collect(); + want.sort(); + assert_eq!(reasons, want, "{r}"); + assert!(reasons.iter().all(|(_, why)| ["hidden", "locked", "template", "isolation"].contains(&why.as_str()))); + // In isolation mode, those outside the isolated group are left out. + s.execute("select.set", &json!({"ids": [mate.0]})).unwrap(); + let iso = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": iso})).unwrap(); + let r = run(&mut s, json!({"status": "linked"})); + assert_eq!(r["selected"], json!([mate.0]), "{r}"); + let why = |id: NodeId| r["skipped"].as_array().unwrap().iter().find(|k| k["id"] == id.0).map(|k| k["reason"].clone()); + assert_eq!(why(free), Some(json!("isolation"))); + assert_eq!(why(hidden), Some(json!("isolation"))); + } + + #[test] + fn bad_params_are_errors_and_leave_the_selection() { + let Links { mut s, ok, _dir, .. } = links("select-bad"); + for p in [ + json!({}), + json!({"status": null}), + json!({"status": []}), + json!({"status": "lost"}), + json!({"status": ["linked", "lost"]}), + json!({"status": 3}), + json!({"status": [true]}), + json!({"status": "linked", "add": "yes"}), + json!({"status": "linked", "zoom": 1}), + json!({"status": "linked", "ids": "1"}), + json!({"status": "linked", "ids": [999_999]}), + json!({"status": "linked", "ids": [-1]}), + json!({"status": "linked", "stauts": "missing"}), + ] { + s.execute("select.set", &json!({"ids": [ok.0]})).unwrap(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![ok], "{p}"); + } + // Without a document it is off, not a crash. + assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); + } +} diff --git a/crates/engine/src/cmd/addons/shapes.rs b/crates/engine/src/cmd/addons/shapes.rs new file mode 100644 index 0000000000..c401733906 --- /dev/null +++ b/crates/engine/src/cmd/addons/shapes.rs @@ -0,0 +1,477 @@ +//! 3D Box and customizable shapes (`addon.shapes.*`), a built-in add-on: creates rotatable 3D boxes +//! (`addon.shapes.box3d`) and customizable rectangles, ellipses, polygons, stars and spirals +//! (`addon.shapes.rectangle`, `addon.shapes.ellipse`, `addon.shapes.polygon`, `addon.shapes.star`, +//! `addon.shapes.spiral`), and configures extended live-shape parameters on selected shapes +//! (`addon.shapes.configure`: symmetric or per-corner radii, pie/chord/arc/whole modes, polygon/star +//! spoke ratio, corner rounding, randomization, spiral turns/divergence/inner radius, and 3D box +//! rotation angles). + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; +use vectorcraft_tools::addons::box3d::CustomShape; + +use super::super::create::insert_look; +use super::super::{ + CommandSpec, Result, Session, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_selection, str_param, targets, +}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "addon.shapes.rectangle", + "Rectangle", + [], + None, + "{x, y, width, height, radius?: pt, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + rectangle + ), + cmd!( + "addon.shapes.ellipse", + "Ellipse", + [], + None, + "{x, y, width, height, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + ellipse + ), + cmd!( + "addon.shapes.polygon", + "Polygon", + [], + None, + "{cx, cy, radius, sides=6, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + polygon + ), + cmd!( + "addon.shapes.star", + "Star", + [], + None, + "{cx, cy, radius1, radius2?, points=5, rounded=0, randomized=0, startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, rotation?: deg} → {id}", + has_doc, + star + ), + cmd!( + "addon.shapes.spiral", + "Spiral", + [], + None, + "{cx, cy, radius, turns=3, divergence=1, innerRadius=0, clockwise=true} → {id}", + has_doc, + spiral + ), + cmd!( + "addon.shapes.box3d", + "3D Box", + [], + None, + "{x, y, width, height, angleX=30, angleY=30, angleZ=0, parallelX=false, parallelY=true, parallelZ=false} → {id}", + has_doc, + box3d + ), + cmd!( + "addon.shapes.configure", + "Configure Shape", + [], + None, + "{ids?, radius?, radii?: [tl,tr,br,bl], startAngle?, endAngle?, arcMode?: whole|pie|chord|arc, sides?, isStar?, spokeRatio?, rounded?, randomized?, turns?, divergence?, innerRadius?, angleX?, angleY?, angleZ?, parallelX?, parallelY?, parallelZ?, reset?: bool} → {updated}", + has_selection, + configure + ), + ] +} + +fn parse_arc_params(p: &Value) -> ((f64, f64), shapes::EllipseMode) { + let start = f64_or(p, "startAngle", 0.0); + let end = f64_or(p, "endAngle", 360.0); + let mode = match str_param(p, "arcMode") { + Some("pie" | "slice") => shapes::EllipseMode::Slice, + Some("chord") => shapes::EllipseMode::Chord, + Some("arc" | "open") => shapes::EllipseMode::Arc, + _ => shapes::EllipseMode::Whole, + }; + let span = (end - start).rem_euclid(360.0); + let pie = if mode == shapes::EllipseMode::Whole && (span < 1e-6 || (span - 360.0).abs() < 1e-6) { (0.0, 360.0) } else { (start, end) }; + (pie, mode) +} + +fn rect_of(p: &Value, c: &str) -> Result { + let x = f64_req(p, "x", c)?; + let y = f64_req(p, "y", c)?; + let w = f64_req(p, "width", c)?; + let h = f64_req(p, "height", c)?; + Ok(Rect::new(x, y, x + w.abs(), y + h.abs()).abs()) +} + +fn rect_xf(r: Rect, rot: f64) -> Affine { + if rot == 0.0 || !rot.is_finite() { + Affine::translate(r.origin().to_vec2()) + } else { + Affine::translate(r.center().to_vec2()) * vectorcraft_geom::rotate_deg(rot) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0)) + } +} + +fn insert_custom(s: &mut Session, label: &str, live: Option, cs: CustomShape) -> Result { + let path = match (&live, cs.needs_extra_storage()) { + (Some(l), false) => l.to_path(), + _ => cs.to_path(), + }; + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: live.map(Box::new), clipping: false, guide: false }; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let val = insert_look(s, label, kind, look, None, true)?; + if cs.needs_extra_storage() + && let Some(raw_id) = val.get("id").and_then(Value::as_u64) + && let Ok(st) = s.doc_mut() + && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) + { + cs.write_to_node(n); + } + Ok(val) +} + +fn rectangle(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.rectangle"; + check_numbers(p, &["radius", "startAngle", "endAngle", "rotation"], c)?; + let r = rect_of(p, c)?; + let radius = f64_or(p, "radius", 0.0).max(0.0); + let mut radii = [radius; 4]; + if let Some(arr) = p.get("radii").and_then(Value::as_array) + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + if let Some(val) = item.as_f64().filter(|n| n.is_finite()) { + radii[i] = val.max(0.0); + } + } + } + let (pie, arc_mode) = parse_arc_params(p); + let xf = rect_xf(r, f64_or(p, "rotation", 0.0)); + let live = LiveShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf }; + let cs = CustomShape::Rectangle { w: r.width(), h: r.height(), radii, kinds: Default::default(), radii_relative: false, xf, pie, arc_mode }; + let label = if radii.iter().any(|&v| v > 0.0) { "Rounded Rectangle" } else { "Rectangle" }; + insert_custom(s, label, Some(live), cs) +} + +fn ellipse(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.ellipse"; + check_numbers(p, &["startAngle", "endAngle", "rotation"], c)?; + let r = rect_of(p, c)?; + let (pie, arc_mode) = parse_arc_params(p); + let xf = rect_xf(r, f64_or(p, "rotation", 0.0)); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie, xf }; + let cs = CustomShape::Ellipse { w: r.width(), h: r.height(), pie, arc_mode, xf }; + insert_custom(s, "Ellipse", Some(live), cs) +} + +fn polygon(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.polygon"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r = f64_req(p, "radius", c)?.abs(); + check_numbers(p, &["sides", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?; + let sides = (f64_or(p, "sides", 6.0).round() as i64).clamp(3, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0); + let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0); + let (pie, arc_mode) = parse_arc_params(p); + let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let live = LiveShape::Polygon { radius: r, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + let cs = CustomShape::Polygon { + radius: r, + sides, + xf, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: None, + rounded, + randomized, + pie, + arc_mode, + }; + insert_custom(s, "Polygon", Some(live), cs) +} + +fn star(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.star"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r1 = f64_req(p, "radius1", c)?.abs(); + check_numbers(p, &["radius2", "points", "rotation", "rounded", "randomized", "startAngle", "endAngle"], c)?; + let r2 = f64_or(p, "radius2", r1 / 2.0).abs(); + let points = (f64_or(p, "points", 5.0).round() as i64).clamp(3, 1000) as u32; + let rot = f64_or(p, "rotation", 0.0); + let rounded = f64_or(p, "rounded", 0.0).clamp(-10.0, 10.0); + let randomized = f64_or(p, "randomized", 0.0).clamp(-10.0, 10.0); + let (pie, arc_mode) = parse_arc_params(p); + let xf = Affine::translate(center.to_vec2()) * vectorcraft_geom::rotate_deg(rot); + let ratio = if r1 > 1e-9 { (r2 / r1).clamp(0.01, 1.0) } else { 0.5 }; + let cs = CustomShape::Polygon { + radius: r1, + sides: points, + xf, + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: Some(ratio), + rounded, + randomized, + pie, + arc_mode, + }; + insert_custom(s, "Star", None, cs) +} + +fn spiral(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.spiral"; + let center = Point::new(f64_req(p, "cx", c)?, f64_req(p, "cy", c)?); + let r = f64_req(p, "radius", c)?.abs(); + check_numbers(p, &["turns", "divergence", "innerRadius"], c)?; + check_switches(p, &["clockwise"], c)?; + let turns = f64_or(p, "turns", 3.0).clamp(0.01, 1024.0); + let divergence = f64_or(p, "divergence", 1.0).clamp(0.0, 1000.0); + let inner_radius = f64_or(p, "innerRadius", 0.0).clamp(0.0, 0.999); + let clockwise = bool_or(p, "clockwise", true); + let cs = CustomShape::Spiral { center, radius: r, turns, divergence, inner_radius, clockwise }; + insert_custom(s, "Spiral", None, cs) +} + +fn box3d(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.box3d"; + let r = rect_of(p, c)?; + check_numbers(p, &["angleX", "angleY", "angleZ"], c)?; + check_switches(p, &["parallelX", "parallelY", "parallelZ"], c)?; + let angle_x = f64_or(p, "angleX", 30.0); + let angle_y = f64_or(p, "angleY", 30.0); + let angle_z = f64_or(p, "angleZ", 0.0); + let parallel_x = bool_or(p, "parallelX", false); + let parallel_y = bool_or(p, "parallelY", true); + let parallel_z = bool_or(p, "parallelZ", false); + let cs = CustomShape::Box3d { + w: r.width(), + h: r.height(), + angle_x, + angle_y, + angle_z, + parallel_x, + parallel_y, + parallel_z, + xf: Affine::translate(r.origin().to_vec2()), + }; + let kind = NodeKind::Path { path: cs.to_path(), rule: FillRule::NonZero, live: None, clipping: false, guide: false }; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let val = insert_look(s, "3D Box", kind, look, Some("3D Box".into()), true)?; + if let Some(raw_id) = val.get("id").and_then(Value::as_u64) + && let Ok(st) = s.doc_mut() + && let Some(n) = std::sync::Arc::make_mut(&mut st.doc).node_mut(NodeId(raw_id)) + { + cs.write_to_node(n); + } + Ok(val) +} + +fn configure(s: &mut Session, p: &Value) -> Result { + let c = "addon.shapes.configure"; + check_numbers( + p, + &[ + "radius", + "startAngle", + "endAngle", + "sides", + "spokeRatio", + "rounded", + "randomized", + "turns", + "divergence", + "innerRadius", + "angleX", + "angleY", + "angleZ", + ], + c, + )?; + check_switches(p, &["isStar", "parallelX", "parallelY", "parallelZ", "reset"], c)?; + let ids = targets(s, p)?; + let reset = bool_or(p, "reset", false); + let spiral_hint = p.get("turns").is_some() || p.get("divergence").is_some() || p.get("innerRadius").is_some(); + let updated = s.edit("Live Shape", |d, _| { + let mut count = 0usize; + for id in ids { + let Some(n) = d.node_mut(id) else { continue }; + let Some(mut cs) = CustomShape::read_for_update(n, spiral_hint) else { continue }; + if apply_shape_params(&mut cs, p, reset) { + cs.write_to_node(n); + count += 1; + } + } + Ok(count) + })?; + Ok(json!({ "updated": updated })) +} + +fn num_param(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()) +} + +fn apply_arc_params(p: &Value, pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool { + let mut changed = false; + if let Some(a0) = num_param(p, "startAngle") { + pie.0 = a0.rem_euclid(360.0); + changed = true; + } + if let Some(a1) = num_param(p, "endAngle") { + pie.1 = a1.rem_euclid(360.0); + changed = true; + } + if let Some(m) = str_param(p, "arcMode") { + *arc_mode = parse_mode(m); + if *arc_mode == shapes::EllipseMode::Whole { + *pie = (0.0, 360.0); + } else if (pie.1 - pie.0).abs() < 1e-6 || ((pie.1 - pie.0).abs() - 360.0).abs() < 1e-6 { + *pie = (0.0, 270.0); + } + changed = true; + } + changed +} + +fn apply_rect_params(p: &Value, reset: bool, max_r: f64, radii: &mut [f64; 4], pie: &mut (f64, f64), arc_mode: &mut shapes::EllipseMode) -> bool { + let mut changed = false; + if reset { + *radii = [0.0; 4]; + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + changed = true; + } + if let Some(r) = num_param(p, "radius") { + *radii = [r.clamp(0.0, max_r); 4]; + changed = true; + } + if let Some(arr) = p.get("radii").and_then(Value::as_array) + && arr.len() == 4 + { + for (i, v) in arr.iter().enumerate() { + if let Some(r) = v.as_f64().filter(|x| x.is_finite()) { + radii[i] = r.clamp(0.0, max_r); + changed = true; + } + } + } + changed | apply_arc_params(p, pie, arc_mode) +} + +fn apply_poly_params(p: &Value, reset: bool, sides: &mut u32, spoke_ratio: &mut Option, rounded: &mut f64, randomized: &mut f64) -> bool { + let mut changed = false; + if reset { + *rounded = 0.0; + *randomized = 0.0; + if spoke_ratio.is_some() { + *spoke_ratio = Some(0.5); + } + changed = true; + } + if let Some(n_sides) = p.get("sides").and_then(Value::as_u64) { + *sides = (n_sides as u32).clamp(3, 1000); + changed = true; + } + if let Some(star) = p.get("isStar").and_then(Value::as_bool) { + *spoke_ratio = if star { Some(spoke_ratio.unwrap_or(0.5)) } else { None }; + changed = true; + } + if let Some(sr) = num_param(p, "spokeRatio") { + *spoke_ratio = Some(sr.clamp(0.01, 1.0)); + changed = true; + } + if let Some(rnd) = num_param(p, "rounded") { + *rounded = rnd.clamp(-10.0, 10.0); + changed = true; + } + if let Some(rand) = num_param(p, "randomized") { + *randomized = rand.clamp(-10.0, 10.0); + changed = true; + } + changed +} + +fn apply_shape_params(cs: &mut CustomShape, p: &Value, reset: bool) -> bool { + match cs { + CustomShape::Rectangle { w, h, radii, pie, arc_mode, .. } => apply_rect_params(p, reset, w.min(*h) / 2.0, radii, pie, arc_mode), + CustomShape::Ellipse { pie, arc_mode, .. } => { + let mut changed = false; + if reset { + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + changed = true; + } + changed | apply_arc_params(p, pie, arc_mode) + } + CustomShape::Polygon { sides, spoke_ratio, rounded, randomized, pie, arc_mode, .. } => { + if reset { + *pie = (0.0, 360.0); + *arc_mode = shapes::EllipseMode::Whole; + } + apply_poly_params(p, reset, sides, spoke_ratio, rounded, randomized) | apply_arc_params(p, pie, arc_mode) + } + CustomShape::Spiral { turns, divergence, inner_radius, .. } => { + let mut changed = false; + if reset { + *turns = 3.0; + *divergence = 1.0; + *inner_radius = 0.0; + changed = true; + } + if let Some(t) = num_param(p, "turns") { + *turns = t.clamp(0.01, 1024.0); + changed = true; + } + if let Some(div) = num_param(p, "divergence") { + *divergence = div.clamp(0.0, 1000.0); + changed = true; + } + if let Some(ir) = num_param(p, "innerRadius") { + *inner_radius = ir.clamp(0.0, 0.999); + changed = true; + } + changed + } + CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. } => { + let mut changed = false; + if reset { + *angle_x = 30.0; + *angle_y = 30.0; + *angle_z = 0.0; + *parallel_x = false; + *parallel_y = true; + *parallel_z = false; + changed = true; + } + for (k, slot) in [("angleX", angle_x), ("angleY", angle_y), ("angleZ", angle_z)] { + if let Some(v) = num_param(p, k) { + *slot = v; + changed = true; + } + } + for (k, slot) in [("parallelX", parallel_x), ("parallelY", parallel_y), ("parallelZ", parallel_z)] { + if let Some(v) = p.get(k).and_then(Value::as_bool) { + *slot = v; + changed = true; + } + } + changed + } + } +} + +fn parse_mode(m: &str) -> shapes::EllipseMode { + match m { + "pie" | "slice" => shapes::EllipseMode::Slice, + "chord" => shapes::EllipseMode::Chord, + "arc" | "open" => shapes::EllipseMode::Arc, + _ => shapes::EllipseMode::Whole, + } +} diff --git a/crates/engine/src/cmd/addons/shapes/tests.rs b/crates/engine/src/cmd/addons/shapes/tests.rs new file mode 100644 index 0000000000..793ae6074c --- /dev/null +++ b/crates/engine/src/cmd/addons/shapes/tests.rs @@ -0,0 +1,137 @@ +use serde_json::json; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_tools::addons::box3d::CustomShape; + +use crate::Session; + +fn new_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s +} + +#[test] +fn default_shapes_do_not_alter_standard_documents() { + let mut s = new_session(); + + // Default rectangle: standard LiveShape::Rectangle, no vc-shape-tools attribute. + let rect_id = + NodeId(s.execute("shape.rectangle", &json!({"x": 10.0, "y": 20.0, "width": 100.0, "height": 50.0})).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(rect_id).unwrap(); + assert!(n.extras().attrs.is_none()); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") }; + assert_eq!( + **live, + LiveShape::Rectangle { + w: 100.0, + h: 50.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((10.0, 20.0)) + } + ); + assert_eq!(path, &shapes::rectangle(Rect::new(10.0, 20.0, 110.0, 70.0))); + + // Default ellipse: standard LiveShape::Ellipse, no vc-shape-tools attribute. + let ell_id = NodeId(s.execute("shape.ellipse", &json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + assert!(n.extras().attrs.is_none()); + let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live path") }; + assert_eq!(**live, LiveShape::Ellipse { w: 80.0, h: 60.0, pie: (0.0, 360.0), xf: Affine::IDENTITY }); + assert_eq!(path, &shapes::ellipse(Rect::new(0.0, 0.0, 80.0, 60.0))); +} + +#[test] +fn addon_shapes_commands_and_format_roundtrip_preserve_paths() { + let mut s = new_session(); + + // Create customizable shapes through addon.shapes.* commands. + let box_id = NodeId( + s.execute( + "addon.shapes.box3d", + &json!({"x": 10.0, "y": 10.0, "width": 100.0, "height": 80.0, "angleX": 30.0, "angleY": 35.0, "angleZ": 0.0}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(box_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert_eq!(path.subpaths.len(), 3); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, angle_y, .. }) if (angle_x - 30.0).abs() < 1e-6 && (angle_y - 35.0).abs() < 1e-6) + ); + + s.execute("addon.shapes.configure", &json!({"angleX": 45.0, "parallelX": true})).unwrap(); + let n = s.doc().unwrap().doc.node(box_id).unwrap(); + assert!(matches!(CustomShape::read(n), Some(CustomShape::Box3d { angle_x, parallel_x: true, .. }) if (angle_x - 45.0).abs() < 1e-6)); + + let ell_id = NodeId( + s.execute( + "addon.shapes.ellipse", + &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 100.0, "arcMode": "arc", "startAngle": 30.0, "endAngle": 210.0}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert!(!path.subpaths[0].closed); + + s.execute("addon.shapes.configure", &json!({"arcMode": "chord"})).unwrap(); + let n = s.doc().unwrap().doc.node(ell_id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("expected path") }; + assert!(path.subpaths[0].closed); + + let rect_id = NodeId( + s.execute("addon.shapes.rectangle", &json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 80.0, "radii": [10.0, 20.0, 5.0, 0.0], "arcMode": "pie", "startAngle": 0.0, "endAngle": 180.0})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(rect_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Rectangle { radii, arc_mode: shapes::EllipseMode::Slice, .. }) if radii == [10.0, 20.0, 5.0, 0.0]) + ); + + let poly_id = NodeId( + s.execute("addon.shapes.polygon", &json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5, "rounded": 0.25, "randomized": 0.1})).unwrap() + ["id"] + .as_u64() + .unwrap(), + ); + s.execute("addon.shapes.configure", &json!({"isStar": true, "spokeRatio": 0.4})).unwrap(); + let n = s.doc().unwrap().doc.node(poly_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Polygon { spoke_ratio: Some(sr), rounded, .. }) if (sr - 0.4).abs() < 1e-6 && (rounded - 0.25).abs() < 1e-6) + ); + + let spiral_id = NodeId( + s.execute("addon.shapes.spiral", &json!({"cx": 60.0, "cy": 60.0, "radius": 45.0, "turns": 4.0, "divergence": 1.4, "innerRadius": 0.2})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let n = s.doc().unwrap().doc.node(spiral_id).unwrap(); + assert!( + matches!(CustomShape::read(n), Some(CustomShape::Spiral { turns, divergence, .. }) if (turns - 4.0).abs() < 1e-6 && (divergence - 1.4).abs() < 1e-6) + ); + + // Verify that saving and reopening a document containing add-on shapes preserves both the + // baked PathData/LiveShape (for a build that ignores the add-on attribute) and the stored + // extras attribute across a save/load roundtrip. + let doc_before = s.doc().unwrap().doc.clone(); + let bytes = vectorcraft_format::save(&doc_before, false); + let doc_after = vectorcraft_format::load(&bytes).unwrap(); + let re_saved = vectorcraft_format::save(&doc_after, false); + assert_eq!(bytes, re_saved); + for id in [box_id, ell_id, rect_id, poly_id, spiral_id] { + let a = doc_before.node(id).unwrap(); + let b = doc_after.node(id).unwrap(); + assert_eq!(a.kind, b.kind); + assert_eq!(CustomShape::read(a), CustomShape::read(b)); + } +} diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index a478b8c00b..bc1d4e4f25 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -2,22 +2,27 @@ //! the selected characters letter by letter, from a start value to an end value along a shape //! (straight, eased, a bow, a spike, or at random), while the text stays live. Values are set as //! the Character panel sets them (`text.setRangeStyle`), in its units and ranges -//! (). Its submenu -//! (Object › Plug-ins › Type Tools) and dialog are the UI's. +//! (). Release Type on a Path +//! splits type on a path into point type holding the same text and the plain path it was set on +//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no +//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's. #[cfg(test)] mod tests; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, TextRun}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun}; +use vectorcraft_geom::{Affine, ArcPath, Point}; use vectorcraft_text::edit; use super::super::menucmds::whole_or; use super::super::object::choice; use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges}; use super::super::typecmd::refresh_bounds; -use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use super::super::typemenu::text_ids; +use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets}; use crate::{EngineError, Result, Session}; /// An attribute Text Tweaker sets: its `text.setRangeStyle` param, the values it takes and its @@ -41,17 +46,33 @@ pub const SHAPES: [&str; 5] = ["straight", "ease", "bow", "spike", "random"]; const MAX_CHARS: usize = 100_000; pub fn specs() -> Vec { - vec![cmd!( - "addon.type.textTweaker", - "Text Tweaker", - ["Object", "Plug-ins", "Type Tools"], - None, - "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", - has_selection, - text_tweaker - )] + vec![ + cmd!( + "addon.type.textTweaker", + "Text Tweaker", + ["Object", "Plug-ins", "Type Tools"], + None, + "{attribute?: \"size\" (pt 0.1..1296) | \"baselineShift\" (pt −1296..1296) | \"rotation\" (° −360..360) | \"hScale\" (% 1..10000) | \"vScale\" (% 1..10000) | \"tracking\" (1/1000 em −1000..10000) | \"leading\" (pt 0.1..5000) | \"strokeWidth\" (pt 0..1000) (\"size\"), from?: the first character's value, to?: the last character's value (each in the attribute's units and range; defaults: size 12 → 36, baselineShift 0 → 12, rotation 0 → 30, hScale and vScale 100 → 150, tracking 0 → 200, leading 12 → 36, strokeWidth 0 → 2), shape?: \"straight\" (an even ramp) | \"ease\" (slow at both ends) | \"bow\" (from at both ends, rising smoothly to `to` in the middle) | \"spike\" (from at both ends, straight up to `to` in the middle) | \"random\" (each character anywhere from `from` to `to`) (\"straight\"), seed?: whole number (0; random: the same seed and text give the same values), skipSpaces?: true (spaces and line breaks keep their values and don't count), id?, start?: byte, end?: byte (range endpoints inside a character round down to its start), ids?: [id…] (instead of id)} give the characters one character attribute letter by letter, from `from` to `to` along the shape, as the Character panel sets it, as one undo step; the text stays live and editable. The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: all its text), else every selected type object; each object gets its own ramp. Stroke weight only shows on characters with a stroke → {count (characters changed), ids}", + has_selection, + text_tweaker + ), + cmd!( + "addon.type.releasePath", + "Release Type on a Path…", + ["Object", "Plug-ins", "Type Tools"], + None, + "{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}", + has_selection, + release_path + ), + ] } +/// Release Type on a Path's command (the id in [`specs`]). +pub const RELEASE: &str = "addon.type.releasePath"; +/// What Release Type on a Path keeps: both, the path only, or the text only. +pub const RELEASE_MODES: [&str; 3] = ["both", "path", "text"]; + /// Where along `shape` (0 at `from`, 1 at `to`) character `i` of `n` lands; `random` for the /// random shape. fn amount(shape: &str, i: usize, n: usize, random: f64) -> f64 { @@ -187,3 +208,143 @@ fn tweak(runs: Vec, changes: &[(usize, CharChange)]) -> Vec { edit::normalize(&mut out); out } + +/// Type on a path among the objects `p` names (or the selection), inside groups too, in stacking +/// order. An id that names no object is an error. +fn path_types(s: &Session, p: &Value) -> Result> { + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + if let Some(id) = ids.iter().find(|id| d.node(**id).is_none()) { + return Err(EngineError::NoNode(*id)); + } + let on_path = |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, TextKind::OnPath { .. })); + Ok(text_ids(d, &ids).into_iter().filter(on_path).collect()) +} + +/// Where the first character laid out in `lay` starts its baseline: the pen position of the first +/// glyph in text order (a list marker, which has no characters, before the character it leads). +/// None without a glyph. +fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option { + lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin) +} + +/// `t`, type on a path, as point type on one straight line: the same runs and character and +/// paragraph attributes, its baseline starting where its first character sat on the path (in the +/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for +/// other type, or when it can't be placed. +fn released_text(t: &TextObject) -> Option { + let TextKind::OnPath { path, .. } = &t.kind else { return None }; + let db = vectorcraft_text::FontDb::global(); + // Where the first character sat. Text that didn't fit on the path has no glyph there: it + // starts at the start bracket. + let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| { + let ap = ArcPath::new(path); + let (from, _) = t.kind.path_span()?; + let (p, _) = ap.at(from * ap.len()); + (p.x.is_finite() && p.y.is_finite()).then_some(p) + })?; + let mut out = t.clone(); + out.kind = TextKind::Point; + out.path_effect = Default::default(); + out.path_align = Default::default(); + out.path_spacing = 0.0; + // Point type is in no thread: its first paragraph starts in it. + out.first_para_continues = false; + // Where the point type puts its own first character; the origin moves so it lands at `at`, + // whatever the paragraph's alignment and direction. + let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO); + let shift = at - own; + if !(shift.x.is_finite() && shift.y.is_finite()) { + return None; + } + out.xf *= Affine::translate(shift); + refresh_bounds(&mut out); + Some(out) +} + +/// The path `t` is set on, as a plain path object `id` in document space, with no fill and no +/// stroke: type paths carry no paint of their own. None for other type. +fn released_path(id: NodeId, t: &TextObject) -> Option { + Some(Node::path(id, t.type_path()?, Appearance::basic(Paint::None, Paint::None, 1.0))) +} + +fn release_path(s: &mut Session, p: &Value) -> Result { + const C: &str = RELEASE; + let mode = choice(p, C, "mode", &RELEASE_MODES)?.unwrap_or("both"); + let keep = switch_or(p, "keepOriginal", false, C)?; + let want_path = mode != "text"; + let ids = path_types(s, p)?; + if ids.is_empty() { + return Ok(json!({ "ids": [], "paths": [], "texts": [] })); + } + // The point type, worked out before the edit: one object that can't be placed fails the run. + let mut plans: Vec<(NodeId, Option)> = Vec::with_capacity(ids.len()); + { + let d = &s.doc()?.doc; + for id in ids { + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { continue }; + let text = match mode { + "path" => None, + _ => Some(released_text(t).ok_or_else(|| bad(C, format!("object {} can't be set as point type", id.0)))?), + }; + plans.push((id, text)); + } + } + let (paths, texts) = s.edit("Release Type on a Path", |d, sel| { + let (mut paths, mut texts) = (vec![], vec![]); + for (id, text) in plans { + let (path, text) = release_one(d, id, text, want_path, keep)?; + paths.extend(path); + texts.extend(text); + } + sel.set(paths.iter().chain(&texts).copied()); + Ok((paths, texts)) + })?; + // Bottom to top. + let d = &s.doc()?.doc; + let mut all: Vec<(Vec, NodeId)> = paths.iter().chain(&texts).map(|id| (d.index_path(*id).unwrap_or_default(), *id)).collect(); + all.sort(); + let nums = |v: &[NodeId]| v.iter().map(|i| i.0).collect::>(); + let all: Vec = all.into_iter().map(|(_, id)| id).collect(); + Ok(json!({ "ids": nums(&all), "paths": nums(&paths), "texts": nums(&texts) })) +} + +/// Release type on a path `id` in `d`: its path (`want_path`) where the type was, or just above it +/// when the original stays (`keep`), then the point type `text` (None: no text) above that. +/// Without `keep` the original goes, and released text takes its place as the same object, so a +/// frame of threaded text leaves its thread with the text it holds, as Convert To Point Type's +/// does. The released (path, text). +fn release_one(d: &mut Document, id: NodeId, text: Option, want_path: bool, keep: bool) -> Result<(Option, Option)> { + let (parent, idx, _) = d.position(id).ok_or(EngineError::NoNode(id))?; + let original = d.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let NodeKind::Text(t) = &original.kind else { return Ok((None, None)) }; + let path = + if want_path { Some(released_path(d.alloc_id(), t).ok_or_else(|| bad(RELEASE, format!("object {} has no path", id.0)))?) } else { None }; + if !keep && text.is_none() { + d.remove(id)?; + } + // Where the next released object goes: above the original when it stays, else in its place. + let mut at = if keep { idx + 1 } else { idx }; + let path = match path { + Some(n) => { + at += 1; + Some(d.insert(parent, at - 1, n)?) + } + None => None, + }; + let text = match text { + None => None, + Some(text) if keep => { + let mut n = original.clone(); + n.id = d.alloc_id(); + n.kind = NodeKind::Text(Box::new(text)); + Some(d.insert(parent, at, n)?) + } + Some(text) => { + // The original, now just above the path. + d.node_mut(id).ok_or(EngineError::NoNode(id))?.kind = NodeKind::Text(Box::new(text)); + Some(id) + } + }; + Ok((path, text)) +} diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index 7f05cb823a..e597525c97 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -1,5 +1,5 @@ //! Text Tweaker: the values each shape gives each character, what it skips and changes, one undo -//! step, and bad params refused without a change. +//! step, and bad params refused without a change. Release Type on a Path ([`release`]). use serde_json::json; use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject}; @@ -221,3 +221,386 @@ fn it_needs_a_selection() { select(&mut s, &[]); assert!(s.execute(C, &json!({})).is_err()); } + +/// Release Type on a Path (#5532): each mode, Keep Original, mixed and empty selections, closed, +/// open, curved and flipped paths, transformed and grouped type, multi-style and unicode text, +/// undo and redo, the preview a dialog shows, and bad params. +mod release { + use serde_json::{Value, json}; + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Justify, NodeId, NodeKind, TextKind, TextObject}; + use vectorcraft_geom::{PathData, Point}; + + use crate::Session; + + const C: &str = "addon.type.releasePath"; + + fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s + } + + fn new_id(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) + } + + /// 12 pt type `words` on a path along `d` (SVG path data), starting where the path is nearest + /// `at`, selected. + fn path_type(s: &mut Session, d: &str, at: [f64; 2], words: &str) -> NodeId { + let pid = s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let id = new_id(&s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": words, "size": 12, "at": at})).unwrap()); + select(s, &[id]); + id + } + + fn rect(s: &mut Session, x: f64) -> NodeId { + new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 20, "height": 20})).unwrap()) + } + + fn point_type(s: &mut Session) -> NodeId { + new_id(&s.execute("text.create", &json!({"x": 40, "y": 500, "text": "point", "size": 12})).unwrap()) + } + + fn select(s: &mut Session, ids: &[NodeId]) { + s.select(|_, sel| sel.set(ids.iter().copied())).unwrap(); + } + + fn doc(s: &Session) -> Document { + (*s.doc().unwrap().doc).clone() + } + + fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.clone() + } + + fn text(s: &Session, id: NodeId) -> TextObject { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + k => panic!("not text: {k:?}"), + } + } + + fn path(s: &Session, id: NodeId) -> PathData { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path.clone(), + k => panic!("not a path: {k:?}"), + } + } + + /// (parent, index) of `id`. + fn place(s: &Session, id: NodeId) -> (Option, usize) { + let (parent, idx, _) = s.doc().unwrap().doc.position(id).unwrap(); + (parent, idx) + } + + /// Each glyph's pen position in the document and its baseline angle, in text order. + fn pens(t: &TextObject) -> Vec<(Point, f64)> { + let mut g: Vec<_> = + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs.into_iter().map(|g| (g.byte, t.xf * g.origin, g.angle)).collect(); + g.sort_by_key(|g| g.0); + g.into_iter().map(|(_, p, a)| (p, a)).collect() + } + + /// How many path objects the document has. + fn paths_in(s: &Session) -> usize { + let mut n = 0; + for l in &s.doc().unwrap().doc.layers { + l.walk(&mut |c| n += usize::from(matches!(c.kind, NodeKind::Path { .. }))); + } + n + } + + fn close(a: Point, b: Point) -> bool { + (a - b).hypot() < 1e-4 + } + + fn ids(v: &Value, key: &str) -> Vec { + v[key].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() + } + + /// `after`, released from `before`: point type with the same text and attributes, on one + /// straight line whose first character starts where `before`'s did on its path, with no Type + /// on a Path Options left. + fn assert_released(before: &TextObject, after: &TextObject) { + assert_eq!(after.kind, TextKind::Point); + assert_eq!(after.runs, before.runs, "the same text and character attributes"); + assert_eq!((&after.para, &after.paras), (&before.para, &before.paras), "the same paragraph attributes"); + assert_eq!(after.plain_text(), before.plain_text()); + assert_eq!((after.path_effect, after.path_align, after.path_spacing), Default::default(), "path options dropped"); + let (was, now) = (pens(before), pens(after)); + assert!(!now.is_empty()); + if let Some((first, _)) = was.first() { + assert!(close(now[0].0, *first), "the baseline starts where the first character sat: {:?} vs {first:?}", now[0].0); + } + assert!(now.iter().all(|(_, a)| *a == 0.0), "a straight baseline"); + // On one line through the first pen, along the object's own x axis. + let [a, b, ..] = after.xf.as_coeffs(); + let axis = vectorcraft_geom::Vec2::new(a, b); + for (p, _) in &now { + let off = *p - now[0].0; + assert!(off.cross(axis).abs() < 1e-4 * axis.hypot().max(1.0) * off.hypot().max(1.0), "{p:?} is on the line"); + } + } + + #[test] + fn both_gives_point_type_and_the_path_in_the_types_place() { + let mut s = session(); + let below = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Curved line"); + let above = rect(&mut s, 50.0); + select(&mut s, &[id]); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let (start, n) = (doc(&s), steps(&s)); + + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let (paths, texts) = (ids(&out, "paths"), ids(&out, "texts")); + assert_eq!((paths.len(), texts.len()), (1, 1)); + let (p, t) = (paths[0], texts[0]); + assert_eq!(ids(&out, "ids"), [p, t], "bottom to top"); + assert_eq!(selected(&s), [p, t], "the released objects are selected"); + + // The path: its exact shape, anchors and handles, with no fill and no stroke, where the type was. + assert_eq!(path(&s, p), before.type_path().unwrap()); + assert_eq!(*s.doc().unwrap().doc.node(p).unwrap().appearance, Appearance::basic(Paint::None, Paint::None, 1.0)); + assert_eq!( + (place(&s, below), place(&s, p), place(&s, t), place(&s, above)), + ((layer, idx - 1), (layer, idx), (layer, idx + 1), (layer, idx + 2)) + ); + // The text replaces the type on a path. + assert_released(&before, &text(&s, t)); + assert_eq!(t, id, "the same type object, now point type"); + + let released = doc(&s); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start, "undone"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(doc(&s), released, "redone"); + } + + #[test] + fn path_only_and_text_only() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], "Line"); + let before = text(&s, id); + let (layer, idx) = place(&s, id); + let out = s.execute(C, &json!({"mode": "path"})).unwrap(); + let p = ids(&out, "paths")[0]; + assert!(ids(&out, "texts").is_empty()); + assert!(s.doc().unwrap().doc.node(id).is_none(), "the type is gone"); + assert_eq!((path(&s, p), place(&s, p)), (before.type_path().unwrap(), (layer, idx))); + assert_eq!(selected(&s), [p]); + + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text"})).unwrap(); + assert!(ids(&out, "paths").is_empty()); + assert_eq!((ids(&out, "texts"), place(&s, id)), (vec![id], (layer, idx)), "the type stays in its place"); + assert_released(&before, &text(&s, id)); + assert_eq!(paths_in(&s), 0, "no path made"); + } + + #[test] + fn keep_original_adds_the_released_objects_above_it() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Keep"); + let (before, (layer, idx)) = (text(&s, id), place(&s, id)); + let original = s.doc().unwrap().doc.node(id).cloned().unwrap(); + let out = s.execute(C, &json!({"keepOriginal": true})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!(s.doc().unwrap().doc.node(id), Some(&original), "the type on a path stays as it is"); + assert_eq!((place(&s, id), place(&s, p), place(&s, t)), ((layer, idx), (layer, idx + 1), (layer, idx + 2))); + assert_ne!(t, id); + assert_eq!(selected(&s), [p, t], "only the released objects are selected"); + assert_released(&before, &text(&s, t)); + + // Text only, kept: the copy goes just above. + select(&mut s, &[id]); + let out = s.execute(C, &json!({"mode": "text", "keepOriginal": true})).unwrap(); + let t2 = ids(&out, "texts")[0]; + assert_eq!(place(&s, t2), (layer, idx + 1)); + assert_released(&before, &text(&s, t2)); + } + + #[test] + fn other_objects_are_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + let a = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "One"); + let b = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "Two"); + let others = [r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()); + select(&mut s, &[r, pt, a, b]); + let n = steps(&s); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for the whole selection"); + assert_eq!((ids(&out, "paths").len(), ids(&out, "texts")), (2, vec![a, b])); + assert_eq!([r, pt].map(|id| s.doc().unwrap().doc.node(id).cloned().unwrap()), others); + assert_eq!(selected(&s).len(), 4, "the two paths and the two texts"); + assert!(!selected(&s).contains(&r) && !selected(&s).contains(&pt)); + + // `ids` picks the objects instead of the selection. + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[r]); + let out = s.execute(C, &json!({"ids": [r.0, b.0]})).unwrap(); + assert_eq!(ids(&out, "texts"), [b]); + assert!(matches!(text(&s, a).kind, TextKind::OnPath { .. })); + } + + #[test] + fn nothing_to_release_changes_nothing() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let pt = point_type(&mut s); + select(&mut s, &[r, pt]); + let (before, n, sel) = (doc(&s), steps(&s), selected(&s)); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"ids": [], "paths": [], "texts": []})); + assert_eq!((doc(&s), steps(&s), selected(&s)), (before, n, sel), "no change, no step"); + } + + #[test] + fn closed_and_open_paths_keep_their_shape() { + for (d, closed) in [ + ("M200 200 L400 200 L400 400 L200 400 Z", true), + ("M100 300 C150 100 250 500 300 300 S450 100 500 300", false), + ("M300 150 C380 150 450 220 450 300 C450 380 380 450 300 450 C220 450 150 380 150 300 C150 220 220 150 300 150 Z", true), + ] { + let mut s = session(); + let id = path_type(&mut s, d, [200.0, 200.0], "Round and round"); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + let p = path(&s, ids(&out, "paths")[0]); + assert_eq!(p, before.type_path().unwrap(), "{d}"); + assert_eq!(p.is_closed(), closed, "{d}"); + assert_released(&before, &text(&s, ids(&out, "texts")[0])); + } + } + + #[test] + fn flipped_type_releases_its_path_as_it_runs() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [300.0, 200.0], "Flipped"); + s.execute("type.pathOptions", &json!({"flip": true, "effect": "skew", "alignToPath": "center", "spacing": 4})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap()); + assert_released(&before, &text(&s, id)); + } + + #[test] + fn transformed_type_keeps_its_transform() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], "Turned"); + s.execute("object.rotate", &json!({"angle": 30, "origin": [300, 300]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150, "origin": [300, 300]})).unwrap(); + let before = text(&s, id); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(path(&s, ids(&out, "paths")[0]), before.type_path().unwrap(), "the transform is in the path"); + let after = text(&s, id); + assert_eq!(after.xf.as_coeffs()[..4], before.xf.as_coeffs()[..4], "turned and scaled as the type was"); + assert_released(&before, &after); + } + + #[test] + fn grouped_type_releases_inside_its_group() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Grouped"); + select(&mut s, &[r, id]); + s.execute("object.group", &json!({})).unwrap(); + let g = place(&s, id).0.unwrap(); + assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Group { .. })); + select(&mut s, &[g]); + let out = s.execute(C, &json!({})).unwrap(); + let (p, t) = (ids(&out, "paths")[0], ids(&out, "texts")[0]); + assert_eq!((place(&s, p).0, place(&s, t).0), (Some(g), Some(g))); + } + + #[test] + fn styles_and_unicode_text_survive() { + let mut s = session(); + let words = "Größe ✓ 日本語 éa"; + let id = path_type(&mut s, "M100 300 C200 150 400 150 500 300", [100.0, 300.0], words); + // "Gr" (bytes 0..2), and "日本" (bytes 12..18, after "Größe ✓ "). + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 2, "size": 24, "fill": "#ff0000"})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 12, "end": 18, "tracking": 200, "hScale": 150})).unwrap(); + // A centred paragraph: the first character still starts where it sat. + s.edit("centre", |d, _| { + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + t.para.justify = Justify::Center; + } + Ok(()) + }) + .unwrap(); + let before = text(&s, id); + assert!(before.runs.len() >= 3, "several styles: {:?}", before.runs); + let out = s.execute(C, &json!({})).unwrap(); + let after = text(&s, ids(&out, "texts")[0]); + assert_eq!(after.plain_text(), words); + assert_released(&before, &after); + } + + #[test] + fn empty_type_starts_at_its_start_bracket() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [300.0, 300.0], ""); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!(ids(&out, "texts"), [id]); + let t = text(&s, id); + assert_eq!(t.kind, TextKind::Point); + assert!(close(t.xf * Point::ZERO, Point::new(300.0, 300.0)), "{:?}", t.xf * Point::ZERO); + } + + /// What a dialog's Preview does: each preview replaces the last, Cancel puts the type back with + /// no step of history, and OK keeps the preview as one step. + #[test] + fn previews_cancel_and_commit() { + let mut s = session(); + let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Preview"); + let (start, n, sel) = (doc(&s), steps(&s), selected(&s)); + let count = paths_in; + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + assert_eq!((count(&s), text(&s, id).kind), (1, TextKind::Point)); + s.preview(C, &json!({"mode": "text"})).unwrap(); + assert_eq!(count(&s), 0, "the next preview replaces the last"); + s.preview(C, &json!({"mode": "path", "keepOriginal": true})).unwrap(); + assert_eq!(count(&s), 1); + assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. })); + s.cancel_interaction().unwrap(); + assert_eq!((doc(&s), steps(&s), selected(&s)), (start.clone(), n, sel), "Cancel: as it was, no step"); + + s.begin_interaction("Release Type on a Path").unwrap(); + s.preview(C, &json!({"mode": "both"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(steps(&s), n + 1, "OK: one step"); + assert_eq!(text(&s, id).kind, TextKind::Point); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s), start); + } + + #[test] + fn bad_params_are_refused_without_a_change() { + let mut s = session(); + path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Bad"); + let (before, n) = (doc(&s), steps(&s)); + for p in [ + json!({"mode": "all"}), + json!({"mode": 1}), + json!({"keepOriginal": "yes"}), + json!({"ids": [999_999]}), + json!({"ids": "1"}), + json!({"id": -1}), + json!({"colour": "red"}), + ] { + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!((doc(&s), steps(&s)), (before.clone(), n), "{p}"); + } + } +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 6507001c71..c8c479bc03 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -190,7 +190,7 @@ impl Session { let ids: Vec = 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 Result { + 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 { + 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 { // 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 { // 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 { 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 { 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() { diff --git a/crates/engine/src/cmd/attributes.rs b/crates/engine/src/cmd/attributes.rs index 0265b4ccd4..684d33a53d 100644 --- a/crates/engine/src/cmd/attributes.rs +++ b/crates/engine/src/cmd/attributes.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index a6505a057b..3e097f8fca 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -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, diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 6ab7acad0b..406511ff16 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -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)>) { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 13186ed2ef..1f2707fbef 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -12,19 +12,19 @@ mod flavours; pub(crate) mod resources; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::Swatch; -use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef}; -use vectorcraft_geom::Rect; +use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; +use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; pub use flavours::{ImageRead, read_image}; pub(crate) use resources::SwatchChoices; -pub use resources::{ArtResources, art_resources}; +pub use resources::{ArtResources, SymbolOptions, art_resources}; use super::{CommandSpec, Result, Session, always, bad, cmd, f64_or, has_doc, point_param, str_param}; use crate::DocState; @@ -70,6 +70,8 @@ pub struct Clipboard { pub images: BTreeMap, /// Symbols the objects place (also inside other symbols and patterns). pub symbols: Vec, + /// The Symbol Options of [`Self::symbols`] (which the document keeps by name), by symbol name. + pub symbol_options: BTreeMap, /// Patterns the objects paint with (pasting makes their swatches again). pub patterns: Vec, /// Global and spot swatches the objects' colours link to, the tint swatches of the tints they @@ -98,6 +100,114 @@ pub struct Clipboard { pub guides: Vec, } +/// Indices of segments selected on `sp` (either explicitly or via incident anchors). +pub(crate) fn subpath_selected_segments( + sp: &vectorcraft_geom::SubPath, + si: usize, + seg_refs: Option<&BTreeSet<(usize, usize)>>, + anchor_refs: Option<&BTreeSet<(usize, usize)>>, +) -> BTreeSet { + let seg_count = sp.segment_count(); + if seg_count == 0 { + return BTreeSet::new(); + } + let n = sp.anchors.len(); + let mut selected_segs = BTreeSet::new(); + + let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si)); + if has_explicit_segs { + if let Some(segments) = seg_refs { + for &(s, seg) in segments { + if s == si && seg < seg_count { + selected_segs.insert(seg); + } + } + } + return selected_segs; + } + + if let Some(anchors) = anchor_refs { + let sub_anchors: BTreeSet = anchors.iter().filter_map(|&(s, a)| (s == si && a < n).then_some(a)).collect(); + if !sub_anchors.is_empty() { + for i in 0..seg_count { + let next = (i + 1) % n; + if sub_anchors.contains(&i) && sub_anchors.contains(&next) { + selected_segs.insert(i); + } + } + + for &i in &sub_anchors { + let prev_selected = if sp.closed { sub_anchors.contains(&((i + n - 1) % n)) } else { i > 0 && sub_anchors.contains(&(i - 1)) }; + let next_selected = if sp.closed { sub_anchors.contains(&((i + 1) % n)) } else { i + 1 < n && sub_anchors.contains(&(i + 1)) }; + if !prev_selected && !next_selected { + if sp.closed { + selected_segs.insert((i + n - 1) % n); + selected_segs.insert(i); + } else { + if i > 0 { + selected_segs.insert(i - 1); + } + if i < seg_count { + selected_segs.insert(i); + } + } + } + } + } + } + + selected_segs +} + +/// When direct selection is active on a path (some anchors or segments selected), extract only +/// the selected runs as new open path nodes (with retracted endpoint handles). Returns `None` +/// when the node is selected whole or is not a path. +pub(crate) fn extract_direct_selection(node: &Node, selection: &Selection) -> Option> { + let seg_refs = selection.segments.get(&node.id); + let anchor_refs = selection.anchors.get(&node.id); + if seg_refs.is_none() && anchor_refs.is_none() { + return None; + } + let path = node.path_data()?; + let mut subpath_segs = Vec::new(); + let mut total_segs = 0; + let mut total_selected = 0; + + for (si, sp) in path.subpaths.iter().enumerate() { + let segs = subpath_selected_segments(sp, si, seg_refs, anchor_refs); + total_segs += sp.segment_count(); + total_selected += segs.len(); + subpath_segs.push(segs); + } + + if total_selected == 0 { + return None; + } + + // When every segment of the path is selected, copy the object unchanged. + if total_segs > 0 && total_selected == total_segs { + return None; + } + + let mut pieces = vec![]; + for (sp, selected_segs) in path.subpaths.iter().zip(subpath_segs) { + let seg_count = sp.segment_count(); + if selected_segs.is_empty() || seg_count == 0 { + continue; + } + let unselected: BTreeSet = (0..seg_count).filter(|i| !selected_segs.contains(i)).collect(); + let surviving = if unselected.is_empty() { vec![sp.clone()] } else { super::path::without_segments(sp.clone(), &unselected) }; + for surviving_sp in surviving { + let mut piece = node.clone(); + if let NodeKind::Path { rule, clipping, guide, .. } = &node.kind { + piece.kind = NodeKind::Path { path: PathData::single(surviving_sp), rule: *rule, live: None, clipping: *clipping, guide: *guide }; + } + pieces.push(piece); + } + } + if pieces.is_empty() { None } else { Some(pieces) } +} + impl Clipboard { pub fn is_empty(&self) -> bool { self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() @@ -118,15 +228,31 @@ impl Clipboard { } /// Objects `roots` of `st`'s document with their resources, source artboard and layers. - pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self { + pub(crate) fn copy(st: &DocState, roots: &[NodeId], direct: bool) -> Self { let d = &*st.doc; let mut nodes = vec![]; let mut source_layers = vec![]; for id in roots { let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue }; - nodes.push(n.clone()); - // The nearest enclosing layer (or sublayer). - source_layers.push(anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone())); + let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone()); + let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. }))); + let inherit_appearance = |mut piece: Node| { + if let Some(parent) = compound_parent + && piece.appearance.items.is_empty() + { + piece.appearance = parent.appearance.clone(); + } + piece + }; + if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) { + for piece in pieces { + nodes.push(inherit_appearance(piece)); + source_layers.push(layer_name.clone()); + } + } else { + nodes.push(inherit_appearance(n.clone())); + source_layers.push(layer_name); + } } // Symbol instances are measured by their art. let symbols = d.symbol_boxes(); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 6a436ab31d..22159ca2a9 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -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, +} + +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 = 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(); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 00ea88ea64..6860df1495 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -721,7 +721,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result { if rotation != 0.0 { t.xf *= vectorcraft_geom::rotate_deg(rotation); } - t.vertical = p.get("vertical").and_then(Value::as_bool).unwrap_or(false); + t.vertical = switch_or(p, "vertical", false, "text.create")?; t.para = new_type_para(); new_type_alignment(s, p, "text.create", &mut t)?; if let Some(a) = p.get("area") { @@ -833,7 +833,10 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle { None if !s.paint.fill.is_none() && s.paint.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::WHITE) => s.paint.fill.clone(), None => vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), }; - // In the document's language (Document Setup), none for the default. - style.language = s.doc().ok().and_then(|d| vectorcraft_doc::setup::char_language(&d.doc.setup.language).ok().flatten()).map(str::to_string); + // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none + // for the default. Type already in a document keeps its own. + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); style } diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index fc146fdec8..5b1b4300b5 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -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 { @@ -716,7 +716,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { } fn lock_guides(s: &mut Session, p: &Value) -> Result { - 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). diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 88bf436f9a..0358acddf7 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: it is not, and the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), @@ -119,7 +119,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index c6d974151d..660f52121e 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -12,7 +12,7 @@ use super::{ /// Fit a freehand polyline: drop jitter, build a spline through the samples (sharp turns stay /// corners) and simplify it to `tol`. fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath { - let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIDELITY * 0.3); + let min = (tol * 0.3).max(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE * 0.3); let (Some(&p0), Some(&pn)) = (pts.first(), pts.last()) else { return SubPath::new(vec![], closed) }; let mut kept: Vec = vec![p0]; for &p in pts.iter().skip(1) { @@ -150,7 +150,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { } let pen = PenRecord::of_samples(&samples); let mut pts: Vec = samples.into_iter().map(|s| s.pt).collect(); - let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0); + let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0); // The tolerance the stroke is fitted at; with `fit: false` it is not fitted. let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol); let closed = switch_or(p, "closed", false, C)?; @@ -336,7 +336,13 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result { if let Some(st) = look.appearance.stroke_mut() { pen.write(st); } - insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected) + let out = insert_look(s, if brush { "Paintbrush" } else { "Pencil" }, path_kind(PathData::single(sp)), look, None, keep_selected)?; + if !keep_selected { + // A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke + // by dropping the earlier selection, it does not keep it (#5752). + s.select(|_, sel| sel.clear())?; + } + Ok(out) } // ---------- Blob Brush ---------- diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index a4aa1f79a8..d63bdaea77 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -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 { // ---------- 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 { + 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 { + 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> { + 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 { 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 { }; 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 { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 41276c2326..bd0e7704fb 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -4,14 +4,14 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, RulerMode, Unit}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; use super::clipboard::SwatchChoices; use super::{ CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok, - point_param, str_param, + point_param, str_param, switch_or, }; use crate::{Clipboard, EngineError, inspect}; @@ -29,6 +29,15 @@ pub fn specs() -> Vec { ), cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{index?}", has_doc, file_close), cmd!("document.activate", "Activate Document", [], None, "{index}", always, doc_activate), + cmd!( + "document.move", + "Move Document", + [], + None, + "{from?: index (default: the current document), to: index (0 = the first tab; past the last document = the last tab)} → {index}: moves the document to tab `to`, as dragging its tab along the tab strip does; the documents between shift by one, the order Window › Next/Previous Document steps through follows, and the current document stays the current one", + has_doc, + doc_move + ), cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), @@ -222,6 +231,23 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result { if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } +fn doc_move(s: &mut Session, p: &Value) -> Result { + let n = s.documents().len(); + let from = match p.get("from") { + None | Some(Value::Null) => s.active_index().ok_or(EngineError::NoDocument)?, + Some(v) => v.as_u64().map(index).ok_or_else(|| bad("document.move", "`from` must be a non-negative integer"))?, + }; + if from >= n { + return Err(bad("document.move", "no such document")); + } + let to = p.get("to").and_then(Value::as_u64).map(index).ok_or_else(|| bad("document.move", "missing `to`: a non-negative integer"))?; + let to = to.min(n.saturating_sub(1)); + if !s.move_document(from, to) { + return Err(bad("document.move", "no such document")); + } + Ok(json!({ "index": to })) +} + fn doc_node(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?; let mut opts = slice_opts(p, "document.node")?; @@ -600,7 +626,7 @@ pub(crate) fn selected_roots(s: &Session) -> Result> { /// rest still go to the compound path, which holds the paint. pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { let st = s.doc()?; - Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_| true)) + Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true)) } /// [`selected_roots`] for the selected objects inside the isolated object `root` @@ -611,18 +637,18 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result> { pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result> { let st = s.doc()?; let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect(); - Ok(roots_within(&st.doc, ids, |compound| members || compound == root)) + Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root)) } /// The top-level objects among `ids` (in paint order): compound-path members stand for their /// compound, and ids whose ancestor is also listed, and layers, are dropped. pub(crate) fn roots_of(doc: &Document, ids: Vec) -> Vec { - roots_within(doc, ids, |_| false) + roots_within(doc, ids, |_, _| false) } -/// [`roots_of`]; a compound path's member listed stays itself when `members` holds for the -/// compound's id. -fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bool) -> Vec { +/// [`roots_of`]; a compound path's member listed stays itself when `keep_member` holds for the +/// compound's id or the member's id. +fn roots_within(doc: &Document, ids: Vec, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec { // Every id's place in the tree, found in one walk (a lookup per id is a walk per id). let paths = doc.index_paths(ids.iter().copied()); // A compound-path member acts as its compound (compounds are one object). @@ -632,7 +658,7 @@ fn roots_within(doc: &Document, ids: Vec, members: impl Fn(NodeId) -> bo let path = paths.get(&id); let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty()); match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) { - Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !members(n.id) => (n.id, Some(up.to_vec())), + Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) && !keep_member(n.id, id) => (n.id, Some(up.to_vec())), _ => (id, path.cloned()), } }) @@ -663,11 +689,24 @@ fn without_inner(doc: &Document, placed: Vec<(NodeId, Option>)>) -> i }) } +/// The direct-selection flag and resolved root nodes for Copy and Cut operations. +fn copy_cut_targets(s: &Session) -> Result<(bool, Vec)> { + let st = s.doc()?; + let in_drawing_tool = matches!(s.tool_id(), "pen" | "curvature"); + let direct = !in_drawing_tool && (!st.selection.anchors.is_empty() || !st.selection.segments.is_empty()); + let in_isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_compound, member| { + in_isolated_compound || (direct && (st.selection.partial(member).is_some() || st.selection.segments.contains_key(&member))) + }); + Ok((direct, roots)) +} + fn copy(s: &mut Session, _: &Value) -> Result { // The Artboard tool copies its artboard (and the art on it). if s.tool_id() == "artboard" { return super::panelcmds::artboard_copy(s, &json!({}), false); } + let (direct, targets) = copy_cut_targets(s)?; let st = s.doc()?; // Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay // behind. @@ -678,9 +717,13 @@ fn copy(s: &mut Session, _: &Value) -> Result { .filter_map(|i| st.doc.guides.get(*i)) .map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() }) .collect(); - let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? }; - let st = s.doc()?; - let mut clip = Clipboard::copy(st, &roots); + let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { targets }; + let mut clip = Clipboard::copy(st, &roots, direct); + // Direct-selected anchors or segments that make no segment: nothing to copy, so the + // clipboard keeps what it held. + if direct && clip.nodes.is_empty() { + return Ok(json!({ "copied": 0 })); + } // Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes // measure from, as the objects' artboard is. if clip.nodes.is_empty() @@ -703,23 +746,81 @@ fn cut(s: &mut Session, p: &Value) -> Result { if s.tool_id() == "artboard" { return super::panelcmds::artboard_copy(s, &json!({}), true); } - // Copy promotes a compound member to its compound. Cut must remove the same objects it - // copied, while Clear on its own deletes exactly the selected members. // Ruler guides selected on their own: Copy takes them, Clear removes them. if s.doc()?.selection.is_empty() { copy(s, p)?; return clear(s, &json!({})); } - let ids = selected_roots(s)?; - copy(s, p)?; + // Copy promotes a compound member to its compound. Cut must remove the same objects it + // copied, while Clear on its own deletes exactly the selected members. + let (direct, roots) = copy_cut_targets(s)?; + let res = copy(s, p)?; + if res.get("copied").and_then(Value::as_u64) == Some(0) { + return Ok(res); + } // The selected ruler guides it copied go with the objects, in the same undo step (#3226). - if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) } + if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) } +} + +fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + // The selected ruler guides were copied too (#3226): they go in the same undo step. + let gone = selection.guides.clone(); + d.retain_guides(selection, |i, _| !gone.contains(&i)); + let mut survivors = vec![]; + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct { + d.remove(*id)?; + continue; + } + let Some(path) = node.path_data() else { + d.remove(*id)?; + continue; + }; + + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + for (si, sp) in path.subpaths.iter().enumerate() { + let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp.clone()); + } else { + subpaths.extend(super::path::without_segments(sp.clone(), &cuts)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + let parent = d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(*id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + } else { + let path_node = super::path::path_mut(d, *id)?; + path_node.subpaths = subpaths; + survivors.push(*id); + } + } + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() } fn clear(s: &mut Session, p: &Value) -> Result { + let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // Direct-selected anchors or segments: remove those, and any objects selected whole with them. - if explicit.is_none() && !s.doc()?.selection.anchors.is_empty() { + if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) { return super::path::delete_anchors(s, p); } // Selected ruler guides (selected on their own). @@ -729,7 +830,8 @@ fn clear(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; // Guides selected with the art go with it (not when ids are given, unless `guides` says so: // Cut, which names the objects it copied). - let with_guides = explicit.is_none() || bool_or(p, "guides", false); + let with_guides = explicit.is_none() || guides; + let is_explicit = explicit.is_some(); let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc)); // Keep the selected ids themselves, without promoting compound members. Delete a selected // ancestor just once; its selected descendants leave with it. Layers themselves are kept. @@ -743,12 +845,26 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { + let parents: Vec<_> = + ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect(); d.remove_many(&ids)?; + for p in parents { + if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { + d.remove(p)?; + } + } if with_guides { let gone = sel.guides.clone(); d.retain_guides(sel, |i, _| !gone.contains(&i)); } - sel.clear(); + if is_explicit { + for id in &ids { + sel.remove(*id); + } + sel.prune(d); + } else { + sel.clear(); + } Ok(()) })?; ok() @@ -777,7 +893,7 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { return Err(EngineError::NoNode(*id)); } - let clip = Clipboard::copy(source, &roots_of(&source.doc, ids)); + let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false); let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?; let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]); if !center.x.is_finite() || !center.y.is_finite() { @@ -848,7 +964,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let off = s.prefs.paste_offset; let st = s.doc()?; let same_doc = clip.source_doc == Some(st.uid); - let parent = st.target_parent()?; + let parent = st.target_parent_for_path()?; // Copied artboards come back with their art: together right of the last artboard, as they lay, // or where they were (Paste in Place, in Front, in Back). Paste on All Artboards pastes only the // art. @@ -881,8 +997,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho let anchor = if front || back { let order = st.selection.in_paint_order(&st.doc); let a = if front { order.last() } else { order.first() }; - let paths_only = clip.nodes.iter().all(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })); - a.map(|id| paste_anchor(&st.doc, *id, paths_only)).and_then(|id| st.doc.position(id)) + let isolated_compound = st.isolation.is_some_and(|iso| st.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let can_enter_compound = clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. })) + || (isolated_compound && clip.nodes.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); + a.map(|id| paste_anchor(&st.doc, *id, can_enter_compound)).and_then(|id| st.doc.position(id)) } else { None }; @@ -949,7 +1067,45 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } }; *placed.entry(par).or_default() += 1; - new_ids.push(d.insert(par, idx, c)?); + let compound_par = par.filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + if let Some(par_id) = compound_par { + match c.kind { + NodeKind::Compound { children, .. } => { + let count = children.len(); + for (offset, child) in children.into_iter().enumerate() { + let mut child_node = Arc::unwrap_or_clone(child); + let child_id = d.alloc_id(); + child_node.id = child_id; + child_node.appearance = Default::default(); + if let NodeKind::Path { live, .. } = &mut child_node.kind { + *live = None; + } + let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) }; + new_ids.push(d.insert(par, insert_idx, child_node)?); + } + if count > 1 { + *placed.entry(par).or_default() += count - 1; + } + } + NodeKind::Path { .. } => { + c.appearance = Default::default(); + if let NodeKind::Path { live, .. } = &mut c.kind { + *live = None; + } + new_ids.push(d.insert(par, idx, c)?); + } + _ => { + let outer_par = d.parent_of(par_id); + let beside_idx = d.position(par_id).map(|(_, i, _)| i + 1).unwrap_or(usize::MAX); + let offset = *placed.entry(outer_par).or_default(); + *placed.entry(outer_par).or_default() += 1; + let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) }; + new_ids.push(d.insert(outer_par, insert_idx, c)?); + } + } + } else { + new_ids.push(d.insert(par, idx, c)?); + } } } sel.set(new_ids.iter().copied()); @@ -990,11 +1146,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho })) } -/// What pasted art goes beside: `id`, or the compound path holding it when the art isn't only -/// paths (a compound path holds paths only). -fn paste_anchor(doc: &Document, id: NodeId, paths_only: bool) -> NodeId { +/// What pasted art goes beside: `id`, or the compound path holding it when the art cannot enter +/// the compound path (a compound path holds paths only; compound paths unpack into isolated compounds). +fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId { match doc.parent_of(id) { - Some(p) if !paths_only && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p, + Some(p) if !can_enter_compound && doc.node(p).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. })) => p, _ => id, } } diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 8718e725fc..f4c0073a3c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -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 { @@ -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 { } let effect = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?; let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default(); + aligned(p, C)?; if let Some(loose) = loose_for_pathfinder(s, p, id)? { let gid = s.edit(&label, |d, sel| { let gid = super::object::group_nodes(d, &loose)?; @@ -375,10 +377,10 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let to = index_param(p, "to", C)?; let src = item_target_at(s, p, "fromItem", C)?; let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let copy = switch_or(p, "copy", false, C)?; let roots = appearance_targets(s, p)?; // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p) && super::appearance::appearances_differ(&s.doc()?.doc, &roots) { + if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) { return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); } // Where the effect landed in each object it moved in, in the order of `ids`. @@ -758,11 +760,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art); m }) - } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && !effects::has_transform_art(&v) { + } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && !effects::has_transform_art(&v) + && !effects::has_transform_copies(&v) + { effects::expand_leaf(d, &v, &mut stroke_art) } else { // Type, images, symbol instances, live objects (and paths whose Transform effect copies - // them with a gradient or changes their fills and strokes): through their outlines. + // them, each copy an object of its own, or changes their fills and strokes): through + // their outlines. let symbol = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => { d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_render::instance_art(&s.art, &n)) diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 7e44e07726..ce8f511834 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -366,14 +366,16 @@ fn expand_appearance_bakes_geometry() { assert!(s.execute("effect.expandAppearance", &json!({})).is_err()); } +/// Each copy is an object of its own (#5612). #[test] -fn expand_transform_copies_makes_compound() { +fn expand_transform_copies_makes_a_group_of_the_copies() { let (mut s, id) = session_with_rect(); s.execute("paint.setStroke", &json!({"none": true})).unwrap(); s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 120, "copies": 1}})).unwrap(); s.execute("effect.expandAppearance", &json!({})).unwrap(); let n = node(&s, id); - assert!(matches!(n.kind, NodeKind::Compound { .. })); + assert!(matches!(n.kind, NodeKind::Group { .. }), "{}", n.kind_label()); + assert_eq!(n.children().map(|c| c.len()), Some(2)); let b = n.geometric_bounds().unwrap(); assert!((b.x1 - 320.0).abs() < 1e-6, "{b:?}"); } @@ -474,6 +476,53 @@ fn expand_appearance_gives_each_copy_of_a_transform_its_own_gradient() { assert_eq!(boxes, vec![100.0; 3], "three squares, each with its own gradient"); } +/// Expand Appearance on a solid-filled path whose Transform effect makes copies gives a group of +/// one path per copy, each with the path's fill, not one compound path (#5612); a second Transform +/// effect's copies of those copies nest, a group per copy of the first. +#[test] +fn expand_appearance_makes_each_copy_of_a_transform_an_object() { + use vectorcraft_color::{Color, Paint}; + let fill = |n: &vectorcraft_doc::Node| n.appearance.fill_paint().color(); + let (mut s, id) = session_with_rect(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":0,"params":{"moveH":150,"copies":2},"ids":[id.0],"item":null})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let n = node(&s, id); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "{}", n.kind_label()); + assert!(n.appearance.effects.is_empty()); + let copies = n.children().unwrap(); + assert_eq!(copies.len(), 3, "the path and its two copies"); + let xs: Vec = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect(); + assert_eq!(xs, vec![100.0, 250.0, 400.0]); + for c in copies { + assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label()); + assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0))); + assert!((c.geometric_bounds().unwrap().width() - 100.0).abs() < 1e-9); + } + let mut ids: Vec = vec![]; + n.walk(&mut |c| ids.push(c.id)); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), 4, "the group and each copy have ids of their own"); + // Two Transform effects: three columns, each a group of the column's two copies. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("effect.apply", &json!({"effect":"distort.transform","ids":[id.0],"item":null})).unwrap(); + s.execute("effect.setParams", &json!({"index":1,"params":{"moveV":150,"copies":1},"ids":[id.0],"item":null})).unwrap(); + s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap(); + let columns = node(&s, id).children().unwrap().to_vec(); + assert_eq!(columns.len(), 3); + for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) { + let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label())); + let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect(); + assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]); + assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. }))); + } +} + /// The object's own effect ids, in order. fn object_effects(s: &Session, id: NodeId) -> Vec { node(s, id).appearance.effects.iter().map(|e| e.id.clone()).collect() diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5b734c5a26..b1a422dea2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Export Selection…", ["File"], None, - "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), scale?: 1, …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export", + "{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export", has_selection, export::export_selection ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index b125e48a88..1108d3e2ca 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -202,13 +202,14 @@ impl RasterOptions { } } - /// The render and encoder settings: `ppi`, else 72 × `scale`, within 0.01–64 pixels per point; + /// The render and encoder settings: `ppi`, else 72 × `scale`, else the document's resolution, + /// within 0.01–64 pixels per point; /// `background`, else `page` (the document's background). - fn settings(&self, page: Option<[u8; 3]>) -> Result { + fn settings(&self, page: Option<[u8; 3]>, document_ppi: f64) -> Result { if let Some(ppi) = self.ppi.filter(|p| !(p.is_finite() && *p > 0.0)) { return Err(bad(C, format!("ppi must be a positive number, not {ppi}"))); } - let ppi = self.ppi.unwrap_or(72.0 * self.scale.unwrap_or(1.0)); + let ppi = self.ppi.unwrap_or_else(|| self.scale.map_or(document_ppi, |scale| 72.0 * scale)); let color_model = parse(self.color_model.as_deref(), jpeg::ColorModel::from_id, "colorModel", "rgb, cmyk or gray")?; let embed_icc = self.embed_icc.unwrap_or(true); Ok(RasterExportOptions { @@ -544,7 +545,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { // New Document → Background Contents: White makes the export opaque, unless `background` // says otherwise (JPEG has no alpha: white either way). let page = (doc.setup.background == vectorcraft_doc::Background::White).then_some([255; 3]); - let mut settings = o.settings(page)?; + let mut settings = o.settings(page, doc.raster_ppi())?; let size = o.pixel_size()?; let format = match f.id { "png" => RasterFormat::Png, diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 09e8de8294..33ecfa8ab2 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -76,7 +76,12 @@ pub(super) const RANGE: FormatOption = FormatOption { description: "1-based artboards such as \"1-3, 5\", or \"all\" (wins over artboards and artboard)", }; -const SCALE: FormatOption = FormatOption { name: "scale", ty: "number", default: "1", description: "pixels per point (0.01–64)" }; +const SCALE: FormatOption = FormatOption { + name: "scale", + ty: "number", + default: "null", + description: "pixels per point (0.01–64); without ppi or scale, uses the document's raster effects resolution", +}; const WIDTH: FormatOption = FormatOption { name: "width", @@ -112,8 +117,8 @@ const RECT: FormatOption = FormatOption { const PPI: FormatOption = FormatOption { name: "ppi", ty: "number", - default: "72", - description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale", + default: "null", + description: "resolution in pixels per inch (72 = one pixel per point; 150, 300…), stored in the file except in GIF, WebP and Targa; wins over scale; without either, uses the document's raster effects resolution", }; const BACKGROUND: FormatOption = FormatOption { diff --git a/crates/engine/src/cmd/fileio/legacy_ai.rs b/crates/engine/src/cmd/fileio/legacy_ai.rs index d4820242d9..691c0e8364 100644 --- a/crates/engine/src/cmd/fileio/legacy_ai.rs +++ b/crates/engine/src/cmd/fileio/legacy_ai.rs @@ -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))) diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index 2f9312259c..4d293fe69d 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "editingData", ty: "boolean", default: "true", - description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, swatches, artboards, the transparency of objects and layers, objects' opacity masks, and clipping groups and layers clipped by a path, with type, gradients, patterns, images, symbols, other clipping objects and live objects as plain filled and stroked paths (written only with every artboard, as Preserve Editing is)", + description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)", }, FormatOption { name: "aiVersion", @@ -121,7 +121,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[ name: "transparentImages", ty: "string", default: "\"flatten\"", - description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity or a blending mode): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)", + description: "with aiVersion 7, the images version 7 can't hold (see-through pixels, opacity, a blending mode, or a colorize color unless every pixel is black or white): flatten (the default: each becomes an opaque image of itself and the art under it, clipped to where it changes what shows; that art stays as it is) or omit (left out)", }, FormatOption { name: "hiddenObjects", diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 69158c04b8..fca92d73f5 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -459,7 +459,7 @@ fn formats_query_lists_readers_writers_and_options() { ); assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string())); let png = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "png").unwrap(); - assert_eq!(png["options"]["scale"]["default"], 1); + assert_eq!(png["options"]["scale"]["default"], Value::Null); assert_eq!(r["openExtensions"].as_array().unwrap().len(), OPEN_EXTS.len()); } diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 0f97a58627..0aa1733d8f 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -124,6 +124,30 @@ fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() { assert_eq!(d.metadata.author, "Ann Lee"); } +#[test] +fn an_ai_file_opens_with_its_active_artboard() { + let board = |x: i32, name: &str| { + format!( + "%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_({name}) /UnicodeString (Name) ,\n%_; ,\n", + x + 200 + ) + }; + let document = format!( + "%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_1 /Int (CropAreaActive) ,\n%_; /NotRecorded ,\n%_;\n", + board(0, "One"), + board(300, "Two") + ); + let data = ai::sample_data(); + let at = data.windows(15).position(|w| w == b"%AI5_BeginLayer").unwrap(); + let data = [&data[..at], document.as_bytes(), &data[at..]].concat(); + let mut s = Session::new(); + let r = open(&mut s, "art.ai", &ai::ai(&compressed(&data), PLACEHOLDER), json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.artboards.iter().map(|a| a.name.as_str()).collect(); + assert_eq!(names, ["One", "Two"], "{r}"); + assert_eq!(d.opened_artboard, Some(d.artboards[1].id), "{r}"); +} + #[test] fn an_ai_unread_group_keeps_its_layers_and_live_neighbor() { let live = format!("0 0 1 0 k\n{}f", ai::rect(10.0, 10.0, 14.0, 14.0)); @@ -287,6 +311,38 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the +/// library the styles of its list, in the list's order, not the default styles; the file opens with +/// them too. +#[test] +fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() { + let style = |name: &str, xa: &str| { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n" + ) + }; + let styles = format!( + "%AI9_BeginArtStyles\n{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Red)\n(Green)\n(Blue)\n%AI9_EndArtStyleList\n", + style("Blue", "0 0 0 0 0 0 1 Xa\n"), + style("Green", "0 0 0 0 0 1 0 Xa\n"), + style("Red", "0 0 0 0 1 0 0 Xa\n") + ); + let data = ai::editing_data(200.0, 100.0, &styles); + let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "fills.ai"}); + let r = s.execute("graphicStyle.loadLibrary", &p).unwrap(); + assert_eq!((&r["name"], &r["count"]), (&json!("fills"), &json!(3)), "{r}"); + let lib = s.execute("graphicStyle.library", &json!({"library": r["library"]})).unwrap(); + let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Red", "Green", "Blue"], "{lib}"); + let r = open(&mut s, "fills.ai", &file, json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let styles: Vec<(&str, u32)> = doc.graphic_styles.iter().map(|g| (g.name.as_str(), g.id)).collect(); + assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}"); +} + /// A 1-bit RGB image opens from the editing data in the colors its PDF part shows. #[test] fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() { @@ -1023,6 +1079,46 @@ fn an_empty_page_with_type_as_outlines_outlines_the_editing_datas_type() { assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "the editing data's layers"); } +/// A story of a `.ai` file's text document with no character or paragraph runs is set in +/// `[Normal Character Style]` and `[Normal Paragraph Style]`; the base attributes give only what +/// those styles leave out. +#[test] +fn an_ai_story_without_runs_takes_the_normal_styles() { + let story = "<< /0 << /0 (Hi\r) >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8191.5 8191.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 3 >> >> ] >> ] >> ] >> ] >> ] >> ] >> >>"; + let char_sheets = "/5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 9.0 \ + /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >>"; + let para_sheets = "/6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 6.0 /9 false >> >> >> ] >>"; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> {char_sheets} {para_sheets} \ + /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ {story} ] /2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 2.0 /9 true >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n2 /TextAntialiasing ,\n;\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ + %AI5_NumLayers: 1\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n%%Trailer\n", + ai::layer("Art", text), + lines.join("\n") + ); + let mut s = Session::new(); + let r = open(&mut s, "plain.ai", &ai::ai(&compressed(data.as_bytes()), ""), json!({})).unwrap(); + let mut texts = vec![]; + s.doc().unwrap().doc.walk(|c| { + if let NodeKind::Text(t) = &c.kind { + texts.push((**t).clone()); + } + }); + let [t] = texts.as_slice() else { panic!("one text object: {r}") }; + assert_eq!(t.plain_text(), "Hi"); + let style = &t.runs[0].style; + assert_eq!(style.size, 9.0, "{r}"); + assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert_eq!((t.para.first_line_indent, t.para.hyphenate), (6.0, false)); +} + /// Type asked for as outlines in a `.ai` saved without PDF compatibility (its page only a /// placeholder): the editing data's type, outlined, as for an empty page. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index ae7c66aa8b..b87ec3ee2e 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -404,6 +404,35 @@ fn ai_export_without_artboards_keeps_art_outside_the_original_pages() { assert!(s.execute("document.export", &json!({"format": "ai", "useArtboards": "yes"})).is_err()); } +/// Color Halftone's Max Radius is in pixels of the raster effects resolution since document +/// version 3 (#3260). A PDF saved with Preserve Editing carries the native document, so one from +/// before that opens with the radius converted, drawing the same dots; one saved since opens as +/// it was. +#[test] +fn a_preserve_editing_pdf_opens_with_its_halftone_radius_in_pixels() { + let halftone = |old: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let r = super::tests_svgedit::rect(&mut s, 10.0, 10.0); + s.execute("effect.apply", &json!({"effect": "pixelate.colorHalftone", "params": {"maxRadius": 8}, "ids": [r]})).unwrap(); + if old { + // As VectorCraft 0.18 wrote it: the document model's version 1, the radius in points. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).version = 1; + } + let pdf = b64(&s.execute("document.exportPdf", &json!({})).unwrap()); + let opened = open(&mut s, "halftone.pdf", &pdf); + assert_eq!(opened["restored"], json!(true), "{opened}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.version, vectorcraft_doc::FORMAT_VERSION); + let n = d.node(vectorcraft_doc::NodeId(r)).unwrap(); + n.appearance.effects.iter().find(|e| e.id == "pixelate.colorHalftone").and_then(|e| e.params["maxRadius"].as_f64()).unwrap() + }; + // 8 pt at 300 ppi are 33⅓ px. + assert!((halftone(true) - 8.0 * 300.0 / 72.0).abs() < 1e-9, "{}", halftone(true)); + assert_eq!(halftone(false), 8.0); +} + /// The layers of `doc` as their names and the kinds and bounds of what they hold, rounded. fn outline(doc: &vectorcraft_doc::Document) -> Vec { fn walk(nodes: &[std::sync::Arc], depth: usize, out: &mut Vec) { @@ -623,3 +652,265 @@ fn transparency_clipping_and_opacity_masks_come_back_from_the_editing_copy() { let kinds = see_through_outline(&legacy.doc); assert!(kinds.iter().any(|l| l.contains(" compound ")) && kinds.iter().any(|l| l.contains("group clip=true")), "{kinds:#?}"); } + +/// The paths and compound paths of `doc`'s art and of its patterns' tiles with their geometric +/// bounds (rounded) and fills and strokes, one line each, then its gradient and pattern swatches: a +/// gradient by its kind, its swatch link (`-` when it names no gradient swatch of `doc`), its stops +/// (place, color, opacity, midpoint, swatch link and tint) and the gradient's place at the corners and +/// center of the paint's bounds (rounded to hundredths); a pattern by its name and placement. +fn paint_outline(doc: &vectorcraft_doc::Document) -> Vec { + use std::sync::Arc; + use vectorcraft_color::Paint; + use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; + let link = |name: &Option| match name.as_deref().and_then(|n| doc.swatch(n)) { + Some(sw) if matches!(sw.paint, Paint::Gradient(_)) => sw.name.clone(), + _ => "-".into(), + }; + let drawn = |p: &Paint, b: vectorcraft_geom::Rect| match p { + Paint::Gradient(g) => { + let geom = g.resolve(b); + let at: Vec = [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1), (b.center().x, b.center().y)] + .map(|(x, y)| (geom.param_at(g.gradient.kind, (x, y).into()) * 100.0).round() / 100.0) + .to_vec(); + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| { + let rgb = s.color.to_rgb().map(|v| (v * 100.0).round()); + format!("{:.3} {rgb:?} {:.2} mid {:.2} {:?} {:.2}", s.offset, s.opacity, s.midpoint, s.swatch, s.tint) + }) + .collect(); + format!("{:?} link {} {stops:?} {at:?}", g.gradient.kind, link(&g.swatch)) + } + Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(|v| (v * 1000.0).round() / 1000.0)), + Paint::Solid { color, .. } => format!("{:?}", color.to_rgb().map(|v| (v * 100.0).round())), + Paint::None => "none".into(), + }; + // A compound path's paint is its own: its members' paint isn't drawn (Release gives them the + // compound path's), so a compound path's line lists only its members' bounds. + fn walk(nodes: &[Arc], f: &mut dyn FnMut(&Node)) { + for n in nodes { + f(n); + if !matches!(n.kind, NodeKind::Compound { .. }) { + walk(n.children().map(Vec::as_slice).unwrap_or_default(), f); + } + } + } + let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + let lines = |nodes: &[Arc]| { + let mut lines = vec![]; + walk(nodes, &mut |n| { + if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { + return; + } + let Some(b) = n.geometric_bounds() else { return }; + let kind = match n.children() { + Some(members) => format!("compound of {:?}", members.iter().map(|m| bounds(m)).collect::>()), + None => "path".into(), + }; + let mut line = format!("{kind} {:?}", [b.x0, b.y0, b.x1, b.y1].map(|v| v.round() as i64)); + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + line += &match it { + AppearanceItem::Fill(f) => format!(" fill {}", drawn(&f.paint, b)), + AppearanceItem::Stroke(st) => format!(" stroke {} {}", st.width, drawn(&st.paint, st.paint_bounds(b))), + }; + } + lines.push(line); + }); + lines + }; + let mut out = lines(&doc.layers); + for p in doc.patterns.iter() { + out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1])); + out.extend(lines(&p.art)); + } + for sw in doc.swatches_iter() { + match &sw.paint { + // A gradient swatch reads back linked to itself. + Paint::Gradient(g) => { + let own = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g.gradient.clone()))); + out.push(format!("swatch {} {}", sw.name, drawn(&own, vectorcraft_geom::Rect::ZERO))); + } + Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", sw.name)), + _ => {} + } + } + out +} + +/// The images of `doc`'s art, one line each: its pixel size, where its corners land (rounded to +/// hundredths), its link's path and relative path, and its pixels (RGBA). +fn image_outline(doc: &vectorcraft_doc::Document) -> Vec { + use vectorcraft_doc::NodeKind; + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + let r = vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)); + let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x0, r.y1)].map(|(x, y)| { + let p = im.xf * vectorcraft_geom::Point::new(x, y); + ((p.x * 100.0).round() / 100.0, (p.y * 100.0).round() / 100.0) + }); + let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); + let pixels = doc.image_blob(im).and_then(|b| image::load_from_memory(&b.bytes).ok()).map(|i| i.to_rgba8().into_raw()); + out.push(format!("{}x{} {corners:?} {link:?} {pixels:?}", im.width, im.height)); + } + }); + out +} + +/// An embedded image (RGBA, part of it see-through, turned) and a linked one come back from the +/// editing copy for other apps alone, pixel for pixel, with every save option that writes the copy; +/// the linked image keeps its path and its path relative to the document's folder. +#[test] +fn images_come_back_from_the_editing_copy() { + let dir = tmp("ai-images"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(format!("{dir}/art")).unwrap(); + let png = |w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 4]| { + let mut out = vec![]; + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + }; + let linked = format!("{dir}/art/linked.png"); + std::fs::write(&linked, png(5, 4, &|x, y| [(x * 50) as u8, (y * 60) as u8, 90, 255])).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let data = vectorcraft_format::base64_encode(&png(6, 3, &|x, y| [200, (x * 40) as u8, (y * 80) as u8, if x < 2 { 100 } else { 255 }])); + s.execute("file.place", &json!({"name": "embedded.png", "dataBase64": data})).unwrap(); + // The placed image is selected. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("file.place", &json!({"path": linked, "link": true})).unwrap(); + let path = format!("{dir}/images.ai"); + s.execute("document.save", &json!({"path": path})).unwrap(); + let before = image_outline(&s.doc().unwrap().doc); + assert_eq!(before.len(), 2, "{before:#?}"); + assert!(before[1].contains("art/linked.png"), "{before:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("image"), "{r}"); + let copy = load::load_with(&path, &b64(&r), &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(copy.editing_data && !copy.restored, "{opts} {:?}", copy.warnings); + assert!(!copy.warnings.iter().any(|w| w.contains("editing data")), "{opts} {:?}", copy.warnings); + assert_eq!(image_outline(©.doc), before, "{opts}"); + } +} + +/// A document of two artboards (the art on the first): a rectangle filled with a linear gradient of +/// three stops placed across part of it, an ellipse filled with an elliptical radial gradient whose +/// focal point is off its center, a rectangle stroked with a gradient, rectangles filled and +/// stroked with the pattern `Dots`, one of them turned, an even-odd compound path filled with a +/// gradient of a gray, a CMYK color and the spot color `Ink` at 70%, and the gradient swatch `Dawn`. +fn gradient_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 200, "artboards": 2})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = |s: &mut Session, x: f64, y: f64, w: f64, h: f64| { + id(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) + }; + let three = json!({"kind": "linear", "stops": [ + {"offset": 0, "color": "#ff0000", "midpoint": 0.3}, + {"offset": 0.4, "color": "#00ff00", "opacity": 0.5}, + {"offset": 1, "color": "#0000ff"} + ], "start": [20, 40], "end": [60, 17]}); + let a = rect(&mut s, 10.0, 10.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [a], "gradient": three})).unwrap(); + let e = id(s.execute("shape.ellipse", &json!({"x": 100, "y": 10, "width": 80, "height": 40})).unwrap()); + let glow = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#1a33cc"}], + "start": [140, 30], "end": [180, 30], "aspect": 50, "focal": [150, 25]}); + s.execute("paint.setFill", &json!({"ids": [e], "gradient": glow})).unwrap(); + let c = rect(&mut s, 190.0, 10.0, 90.0, 40.0); + let two = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#000000"}]}); + s.execute("paint.setStroke", &json!({"ids": [c], "gradient": two, "width": 6})).unwrap(); + let tile = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [tile], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [tile], "none": true})).unwrap(); + s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap(); + let p = rect(&mut s, 10.0, 70.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [p], "swatch": "Dots"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [p], "swatch": "Dots", "width": 4})).unwrap(); + let turned = rect(&mut s, 100.0, 70.0, 80.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [turned], "swatch": "Dots"})).unwrap(); + // Turned 30° and scaled to half about (140, 90). + let (c, k) = (30f64.to_radians().cos() * 0.5, 30f64.to_radians().sin() * 0.5); + let m = [c, k, -k, c, 140.0 - 140.0 * c + 90.0 * k, 90.0 - 140.0 * k - 90.0 * c]; + s.execute("pattern.transform", &json!({"ids": [turned], "matrix": m})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff9900", "spot": true})).unwrap(); + let outer = rect(&mut s, 190.0, 70.0, 90.0, 40.0); + let hole = rect(&mut s, 210.0, 80.0, 40.0, 20.0); + let ring = id(s.execute("object.compoundPath.make", &json!({"ids": [outer, hole]})).unwrap()); + let mixed = json!({"kind": "linear", "stops": [ + {"offset": 0, "color": {"gray": 0.8}}, + {"offset": 0.5, "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "midpoint": 0.7}, + {"offset": 1, "swatch": "Ink", "tint": 70} + ]}); + s.execute("paint.setFill", &json!({"ids": [ring], "gradient": mixed})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [ring], "none": true})).unwrap(); + let dawn = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]}); + s.execute("swatch.new", &json!({"name": "Dawn", "gradient": dawn})).unwrap(); + s +} + +/// Gradients and patterns come back from the editing copy for other apps alone (the native +/// document left out), with every save option that writes the copy; where the file has PDF pages, +/// the reader takes the copy only when it draws as its page does. The version 7 `.ai` keeps each +/// gradient. +#[test] +fn gradients_and_patterns_come_back_from_the_editing_copy() { + let mut s = gradient_session(); + let before = (*s.doc().unwrap().doc).clone(); + let want = paint_outline(&before); + assert!(want.iter().filter(|l| l.starts_with("path") && l.contains("pattern Dots")).count() == 2, "{want:#?}"); + assert!(want.iter().any(|l| l.starts_with("compound") && l.contains("Ink") && l.contains(") 0.70")), "{want:#?}"); + assert!(want.iter().any(|l| l.contains("mid 0.30")) && want.iter().any(|l| l.starts_with("swatch Dawn")), "{want:#?}"); + for opts in [ + json!({"format": "ai"}), + json!({"format": "ai", "compress": false}), + json!({"format": "ai", "embedProfiles": false}), + json!({"format": "ai", "includeLinked": true}), + json!({"format": "ai", "range": "all"}), + json!({"format": "ai", "pdfCompatible": false}), + ] { + let r = s.execute("document.export", &opts).unwrap(); + assert!(!r["warnings"].to_string().contains("gradient") && !r["warnings"].to_string().contains("pattern"), "{r}"); + let copy = editing_copy(&b64(&r)); + assert_eq!(paint_outline(©), want, "{opts}"); + } + let path = tmp("gradients.ai"); + let r = s.execute("document.save", &json!({"path": path, "separateArtboards": true})).unwrap(); + let files: Vec = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect(); + assert_eq!(files.len(), 3, "{r}"); + for f in files.iter().filter(|f| !f.ends_with("-2.ai")) { + assert_eq!(paint_outline(&editing_copy(&std::fs::read(f).unwrap())), want, "{f}"); + } + let r = s.execute("document.export", &json!({"format": "ai", "aiVersion": 7})).unwrap(); + let legacy = load::load_with("art.ai", &b64(&r), &LoadOptions::default()).unwrap(); + // Each gradient the art paints with, by its kind and its stops' places and colors to 5% (version + // 7 writes a gradient stroke as its filled outline, so the objects differ, and a spot color's + // tint through its CMYK equivalent, 2% off here). + let gradients = |doc: &vectorcraft_doc::Document| { + let mut all = std::collections::BTreeSet::new(); + doc.walk(|node| { + for it in node.appearance.items.iter() { + if let vectorcraft_color::Paint::Gradient(g) = it.paint() { + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| format!("{:.3} {:?}", s.offset, s.color.to_rgb().map(|v| (v * 20.0).round() * 5.0))) + .collect(); + all.insert(format!("{:?} {stops:?}", g.gradient.kind)); + } + } + }); + all + }; + assert_eq!(gradients(&legacy.doc), gradients(&before)); +} diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index 0c01844463..80001476a4 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -32,6 +32,44 @@ fn png_chunk<'a>(file: &'a [u8], ty: &[u8; 4]) -> Option<&'a [u8]> { None } +#[test] +fn raster_export_defaults_to_document_resolution() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 72, "height": 36, "rasterEffectsPpi": 300})).unwrap(); + assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0); + for format in ["png", "psd"] { + for (options, size, ppi) in [ + (json!({}), (300, 150), 300.0), + (json!({"scale": 1}), (72, 36), 72.0), + (json!({"scale": 2}), (144, 72), 144.0), + (json!({"ppi": 150, "scale": 2}), (150, 75), 150.0), + ] { + let mut params = options; + params["format"] = json!(format); + let bytes = b64(&s.execute("document.export", ¶ms).unwrap()); + assert_eq!(super::ppi::resolution(&bytes), Some((ppi, ppi)), "{params}"); + let image = super::load::raster_image(&bytes).unwrap(); + assert_eq!((image.width, image.height), size, "{params}"); + } + } +} + +#[test] +fn raster_export_default_uses_the_sanitised_document_resolution() { + // A stored resolution that isn't finite or is outside 1–2400 ppi exports at the resolution the + // document reports (72 when not finite, else clamped), not at a zero, huge or failed size. + for (stored, (width, height), size) in [(f64::NAN, (72, 36), (72, 36)), (0.0, (144, 72), (2, 1)), (1e9, (36, 18), (1200, 600))] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": width, "height": height})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).raster_effects_ppi = stored; + for format in ["png", "psd"] { + let bytes = b64(&s.execute("document.export", &json!({"format": format})).unwrap()); + let image = super::load::raster_image(&bytes).unwrap(); + assert_eq!((image.width, image.height), size, "{format} with a stored {stored} ppi"); + } + } +} + #[test] fn png_options_resolution_background_interlace_and_anti_aliasing() { let mut s = session(40.0, 30.0, 1); @@ -183,7 +221,7 @@ fn formats_list_the_raster_options() { assert!(opts("png").get(k).is_some(), "png lists {k}"); } assert_eq!(opts("png")["antiAlias"]["default"], "art"); - assert_eq!(opts("png")["ppi"]["default"], 72); + assert_eq!(opts("png")["ppi"]["default"], Value::Null); assert!(opts("jpg").get("quality").is_some() && opts("jpg").get("interlaced").is_none()); assert!(opts("webp").get("antiAlias").is_some() && opts("svg").get("antiAlias").is_none()); } diff --git a/crates/engine/src/cmd/fileio/tests_svgedit.rs b/crates/engine/src/cmd/fileio/tests_svgedit.rs index 06f9888469..4b0998c643 100644 --- a/crates/engine/src/cmd/fileio/tests_svgedit.rs +++ b/crates/engine/src/cmd/fileio/tests_svgedit.rs @@ -12,7 +12,7 @@ fn new_id(v: &Value) -> u64 { v["id"].as_u64().or_else(|| v["ids"][0].as_u64()).unwrap_or_else(|| panic!("no id in {v}")) } -fn rect(s: &mut Session, x: f64, y: f64) -> u64 { +pub(super) fn rect(s: &mut Session, x: f64, y: f64) -> u64 { new_id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()) } diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index d4f18f3857..52a9002890 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -151,11 +151,16 @@ impl FlattenOptions { /// Whether colorized image `n`, art of `d`, counts as transparency by itself. With /// [`Self::keeps_colorize`], an image colorized with a solid paint whose pixels are grayscale - /// or 1-bit doesn't: the EPS writer draws it in that paint. + /// or 1-bit doesn't: the EPS writer draws it in that paint. An image whose pixels don't take + /// the paint ([`vectorcraft_doc::ImageBlob::takes_colorize`]) never counts: it draws uncolorized. pub(crate) fn counts_colorize(&self, d: &Document, n: &Node) -> bool { let NodeKind::Image(im) = &n.kind else { return true }; + let blob = d.image_blob(im); + if blob.is_some_and(|b| !b.takes_colorize()) { + return false; + } let solid = matches!(n.extras().colorize.as_deref(), Some(Paint::Solid { .. })); - !self.keeps_colorize || !solid || d.image_blob(im).is_some_and(|b| b.gray_source().is_none()) + !self.keeps_colorize || !solid || blob.is_some_and(|b| b.gray_source().is_none()) } /// `n` shows an image whose see-through pixels count as transparency. diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 585cd8a793..efe9786287 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -2,7 +2,7 @@ //! another everywhere or in the selection, and selecting the text that uses a font. Also the fonts //! available (the bundled and installed ones) and rescanning the installed fonts. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; @@ -64,18 +64,19 @@ pub fn specs() -> Vec { } /// Text objects in scope: the selection's (and their descendants') or the whole document's. -fn scope(s: &Session, selection_only: bool) -> Result> { +fn scope(s: &Session, selection_only: bool, selected: Option<&[NodeId]>) -> Result> { let st = s.doc()?; let mut v = vec![]; + let mut seen = HashSet::new(); let mut add = |n: &vectorcraft_doc::Node| { n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Text(_)) && !v.contains(&c.id) { + if matches!(c.kind, NodeKind::Text(_)) && seen.insert(c.id) { v.push(c.id); } }) }; if selection_only { - for id in &st.selection.objects { + for id in selected.unwrap_or(&st.selection.objects) { if let Some(n) = st.doc.node(*id) { add(n); } @@ -97,7 +98,7 @@ fn being_edited(d: &Document, name: &str) -> bool { /// descendants, and of the instances in those symbols' art that are not hidden or locked, nor in a /// hidden or locked group of the art. Returned as (all of them, those shown by instances the /// Selection tool can reach: not hidden or locked, as `Document::editable` says). -fn selected_symbols(s: &Session) -> Result<(BTreeSet, BTreeSet)> { +fn selected_symbols(s: &Session, selected: Option<&[NodeId]>) -> Result<(BTreeSet, BTreeSet)> { fn open_instances(n: &Node, out: &mut BTreeSet) { if !n.visible || n.locked { return; @@ -123,7 +124,7 @@ fn selected_symbols(s: &Session) -> Result<(BTreeSet, BTreeSet)> let st = s.doc()?; let (mut all, mut open) = (BTreeSet::new(), BTreeSet::new()); let editable = st.doc.editable(); - for id in &st.selection.objects { + for id in selected.unwrap_or(&st.selection.objects) { if let Some(n) = st.doc.node(*id) { n.walk(&mut |c| { if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { @@ -482,12 +483,66 @@ fn text(d: &Document, id: NodeId) -> Option<&vectorcraft_doc::TextObject> { } fn fonts(s: &mut Session, p: &Value) -> Result { - let selection_only = bool_or(p, "selectionOnly", false); - let ids = scope(s, selection_only)?; + if bool_or(p, "selectionOnly", false) { + let selected = s.doc()?.selection.objects.clone(); + font_inventory(s, Some(&selected)) + } else { + font_inventory(s, None) + } +} + +impl Session { + /// List the fonts in the document, or in the given objects and their symbols. + pub fn font_inventory(&self, selected: Option<&[NodeId]>) -> Result { + font_inventory(self, selected) + } + + /// List text currently unavailable to a Replace Font request in its original selection. + pub fn skipped_font_ids(&self, params: &Value, selected: Option<&[NodeId]>) -> Result> { + let (family, style) = font_param(params, "from", "text.replaceFont")?; + let selection_only = bool_or(params, "selectionOnly", false); + let selected_symbols = selection_only.then(|| selected_symbols(self, selected)).transpose()?; + let d = &self.doc()?.doc; + let other: Vec = { + let editable = d.editable(); + scope(self, selection_only, selected)?.into_iter().filter(|id| !editable(*id)).collect() + }; + let uses = |t: &TextObject| { + t.runs.iter().any(|r| { + r.style.font_family.eq_ignore_ascii_case(&family) && style.as_ref().is_none_or(|name| r.style.font_style.eq_ignore_ascii_case(name)) + }) + }; + let mut ids = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).collect::>(); + fn visit(n: &Node, open: bool, closed: bool, uses: &impl Fn(&TextObject) -> bool, ids: &mut Vec) { + let open = open && n.visible && !n.locked; + if let NodeKind::Text(t) = &n.kind + && (!open || closed) + && uses(t) + { + ids.push(n.id); + } + for child in n.children().map(Vec::as_slice).unwrap_or_default() { + visit(child, open, closed, uses, ids); + } + } + for symbol in d + .symbols + .iter() + .filter(|symbol| !being_edited(d, &symbol.name) && selected_symbols.as_ref().is_none_or(|(all, _)| all.contains(&symbol.name))) + { + let closed = selected_symbols.as_ref().is_some_and(|(_, open)| !open.contains(&symbol.name)); + visit(&symbol.art, true, closed, &uses, &mut ids); + } + Ok(ids) + } +} + +fn font_inventory(s: &Session, selected: Option<&[NodeId]>) -> Result { + let ids = scope(s, selected.is_some(), selected)?; let d = &s.doc()?.doc; let db = vectorcraft_text::FontDb::global(); // The type in the art of the symbols in scope too: all of them, or those the selection shows. - let symbols = if selection_only { Some(selected_symbols(s)?.0) } else { None }; + let symbols = if selected.is_some() { Some(selected_symbols(s, selected)?.0) } else { None }; let mut texts: Vec<&TextObject> = ids.iter().filter_map(|id| text(d, *id)).collect(); texts.extend(symbol_texts(d, symbols.as_ref()).into_iter().map(|(t, _)| t)); let mut found: BTreeMap = BTreeMap::new(); @@ -536,6 +591,21 @@ fn font_param(p: &Value, k: &str, c: &str) -> Result<(String, Option)> { Ok((family.to_string(), v.get("style").and_then(Value::as_str).map(str::to_string))) } +fn skipped_font_texts( + d: &Document, + other: &[NodeId], + symbols: &[(&TextObject, bool)], + closed: &BTreeSet, + uses: &impl Fn(&TextObject) -> bool, +) -> usize { + let mut skipped = other.iter().filter(|id| text(d, **id).is_some_and(uses)).count(); + skipped += symbols.iter().filter(|(t, open)| !open && uses(t)).count(); + if !closed.is_empty() { + skipped += symbol_texts(d, Some(closed)).into_iter().filter(|(t, _)| uses(t)).count(); + } + skipped +} + fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "text.replaceFont"; let (ff, fs) = font_param(p, "from", C)?; @@ -567,7 +637,7 @@ fn replace(s: &mut Session, p: &Value) -> Result { // With selectionOnly: the symbols the selection shows; those shown only by hidden or locked // instances keep their type, counted in `skipped`. let (symbols, closed) = if selection_only { - let (all, open) = selected_symbols(s)?; + let (all, open) = selected_symbols(s, None)?; let closed: BTreeSet = all.difference(&open).cloned().collect(); (Some(open), closed) } else { @@ -579,13 +649,9 @@ fn replace(s: &mut Session, p: &Value) -> Result { let (ids, skipped, in_symbols) = { let d = &s.doc()?.doc; let editable = d.editable(); - let (ids, other): (Vec, Vec) = scope(s, selection_only)?.into_iter().partition(|id| editable(*id)); - let mut skipped = other.into_iter().filter(|id| text(d, *id).is_some_and(uses)).count(); + let (ids, other): (Vec, Vec) = scope(s, selection_only, None)?.into_iter().partition(|id| editable(*id)); let texts = symbol_texts(d, symbols.as_ref()); - skipped += texts.iter().filter(|(t, open)| !open && uses(t)).count(); - if !closed.is_empty() { - skipped += symbol_texts(d, Some(&closed)).into_iter().filter(|(t, _)| uses(t)).count(); - } + let skipped = skipped_font_texts(d, &other, &texts, &closed, &uses); // The text that changes: when none does, the document and its undo history stay as they are. let ids: Vec = ids.into_iter().filter(|id| text(d, *id).is_some_and(changes)).collect(); let in_symbols = texts.iter().any(|(t, open)| *open && changes(t)); @@ -646,7 +712,7 @@ const REPLACE_SKIPPED: &str = "some text is hidden or locked, so its font wasn't fn select_font(s: &mut Session, p: &Value) -> Result { let family = str_param(p, "family").ok_or_else(|| bad("select.font", "missing `family`"))?.to_string(); let style = str_param(p, "style").map(str::to_string); - let ids = scope(s, false)?; + let ids = scope(s, false, None)?; let d = &s.doc()?.doc; // Only text the Selection tool can reach: not hidden or locked, in a hidden or locked group // or layer, or on a locked artboard. diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index b958f51c16..2b0e214cc0 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -262,7 +262,59 @@ impl Form { /// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists /// images, text, masks and links as unsupported). fn supported(n: &Node) -> bool { - n.extras().mask.is_none() && Form::of(n).is_some() + n.extras().mask.is_none() && has_form(n) +} + +/// Does [`Form::of`] give `n` a form? The same walk and the same box, without collecting the +/// points or placing them in a unit box. +fn has_form(n: &Node) -> bool { + let mut b = None; + form_box(n, 0, &mut b).is_some() + && b.is_some_and(|b: Rect| { + let side = b.width().max(b.height()); + side.is_finite() && side > 1e-9 + }) +} + +/// [`Form::add`] without the form: `b` grows by each point it would add; `None` when `n` isn't +/// supported. +fn form_box(n: &Node, depth: usize, b: &mut Option) -> Option<()> { + match &n.kind { + NodeKind::Path { path, clipping, guide: false, .. } if !*clipping || depth > 0 => grow_by_path(b, path), + NodeKind::Compound { children, .. } => { + for c in children { + grow_by_path(b, c.path_data()?); + } + } + NodeKind::SymbolInstance { xf, .. } => { + for p in [*xf * Point::ZERO, *xf * Point::new(1.0, 0.0), *xf * Point::new(0.0, 1.0)] { + grow(b, p); + } + } + NodeKind::Group { children, .. } if plain_group(n) && depth < vectorcraft_doc::MAX_DEPTH => { + for c in children { + if c.extras().mask.is_some() { + return None; + } + form_box(c, depth + 1, b)?; + } + } + _ => return None, + } + Some(()) +} + +fn grow_by_path(b: &mut Option, path: &PathData) { + for a in path.subpaths.iter().flat_map(|sp| &sp.anchors) { + for p in [a.p, a.h_in, a.h_out] { + grow(b, p); + } + } +} + +/// `b` grown to take in `p`, as [`Form::of`] measures its points. +fn grow(b: &mut Option, p: Point) { + *b = Some(b.unwrap_or(Rect::from_points(p, p)).union_pt(p)); } /// A plain group (a clip group too), not one that is live art (a graph, Shaper group, dimension, @@ -374,8 +426,9 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> { let [id] = st.selection.objects.as_slice() else { return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into()); }; - // A group's contents are checked when Global Edit starts: building its shape here would walk - // every object in it each time the menu or the Properties panel asks. + // A group's contents are checked when Global Edit starts: measuring them here would walk + // every object in it each time the menu or the Properties panel asks. Other objects are + // measured ([`supported`]), not reduced to their form: the Control bar asks every frame. match st.doc.node(*id) { Some(n) if n.extras().mask.is_none() && plain_group(n) => Ok(()), Some(n) if supported(n) => Ok(()), @@ -750,3 +803,195 @@ pub fn highlights(s: &Session) -> Outlines { *ge.outlines.borrow_mut() = Some((st.revision, out.clone())); out } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use vectorcraft_doc::OpacityMask; + use vectorcraft_geom::{Anchor, SubPath}; + + /// Global Edit's support as it was decided by building the form. + fn by_form(n: &Node) -> bool { + n.extras().mask.is_none() && Form::of(n).is_some() + } + + /// A small seeded generator (xorshift64*), so that a failure repeats. + struct Rng(u64); + + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + /// A spread for the points of one object: none, below and around the smallest size a form + /// takes, ordinary, or past every bound. + fn spread(&mut self) -> f64 { + [0.0, 1e-10, 5e-10, 1e-9, 2e-9, 1.0, 1.0, 100.0, 100.0, 100.0, f64::INFINITY, f64::NAN][self.below(12) as usize] + } + fn point(&mut self, base: Point, spread: f64) -> Point { + let mut c = |b: f64| match self.below(400) { + 0 => f64::NAN, + 1 => f64::INFINITY, + 2 => f64::NEG_INFINITY, + _ => b + (self.unit() - 0.5) * spread, + }; + Point::new(c(base.x), c(base.y)) + } + } + + fn path_data(r: &mut Rng) -> PathData { + let (base, spread) = (Point::new(r.unit() * 200.0, r.unit() * 200.0), r.spread()); + let subpaths = (0..r.below(3)) + .map(|_| { + let anchors = (0..r.below(4)) + .map(|_| Anchor { p: r.point(base, spread), h_in: r.point(base, spread), h_out: r.point(base, spread), ..Anchor::corner(base) }) + .collect(); + SubPath::new(anchors, r.below(2) == 0) + }) + .collect(); + PathData::new(subpaths) + } + + /// A random object: paths (clipping paths and guides too), compound paths, symbol instances, + /// groups (clip groups, live art, members with an opacity mask), type, blends and intertwined + /// objects, any of them with an opacity mask. + fn object(r: &mut Rng, d: &mut Document, text: &Node, depth: usize) -> Node { + let leaf = depth >= 3; + let mut n = match r.below(if leaf { 4 } else { 8 }) { + 0 | 1 => { + let mut n = Node::path(d.alloc_id(), path_data(r), Appearance::default()); + if let NodeKind::Path { clipping, guide, .. } = &mut n.kind { + *clipping = r.below(6) == 0; + *guide = r.below(8) == 0; + } + n + } + 2 => { + let xf = match r.below(4) { + 0 => Affine::scale(0.0), + 1 => Affine::scale(1e-10), + _ => Affine::translate((r.unit() * 100.0, r.unit() * 100.0)) * Affine::scale(r.spread()), + }; + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf }) + } + 3 => { + let mut t = text.clone(); + t.id = d.alloc_id(); + t + } + 4 => { + let children = (0..r.below(4)) + .map(|_| match r.below(5) { + 0 => Arc::new(object(r, d, text, depth + 1)), + _ => Arc::new(Node::path(d.alloc_id(), path_data(r), Appearance::default())), + }) + .collect(); + Node::new(d.alloc_id(), NodeKind::Compound { children, rule: vectorcraft_geom::FillRule::NonZero }) + } + 5 => { + let children = (0..r.below(3)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect(); + Node::new(d.alloc_id(), NodeKind::Blend { children, spec: Box::default() }) + } + _ => { + let children = (0..r.below(4)).map(|_| Arc::new(object(r, d, text, depth + 1))).collect(); + let mut g = Node::new(d.alloc_id(), NodeKind::Group { children, clip: r.below(3) == 0 }); + if r.below(8) == 0 { + g.extras_mut().trace = Some(Box::new(Value::Null)); + } + g + } + }; + if r.below(10) == 0 { + n.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::path(d.alloc_id(), path_data(r), Appearance::default()), true))); + } + n + } + + /// `n` and every object in it. + fn every(n: &Node) -> Vec { + let mut out = vec![]; + n.walk(&mut |c| out.push(c.clone())); + out + } + + #[test] + fn support_is_decided_as_building_the_form_decides() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 50, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let text = s.doc().unwrap().doc.node(t).unwrap().clone(); + let layer = s.doc().unwrap().doc.layers[0].id; + let (mut checked, mut taken, mut asked) = (0, 0, 0); + for seed in 1..=400u64 { + let mut r = Rng(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1); + let n = object(&mut r, Arc::make_mut(&mut s.doc_mut().unwrap().doc), &text, 0); + for c in every(&n) { + assert_eq!(supported(&c), by_form(&c), "seed {seed}: {c:?}"); + checked += 1; + taken += usize::from(by_form(&c)); + } + // The enabled check of Start Global Edit on it, and Start Global Edit itself. + let id = Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, n.clone()).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + if s.doc().unwrap().selection.objects != [id] { + continue; + } + asked += 1; + let today = n.extras().mask.is_none() && plain_group(&n) || by_form(&n); + assert_eq!(can_toggle(&s).is_ok(), today, "seed {seed}"); + match s.execute(C, &json!({})) { + Ok(_) => { + assert!(by_form(&n), "seed {seed}"); + s.execute(C, &json!({})).unwrap(); + } + Err(e) => assert_eq!(e.to_string().contains(UNSUPPORTED), !by_form(&n), "seed {seed}: {e}"), + } + } + // Both answers came up often, and most objects could be selected alone. + assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected"); + } + + #[test] + fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() { + let mut d = Document::new(800.0, 600.0); + let corner = |x: f64, y: f64| Anchor::corner(Point::new(x, y)); + let path = |d: &mut Document, subpaths: Vec| Node::path(d.alloc_id(), PathData::new(subpaths), Appearance::default()); + let mut cases = vec![ + path(&mut d, vec![]), + path(&mut d, vec![SubPath::new(vec![], true)]), + path(&mut d, vec![SubPath::new(vec![corner(5.0, 5.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 1e-9)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(0.0, 2e-9)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(f64::INFINITY, 0.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, 0.0), corner(10.0, 0.0), corner(0.0, 0.0)], false)]), + path(&mut d, vec![SubPath::new(vec![corner(f64::NAN, f64::NAN)], false)]), + Node::new(d.alloc_id(), NodeKind::Compound { children: vec![], rule: Default::default() }), + Node::group(d.alloc_id(), vec![]), + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::scale(0.0) }), + Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY }), + ]; + // A group as deep as the walk goes, and one level deeper. + let mut deep = path(&mut d, vec![SubPath::new(vec![corner(0.0, 0.0), corner(10.0, 10.0)], false)]); + for _ in 0..=vectorcraft_doc::MAX_DEPTH { + deep = Node::group(d.alloc_id(), vec![Arc::new(deep)]); + cases.push(deep.clone()); + } + let expected = [false, false, false, false, true, false, true, false, false, false, false, true]; + for (i, n) in cases.iter().enumerate() { + assert_eq!(supported(n), by_form(n), "case {i}: {n:?}"); + if let Some(e) = expected.get(i) { + assert_eq!(supported(n), *e, "case {i}"); + } + } + assert!(supported(&cases[cases.len() - 2]) && !supported(&cases[cases.len() - 1])); + } +} diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index f777628f20..47989a29c0 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -197,7 +197,8 @@ pub(crate) fn with_stored_stops<'a>(g: &'a Value, old: &Paint, stored: &StopColo /// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid /// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the /// diamond's range; `swatch` and `tint` (%) keep a stop's link as given (resolve them first with -/// [`link_stops`]). The result is sorted by offset. +/// [`link_stops`]), and `plates` (C, M, Y, K, 0..1) the process inks a linked stop prints with its +/// spot ink. The result is sorted by offset. pub(crate) fn parse_stops(v: &Value) -> Parsed> { let arr = v.as_array().ok_or("`stops` must be an array")?; if arr.len() < 2 { @@ -213,6 +214,10 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { let opacity = num("opacity")?.map(|o| if o > 1.0 { o / 100.0 } else { o }).unwrap_or(1.0); let swatch = str_param(st, "swatch").map(str::to_string); let tint = num("tint")?.filter(|_| swatch.is_some()).map_or(1.0, |t| (t / 100.0).clamp(0.0, 1.0) as f32); + let plates = match st.get("plates").filter(|_| swatch.is_some()) { + None | Some(Value::Null) => None, + Some(p) => Some(plates_param(p).ok_or_else(|| format!("stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K)"))?), + }; Ok(GradientStop { offset: offset.clamp(0.0, 1.0) as f32, color, @@ -220,6 +225,7 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { midpoint: num("midpoint")?.unwrap_or(0.5).clamp(0.13, 0.87) as f32, swatch, tint, + plates, }) }) .collect::>>()?; @@ -227,6 +233,17 @@ pub(crate) fn parse_stops(v: &Value) -> Parsed> { Ok(out) } +/// A stop's `plates` param: the process inks (C, M, Y, K, 0..1) printed with its spot swatch. +fn plates_param(v: &Value) -> Option<[f32; 4]> { + let a = v.as_array().filter(|a| a.len() == 4)?; + let mut out = [0.0f32; 4]; + for (o, x) in out.iter_mut().zip(a) { + let x = x.as_f64().filter(|x| x.is_finite())?; + *o = x.clamp(0.0, 1.0) as f32; + } + Some(out) +} + /// Parse a gradient paint object (the `gradient` param of `paint.setFill`). Lossless for everything /// `vectorcraft_tools::params::gradient_params` writes. pub(crate) fn parse_gradient(g: &Value) -> Parsed { diff --git a/crates/engine/src/cmd/intertwine.rs b/crates/engine/src/cmd/intertwine.rs index 23f1be1906..b19206c397 100644 --- a/crates/engine/src/cmd/intertwine.rs +++ b/crates/engine/src/cmd/intertwine.rs @@ -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: (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 { + 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], face: &Face, order: &[usize]) { +/// are (`areas`: what each member paints, [`painted_areas`]). +fn arrange_face(children: &mut [Arc], face: &Face, order: &[usize], areas: &[Option]) { 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 { 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 { 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(()) })?; diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index ff4e3d0fbd..c85fe7e370 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -100,7 +100,31 @@ pub enum ItemKind { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LibraryColor { pub name: String, + /// The colour; a spot colour's full-strength ink (its swatch's colour), without the tint. pub color: Color, + /// A spot colour's ink (its swatch's name): using it adds the document's spot swatch of that + /// name and links the paint to it (#5812). Files written before spot colours have none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spot: Option, + /// A spot colour's tint (0..1; 1 for a process colour). + #[serde(default = "full_tint", skip_serializing_if = "is_full_tint")] + pub tint: f32, +} + +fn full_tint() -> f32 { + 1.0 +} + +fn is_full_tint(t: &f32) -> bool { + *t >= 1.0 +} + +/// A library colour as `library.add` reads it from the selection or params. +struct NewColor { + name: String, + color: Color, + spot: Option, + tint: f32, } /// A graphic: the art as a native document (its own resources included) and its thumbnail. @@ -369,6 +393,13 @@ impl Library { fn sanitize(&mut self) { clip(&mut self.name); self.colors.truncate(MAX_ITEMS); + for c in &mut self.colors { + if let Some(ink) = &mut c.spot { + clip(ink); + } + c.spot = c.spot.take().filter(|ink| !ink.trim().is_empty()); + c.tint = if c.spot.is_some() && c.tint.is_finite() { c.tint.clamp(0.0, 1.0) } else { 1.0 }; + } self.gradients.retain_mut(|g| clean_gradient(&mut g.gradient)); self.gradients.truncate(MAX_ITEMS); self.patterns.truncate(MAX_ITEMS); @@ -598,7 +629,7 @@ pub fn specs() -> Vec { "Library", [], None, - "{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}", + "{library?: id or name (default: the current library)} → {id, name, graphics: [{id, name, width, height, thumbnail: PNG base64}], colors: [{name, hex, color, spot: ink name or null, tint: 0..1}], gradients: [{name, gradient: {gradient: {kind, stops}, angle}}], patterns: [{name, pattern: its name in the item, thumbnail: PNG base64}], charStyles: [{name, attrs}], paraStyles: [{name, attrs}], groups: [{name, items: [{kind: color|gradient|pattern|charStyle|paraStyle|graphic, item: name (graphic: id)}]}] (an item is in one group at most; the others are ungrouped)}", always, get ), @@ -643,7 +674,7 @@ pub fn specs() -> Vec { "Add to Library", [], None, - "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", + "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint; with `color`, the spot swatch it is, kept as a spot colour), tint?: 0..100 (with `color` and a spot `swatch`: its %), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke), a colour linked to a spot swatch kept as a spot colour (the swatch's name, its colour and the tint); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", has_doc, add ), @@ -652,7 +683,7 @@ pub fn specs() -> Vec { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -782,7 +813,7 @@ fn get(s: &mut Session, p: &Value) -> Result { "id": id, "name": lib.name, "graphics": lib.graphics.iter().map(|g| json!({"id": g.id, "name": g.name, "width": g.width, "height": g.height, "thumbnail": g.thumbnail})).collect::>(), - "colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color})).collect::>(), + "colors": lib.colors.iter().map(|c| json!({"name": c.name, "hex": c.color.to_hex(), "color": c.color, "spot": c.spot, "tint": c.tint})).collect::>(), "gradients": lib.gradients.iter().map(|g| json!({"name": g.name, "gradient": g.gradient})).collect::>(), "patterns": lib.patterns.iter().map(|p| json!({"name": p.name, "pattern": p.pattern, "thumbnail": p.thumbnail})).collect::>(), "charStyles": lib.char_styles.iter().map(|t| json!({"name": t.name, "attrs": t.attrs})).collect::>(), @@ -856,13 +887,14 @@ fn add(s: &mut Session, p: &Value) -> Result { lib.graphics.push(g); placed(lib, &place, ItemRef { kind: item_kind, item: key }, v)? } - Item::Color((name, color)) => { + Item::Color(NewColor { name, color, spot, tint }) => { full(lib.colors.len())?; - if let Some(old) = lib.colors.iter().find(|o| o.color == color) { + // A spot colour is its ink: one of another ink (or a process colour) is another item. + if let Some(old) = lib.colors.iter().find(|o| o.color == color && o.spot == spot && o.tint == tint) { return Ok(json!({ "name": old.name, "existing": true })); } let name = unique(&given.clone().unwrap_or(name), |n| lib.colors.iter().any(|o| o.name == n)); - lib.colors.push(LibraryColor { name: name.clone(), color }); + lib.colors.push(LibraryColor { name: name.clone(), color, spot, tint }); placed(lib, &place, ItemRef { kind: item_kind, item: name.clone() }, json!({ "name": name, "existing": false }))? } Item::Gradient(mut g) => { @@ -925,7 +957,7 @@ fn placed(lib: &mut Library, place: &Placement, r: ItemRef, mut v: Value) -> Res enum Item { Graphic(LibraryGraphic), - Color((String, Color)), + Color(NewColor), Gradient(LibraryGradient), Pattern(LibraryPattern), Style(bool, Map), @@ -942,7 +974,7 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result { if roots.is_empty() { return Err(bad(cmd, "select the art to add first")); } - let clip = Clipboard::copy(st, &roots); + let clip = Clipboard::copy(st, &roots, false); let bounds = clip.bounds().ok_or_else(|| bad(cmd, "the selection draws nothing"))?; let mut doc = clip.to_document(); let board = bounds.inflate(1.0, 1.0); @@ -963,23 +995,38 @@ fn graphic_of(s: &Session, p: &Value, cmd: &str) -> Result { } /// The first selected object's solid fill (`stroke`: stroke) colour, else the default one, with a -/// name: its swatch's, else its hex. -fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result<(String, Color)> { - // A colour given (a swatch dropped on the panel). +/// name: its swatch's, else its hex. A colour linked to a spot swatch keeps the ink (the swatch's +/// name and full-strength colour) and its tint. +fn color_of(s: &Session, p: &Value, stroke: bool, cmd: &str) -> Result { + // A colour given (a swatch dropped on the panel), with its spot swatch's name when it has one. if let Some(c) = p.get("color").filter(|v| !v.is_null()) { let color = color_value(c).ok_or_else(|| bad(cmd, "bad colour"))?; - return Ok((color.to_hex(), color)); + let swatch = str_param(p, "swatch").map(str::to_string); + let tint = super::paint::tint_param(p, cmd)?.unwrap_or(1.0); + let given = NewColor { name: color.to_hex(), color, spot: None, tint: 1.0 }; + return Ok(spot_color(s, given, swatch, tint)); } match selected_paint(s, p, stroke)? { - Paint::Solid { color, swatch, .. } => { - let name = swatch.filter(|n| !n.is_empty()).unwrap_or_else(|| color.to_hex()); - Ok((name, color)) + Paint::Solid { color, swatch, tint } => { + let swatch = swatch.filter(|n| !n.is_empty()); + let name = swatch.clone().unwrap_or_else(|| color.to_hex()); + Ok(spot_color(s, NewColor { name, color, spot: None, tint: 1.0 }, swatch, tint)) } Paint::None => Err(bad(cmd, if stroke { "the selection has no stroke colour" } else { "the selection has no fill colour" })), _ => Err(bad(cmd, "only solid colours can be added (not gradients or patterns)")), } } +/// `c` as the spot colour of the active document's spot swatch `swatch` at `tint` (0..1), when +/// there is one: named after it, with its full-strength colour; else `c` as it is. +fn spot_color(s: &Session, c: NewColor, swatch: Option, tint: f32) -> NewColor { + let Some(doc) = s.active().map(|st| &st.doc) else { return c }; + let Some(name) = swatch else { return c }; + let Some(ink) = doc.swatch(&name).filter(|w| w.spot).and_then(|w| w.paint.color()) else { return c }; + let tint = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 1.0 }; + NewColor { name: name.clone(), color: ink, spot: Some(name), tint } +} + /// The first selected object's (or `ids`') fill (`stroke`: stroke) paint (type's: its first /// character's, as the proxy shows it), else the default one. fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result { @@ -989,11 +1036,13 @@ fn selected_paint(s: &Session, p: &Value, stroke: bool) -> Result { None => st.selection.objects.clone(), }; let from_art = ids.iter().filter_map(|id| st.doc.node(*id)).find_map(|n| { - let (paint, to_doc, _) = n.proxy_paint(stroke, None)?; + let (paint, to_doc, bounds) = n.proxy_paint(stroke, None)?; // Type's characters paint in its own space: a gradient there takes its placement in the // document, so that it keeps the direction it shows. - match (paint, n.proxy_gradient(stroke, None)) { - (Paint::Gradient(g), Some((_, geom))) if to_doc != vectorcraft_geom::Affine::IDENTITY => { + match paint { + Paint::Gradient(g) if to_doc != vectorcraft_geom::Affine::IDENTITY => { + let mut geom = g.resolve(bounds); + geom.transform(to_doc, g.gradient.kind); Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() }))) } _ => Some(paint.clone()), @@ -1100,7 +1149,10 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } Kind::FillColor | Kind::StrokeColor => { let c = lib.colors.iter().find(|c| c.name == item).ok_or_else(missing)?; - json!({ "color": c.color }) + match &c.spot { + Some(ink) => json!({ "color": c.color, "spot": ink, "tint": c.tint }), + None => json!({ "color": c.color }), + } } Kind::FillGradient | Kind::StrokeGradient => { let g = lib.gradients.iter().find(|g| g.name == item).ok_or_else(missing)?; @@ -1143,7 +1195,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result { Kind::FillColor | Kind::StrokeColor => { let stroke = to_stroke(p, kind)?; let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?; - s.execute(if stroke { "paint.setStroke" } else { "paint.setFill" }, &json!({ "color": color }))?; + let set = if stroke { "paint.setStroke" } else { "paint.setFill" }; + match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) { + Some(ink) => use_spot(s, set, ink, &color, &data)?, + None => { + s.execute(set, &json!({ "color": color }))?; + } + } Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } })) } Kind::FillGradient | Kind::StrokeGradient => { @@ -1185,6 +1243,32 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } } +/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its +/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of +/// that name: the one it has when it is the same colour, else a new one (a name taken by another +/// colour gets a number), one undo step (#5812). +fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> { + const C: &str = "library.use"; + let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?; + let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0)); + let doc = &s.doc()?.doc; + let have = doc.swatch(ink).is_some_and(|w| w.spot && w.paint.color() == Some(c)); + in_one_step(s, |s| { + let swatch = if have { + ink.to_string() + } else { + let r = s.execute("swatch.new", &json!({ "name": ink, "color": color, "spot": true, "keepModel": true }))?; + r.get("name").and_then(Value::as_str).ok_or_else(|| bad(C, "the spot colour couldn't be added"))?.to_string() + }; + let mut p = json!({ "swatch": swatch }); + if tint < 1.0 { + p["tint"] = json!(tint * 100.0); + } + s.execute(set, &p)?; + Ok(()) + }) +} + /// The `to` param of `library.use`: whether the item paints the stroke (default: the kind's). fn to_stroke(p: &Value, kind: Kind) -> Result { match str_param(p, "to") { diff --git a/crates/engine/src/cmd/linkfiles.rs b/crates/engine/src/cmd/linkfiles.rs index c874a70ee9..5b5a6aa48a 100644 --- a/crates/engine/src/cmd/linkfiles.rs +++ b/crates/engine/src/cmd/linkfiles.rs @@ -2,7 +2,7 @@ //! subfolders (`links.findFiles`, searched on separate threads: [`super::findfiles`]). A file with //! a linked file's name, in any letter case, is ranked by what the link saved //! ([`vectorcraft_doc::LinkInfo`]): the same file (its size and hash), the same size (when the link -//! saved no hash, or the file is larger than 1 GB and isn't hashed), or the name only. +//! saved no hash, or the file is larger than 1 GiB and isn't hashed), or the name only. use std::collections::HashMap; use std::path::{Component, Path, PathBuf}; @@ -29,7 +29,7 @@ pub fn specs() -> Vec { "Find Linked Files", [], None, - "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", + "{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}", always, find )] @@ -176,10 +176,29 @@ fn find(s: &mut Session, p: &Value) -> Result { } /// How many folder names the file at `found` has in common with the saved path `saved` (whichever -/// system's separators it uses), counted from the innermost out up to the first that differs, -/// compared in lowercase. +/// system's separators it uses, [`vectorcraft_doc::links::path_separators`]), counted from the +/// innermost out up to the first that differs, compared in lowercase. The saved path's parent +/// components are resolved first: `..` in a `/` or `\` path, and each colon after the first in a +/// run of colons in a classic Mac OS path (`Disk:Projects:Art::photo.png` is in `Projects`). fn shared_folders(saved: &str, found: &Path) -> usize { - let saved = saved.rsplit(['/', '\\']).skip(1).filter(|c| !c.is_empty()); + let separators = vectorcraft_doc::links::path_separators(saved); + let classic = separators == [':']; + let mut up = 0usize; + let saved = saved.rsplit(separators).skip(1).filter(move |c| { + let parent = if classic { c.is_empty() } else { *c == ".." }; + if parent { + up += 1; + return false; + } + if c.is_empty() || *c == "." && !classic { + return false; + } + if up > 0 { + up -= 1; + return false; + } + true + }); let found = found.parent().into_iter().flat_map(|p| p.components().rev()).map_while(|c| match c { Component::Normal(n) => n.to_str(), _ => None, diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 441249b05b..bcda11c2bd 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1110,7 +1110,7 @@ fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result { /// Per linked image in the layers of `st`: its file's status, where it was found when away from /// its path, and whether the image shows its preview (each file probed once). -fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { +pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap, bool)> { let mut out = BTreeMap::new(); for g in groups(&st.doc, None).iter().filter(|g| !g.ids.is_empty()) { let (status, found) = probe(g, st.path.as_deref()); @@ -1349,12 +1349,11 @@ fn file_fields_here(st: &crate::DocState, id: NodeId, l: &LinkInfo, out: &mut Va let doc_path = st.path.as_deref(); let path = fileio::document_path(&l.path, doc_path).ok(); let stamp = path.as_deref().and_then(file_stamp); - let folder_len = l.path.len().saturating_sub(l.name().len()); out["status"] = json!(status.as_str()); note_refused(out, l, doc_path); out["path"] = json!(l.path); out["fileName"] = json!(l.name()); - out["location"] = json!(l.path.get(..folder_len).unwrap_or_default().trim_end_matches(['/', '\\'])); + out["location"] = json!(l.folder()); for (k, v) in [ ("page", l.page.map(u64::from)), ("fileSize", stamp.map(|s| s.0).or(l.size)), diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 73f0922145..9933b20718 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -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 { 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> { + 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 { 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 { 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 { 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 = 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); } diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 99c813fa3e..abd88c3777 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/maskedit.rs b/crates/engine/src/cmd/maskedit.rs index 83c7abf7c6..65bf150868 100644 --- a/crates/engine/src/cmd/maskedit.rs +++ b/crates/engine/src/cmd/maskedit.rs @@ -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 { 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; diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 9401402c50..34db64081b 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -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 { vec![ @@ -216,7 +216,7 @@ impl Session { } fn set_basic(s: &mut Session, p: &Value) -> Result { - 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 })) } diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index bed6e6c381..b400f637af 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -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)) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 211905166b..390f6ef499 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -732,7 +732,7 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option Vec { "Convert to Text", [], None, - "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them; in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", + "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, convert_list_to_text ), @@ -207,7 +207,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result = indices.iter().filter_map(|i| st.doc.artboards.get(*i).cloned()).collect(); - let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art) }; + let clip = Clipboard { source_artboard: boards.first().map(|a| a.rect), artboards: boards, ..Clipboard::copy(st, &art, false) }; let copied = clip.nodes.len(); if cut { s.edit("Cut Artboard", |d, sel| { @@ -876,8 +876,23 @@ fn move_editing_selection( fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { const C: &str = "text.convertListToText"; use vectorcraft_doc::text::ParaList; - let ids = super::typecmd::text_targets(s, p, C)?; let range = super::typecmd::TextRange::parse(p, C)?; + // After Select All in a frame of threaded text, a call that names no type and no range takes + // every paragraph of the story's editable frames; its locked and hidden frames stay as they are + // whichever way they are named. + let full = super::textedit::editing_story(s); + let story: Vec = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect(); + let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); + let ids = if !story.is_empty() && !named && range.is_none() { + story.clone() + } else { + super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect() + }; + // The selected story's locked and hidden frames: no paragraph whose text starts in one is + // converted, and none of their paragraphs is restyled. + let held: Vec = full.iter().copied().filter(|f| !story.contains(f)).collect(); + // Converting the whole story leaves it selected. + let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f)); let editing = match super::textedit::editing_range(s)? { Some((id, _, _)) => { let options = s.tool_options(); @@ -909,6 +924,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let mut converted = 0; for story in &stories { let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect(); + let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id)); let mut paras: Vec = vec![]; let mut named_parts = vec![]; let plains: Vec = frames.iter().map(|t| t.plain_text()).collect(); @@ -934,7 +950,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { } for (i, named) in named_parts { if let Some(para) = paras.get_mut(i) { - let listed = para.main_part().is_some_and(|p| p.list.is_some()); + let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame)); para.converts |= named && listed; } } @@ -1021,7 +1037,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' }; style.tabs.insert(i, tab); } - for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) { + for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) { if let Some((stops, _)) = frame_edits.get_mut(part.frame) { stops.push((part.index, style.clone())); } @@ -1058,7 +1074,8 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - if let Some(editing) = editing { + // A whole story selected by Select All stays selected, with the characters inserted. + if let Some(editing) = editing.filter(|_| !whole_story) { move_editing_selection(s, editing, &story_before, &insertions)?; } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 2def5ce9ea..e0de6bd4ad 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -10,8 +10,8 @@ use super::create::anchor_from_json; use super::draw2::usize_opt; use super::pathops::Beside; use super::{ - CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selection, - id_param, ids_param, index, number_or, ok, str_param, switch_or, targets, + CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path, + has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets, }; use crate::EngineError; @@ -77,7 +77,7 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}", - has_doc, + has_selected_path, reverse ), cmd!( @@ -86,7 +86,7 @@ pub fn specs() -> Vec { ["Object", "Path"], Some("Cmd+J"), "{ids?: [path, ...] (default: the selected paths; a compound path ID expands to its open member paths), subpaths?: [usize, usize] (which subpaths to join), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, for two paths/subpaths; default without ids: direct-selected ends if any, else the nearest pair; default with ids: the nearest pair), to?: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours)} join two or more open paths/subpaths into one (the first keeps its id, selected), or close a single open path; without ids, direct-selected anchors lying on one another along a path merge into one anchor instead", - has_selection, + has_selected_path, join ), cmd!( @@ -95,7 +95,7 @@ pub fn specs() -> Vec { ["Object", "Path"], Some("Cmd+Alt+J"), "{axis?: \"horizontal\"|\"vertical\"|\"both\"}", - has_selection, + has_selected_path, average ), cmd!( @@ -104,7 +104,7 @@ pub fn specs() -> Vec { ["Object", "Path"], Some("Cmd+Alt+Shift+J"), "{to: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours), ids?: [path, ...] (default: the selection; a compound path ID expands to its open member paths)} move two open path ends to their midpoint and join them there, as one undo step: the two direct-selected anchors when they are open path ends, else the nearest ends of the two open paths in ids or the selection (or both ends of one open path, closing it) → the joined path stays selected", - has_selection, + has_selected_path, average_join ), cmd!( @@ -1191,7 +1191,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { // `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(); diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index e1fecc6da3..5fd0f54434 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -15,8 +15,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp}; use super::edit::selected_roots; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, number_or, str_param, - switch_or, + CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, + number_or, str_param, switch_or, }; pub fn specs() -> Vec { @@ -153,7 +153,7 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{tolerance?: pt (1), level?: 0..100 (the Simplify slider, in place of tolerance: 0 fewest anchor points, 50 is 1 pt, every 10 levels halves or doubles it), auto?: bool (Auto-Simplify: the lowest level whose tolerance is at most 1/400 of the selection's longer side, or 100 when that side is under 12.5 pt), cornerAngle?: deg (30), straightLines?: bool, wholePaths?: bool (false: a path with segments direct-selected, or between direct-selected anchors, simplifies only each run of them between its end anchors, which stay as they are, and keeps the runs selected; true simplifies those paths whole)} → {ids, before, after} anchor counts, and the level used with level or auto", - has_selection, + has_selected_path, simplify ), cmd!( @@ -162,17 +162,17 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{level?: 0..100 (50; the Smooth slider: 0 minimum smoothing, the path staying within 0.1% of its longer side, 100 maximum: smoothed along its length by up to 5% of it and refitted with curves within up to 2.5% of it, corners kept only where the path turns back, never with more anchor points), auto?: bool (Auto-Smooth: level 50), ids?: [id…] (default: the selection)} smooth each path under the objects, compound path members included, as one undo step; without ids, a path with anchor points or segments direct-selected smooths only the sections between them, which stay selected → {ids, before, after} anchor counts, and the level used", - has_selection, + has_selected_path, smooth ), - cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selection, add_anchor_points), + cmd!("object.path.addAnchorPoints", "Add Anchor Points", ["Object", "Path"], None, "{} → {ids}", has_selected_path, add_anchor_points), cmd!( "object.path.divideObjectsBelow", "Divide Objects Below", ["Object", "Path"], None, "{} cut the objects below with the selected path (which is removed) → {ids}", - has_selection, + has_selected_path, divide_objects_below ), cmd!( @@ -181,7 +181,7 @@ pub fn specs() -> Vec { ["Object", "Path"], None, "{rows?: 2, columns?: 2, gutter?: pt (12; rowGutter?, columnGutter?: one of the two), totalHeight?, totalWidth?: pt (the grid's size; the selected paths' when left out), height?, width?: pt (each row's and column's size, which then sets the total), addGuides?: false (ruler guides along the row and column edges)} one grid of rectangles over the selected paths replaces them, painted as the topmost one → {ids, guides: count}", - has_selection, + has_selected_path, split_into_grid ), cmd!( @@ -770,7 +770,14 @@ fn offset_path(s: &mut Session, p: &Value) -> Result { let Some((path, rule)) = node_path(l) else { continue }; paths = true; let base = if matches!(l.kind, NodeKind::Compound { .. }) && path.is_closed() { po::normalize(&path, rule) } else { path }; - let off = po::offset_path(&base, delta, join, miter); + let off = match po::try_offset_path(&base, delta, join, miter) { + Ok(p) => p, + Err(po::PathOpsError::NonFinite) => continue, + Err(po::PathOpsError::TooComplex) => { + return Err(EngineError::Other("Offset Path: the path is too complex to offset".into())); + } + Err(e) => return Err(EngineError::Other(format!("Offset Path: {e}"))), + }; if off.is_empty() { continue; } @@ -890,6 +897,8 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br return None; } let (path, rule) = node_path(l)?; + // A fill belongs to the source path, whether open or closed. Converting its stroke + // preserves that fill on a separate copy (including compound member geometry). let mut parts: Vec = vec![]; let mut fills: Vec = vec![]; for item in &l.appearance.items { diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index cd03a41512..8d1bb04085 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -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)> { /// `plugin.list` entry. fn install(s: &mut Session, p: &Value) -> Result { 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, diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index ad24afacbc..029f3608f6 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -260,14 +260,40 @@ pub const PREF_SPECS: &[PrefSpec] = &[ "", "Default Language", choice(&[ - ("English: USA", "English: USA"), - ("English: UK", "English: UK"), - ("French", "French"), - ("German", "German"), - ("Spanish", "Spanish"), - ("Italian", "Italian"), - ("Dutch", "Dutch"), - ("Portuguese", "Portuguese") + ("en-US", "English: USA"), + ("en-GB", "English: UK"), + ("de", "German"), + ("de-CH", "German: Swiss"), + ("fr", "French"), + ("it", "Italian"), + ("es", "Spanish"), + ("ca", "Catalan"), + ("pt", "Portuguese"), + ("nl", "Dutch"), + ("da", "Danish"), + ("sv", "Swedish"), + ("fi", "Finnish"), + ("nb", "Norwegian"), + ("pl", "Polish"), + ("cs", "Czech"), + ("ru", "Russian"), + ("sr-Cyrl", "Serbian: Cyrillic"), + ("sr-Latn", "Serbian: Latin"), + ("hr", "Croatian"), + ("tr", "Turkish"), + ("ja", "Japanese"), + ("zh", "Chinese"), + ("hi", "Hindi"), + ("mr", "Marathi"), + ("gu", "Gujarati"), + ("bn", "Bengali"), + ("pa", "Punjabi"), + ("ta", "Tamil"), + ("te", "Telugu"), + ("kn", "Kannada"), + ("ml", "Malayalam"), + ("or", "Odia"), + ("ur", "Urdu") ]) ), p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), diff --git a/crates/engine/src/cmd/printtiling.rs b/crates/engine/src/cmd/printtiling.rs index 6c683ac791..3dabe747e6 100644 --- a/crates/engine/src/cmd/printtiling.rs +++ b/crates/engine/src/cmd/printtiling.rs @@ -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 { fn show(s: &mut Session, p: &Value) -> Result { 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 })) } diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index cc8598a5cc..c2092da0a8 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -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 { } fn clip_to_artboard(s: &mut Session, p: &Value) -> Result { - 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 { } fn hide(s: &mut Session, p: &Value) -> Result { - 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 { } fn lock(s: &mut Session, p: &Value) -> Result { - 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); diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 3b1289a862..4937ff200a 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -24,6 +24,24 @@ pub fn specs() -> Vec { 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 { Ok(json!({"objects": ids.iter().collect::>().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 { + 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::>().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 { 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); + } +} diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 8e929f14d2..9ecec6c672 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -211,7 +211,28 @@ impl Libraries { .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 = 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)))?; diff --git a/crates/engine/src/cmd/tabs.rs b/crates/engine/src/cmd/tabs.rs index 570a93c77a..331227e3be 100644 --- a/crates/engine/src/cmd/tabs.rs +++ b/crates/engine/src/cmd/tabs.rs @@ -13,7 +13,7 @@ pub fn specs() -> Vec { "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> { 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(); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 33fa1a5142..fba84acafe 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1585,7 +1585,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { }; 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 }], diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 9d56ca0c90..71d175b3ac 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -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(); diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 4806531cde..426479070d 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -856,7 +856,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 429a854f4b..54f3689e99 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -258,24 +258,33 @@ fn parse_library(xml: &str, cmd: &str) -> Result { /// 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: +/// ). 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 { 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 = 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 = vars.variables.iter().filter(|v| !kept(v)).map(|v| v.name.clone()).collect(); let deleted_sets: Vec = vars.datasets.iter().map(|d| d.name.clone()).collect(); + let added: Vec = 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 = lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(); let names: Vec = 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| { diff --git a/crates/engine/src/cmd/views.rs b/crates/engine/src/cmd/views.rs index 8597a0963e..fd9e11bcf7 100644 --- a/crates/engine/src/cmd/views.rs +++ b/crates/engine/src/cmd/views.rs @@ -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 { vec![ @@ -64,7 +64,7 @@ fn caps_lock(s: &mut Session, p: &Value) -> Result { fn transparency_grid(s: &mut Session, p: &Value) -> Result { 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 })) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 34592575c3..3d1c4be89b 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -452,27 +452,66 @@ impl DocState { pub fn current_layer(&self) -> Option { self.active_layer.filter(|l| self.doc.node(*l).is_some_and(|n| n.is_layer())) } + /// Where new art is inserted: the isolation container (or its parent if the container cannot hold + /// the art type), else the active layer. pub fn insertion_parent(&self) -> Option { - // Ids are reused after undo (the id counter is part of the document), so a remembered - // layer or isolated group must still be one: a pasted group must never land in a path. - if let Some(i) = self.isolation - && self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) - { - return Some(i); + self.insertion_parent_for(false) + } + + /// Where new path art is inserted. When a compound path is isolated, returns the compound path + /// so new paths become members of the compound path. + pub fn insertion_parent_for_path(&self) -> Option { + self.insertion_parent_for(true) + } + + fn insertion_parent_for(&self, for_path: bool) -> Option { + if let Some(i) = self.isolation { + if self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) { + return Some(i); + } + if for_path && self.doc.node(i).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) { + return Some(i); + } } - // A single object isolated: new art goes beside it, in its group or layer. - if let Some(p) = self.isolation.filter(|i| self.doc.node(*i).is_some_and(|n| !n.is_container())).and_then(|i| self.doc.parent_of(i)) - && self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) - { - return Some(p); + if let Some(p) = self.isolation.filter(|i| self.doc.node(*i).is_some_and(|n| !n.is_container())).and_then(|i| self.doc.parent_of(i)) { + if self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) { + return Some(p); + } + if for_path && self.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) { + return Some(p); + } + } + // Non-path art created while a compound path is isolated goes into the compound's parent container: + if let Some(iso) = self.isolation { + let compound = if self.doc.node(iso).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })) { + Some(iso) + } else { + self.doc.parent_of(iso).filter(|p| self.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) + }; + if let Some(c) = compound + && let Some(p) = self.doc.parent_of(c) + && self.doc.is_editable(p) + { + return Some(p); + } } // A sublayer takes new art only while it and the layers around it are shown and unlocked. self.active_layer.filter(|l| self.doc.node(*l).is_some_and(|n| n.is_layer()) && self.doc.is_editable(*l)).or_else(|| self.doc.default_layer()) } + /// [`Self::insertion_parent`] for new art, which a locked or hidden layer never takes: an error /// when no layer is shown and unlocked, so the art is refused rather than hidden or locked away. pub fn target_parent(&self) -> Result> { - match self.insertion_parent() { + self.target_parent_for(false) + } + + /// [`Self::insertion_parent_for_path`] for new path art. + pub fn target_parent_for_path(&self) -> Result> { + self.target_parent_for(true) + } + + fn target_parent_for(&self, for_path: bool) -> Result> { + match self.insertion_parent_for(for_path) { Some(p) if !self.doc.is_editable(p) => Err(EngineError::Other("the target layer is locked or hidden".into())), parent => Ok(parent), } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 722b854d69..0565a9115f 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -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 { } /// 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}"); } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5deb00ddde..ce7c5e4a62 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,14 @@ pub enum DrawMode { Inside, } +/// A saved Default Language as its tag: older preferences hold the language's name, and one the list +/// no longer has reads as the default. +fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + let tag = vectorcraft_doc::setup::char_language(&saved).ok().flatten(); + Ok(tag.or_else(|| vectorcraft_doc::setup::LANGUAGES.first().map(|(_, t, _)| *t)).unwrap_or_default().to_string()) +} + /// Application preferences (Edit → Preferences). Every field is reachable through `prefs.get` / /// `prefs.set {key, value}` (camelCase keys, validated against [`cmd::prefscmds::PREF_SPECS`]). #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -114,6 +122,9 @@ pub struct Prefs { pub show_slice_numbers: bool, pub slice_line_color: String, // Hyphenation + /// Default Language: the BCP 47 tag of the language new type takes when its document's language + /// is the default ([`vectorcraft_doc::setup::LANGUAGES`]). + #[serde(deserialize_with = "language_tag")] pub hyphenation_language: String, pub hyphenation_exceptions: String, /// Type › Options › Additional Fonts Folder: a folder (read with its subfolders) whose fonts @@ -404,7 +415,7 @@ impl Default for Prefs { snap_perpendicular: true, show_slice_numbers: true, slice_line_color: s("#ff3f3f"), - hyphenation_language: s("English: USA"), + hyphenation_language: s("en-US"), hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6b048e6fa3..41946c0ebd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -292,6 +292,27 @@ impl Session { true } + /// Move the document in tab `from` to tab `to` (a document tab dragged along the strip, + /// `document.move`); the documents between them shift by one. The current document stays the + /// current one, wherever it moves to, and its tool keeps its state: no document is switched to. + /// False, changing nothing, when either index is past the last document. + pub fn move_document(&mut self, from: usize, to: usize) -> bool { + let n = self.docs.len(); + if from >= n || to >= n { + return false; + } + if from == to { + return true; + } + let active = self.active().map(|d| d.uid); + let d = self.docs.remove(from); + self.docs.insert(to, d); + if let Some(uid) = active { + self.active = self.docs.iter().position(|d| d.uid == uid); + } + true + } + /// Commands with enablement (for menus, palette, MCP `list_commands`). pub fn commands(&self) -> Vec { command_specs().iter().map(|c| c.info(self)).collect() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a1fa3e0487..812a6282f2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -41,6 +41,7 @@ mod cut; mod dashalign; mod distort; mod docsetup; +mod document_move; mod draw2; mod dynamic_symbols; mod editcolors; @@ -108,6 +109,7 @@ mod paintproxy; mod panelcmds; mod paragraphs; mod params; +mod path_menu_enabled; mod pathops; mod pathtype; mod pattern; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index ada5fdd2f0..8d70237276 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -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, ¶ms).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"); +} diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 5db598a197..c22eb188b7 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -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 = 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] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c6bd07ecff..b4be82c2ec 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -830,6 +830,39 @@ fn shape_builder_drag_from_a_merged_shape_over_a_line_under_its_edge_makes_one_r assert!(left_half_gone(&s, h)); } +#[test] +fn shape_builder_removes_the_stretch_of_every_line_under_a_merged_edge() { + // Two lines along the same stretch, under the bottom edge of the merged top row: merging the + // row with the cell below takes the stretch between them from both lines. + for erase in [false, true] { + let mut s = session(); + let h1 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let h2 = line(&mut s, (100.0, 200.0), (300.0, 200.0)); + let v = line(&mut s, (200.0, 100.0), (200.0, 300.0)); + let sq = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + s.edit("t", |d, _| { + for id in [h1, h2, v, sq] { + d.node_mut(id).unwrap().appearance.set_fill(Paint::None); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [h1.0, h2.0, v.0, sq.0]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[150, 150], [250, 150]]})).unwrap(); + s.execute("shapeBuilder.merge", &json!({"points": [[250, 150], [150, 250]], "erase": erase})).unwrap(); + let d = &s.doc().unwrap().doc; + let left: Vec = d + .children(d.default_layer()) + .into_iter() + .flatten() + .filter(|n| !outline(n).0.is_closed()) + .filter_map(|n| n.geometric_bounds()) + .filter(|b| b.height() < 1e-6 && (b.y0 - 200.0).abs() < 1e-6 && b.x0 < 199.0) + .collect(); + assert!(left.is_empty(), "erase {erase}: {left:?}"); + } +} + #[test] fn shape_builder_alt_deletes_a_region_or_a_line_piece() { let mut s = session(); diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index e7ddbc7c08..79b336df0e 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -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"); +} diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index bcd590c2d4..40152af747 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -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] @@ -411,6 +419,27 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() { assert!(out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")), "{}", out["warnings"]); } +/// A linked image showing the missing-link placeholder draws uncolorized, so its colorize paint +/// doesn't flatten it in EPS or PDF 1.3 export. +#[test] +fn a_colorized_missing_link_placeholder_is_not_flattened() { + let mut s = session(); + let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + s.edit("Colorize", |d, _| { + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0)))); + Ok(()) + }) + .unwrap(); + let flattened = + |out: &serde_json::Value| out["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("transparency is flattened")); + let eps = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + assert!(!flattened(&eps), "{}", eps["warnings"]); + let pdf = s.execute("document.exportPdf", &json!({"compatibility": "1.3"})).unwrap(); + assert!(!flattened(&pdf), "{}", pdf["warnings"]); + assert_eq!(colorize(&s, id), Some(Paint::solid(Color::rgb8(255, 0, 0))), "the image keeps its paint"); +} + #[test] fn flattened_colorized_image_shows_the_art_under_white_pixels() { let mut s = session(); diff --git a/crates/engine/src/tests/compound_shape.rs b/crates/engine/src/tests/compound_shape.rs index 2de8a35b95..7455fbfa5a 100644 --- a/crates/engine/src/tests/compound_shape.rs +++ b/crates/engine/src/tests/compound_shape.rs @@ -664,3 +664,35 @@ fn expanded(s: &mut Session, id: NodeId) -> f64 { let made = run(s, "object.compoundShape.expand", json!({})); node_area(&node(s, NodeId(made["ids"][0].as_u64().unwrap()))) } + +/// Locking (or hiding) the layer of an isolated compound shape locks its members too: a click or +/// a marquee with the Selection tool selects none of them, as outside isolation mode (#5309). +#[test] +fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + for (prop, value) in [("locked", true), ("visible", false)] { + let (mut s, back, _front) = two_squares(); + let id = NodeId(run(&mut s, "object.compoundShape.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "object.isolate", json!({"id": id.0})); + let layer = s.doc().unwrap().doc.parent_of(id).unwrap(); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + }; + click(&mut s, 25.0, 50.0); + assert_eq!(selected(&s), vec![back], "isolated, a click selects a member"); + run(&mut s, "select.none", json!({})); + run(&mut s, "layer.setProps", json!({"id": layer.0, prop: value})); + click(&mut s, 25.0, 50.0); + assert!(selected(&s).is_empty(), "{prop}: the layer's art isn't selected by a click"); + for (k, x, y) in + [(PointerKind::Down, -10.0, -10.0), (PointerKind::Drag, 60.0, 60.0), (PointerKind::Drag, 120.0, 120.0), (PointerKind::Up, 120.0, 120.0)] + { + s.pointer(&PointerEvent::new(k, x, y), v).unwrap(); + } + assert!(selected(&s).is_empty(), "{prop}: nor by a marquee"); + } +} diff --git a/crates/engine/src/tests/document_move.rs b/crates/engine/src/tests/document_move.rs new file mode 100644 index 0000000000..f68c729081 --- /dev/null +++ b/crates/engine/src/tests/document_move.rs @@ -0,0 +1,133 @@ +//! `document.move` (#5663): a document tab dragged along the tab strip moves its document to +//! another place among the open documents, and the current document stays the current one. + +use serde_json::{Value, json}; + +use crate::*; + +/// A session with documents A, B, C and D, in that order, D current. +fn four() -> Session { + let mut s = Session::new(); + for name in ["A", "B", "C", "D"] { + s.execute("file.new", &json!({"name": name, "created": null})).unwrap(); + } + s +} + +fn order(s: &Session) -> String { + s.documents().iter().map(DocState::title).collect::>().join("") +} + +fn current(s: &Session) -> String { + s.active().map(DocState::title).unwrap_or_default() +} + +fn moved(s: &mut Session, p: Value) -> Value { + s.execute("document.move", &p).unwrap_or_else(|e| panic!("document.move {p}: {e}")) +} + +#[test] +fn a_document_moves_to_its_new_tab_and_the_others_shift() { + let mut s = four(); + assert_eq!(order(&s), "ABCD"); + assert_eq!(moved(&mut s, json!({"from": 0, "to": 2})), json!({"index": 2})); + assert_eq!(order(&s), "BCAD", "forward: the documents between shift left"); + assert_eq!(moved(&mut s, json!({"from": 3, "to": 0})), json!({"index": 0})); + assert_eq!(order(&s), "DBCA", "backward: the documents between shift right"); + assert_eq!(moved(&mut s, json!({"from": 1, "to": 1})), json!({"index": 1})); + assert_eq!(order(&s), "DBCA", "onto itself: nothing changes"); +} + +#[test] +fn the_current_document_stays_current_wherever_the_move_puts_it() { + let mut s = four(); + assert!(s.set_active(1)); + // The current document itself moves. + moved(&mut s, json!({"from": 1, "to": 3})); + assert_eq!((order(&s), current(&s)), ("ACDB".into(), "B".into())); + assert_eq!(s.active_index(), Some(3)); + // A document moves past the current one, which shifts by one. + moved(&mut s, json!({"from": 3, "to": 0})); + moved(&mut s, json!({"from": 3, "to": 0})); + assert_eq!((order(&s), current(&s)), ("DBAC".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); + // A move on one side of the current document leaves it where it is. + moved(&mut s, json!({"from": 2, "to": 3})); + assert_eq!((order(&s), current(&s)), ("DBCA".into(), "B".into())); + assert_eq!(s.active_index(), Some(1)); +} + +#[test] +fn without_from_the_current_document_moves() { + let mut s = four(); + assert!(s.set_active(2)); + moved(&mut s, json!({"to": 0})); + assert_eq!((order(&s), current(&s)), ("CABD".into(), "C".into())); +} + +#[test] +fn a_move_past_the_last_tab_ends_there_and_bad_indices_change_nothing() { + let mut s = four(); + assert_eq!(moved(&mut s, json!({"from": 0, "to": 99})), json!({"index": 3})); + assert_eq!(order(&s), "BCDA"); + assert_eq!(moved(&mut s, json!({"from": 0, "to": u64::MAX})), json!({"index": 3})); + assert_eq!(order(&s), "CDAB"); + for p in [ + json!({"from": 4, "to": 0}), + json!({"from": u64::MAX, "to": 0}), + json!({"from": 0}), + json!({"from": -1, "to": 0}), + json!({"from": 0, "to": "1"}), + ] { + assert!(s.execute("document.move", &p).is_err(), "{p} is refused"); + assert_eq!(order(&s), "CDAB", "{p} changes nothing"); + } + assert!(!s.move_document(0, 4)); + assert!(!s.move_document(4, 0)); + assert_eq!(order(&s), "CDAB"); +} + +#[test] +fn moving_needs_an_open_document_and_one_document_stays_put() { + let mut s = Session::new(); + assert!(s.execute("document.move", &json!({"to": 0})).is_err(), "no document open"); + s.execute("file.new", &json!({"name": "A", "created": null})).unwrap(); + assert_eq!(moved(&mut s, json!({"to": 5})), json!({"index": 0})); + assert_eq!((order(&s), current(&s)), ("A".into(), "A".into())); +} + +#[test] +fn a_move_keeps_the_tool_and_the_documents_edits() { + let mut s = four(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let resets = s.tool_resets; + let nodes = s.doc().unwrap().doc.node_count(); + let history = super::history(&s); + moved(&mut s, json!({"from": 3, "to": 0})); + assert_eq!(super::history(&s), history, "a move is no undo step, and it keeps Redo"); + assert_eq!(s.tool_resets, resets, "no document was switched to, so the tool is not reset"); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes); + assert!(s.doc().unwrap().is_dirty(), "the document keeps its unsaved edit"); +} + +/// A recording replays the move before the steps after it, so an `index` they name is the same +/// document as when they were recorded. +#[test] +fn a_journaled_move_replays_in_order() { + let mut s = four(); + for (id, p) in [ + ("document.move", json!({"from": 0, "to": 3})), + ("document.activate", json!({"index": 3})), + ("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!((order(&s), current(&s)), ("BCDA".into(), "A".into())); + let mut r = Session::new(); + for (id, p) in &s.journal { + r.execute(id, p).unwrap(); + } + assert_eq!((order(&r), current(&r)), ("BCDA".into(), "A".into())); + let counts = |s: &Session| s.documents().iter().map(|d| d.doc.node_count()).collect::>(); + assert_eq!(counts(&r), counts(&s), "the rectangle is in the same document after the replay"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 30b1c4a3f7..1af4ac40f0 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -386,10 +386,11 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } -/// With Keep selected off, the path a stroke draws or continues is not selected afterwards, the -/// rest of the selection stays, and the stroke is one undo step. +/// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too, +/// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is +/// deselected and the rest of the selection stays. The stroke is one undo step. #[test] -fn pencil_with_keep_selected_off_leaves_the_new_path_unselected() { +fn pencil_with_keep_selected_off_leaves_nothing_selected() { let mut s = session(); let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0); let selected = |s: &Session| s.doc().unwrap().selection.objects.clone(); @@ -401,7 +402,7 @@ fn pencil_with_keep_selected_off_leaves_the_new_path_unselected() { let off = s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false})).unwrap(); let off = NodeId(off["id"].as_u64().unwrap()); assert!(s.doc().unwrap().doc.node(off).is_some()); - assert_eq!(selected(&s), vec![r]); + assert!(selected(&s).is_empty(), "a new stroke with Keep selected off leaves nothing selected, the rectangle included"); assert_eq!(undo_steps(&s), undo + 1); // Continuing a selected open path deselects it and keeps the rest. let l = line(&mut s, 100.0, 300.0, 200.0, 300.0); @@ -1342,6 +1343,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 = 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(); @@ -2708,6 +2757,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::>()); + 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 @@ -3999,11 +4084,17 @@ fn pen_continue_at_a_first_anchor_in_a_compound_reverses_only_that_subpath() { /// The anchors of a closed, slightly wobbly blob drawn at `fidelity`: samples half a point apart, /// with a small tremor on top of the outline. fn blob_anchors(s: &mut Session, fidelity: f64) -> usize { + scaled_blob_anchors(s, fidelity, 1.0) +} + +/// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale` +/// times. +fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize { let pts: Vec<_> = (0..1200) .map(|i| { let a = i as f64 / 1200.0 * std::f64::consts::TAU; let r = 90.0 + 12.0 * (3.0 * a).sin() + 0.15 * (97.0 * a).sin(); - json!([400.0 + r * a.cos(), 300.0 + r * a.sin()]) + json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale]) }) .collect(); let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap(); @@ -4018,9 +4109,26 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() { assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}"); // Below the old floor of 0.05 the stroke keeps more of itself. assert!(counts[4] > counts[2], "{counts:?}"); - // Below 0.01 is read as 0.01. - assert_eq!(blob_anchors(&mut s, 0.001), counts[4]); - assert_eq!(blob_anchors(&mut s, 0.0), counts[4]); + // Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the + // floor (#5729). + let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0; + let at_floor = blob_anchors(&mut s, floor); + assert!(at_floor >= counts[4], "{counts:?}"); + assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor); + assert_eq!(blob_anchors(&mut s, 0.0), at_floor); +} + +/// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as +/// many anchors, down to the lowest Fidelity at the highest zoom. +#[test] +fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() { + let mut s = session(); + for fidelity in [1.5, 0.1, 0.01] { + let want = blob_anchors(&mut s, fidelity); + for zoom in [4.0, 64.0, 640.0] { + assert_eq!(scaled_blob_anchors(&mut s, fidelity / zoom, 1.0 / zoom), want, "{fidelity} at {zoom}x"); + } + } } /// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never diff --git a/crates/engine/src/tests/effectedit.rs b/crates/engine/src/tests/effectedit.rs index f660928ea6..2d10c3f5d9 100644 --- a/crates/engine/src/tests/effectedit.rs +++ b/crates/engine/src/tests/effectedit.rs @@ -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", ¶ms).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() { diff --git a/crates/engine/src/tests/intertwine.rs b/crates/engine/src/tests/intertwine.rs index 6895d74a07..ecb9742a30 100644 --- a/crates/engine/src/tests/intertwine.rs +++ b/crates/engine/src/tests/intertwine.rs @@ -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(); diff --git a/crates/engine/src/tests/legacy_ai.rs b/crates/engine/src/tests/legacy_ai.rs index b9f67f51aa..c4722c9c16 100644 --- a/crates/engine/src/tests/legacy_ai.rs +++ b/crates/engine/src/tests/legacy_ai.rs @@ -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) { + 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)>, Option); + +/// The colorized image of each image node of `d`, with its pixels' coverage. +fn colorized(d: &vectorcraft_doc::Document) -> Vec { + 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 = 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 diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index a9bafc540b..d232b26767 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -111,6 +111,69 @@ fn colours_come_from_the_selection_and_paint_it() { assert!(s.execute("library.use", &json!({"library": lib, "kind": "fillColor", "item": "#nope"})).is_err()); } +/// The spot swatch of object `id`'s fill: its name, whether it is spot, the paint's tint. +fn spot_of(s: &Session, id: &Value) -> (String, bool, f32) { + match paint_of(s, id, false) { + vectorcraft_color::Paint::Solid { swatch: Some(name), tint, .. } => { + let spot = s.doc().unwrap().doc.swatch(&name).is_some_and(|w| w.spot); + (name, spot, tint) + } + other => panic!("not linked to a swatch: {other:?}"), + } +} + +/// A spot colour added to a library keeps its ink, kept in the library's file: used in a new +/// document (or after its own was closed) it adds the spot swatch of that name and colour and +/// links the paint to it, at its tint; one the document has already is reused (#5812). +#[test] +fn a_spot_colour_stays_spot_in_another_document() { + let dir = std::env::temp_dir().join(format!("vc-libraries-spot-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let folder = dir.to_string_lossy().to_string(); + let mut s = session(); + s.libraries.set_dir(Some(folder.clone())); + let lib = run(&mut s, "library.create", json!({"name": "Inks"}))["id"].as_str().unwrap().to_string(); + let ink = vectorcraft_color::Color::cmyk(0.0, 1.0, 0.0, 0.0); + run(&mut s, "swatch.new", json!({"name": "Kiss-cut", "color": ink, "spot": true})); + let a = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Kiss-cut", "ids": [a]})); + run(&mut s, "select.set", json!({"ids": [a]})); + assert_eq!(run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor"}))["name"], "Kiss-cut"); + // A swatch dropped on the panel: its colour with its spot swatch's name and tint. + let r = run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor", "color": ink, "swatch": "Kiss-cut", "tint": 40, "name": "Light"})); + assert_eq!(r["existing"], false, "a tint is another colour"); + // The same colour as a process colour is another item. + run(&mut s, "paint.setFill", json!({"color": ink, "ids": [a]})); + assert_eq!(run(&mut s, "library.add", json!({"library": lib, "kind": "fillColor"}))["existing"], false); + run(&mut s, "file.close", json!({})); + + // Another session reads the library's file into a new document. + let mut t = session(); + t.libraries.set_dir(Some(folder)); + let got = run(&mut t, "library.get", json!({"library": "Inks"})); + assert_eq!(got["colors"][0]["spot"], "Kiss-cut"); + assert_eq!(got["colors"][2]["spot"], Value::Null); + let b = run(&mut t, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone(); + run(&mut t, "select.set", json!({"ids": [b]})); + run(&mut t, "library.use", json!({"library": "Inks", "kind": "fillColor", "item": "Kiss-cut"})); + assert_eq!(spot_of(&t, &b), ("Kiss-cut".to_string(), true, 1.0)); + let doc = &t.doc().unwrap().doc; + assert_eq!(doc.swatch("Kiss-cut").unwrap().paint.color(), Some(ink), "the ink keeps its values"); + assert!(doc.spot_names().contains(&"Kiss-cut".to_string())); + // Its tint links to the same swatch: none is added again. + let swatches = doc.swatches.len(); + run(&mut t, "library.use", json!({"library": "Inks", "kind": "fillColor", "item": "Light"})); + let (name, spot, tint) = spot_of(&t, &b); + assert_eq!((name.as_str(), spot), ("Kiss-cut", true)); + assert!((tint - 0.4).abs() < 1e-4, "{tint}"); + assert_eq!(t.doc().unwrap().doc.swatches.len(), swatches); + // One undo step takes back the new swatch along with the paint. + run(&mut t, "edit.undo", json!({})); + run(&mut t, "edit.undo", json!({})); + assert!(t.doc().unwrap().doc.swatch("Kiss-cut").is_none()); + let _ = std::fs::remove_dir_all(&dir); +} + /// The fill (`stroke`: stroke) paint of object `id`. fn paint_of(s: &Session, id: &Value, stroke: bool) -> vectorcraft_color::Paint { let n = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().clone(); diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index eb4712cfce..951a9ec31a 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -192,6 +192,27 @@ fn spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); } +#[test] +fn spot_stops_with_process_plates_export_both_in_device_n_shadings() { + // #3235: Ink 0 % to 100 % over a constant 30 % cyan plate, as a DeviceN gradient imported + // from a PDF has it. + let (mut s, id) = setup(); + let cyan = json!({"c": 0.3, "m": 0, "y": 0, "k": 0}); + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "color": cyan}, {"offset": 1, "swatch": "Ink", "plates": [0.3, 0, 0, 0]}]})); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/DeviceN[/Cyan/Ink]/DeviceCMYK"), "a DeviceN shading of Cyan and Ink"); + assert!(pdf.contains("/C0[0.3 0]/C1[0.3 1]"), "the cyan plate runs under the whole gradient"); + assert!(!warnings.iter().any(|w| w.contains("spot")), "{warnings:?}"); + let stops = gradient(&s, id).gradient.stops; + assert_eq!((stops[1].swatch.as_deref(), stops[1].plates), (Some("Ink"), Some([0.3, 0.0, 0.0, 0.0])), "{stops:?}"); + // The plates are part of the stop's params, so moving the vector keeps them. + run(&mut s, "paint.editGradient", json!({"angle": 45})); + assert_eq!(gradient(&s, id).gradient.stops[1].plates, Some([0.3, 0.0, 0.0, 0.0])); + // An unlinked stop has none. + run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "color": cyan}, {"offset": 1, "color": "#ffffff", "plates": [0.3, 0, 0, 0]}]})); + assert_eq!(gradient(&s, id).gradient.stops[1].plates, None); +} + #[test] fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() { let (mut s, _) = setup(); diff --git a/crates/engine/src/tests/linkfiles.rs b/crates/engine/src/tests/linkfiles.rs index 5990b35234..695ea41419 100644 --- a/crates/engine/src/tests/linkfiles.rs +++ b/crates/engine/src/tests/linkfiles.rs @@ -123,6 +123,67 @@ fn files_found_are_ranked_by_what_the_link_saved() { assert_eq!(photo_row["path"], json!(root.join("orig/photo.png"))); } +/// A link saved as a classic Mac OS path (`Disk:Folder:file`) is looked for by its file name, and +/// the files found are ranked by the folder names they share with that path. +#[test] +fn a_classic_mac_path_is_found_by_its_name_and_folders() { + let root = folder("classic"); + let mut s = session_for(&root); + let photo = png(50, 30, BLUE); + write(&root.join("orig/photo.png"), &photo); + let id = placed(&mut s, &root.join("orig/photo.png")); + s.edit("classic path", |d, _| { + if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind { + im.link.as_mut().unwrap().path = "Old Disk:Art:Images:photo.png".into(); + } + Ok(()) + }) + .unwrap(); + std::fs::remove_dir_all(root.join("orig")).unwrap(); + // Other files of the name (a search ends once it finds the same file). + let search = root.join("search"); + let mut changed = photo.clone(); + *changed.last_mut().unwrap() ^= 1; + write(&search.join("a/photo.png"), &changed); + write(&search.join("z/Art/Images/photo.png"), &changed); + s.execute("links.findFiles", &json!({"folder": search})).unwrap(); + let r = finished(&mut s); + assert_eq!(r["state"].as_str(), Some("done"), "{r}"); + let files = [("search/z/Art/Images/photo.png", "name", false), ("search/a/photo.png", "name", false)]; + assert_eq!(found(&r, "photo.png", &root), files.map(|(p, k, c)| (p.to_string(), k.to_string(), c))); +} + +/// The folders a saved path shares with a file found are counted after its parent components are +/// resolved: `Art::` in a classic Mac OS path and `Art/..` in any other path go back to `Projects`. +#[test] +fn parent_components_in_a_saved_path_are_resolved_before_ranking() { + for (tag, saved) in [("classic-up", "Old Disk:Projects:Art::photo.png"), ("slash-up", "/old/Projects/Art/../photo.png")] { + let root = folder(tag); + let mut s = session_for(&root); + let photo = png(50, 30, BLUE); + write(&root.join("orig/photo.png"), &photo); + let id = placed(&mut s, &root.join("orig/photo.png")); + s.edit("saved path", |d, _| { + if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind { + im.link.as_mut().unwrap().path = saved.into(); + } + Ok(()) + }) + .unwrap(); + std::fs::remove_dir_all(root.join("orig")).unwrap(); + let search = root.join("search"); + let mut changed = photo.clone(); + *changed.last_mut().unwrap() ^= 1; + write(&search.join("Art/photo.png"), &changed); + write(&search.join("Projects/photo.png"), &changed); + s.execute("links.findFiles", &json!({"folder": search})).unwrap(); + let r = finished(&mut s); + assert_eq!(r["state"].as_str(), Some("done"), "{saved}: {r}"); + let files = [("search/Projects/photo.png", "name", false), ("search/Art/photo.png", "name", false)]; + assert_eq!(found(&r, "photo.png", &root), files.map(|(p, k, c)| (p.to_string(), k.to_string(), c)), "{saved}"); + } +} + /// Without `ids`, a search looks for the files that can't be found; with them, for those objects' /// files, whatever their status. #[test] diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 41bc6b8fb8..7cdf43ad7d 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -283,6 +283,44 @@ fn a_missing_link_renders_its_preview_and_relinks() { assert!(s.execute("links.relink", &json!({"ids": [id.0]})).is_err(), "path or folder"); } +/// A link stored as a classic Mac OS path (`Disk:Folder:file`, as older `.ai` files keep them) is +/// named by its last component: the Links panel shows that name and its folder, Relink to Folder +/// looks for that name, and the document's own folder is searched for it. The stored path is kept. +#[test] +fn a_classic_mac_path_is_found_by_its_file_name() { + const CLASSIC: &str = "Macintosh HD:Images:photo.png"; + let dir = Folder::new("classic-mac"); + let pic = dir.file("art/photo.png"); + write(&pic, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + saved_image(&mut v)["link"] = json!({ "path": CLASSIC }); + let doc_path = dir.file("poster.vectorcraft"); + write(&doc_path, &serde_json::to_vec(&v).unwrap()); + let r = open(&mut s, &doc_path); + let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + assert_eq!(r["missingLinks"], json!([{"name": "photo.png", "path": CLASSIC, "ids": [id.0]}])); + let i = s.execute("links.info", &json!({"id": id.0})).unwrap(); + assert_eq!( + (i["fileName"].as_str(), i["location"].as_str(), i["path"].as_str()), + (Some("photo.png"), Some("Macintosh HD:Images"), Some(CLASSIC)), + "{i}" + ); + // Relink to Folder: the file of the link's name there. + let r = s.execute("links.relink", &json!({"ids": [id.0], "folder": dir.file("found")})).unwrap(); + assert_eq!(r, json!({"relinked": [], "notFound": ["photo.png"]})); + write(&dir.file("found/photo.png"), &png(600, 300, BLUE)); + let r = s.execute("links.relink", &json!({"ids": [id.0], "folder": dir.file("found")})).unwrap(); + assert_eq!(r, json!({"relinked": [id.0], "notFound": []})); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + // The document's folder: the file of the link's name beside the document. + write(&dir.file("photo.png"), &png(600, 300, RED)); + let r = open(&mut s, &doc_path); + assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}"); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + /// A `w`×`h` PNG of noise cut to half its length: its header reads, its pixels don't. pub(crate) fn cut_png(w: u32, h: u32) -> Vec { let img = image::RgbImage::from_fn(w, h, |x, y| { diff --git a/crates/engine/src/tests/maskview.rs b/crates/engine/src/tests/maskview.rs index e222a136d2..9809d09e70 100644 --- a/crates/engine/src/tests/maskview.rs +++ b/crates/engine/src/tests/maskview.rs @@ -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", ¶ms).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})); +} diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 450baabc11..ad862376cf 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -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", ¶ms).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", ¶ms).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] diff --git a/crates/engine/src/tests/nativefile.rs b/crates/engine/src/tests/nativefile.rs index 5b9973e563..e3a5588b7d 100644 --- a/crates/engine/src/tests/nativefile.rs +++ b/crates/engine/src/tests/nativefile.rs @@ -188,7 +188,7 @@ fn newer_keys_and_legacy_profiles_survive_open_and_save() { /// A version 1 document saved before VectorCraft 0.21.0 turned its Twist effects counterclockwise /// for a positive angle. It opens with the angles negated, so its art turns as it did; saved -/// again it is a version 2 document, and saved for an older file version it is version 1 again. +/// again it is a document of the current version, and saved for an older file version it is version 1 again. #[test] fn a_version_1_documents_twist_turns_as_it_was_saved() { use vectorcraft_doc::{Appearance, Document, Effect, Node}; @@ -212,7 +212,7 @@ fn a_version_1_documents_twist_turns_as_it_was_saved() { let p = turned.subpaths[0].anchors[0].p; assert!(p.y < 49.5, "{p:?}"); let again = json_of(&saved(&mut s, json!({}))); - assert_eq!(again["document"]["version"], 2); + assert_eq!(again["document"]["version"], vectorcraft_doc::FORMAT_VERSION); assert!(again.to_string().contains(r#""angle":-45.0"#), "{again}"); // Saved for an older file version, it is version 1 with its angle as 0.20.0 saved it. let older = json_of(&saved(&mut s, json!({"version": 3}))); diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 6bc5eb48bc..0f41a5b9d1 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -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", ¶ms).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(); diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index a9e832bb36..b64736b973 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -414,3 +414,258 @@ fn a_group_shows_its_contents_in_the_proxies() { s.execute("select.none", &json!({})).unwrap(); assert_eq!(s.proxy_paints().0, s.paint.fill); } + +/// The top fill and top stroke of object `id`. +fn paints(s: &Session, id: NodeId) -> (Paint, Paint, f64) { + let n = node(s, id); + (n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map_or(0.0, |st| st.width)) +} + +/// Apply Fill to Stroke gives each selected object a stroke of its own fill, not the first +/// object's; Apply Stroke to Fill does the other way (#5530). A stroke that had no paint and no +/// width gets the 1 pt Swap Fill and Stroke gives it, and the paint copied from stays. +#[test] +fn each_object_copies_its_own_paint_onto_the_other() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + for (id, hex) in [(a, "#ff0000"), (b, "#0080ff")] { + s.execute("paint.setFill", &json!({"ids": [id.0], "color": hex})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("object.setStrokeWidth", &json!({"ids": [id.0], "width": 0})).ok(); + } + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let r = s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(r["objects"], 2); + for (id, hex) in [(a, "#ff0000"), (b, "#0080ff")] { + let (fill, stroke, width) = paints(&s, id); + assert_eq!(fill.color().unwrap().to_hex(), hex, "the fill stays"); + assert_eq!(stroke, fill, "the stroke is the object's own fill"); + assert!(width > 0.0, "and shows: {width}"); + } + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#00ff00"})).unwrap(); + s.execute("addon.color.strokeToFill", &json!({"ids": [a.0]})).unwrap(); + let (fill, stroke, _) = paints(&s, a); + assert_eq!((fill.color().unwrap().to_hex(), stroke.color().unwrap().to_hex()), ("#00ff00".into(), "#00ff00".into())); + assert_eq!(paints(&s, b).0.color().unwrap().to_hex(), "#0080ff", "an object not aimed at is left alone"); +} + +/// A global swatch at a tint stays linked at that tint, and a gradient keeps its stops and +/// placement: the paint is copied as it is. +#[test] +fn a_linked_swatch_and_a_gradient_copy_as_they_are() { + let mut s = session(); + let a = rect(&mut s); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#c82828", "global": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap(); + let (fill, stroke, _) = paints(&s, a); + assert!(matches!(&stroke, Paint::Solid { swatch: Some(name), .. } if name == "Ink"), "{stroke:?}"); + assert_eq!(stroke, fill); + let g = json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}], "angle": 30}}); + let mut q = g.clone(); + q["ids"] = json!([a.0]); + s.execute("paint.setFill", &q).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap(); + let (fill, stroke, _) = paints(&s, a); + assert!(matches!(stroke, Paint::Gradient { .. }), "{stroke:?}"); + assert_eq!(stroke, fill, "the same stops and placement"); +} + +/// None copies as None, as Swap moves it; `skipNone` leaves an object whose source is None alone. +#[test] +fn none_copies_unless_skipped() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#123456"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#ff8000"})).unwrap(); + let r = s.execute("addon.color.fillToStroke", &json!({"ids": [a.0, b.0], "skipNone": true})).unwrap(); + assert_eq!(r["objects"], 1, "only the object with a fill changed"); + assert_eq!(paints(&s, a).1.color().unwrap().to_hex(), "#123456", "skipped: its stroke stays"); + assert_eq!(paints(&s, b).1.color().unwrap().to_hex(), "#ff8000"); + s.execute("addon.color.fillToStroke", &json!({"ids": [a.0]})).unwrap(); + assert!(paints(&s, a).1.is_none(), "without skipNone, no fill gives no stroke"); +} + +/// The objects inside a group each copy their own paint, as for Swap Fill and Stroke. +#[test] +fn a_groups_members_each_copy_their_own() { + let mut s = session(); + let (a, b) = (rect(&mut s), rect(&mut s)); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(paints(&s, a).1.color().unwrap().to_hex(), "#ff0000"); + assert_eq!(paints(&s, b).1.color().unwrap().to_hex(), "#00ff00"); +} + +/// Type: each run's stroke takes its own fill, so multi-colour text keeps its colours. +#[test] +fn each_text_run_copies_its_own_fill() { + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#aa0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [id.0]})).unwrap(); + let NodeKind::Text(t) = &node(&s, id).kind else { panic!("not text") }; + for r in &t.runs { + assert_eq!(r.style.stroke, r.style.fill, "{:?}", r.text); + assert!(r.style.stroke_width > 0.0, "a painted stroke is visible"); + } +} + +/// One undo step each; when nothing changes, none, and the document stays unmodified. Bad +/// parameters change nothing, not even the defaults. +#[test] +fn one_undo_step_none_when_nothing_changes_and_bad_params_change_nothing() { + let mut s = session(); + let id = rect(&mut s); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap(); + select_with_a_step_to_redo(&mut s, &[id]); + let before = history(&s); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + s.execute("addon.color.strokeToFill", &json!({})).unwrap(); + assert_eq!(history(&s), before, "the paints were already the same"); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap(); + let before = history(&s); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(history(&s), (before.0 + 1, 0, true), "one step"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Apply Fill to Stroke")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paints(&s, id).1.color().unwrap().to_hex(), "#0000ff"); + let defaults = (s.paint.fill.clone(), s.paint.stroke.clone()); + for (cmd, p) in [("addon.color.fillToStroke", json!({"ids": "not an array"})), ("addon.color.strokeToFill", json!({"skipNone": "yes"}))] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), defaults, "the defaults are as they were"); +} + +/// With nothing selected the defaults for new art change the same way: the default stroke takes +/// the default fill, with the weight Swap gives a stroke that had none. +#[test] +fn with_nothing_selected_the_defaults_take_it() { + let mut s = session(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let r = s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + assert_eq!(r["objects"], 0); + assert_eq!(s.paint.stroke, s.paint.fill); + assert!(s.paint.stroke_width > 0.0); + s.execute("paint.setStroke", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("addon.color.strokeToFill", &json!({})).unwrap(); + assert_eq!(s.paint.fill.color().unwrap().to_hex(), "#ff00ff"); +} + +/// Copying None onto an item the object doesn't have adds nothing: with no fill and no stroke +/// item at all, neither command records an undo step or touches the object. +#[test] +fn copying_none_onto_a_missing_item_changes_nothing() { + let mut s = session(); + let id = rect(&mut s); + s.edit("No paint items", |d, _| { + d.node_mut(id).unwrap().appearance.items.clear(); + Ok(()) + }) + .unwrap(); + assert_eq!((paints(&s, id).0, paints(&s, id).1), (Paint::None, Paint::None)); + select_with_a_step_to_redo(&mut s, &[id]); + let (before, art) = (history(&s), node(&s, id)); + for cmd in ["addon.color.fillToStroke", "addon.color.strokeToFill"] { + assert_eq!(s.execute(cmd, &json!({})).unwrap()["objects"], 0, "{cmd}"); + assert_eq!(history(&s), before, "{cmd}: no undo step"); + assert_eq!(node(&s, id), art, "{cmd}: no item added"); + } +} + +/// A graph's series and its labels keep the copied paint when the graph is drawn again: the +/// graph takes it in the same undo step, as it does from paint.setFill. +#[test] +fn a_graph_series_and_its_labels_keep_the_copied_paint_when_drawn_again() { + let mut s = session(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let g = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let series = |s: &Session| node(s, g).children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + let label = |s: &Session| { + let axes = node(s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + axes.children().unwrap().iter().find(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == "4")).unwrap().clone() + }; + let sid = series(&s).id; + s.execute("paint.setFill", &json!({"ids": [sid.0], "color": "#12ab34"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [sid.0], "none": true})).unwrap(); + let lid = label(&s).id; + s.execute("paint.setFill", &json!({"ids": [lid.0], "color": "#e8573f"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("addon.color.fillToStroke", &json!({"ids": [sid.0, lid.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one step"); + let kept = s.doc().unwrap().doc.node(g).unwrap().extras().graph.as_deref().unwrap().clone(); + assert_eq!(kept.series_paints[0].stroke.as_ref().and_then(Paint::color).map(|c| c.to_hex()), Some("#12ab34".into())); + assert_eq!(kept.label_styles.values.as_ref().and_then(|st| st.stroke.color()).map(|c| c.to_hex()), Some("#e8573f".into())); + s.execute("graph.setData", &json!({"id": g.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + let marks = series(&s).children().unwrap().to_vec(); + let bars: Vec<_> = marks.iter().filter(|m| matches!(m.kind, NodeKind::Path { .. })).collect(); + assert!(!bars.is_empty()); + for m in bars { + assert_eq!(m.appearance.stroke_paint().color().map(|c| c.to_hex()), Some("#12ab34".into()), "a redrawn mark keeps the stroke"); + } + let redrawn = node(&s, g).children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + let text = redrawn.children().unwrap().iter().find_map(|c| if let NodeKind::Text(t) = &c.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!(text.runs[0].style.stroke.color().map(|c| c.to_hex()), Some("#e8573f".into()), "a redrawn value label keeps the stroke"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let back = s.doc().unwrap().doc.node(g).unwrap().extras().graph.as_deref().unwrap().clone(); + assert!( + back.series_paints[0].stroke.as_ref().is_none_or(|p| p.is_none()), + "undo takes the graph's stroke back: {:?}", + back.series_paints[0].stroke + ); +} + +/// A series drawn with a marker design: its own marks copy their paint, but the design's art +/// keeps the design's paint, as paint.setFill leaves it (painting it would last only until the +/// graph is drawn again). +#[test] +fn a_marker_designs_art_in_a_series_keeps_its_paint() { + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [r], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [r], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Square"})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let g = NodeId( + s.execute("graph.create", &json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Square"})).unwrap(); + let series = node(&s, g).children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + // The design's paths sit in groups inside the series; its own marks are its direct children. + let design_strokes = |s: &Session| { + let grp = node(s, series.id); + let mut out = vec![]; + for c in grp.children().unwrap() { + if !matches!(c.kind, NodeKind::Path { .. }) { + c.walk(&mut |n| { + if let NodeKind::Path { .. } = n.kind { + out.push(n.appearance.stroke_paint()); + } + }); + } + } + out + }; + let before = design_strokes(&s); + assert!(!before.is_empty(), "the series draws the design"); + s.execute("addon.color.fillToStroke", &json!({"ids": [series.id.0]})).unwrap(); + assert_eq!(design_strokes(&s), before, "the design's art keeps its paint"); +} diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index e989597ae5..2eba6c81ae 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -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`?" diff --git a/crates/engine/src/tests/path_menu_enabled.rs b/crates/engine/src/tests/path_menu_enabled.rs new file mode 100644 index 0000000000..2b9eb44aae --- /dev/null +++ b/crates/engine/src/tests/path_menu_enabled.rs @@ -0,0 +1,35 @@ +//! Object → Path items that work on paths are disabled while only non-path objects are selected. + +use serde_json::json; + +use crate::*; + +const PATH_ITEMS: [&str; 9] = [ + "path.reverse", + "path.join", + "path.average", + "path.averageJoin", + "object.path.simplify", + "object.path.smooth", + "object.path.addAnchorPoints", + "object.path.divideObjectsBelow", + "object.path.splitIntoGrid", +]; + +fn enabled(s: &Session, id: &str) -> bool { + command_specs().iter().find(|c| c.id == id).is_some_and(|c| (c.enabled)(s).is_ok()) +} + +#[test] +fn path_items_need_a_path_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); + for id in PATH_ITEMS { + assert!(!enabled(&s, id), "{id} enabled for text"); + } + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + for id in PATH_ITEMS { + assert!(enabled(&s, id), "{id} disabled for a path"); + } +} diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 2eaeeb594c..a5bd60490b 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -459,6 +459,26 @@ fn outline_stroke_of_line() { assert!((area_of(&s, r[0]) - 1000.0).abs() < 1.0); } +#[test] +fn outline_stroke_preserves_a_zero_area_fill_without_retaining_a_live_stroke() { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 60, "y2": 90})).unwrap(); + s.execute("paint.setFill", &json!({"color":"#ffffff"})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let n = node(&s, result[0]); + let children = n.children().expect("the original fill and the outlined stroke"); + assert_eq!(children.len(), 2); + assert!(children.iter().all(|n| n.appearance.stroke().is_none())); + assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)), "an invisible fill is not a live stroke"); + assert!(n.appearance.stroke().is_none()); + assert!(children.iter().any(|n| n.appearance.fill_paint() == Paint::solid(Color::BLACK))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(node(&s, result[0]).appearance.stroke().is_none()); +} + #[test] fn outline_stroke_with_fill_makes_group() { let mut s = session(); @@ -1076,6 +1096,207 @@ fn trim_merge_and_crop_remove_strokes() { } } +#[test] +fn outline_stroke_preserves_tiny_and_signed_area_canceling_closed_fills() { + for points in [vec![[0.0, 0.0], [100.0, 100.0], [0.0, 100.0], [100.0, 0.0]], vec![[0.0, 0.0], [1e-8, 0.0], [1e-8, 1e-8]]] { + let mut s = session(); + let anchors: Vec = points.into_iter().map(|[x, y]| json!({"x":x,"y":y})).collect(); + s.execute("path.create", &json!({"anchors":anchors,"closed":true})).unwrap(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let n = node(&s, result[0]); + let retains_fill = n.children().is_some_and(|ch| ch.iter().any(|c| c.appearance.fill_paint() == Paint::solid(Color::WHITE))) + || n.appearance.fill_paint() == Paint::solid(Color::WHITE); + assert!(retains_fill, "a real fill survives independently of its signed area or scale"); + } +} + +#[test] +fn outline_stroke_preserves_bent_open_fill_and_history() { + let mut s = session(); + s.execute("path.create", &json!({"anchors":[{"x":0,"y":0},{"x":60,"y":0},{"x":75,"y":-15},{"x":110,"y":-15}],"closed":false})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let n = node(&s, result[0]); + let children = n.children().expect("original fill beside the outlined stroke"); + assert_eq!(children.len(), 2); + let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap(); + assert!(!fill.path_data().unwrap().subpaths[0].closed); + assert!(children.iter().all(|n| n.appearance.stroke().is_none())); + let after = s.doc().unwrap().doc.layers.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, after); +} + +#[test] +fn outline_stroke_mixed_contours_preserve_all_fill() { + use vectorcraft_geom::{Anchor, Point, SubPath}; + let mut s = session(); + let id = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + s.edit("mixed contours", |d, _| { + let n = d.node_mut(id).unwrap(); + if let NodeKind::Path { path, .. } = &mut n.kind { + path.subpaths.push(SubPath::new( + vec![Anchor::corner(Point::new(50.0, 0.0)), Anchor::corner(Point::new(80.0, 0.0)), Anchor::corner(Point::new(80.0, 20.0))], + false, + )); + } + Ok(()) + }) + .unwrap(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap()); + let outlined = node(&s, result[0]); + let children = outlined.children().unwrap(); + let fill = children.iter().find(|n| n.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap(); + let NodeKind::Path { path, .. } = &fill.kind else { panic!("fill is a path") }; + assert_eq!(path.subpaths.len(), 2); + assert!(path.subpaths[0].closed); + assert!(!path.subpaths[1].closed); +} + +#[test] +fn outline_stroke_keeps_closed_compound_members_editable() { + check_outlined_compound_members(false); +} + +#[test] +fn outline_stroke_keeps_open_compound_contours_and_members() { + check_outlined_compound_members(true); +} + +fn check_outlined_compound_members(mixed: bool) { + use vectorcraft_geom::{Anchor, Point, SubPath}; + let mut s = session(); + let outer = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + let inner = rect(&mut s, 35.0, 35.0, 30.0, 30.0); + let mut members = vec![outer.0, inner.0]; + if mixed { + let open = s.execute("path.create", &json!({"anchors":[{"x":140,"y":10},{"x":170,"y":30},{"x":140,"y":50}]})).unwrap(); + members.push(open["id"].as_u64().unwrap()); + s.edit("Mixed compound member", |d, _| { + let NodeKind::Path { path, .. } = &mut d.node_mut(inner).unwrap().kind else { panic!("path") }; + path.subpaths.push(SubPath::new(vec![Anchor::corner(Point::new(45.0, 80.0)), Anchor::corner(Point::new(70.0, 90.0))], false)); + Ok(()) + }) + .unwrap(); + } + s.execute("select.set", &json!({"ids":members})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Compound member names and rule", |d, _| { + d.node_mut(outer).unwrap().name = Some("outer-member".into()); + d.node_mut(inner).unwrap().name = Some("inner-member".into()); + let NodeKind::Compound { rule, .. } = &mut d.node_mut(compound).unwrap().kind else { panic!("compound") }; + *rule = FillRule::EvenOdd; + Ok(()) + }) + .unwrap(); + let original = node(&s, compound); + let expected: Vec<_> = original + .children() + .unwrap() + .iter() + .map(|child| { + let path = child.path_data().unwrap().clone(); + (child.name.clone(), path) + }) + .collect(); + let before = s.doc().unwrap().doc.layers.clone(); + let result = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0]; + let group = node(&s, result); + let fill = group.children().unwrap().iter().find(|child| child.appearance.fill_paint() == Paint::solid(Color::WHITE)).unwrap(); + let NodeKind::Compound { children, rule } = &fill.kind else { panic!("closed fill must retain editable compound members") }; + assert_eq!(*rule, FillRule::EvenOdd); + assert_eq!(children.len(), if mixed { 3 } else { 2 }); + for (child, (name, path)) in children.iter().zip(expected) { + assert_eq!(child.name, name); + assert_eq!(child.path_data().unwrap(), &path); + assert_ne!(child.id, outer); + assert_ne!(child.id, inner); + } + let member = children[0].id; + let sibling = children[1].id; + let member_bounds = children[0].geometric_bounds().unwrap(); + let sibling_before = children[1].clone(); + let after = s.doc().unwrap().doc.layers.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, after); + // Group Selection can still address one retained child without moving its sibling. + s.execute("select.set", &json!({"ids":[member.0]})).unwrap(); + s.execute("object.move", &json!({"dx":7,"dy":3})).unwrap(); + assert!(close( + node(&s, member).geometric_bounds().unwrap(), + Rect::new(member_bounds.x0 + 7.0, member_bounds.y0 + 3.0, member_bounds.x1 + 7.0, member_bounds.y1 + 3.0), + 1e-6 + )); + assert_eq!(node(&s, sibling), *sibling_before); +} + +/// Exercise the real Group Selection pointer route, not select.set by id. +#[test] +fn outline_fill_and_stroke_move_independently_with_group_selection() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + for closed in [true, false] { + for move_fill in [false, true] { + for click_first in [false, true] { + let mut s = session(); + s.execute( + "path.create", + &json!({"anchors":[{"x":100,"y":100},{"x":200,"y":100},{"x":200,"y":200},{"x":100,"y":200}],"closed":closed}), + ) + .unwrap(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color":"#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight":10})).unwrap(); + let root = ids(&s.execute("object.path.outlineStroke", &json!({})).unwrap())[0]; + let group = node(&s, root); + let children = group.children().expect("fill and outlined stroke stay separate"); + assert_eq!(children.len(), 2); + let fill = children.iter().find(|c| c.appearance.fill_paint().color().is_some_and(|c| c.to_hex() == "#ff0000")).unwrap().id; + let stroke = children.iter().find(|c| c.id != fill).unwrap().id; + group.walk(&mut |n| assert!(n.appearance.stroke().is_none(), "no retained live stroke")); + let moved = if move_fill { fill } else { stroke }; + let other = if move_fill { stroke } else { fill }; + let other_before = node(&s, other); + let bounds_before = bounds(&s, moved); + let layers_before_move = s.doc().unwrap().doc.layers.clone(); + let v = ViewInfo { smart_guides: false, snap_to_point: false, ..ViewInfo::default() }; + s.select_tool("groupSelection", v).unwrap(); + // Start empty, as clicking the art with Group Selection does after deselection. + s.execute("select.none", &json!({})).unwrap(); + let (x, y) = if move_fill { (150.0, 150.0) } else { (150.0, 100.0) }; + let compound_stroke = !move_fill && matches!(node(&s, stroke).kind, NodeKind::Compound { .. }); + for _ in 0..if compound_stroke { + 2 + } else if click_first { + 1 + } else { + 0 + } { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap(); + } + for (kind, x, y) in [(PointerKind::Down, x, y), (PointerKind::Drag, x + 30.0, y + 15.0), (PointerKind::Up, x + 30.0, y + 15.0)] { + s.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } + assert_eq!(node(&s, other), other_before, "sibling unchanged: closed={closed}, fill={move_fill}, click_first={click_first}"); + let b = bounds(&s, moved); + assert!( + close(b, Rect::new(bounds_before.x0 + 30.0, bounds_before.y0 + 15.0, bounds_before.x1 + 30.0, bounds_before.y1 + 15.0), 1e-6), + "moved leaf: {b:?}" + ); + let layers_after_move = s.doc().unwrap().doc.layers.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, layers_before_move); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, layers_after_move); + } + } + } +} + /// #1590: an inset larger than the shape leaves nothing, and the error says so rather than asking /// for paths that are selected. #[test] diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1d0926f53a..194c56178b 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -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] diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 87b943d6c1..dcd1bd6a1b 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -582,6 +582,60 @@ fn set_pref(s: &mut Session, key: &str, value: Value) { s.execute("prefs.set", &json!({"key": key, "value": value})).unwrap(); } +/// New type with the session's defaults: its id and language. +fn new_type(s: &mut Session) -> (NodeId, Option) { + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + (id, type_language(s, id)) +} + +fn type_language(s: &Session, id: NodeId) -> Option { + let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("not text") }; + t.runs[0].style.language.clone() +} + +/// Preferences › Hyphenation › Default Language (#394) is the language of new type, stored as its +/// tag. Type already there keeps its language, and a language chosen in Document Setup comes first. +#[test] +fn default_language_is_the_language_of_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let (before, language) = new_type(&mut s); + assert_eq!(language, None, "the default language isn't stored"); + + set_pref(&mut s, "hyphenationLanguage", json!("German")); + assert_eq!(s.prefs.hyphenation_language, "de", "a name is stored as its tag"); + assert_eq!(new_type(&mut s).1.as_deref(), Some("de")); + assert_eq!(type_language(&s, before), None, "type already there stays as it is"); + + s.execute("document.setup", &json!({"language": "French"})).unwrap(); + assert_eq!(new_type(&mut s).1.as_deref(), Some("fr"), "the document's own language comes first"); + + set_pref(&mut s, "hyphenationLanguage", json!("en-US")); + s.execute("document.setup", &json!({"language": "English: USA"})).unwrap(); + assert_eq!(new_type(&mut s).1, None); +} + +/// Preferences saved before the language was a tag hold its name; a language no longer in the list +/// reads as the default. +#[test] +fn a_saved_default_language_reads_as_its_tag() { + let read = |v: &str| serde_json::from_value::(json!({"hyphenationLanguage": v})).unwrap().hyphenation_language; + assert_eq!(read("German"), "de"); + assert_eq!(read("English: USA"), "en-US"); + assert_eq!(read("de"), "de"); + assert_eq!(read("Klingon"), "en-US"); + assert_eq!(Prefs::default().hyphenation_language, "en-US"); +} + +/// The preference offers every language the Character panel and Document Setup do. +#[test] +fn default_language_offers_every_language() { + let spec = PREF_SPECS.iter().find(|p| p.key == "hyphenationLanguage").unwrap(); + let crate::cmd::prefscmds::PrefKind::Choice(options) = spec.kind else { panic!("a choice") }; + let languages: Vec<(&str, &str)> = vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, tag, _)| (*tag, *name)).collect(); + assert_eq!(options, languages.as_slice()); +} + fn gesture(s: &mut Session, v: ViewInfo, events: &[(vectorcraft_tools::PointerKind, f64, f64)]) { for (k, x, y) in events { s.pointer(&vectorcraft_tools::PointerEvent::new(*k, *x, *y), v).unwrap(); @@ -1072,8 +1126,8 @@ fn a_drag_from_a_fill_moves_only_the_selected_anchors_of_partly_selected_paths() } /// A path selected whole inside a selected group moves once, with the group, when the selection -/// also holds a direct-selected anchor: a Group Selection drag from the path's fill (which adds -/// the group) and an arrow key move both by 10 pt. +/// also holds a direct-selected anchor: a completed Group Selection click adds the group, then +/// a drag and an arrow key move both by 10 pt. A leaf drag before that click keeps its sibling still. #[test] fn a_path_in_a_selected_group_moves_once_with_selected_anchors() { use vectorcraft_tools::PointerKind::{Down, Drag, Up}; @@ -1088,7 +1142,14 @@ fn a_path_in_a_selected_group_moves_once_with_selected_anchors() { s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]); - assert!(s.doc().unwrap().selection.contains(g), "the press added the group"); + assert!(!s.doc().unwrap().selection.contains(g), "the leaf drag keeps its selection"); + assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (160.0, 100.0), 310.0), "the leaf and selected anchor move"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + gesture(&mut s, v, &[(Down, 125.0, 125.0), (Up, 125.0, 125.0)]); + assert!(s.doc().unwrap().selection.contains(g), "the completed click added the group"); + gesture(&mut s, v, &[(Down, 125.0, 125.0), (Drag, 130.0, 125.0), (Drag, 135.0, 125.0), (Up, 135.0, 125.0)]); assert_eq!((top_left(&s, a), top_left(&s, b), first_x(&s)), ((110.0, 100.0), (170.0, 100.0), 310.0), "the drag"); s.execute("edit.undo", &json!({})).unwrap(); s.execute("select.set", &json!({"ids": [g.0, a.0]})).unwrap(); @@ -1947,6 +2008,52 @@ fn a_move_held_by_a_paths_stroke_lands_the_path_on_a_ruler_guide() { } } +/// #5746: a rectangle dragged until its left edge and its top edge are each 1 px from a ruler +/// guide lands on both guides, with "align", whichever guide was added last and wherever it was +/// grabbed; between two upright guides, its left edge lands on the one within reach; and an edge +/// Smart Guides line up with another object stays there, not on a ruler guide as near. +#[test] +fn a_moved_rectangle_lines_its_edges_up_with_two_ruler_guides() { + use vectorcraft_tools::Overlay; + use vectorcraft_tools::PointerKind::{Down, Drag, Up}; + let v = ViewInfo::default(); + // (guides as (vertical, pos), where it is grabbed, the top left it lands on) + type Case = (&'static [(bool, f64)], (f64, f64), (f64, f64)); + let cases: [Case; 3] = [ + (&[(true, 250.0), (false, 320.0)], (200.0, 100.0), (250.0, 320.0)), + (&[(false, 320.0), (true, 250.0)], (100.0, 175.0), (250.0, 320.0)), + (&[(true, 250.0), (true, 455.0)], (200.0, 175.0), (250.0, 100.0)), + ]; + for (guides, (x, y), want) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap()["id"].as_u64().unwrap()); + for (vertical, pos) in guides { + s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + // 1 px past the guides: the left edge at 251, the top edge at 321 (or where it was). + let (to_x, to_y) = (x + 151.0, if want.1 == 100.0 { y } else { y + 221.0 }); + gesture(&mut s, v, &[(Down, x, y), (Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), (Drag, to_x, to_y)]); + let align = s.overlays(v).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "align")); + gesture(&mut s, v, &[(Up, to_x, to_y)]); + assert_eq!(top_left(&s, id), want, "guides {guides:?}, grabbed at ({x}, {y})"); + assert!(align, "guides {guides:?}, grabbed at ({x}, {y}): no align"); + } + // Dragged by its centre until its left edge is at 401: 1 px from another rectangle's left + // edge (400) and 1 px from a ruler guide (402). + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap()["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 400, "y": 400, "width": 60, "height": 60})).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 402.0})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + gesture(&mut s, v, &[(Down, 200.0, 175.0), (Drag, 350.0, 175.0), (Drag, 501.0, 175.0), (Up, 501.0, 175.0)]); + assert_eq!(top_left(&s, id), (400.0, 100.0), "a Smart Guides alignment gave way to a ruler guide"); +} + /// #3701: at 28,757%, Direct Selection pressed 1.5 px beside a rectangle's straight left side and /// dragged until the side is 1 px from a ruler guide lands both its anchors on the guide; so does /// the same press and drag on the rectangle selected whole, which moves it. diff --git a/crates/engine/src/tests/previewbounds.rs b/crates/engine/src/tests/previewbounds.rs index f1b31671e4..c9bad6e60d 100644 --- a/crates/engine/src/tests/previewbounds.rs +++ b/crates/engine/src/tests/previewbounds.rs @@ -878,6 +878,31 @@ fn a_handle_drag_keeps_the_opposite_edge_of_the_offset_shape() { } } +#[test] +fn a_hover_checks_the_memo_as_often_however_many_objects_are_selected() { + let checks = |objects: u32| { + let mut s = session(); + for i in 0..objects { + rect(&mut s, f64::from(i), 1.0, 0.0); + } + run(&mut s, "select.all", json!({})); + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + // Off the art, so the hover walks every selected object and finds no anchor or center. + let hover = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Move, 350.0, 350.0), v).unwrap(); + s.cursor(Point::new(350.0, 350.0), Mods::default(), v) + }; + hover(&mut s); + let before = s.preview_memo.checks(); + hover(&mut s); + s.preview_memo.checks() - before + }; + let few = checks(3); + assert!(few > 0, "a hover asks the memo"); + assert_eq!(checks(60), few, "a check compares the whole selection: one per object is quadratic"); +} + #[test] fn hovering_over_an_unchanged_document_measures_nothing_again() { // A selected square with Offset Path 10, drawn from 90 to 210, with Use Preview Bounds and Smart diff --git a/crates/engine/src/tests/printtiling.rs b/crates/engine/src/tests/printtiling.rs index 9d82820536..7bc37d8b19 100644 --- a/crates/engine/src/tests/printtiling.rs +++ b/crates/engine/src/tests/printtiling.rs @@ -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", ¶ms).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})); +} diff --git a/crates/engine/src/tests/slices.rs b/crates/engine/src/tests/slices.rs index 1576f50ce3..87d0088d97 100644 --- a/crates/engine/src/tests/slices.rs +++ b/crates/engine/src/tests/slices.rs @@ -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, ¶ms).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); +} diff --git a/crates/engine/src/tests/strokeux.rs b/crates/engine/src/tests/strokeux.rs index 82d3aae69a..1c94cfa01f 100644 --- a/crates/engine/src/tests/strokeux.rs +++ b/crates/engine/src/tests/strokeux.rs @@ -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+,")); +} diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 7d1f77cd7e..23980c5d5a 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -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!( diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 9f607d78a3..dde0c4bf5f 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1645,6 +1645,173 @@ fn select_all_in_one_frame_selects_only_its_text_once_the_caret_moves() { assert!(s.execute("text.editRange", &json!({"id": a.0, "start": 0, "end": 0, "clear": "x"})).is_err()); } +/// A story of bulleted paragraphs threaded from area type `a` into frame `b`, each frame holding +/// paragraph returns, with the Type tool editing `b` at its start. +fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, String) { + let mut s = session(); + let story = "Alpha beta.\n".repeat(12); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a, b], "list": "bullet"})).unwrap(); + let (a, b) = (NodeId(a), NodeId(b)); + for id in [a, b] { + let t = obj(&s, id); + assert!(t.plain_text().contains('\n'), "frame {} holds paragraph returns", id.0); + assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_some()), "frame {} is a list", id.0); + } + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + (s, a, b, story) +} + +#[test] +fn remove_breaks_takes_the_whole_story_that_select_all_selected() { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()); + assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "every frame's returns go, each between words as a space"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story); + assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n')); +} + +#[test] +fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + assert!(obj(&s, a).plain_text().ends_with('\n'), "the first frame ends with a paragraph return"); + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()); + assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "the return at the end of the first frame becomes a space"); +} + +#[test] +fn remove_breaks_in_one_frames_selection_leaves_the_other_frames() { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + let (in_a, b_len) = (obj(&s, a).plain_text(), obj(&s, b).plain_text().len()); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": b_len})); + s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(obj(&s, a).plain_text(), in_a, "the first frame keeps its returns"); + assert!(!obj(&s, b).plain_text().contains('\n'), "the edited frame's returns go"); +} + +#[test] +fn convert_to_text_takes_the_whole_story_that_select_all_selected() { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("text.convertListToText", &json!({})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + for id in [a, b] { + let t = obj(&s, id); + assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none()), "frame {} leaves its list", id.0); + assert!(t.plain_text().contains("\u{2022}\t"), "frame {} holds its bullets as characters", id.0); + } + assert!(s.tool_options().get("story").is_some(), "the whole story stays selected"); + s.execute("edit.undo", &json!({})).unwrap(); + for id in [a, b] { + let t = obj(&s, id); + assert!((0..t.paragraph_count()).all(|k| t.para_at(k).list.is_some()), "frame {} is a list again", id.0); + } +} + +#[test] +fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() { + // Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story. + for named in [false, true] { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + s.execute("object.lock", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + // The first frame ends with a paragraph return, so the paragraph that starts the locked + // frame takes in the first frame's empty last part and starts its text there. + let in_a = obj(&s, a).plain_text(); + assert!(in_a.ends_with('\n')); + let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count(); + let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; + let r = s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})"); + assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert"); + assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0))); + let (ta, tb) = (obj(&s, a), obj(&s, b)); + assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted"); + let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count(); + assert_eq!(markers, own, "the locked frame's first paragraph keeps its list"); + // The converted text is longer, so the story flows on into the locked frame; its own + // paragraphs stay a list. + let last = tb.paragraph_count() - 2; + assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})"); + assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n")); + assert!(s.tool_options().get("story").is_some(), "the whole story stays selected"); + } +} + +#[test] +fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() { + for named in [false, true] { + let mut s = session(); + let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40)); + let a = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let b = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 900})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap(); + let in_a = obj(&s, a).plain_text(); + assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second"); + s.execute("object.lock", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; + let r = s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})"); + // The two paragraphs that start in the editable frame, and the empty one that ends the story. + assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert"); + let (ta, tb) = (obj(&s, a), obj(&s, b)); + assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was"); + assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list"); + assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list"); + assert!(!tb.plain_text().starts_with('\u{2022}')); + assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2); + } +} + +#[test] +fn convert_to_text_of_named_frames_ends_the_story_selection() { + let (mut s, _, b, _) = threaded_list_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("text.convertListToText", &json!({"ids": [b.0]})).unwrap(); + assert!(obj(&s, b).plain_text().contains("\u{2022}\t")); + assert!(s.tool_options().get("story").is_none(), "the Type tool's selection moves past the characters inserted"); +} + +#[test] +fn convert_to_text_in_one_frame_leaves_the_other_frames() { + let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); + let in_a = obj(&s, a).plain_text(); + s.execute("text.convertListToText", &json!({})).unwrap(); + let (ta, tb) = (obj(&s, a), obj(&s, b)); + assert_eq!(ta.plain_text(), in_a, "the first frame's text is as it was"); + assert!(ta.para_at(0).list.is_some(), "the first frame stays a list"); + assert!((0..tb.paragraph_count()).all(|k| tb.para_at(k).list.is_none()), "the edited frame leaves its list"); + assert!(tb.plain_text().contains("\u{2022}\t"), "the edited frame holds its bullets as characters"); +} + #[test] fn a_frame_dragged_with_the_type_tools_is_the_dragged_rectangle() { for tool in ["type", "verticalType"] { @@ -2823,9 +2990,11 @@ fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() { let glyphs = vectorcraft_text::layout(db, &obj(&s, open)).glyphs; let fallback = db.face_by_id(glyphs[0].font_id).expect("the fallback face"); assert_ne!(fallback.id(), requested.id()); - let (ka, sign) = (fallback.glyph_for('क'), fallback.glyph_for('\u{93F}')); + let ka = fallback.glyph_for('क'); let drawn: Vec<_> = glyphs.iter().map(|g| (g.gid, g.byte)).collect(); - assert_eq!(drawn, [(sign, 0), (ka, 0)], "the vowel sign is drawn first, in Ka's cluster ({} or {MATRA_FAMILY})", fallback.family); + // A face may draw the vowel sign with a glyph other than its own, so only its place is checked. + let sign_first = matches!(drawn[..], [(sign, 0), (k, 0)] if sign != 0 && sign != ka && k == ka); + assert!(sign_first, "the vowel sign is drawn first, in Ka's cluster ({} or {MATRA_FAMILY}): {drawn:?}", fallback.family); let query = s.execute("text.glyphAlternates", &json!({"id": open.0, "start": 0})).unwrap(); assert_eq!(query["chosen"], json!(ka), "the fallback face's glyph for Ka"); @@ -2834,3 +3003,28 @@ fn the_fallback_glyph_of_a_consonant_after_its_vowel_sign_is_reported() { let query = s.execute("text.glyphAlternates", &json!({"id": boxed.0, "start": 0})).unwrap(); assert_eq!(query["chosen"], json!(ka), "an overflowing Ka reports the fallback face's glyph for Ka"); } + +/// Apply Fill to Stroke with characters selected with the Type tool: only those characters take +/// a stroke of their own fill, as one undo step (#5530). +#[test] +fn apply_fill_to_stroke_with_characters_selected_changes_only_them() { + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + click(&mut s, 50.0, 300.0); + let id = s.doc().unwrap().selection.objects[0]; + s.tool_text("Sample Text", v).unwrap(); + // All of it red, then the first word green: a stroke on the rest would show. + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#ff0000"})).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 6})); + s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("addon.color.fillToStroke", &json!({})).unwrap(); + let t = obj(&s, id); + assert_eq!(t.runs[0].text, "Sample"); + assert_eq!(t.runs[0].style.stroke, t.runs[0].style.fill, "the selected characters take their fill as a stroke"); + assert!(t.runs[0].style.stroke_width > 0.0); + assert!(t.runs[1].style.stroke.is_none(), "the rest of the type keeps its stroke"); + let labels = undo_labels(&s); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Apply Fill to Stroke"))); +} diff --git a/crates/engine/src/tests/transparencygrid.rs b/crates/engine/src/tests/transparencygrid.rs index 974fb0343b..06efa70fb1 100644 --- a/crates/engine/src/tests/transparencygrid.rs +++ b/crates/engine/src/tests/transparencygrid.rs @@ -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", ¶ms).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})); +} diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index e6ef5e69dd..715bae959b 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -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(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 18e8da3d59..66d84a925b 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -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; ). /// 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. diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 3010901ca7..42970aa160 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -239,6 +239,10 @@ fn structured_junk() { ("addon.select.byArtboards", json!({"artboards": [0, u64::MAX, -1, "x", null, 1.5], "relation": "inside"})), ("addon.select.byArtboards", json!({"artboards": [1e308], "relation": [1]})), ("addon.select.byArtboards", json!({"artboards": {"a": 1}, "relation": "outside"})), + ("addon.select.byLinkStatus", json!({"status": ["linked", "missing", null, 7, {"a": 1}], "ids": [2, u64::MAX, -1, "x", 1.5]})), + ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), + ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), + ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), ("object.transform", json!({"matrix": [0, 0, 0, 0, 0, 0]})), ("object.transform", json!({"matrix": [1e308, 1e308, 1e308, 1e308, 1e308, 1e308]})), ("object.transform", json!({"matrix": [1, 2, 3]})), @@ -526,6 +530,10 @@ fn structured_junk() { ("document.open", json!({"name": "x.pdf", "dataBase64": "JVBERi0xLjQK"})), ("document.open", json!({"name": "x.vectorcraft", "dataBase64": "e30="})), ("document.activate", json!({"index": 99})), + ("document.move", json!({"from": 99, "to": 0})), + ("document.move", json!({"from": 0, "to": u64::MAX})), + ("document.move", json!({"from": -1, "to": 1e308})), + ("document.move", json!({"from": "x", "to": null})), ("file.close", json!({"index": 99})), ("file.new", json!({"width": -1, "height": 0, "artboards": 1000000})), ("command.batch", json!({"commands": [{"command": 5}, {"params": 3}]})), @@ -593,6 +601,12 @@ fn structured_junk() { ("addon.pathtools.cornerSet", json!({"items": [1, null, {"anchors": "x"}], "radius": 1})), ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 1e308, "kind": "spiky"})), ("addon.pathtools.cornerSet", json!({"items": "all", "radius": f64::NAN, "anchors": [-1, 1.5, "x"]})), + ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "every": "odd"})), + ("addon.pathtools.cornerSet", json!({"items": [{"id": 2, "anchors": [1, u64::MAX]}], "radius": 5, "every": "even"})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "every": [1, "x", null]})), + ("addon.pathtools.cornerSet", json!({"ids": [2, 3], "radius": 5, "minAngle": 0, "maxAngle": 0})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "minAngle": 180, "maxAngle": 180, "every": "odd"})), + ("addon.pathtools.cornerSet", json!({"ids": [2], "radius": 5, "minAngle": f64::MAX, "maxAngle": -1e-300})), ("addon.pathtools.cornerRemove", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.cornerRemove", json!({"items": [{"id": 2, "anchors": [u64::MAX]}]})), ("addon.pathtools.slideAnchor", json!({"id": 2, "anchor": 1, "t": 0.98})), @@ -662,6 +676,11 @@ fn structured_junk() { ("addon.type.textTweaker", json!({"attribute": "rotation", "from": -360, "to": 360, "shape": "bow", "skipSpaces": false, "ids": [u64::MAX]})), ("addon.type.textTweaker", json!({"attribute": "hScale", "id": 2, "start": u64::MAX, "end": 0, "shape": "ease"})), ("addon.type.textTweaker", json!({"attribute": ["size"], "from": "x", "seed": 1e308, "skipSpaces": "no", "ids": "all"})), + ("addon.type.releasePath", json!({"mode": "both", "keepOriginal": true, "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8]})), + ("addon.type.releasePath", json!({"mode": "path", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), + ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), + ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), + ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), ("addon.cleanup.breakText", json!({"by": "glyphs", "ids": [0, 1, 2, 3, 4, 5, 6, 7, 8, u64::MAX]})), ("addon.cleanup.breakText", json!({"by": ["lines"]})), ("addon.cleanup.breakText", json!({"by": "paragraphs"})), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index cbe713e444..46ca4a0781 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2763,6 +2763,10 @@ fn editing_text() -> String { "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceCMYK XN\n[ 4 0 0 4 10 30 ] 2 1 0 Xh\n[ 4 0 0 4 10 30 ] 0 0 2 1 2 1 8 4 1 0 0 0 4 4 0 0\n\ %%BeginData: 18\rXI\nff000000000000ff80ff\n%%EndData\nXH\n%AI5_EndRaster\nN" .into(), + // A 9 × 2 1-bit image mask (ImageMask 1) colorized by the global fill before it, in hex. + "0 0 0 1 (Black global) 0.4 0 Xk\n%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceGray XN\n[ 4 0 0 4 10 30 ] 9 2 0 Xh\n\ + [ 4 0 0 4 10 30 ] 0 0 9 2 9 2 1 1 0 0 0 1 4 4 0 0\n%%BeginData: 8\rXI\n6080ff00\n%%EndData\nXH\n%AI5_EndRaster\nN" + .into(), ] .join("\n"); let layer = |name: &str, visible: u8, body: &str| { @@ -2849,6 +2853,23 @@ fn the_editing_fixture_reads_its_cmyk_image_with_its_mask() { assert!(layers && found.contains(&(Some(vec![255, 0, 0, 0, 0, 0, 0, 255]), true)), "{found:?} {warnings:?}"); } +/// The fuzzed editing data, as it is, reads its 1-bit image mask as an image colorized with the +/// global color before it. +#[test] +fn the_editing_fixture_reads_its_image_mask_colorized() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing_text())].concat(); + let (doc, warnings, layers) = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0); + let mut found = vec![]; + doc.visit_images(|n, im| { + if let Some(vectorcraft_color::Paint::Solid { swatch, .. }) = n.extras().colorize.as_deref() { + found.push((swatch.clone(), im.width, im.height, doc.images[&im.key].coverage().map(|c| c.2))); + } + }); + // Clear bits (black) show the color; set bits (white) are transparent. + let cover = vec![255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255]; + assert!(layers && found == [(Some("Black global".to_string()), 9, 2, Some(cover))], "{found:?} {warnings:?}"); +} + /// The text document of a story of centred type with two styles, as an editing copy keeps it. fn text_document_text() -> String { "/0 << /1 << /0 [ << /0 << /0 << /0 (Helvetica) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 3 4 ] >> >> >> ] >> >>\n\ @@ -3291,7 +3312,7 @@ proptest! { #[test] fn ai_line_widths_never_panic( width in prop::sample::select(vec!["0", "0.0", "-0", "-1", "1e308", "1e-308", "nan", "inf", "2"]), - render in prop::sample::select(vec!["0", "1", "2", "5", "6", "7", "-1", "99"]), + render in prop::sample::select(vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "4.5", "-1", "99"]), cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', 'w', 'B', 'S', 'T'])), 0..8), ) { @@ -3307,6 +3328,88 @@ proptest! { survive("hostile .ai line widths", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose pattern definition (a marked tile box, a gradient placed by `Bg`'s matrix) and + /// pattern fill are damaged or hostile. + #[test] + fn ai_pattern_definitions_never_panic( + cut in 0usize..2_000, + edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', 'n', 'E', 'p', 'B'])), 0..12), + ) { + use vectorcraft_testkit::ai; + let gradient = "%AI5_BeginGradient: (G)\n(G) 1 2 Bd\n[\n%_0 0 0 0 1 0 0 2 1 6 50 0 Bs\n%_0 0 0 0 0 0 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let pattern = "%AI3_BeginPattern: (P)\n(P) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n%_10 0 L\n%_10 -10 L\n%_0 -10 L\n%_0 0 L\n%_n\n\ + %_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n%_2 -2 m\n%_8 -2 L\n%_8 -8 L\n%_2 -8 L\n%_Bb\n\ + %_0.1 0.2 45 0.3 Bh\n%_1 (G) 0.1 0.2 0 1.5 3 0 0 3 0 0 1 Bg\n%_3 0 0 3 -8000 8000 Bm\n%_f\n%_0 BB\nE\n%AI3_EndPattern\n"; + let art = format!("(P) 0 0 1 1 0 0 0 0 0 [0.5 0.2 -0.2 0.5 3 -4] p\n{}f\n", ai::rect(20.0, 20.0, 80.0, 80.0)); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{gradient}{pattern}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai patterns", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose gradients and patterns have names with newlines (blank before one, several, + /// repeated, one shown like another's numbered name), used by fills and a palette, damaged or + /// hostile. + #[test] + fn ai_global_names_with_newlines_never_panic( + names in prop::collection::vec(prop::sample::select(vec!["Sky\\n1", "Sky\\n2", "Sky", "Sky 2", "\\n3", "\\n", "Sky\\n\\n1", "\\012x"]), 1..6), + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec!['\\', 'n', '(', ')', ' ', '\n', 'B', 'p', 'E', '%'])), 0..10), + ) { + use vectorcraft_testkit::ai; + let mut setup = String::new(); + let mut art = String::new(); + let mut cells = String::new(); + for name in &names { + setup.push_str(&format!( + "%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n\ + %AI3_BeginPattern: ({name})\n({name}) 0 0 6 6\n%_0 A\n%_0 0 m\n%_0 6 L\n%_6 6 L\n%_6 0 L\n%_0 0 0 1 k\n%_f\nE\n%AI3_EndPattern\n" + )); + art.push_str(&format!("Bb\n1 ({name}) 0 0 0 50 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", ai::rect(10.0, 10.0, 40.0, 40.0))); + art.push_str(&format!("({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", ai::rect(50.0, 50.0, 90.0, 90.0))); + cells.push_str(&format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n({name}) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\n")); + } + setup.push_str(&format!("%AI5_BeginPalette\n0 0 Pb\n{cells}PB\n%AI5_EndPalette\n")); + let data = mutate_text(&ai::editing_data(100.0, 100.0, &format!("{setup}{}", ai::layer("L", &art))), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai global names", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + + /// A `.ai` whose images (binary samples with an alpha channel, the operators that end a raster, + /// then a name and an opacity mask) and placed file (an empty relative folder, a preview) are + /// damaged or hostile, bytes of the samples included. + #[test] + fn ai_images_and_placed_files_never_panic( + cut in 0usize..3_000, + edits in prop::collection::vec((0usize..3_000, prop::sample::select(vec![b'0', b'1', b'9', b' ', b'\r', b'\n', b'(', b')', b'[', b']', b'%', b'_', b'N', b'X', b'~', 0u8, 255u8])), 0..12), + ) { + use vectorcraft_testkit::ai; + let raster = "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 2 1 0 Xh\n[10 0 0 10 20 -30] 0 0 2 1 2 1 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 10\nXI\n@@%%EndData\nXH\n\ + %AI17_Begin_Content_if_version_gt:24 17\n72 72 Xr\n%AI17_End_Versioned_Content\n%AI5_EndRaster\nN\n\ + %_/ArtDictionary :\n%_/Mask :\n%_X=\n%_0 g\n%_0 0 m\n%_5 0 l\n%_5 -5 l\n%_f\n%_X+\n%_ (Art) ,\n%_; (AI9_Mask) ,\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\n%_;\n%_\n"; + let place = "%AI5_BeginPlace\n%%FileType: 1\n[1 0 0 -1 -8000 8000] 8000 8000 8002 8001 4 4 0\n(/tmp/p.png)`\n%%IncludeFile:/tmp/p.png\n\ + %AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n()\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n\ + %AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n2 1 8 32 17 @@\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"; + let text = ai::editing_data(100.0, 100.0, &ai::layer("L", &format!("{raster}{place}"))); + let samples: &[u8] = &[255, 0, 0, 0, 0, 255, 128, 0]; + let preview: &[u8] = &[255, 255, 0, 0, 0, 0, 0, 0]; + let mut data = Vec::new(); + for (i, part) in text.split("@@").enumerate() { + if i > 0 { + data.extend_from_slice(if i == 1 { samples } else { preview }); + } + data.extend_from_slice(part.as_bytes()); + } + for &(i, b) in &edits { + let n = data.len(); + if n > 0 { + data[i % n] = b; + } + } + data.truncate(cut.min(data.len())); + let private = [b"%AI24_ZStandard_Data".as_slice(), &ruzstd::encoding::compress_to_vec(data.as_slice(), ruzstd::encoding::CompressionLevel::Fastest)].concat(); + survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; + } + /// A `.ai` whose variable library is damaged or hostile: the library is counted for the warning /// whether the layers are read or not (an inserted `Z` can make an operator the reader doesn't /// handle, and then the layers aren't read). @@ -3420,6 +3523,7 @@ proptest! { ], 0..12), ended in any::(), objects in prop::collection::vec((prop_oneof![arb_num(), prop::sample::select(vec!["1".to_string(), "6".into(), "9".into()])], prop::sample::select(vec!["A", "B", "", "Caf\u{e9}", "Missing"]), any::()), 0..6), + unit in prop::sample::select(vec![1.0, 2.0, 0.0, -1.0, f64::NAN, f64::INFINITY]), ) { use vectorcraft_testkit::ai; let style = |name: &str| { @@ -3448,6 +3552,11 @@ proptest! { survive("style lists and links", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; let eps = ai::eps(data.as_bytes(), ai::page_ps()); survive("style lists and links in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + // A graphic style library: the styles and their list, no layers. + let library = ai::editing_data(200.0, 100.0, &header); + survive("style library", || Some(vectorcraft_eps::layered_ai(library.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, unit).0))?; + let eps = ai::eps(library.as_bytes(), ai::page_ps()); + survive("style library in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; } /// Objects on Path records of any shape: ids in any order, repeated or missing, any number of @@ -3512,6 +3621,114 @@ proptest! { Some(d) })?; } + + /// A `.ai` whose symbols are damaged or hostile: their definitions, the symbol list and the + /// instances (on the page and in a symbol's art), cut short or edited. + #[test] + fn ai_symbols_never_panic(cut in 0usize..2_000, edits in prop::collection::vec((0usize..2_000, prop::sample::select(vec!['0', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', 'u', 'U', 'A', 'Z'])), 0..12)) { + let text = mutate_text(&symbols_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; + } +} + +/// Editing data with two symbols (S2's art holds an instance of S1), the symbol list and a layer of +/// instances, as the format writes them. +fn symbols_text() -> String { + use vectorcraft_testkit::ai; + let def = |name: &str, art: &str, reg: u32| { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{reg} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n" + ) + }; + let inst = |name: &str, m: &str| format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{m} /RTransformMatrix\n;\n9 () XW\n"); + let defs = def("S1", "0 1 1 0 1 0 0 Xa\n-2 -2 m\n2 -2 L\n2 2 L\n-2 2 L\nf\n", 5) + &def("S2", &inst("S1", "1 0 0 -1 -8081 8237"), 1); + let list = "%AI24_BeginSymbolList\n(S2)\n(S1)\n%AI24_EndSymbolList\n"; + let page = ai::layer( + "L", + &format!( + "1 Xw\n{}0 Xw\n{}1 0.5 0 2 0 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}10 10 m\n30 10 L\n30 30 L\nh\nW\nn\nQ\n", + inst("S1", "1 0 0 -1 20 50"), + inst("S2", "2 0 0 -2 100 50"), + inst("S1", "1 0 0 -1 20 20") + ), + ); + let data = ai::editing_data( + 200.0, + 100.0, + &format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n%AI5_Begin_NonPrinting\n{list}%AI5_End_NonPrinting--\n{page}"), + ); + data.replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1) +} + +/// The data [`ai_symbols_never_panic`] damages, as it is, opens with its symbols and instances live. +#[test] +fn the_symbols_fuzz_data_opens_live() { + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&symbols_text())].concat(); + let (doc, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["S2", "S1"]); + let mut instances = 0; + doc.walk(|n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))); + assert_eq!(instances, 3); +} + +/// Symbols the reader must stop at: sections that don't end, references and matrices it can't +/// use, definitions nested deeper than it reads, and symbols that hold each other. +#[test] +fn ai_symbol_limits_never_panic() { + use vectorcraft_testkit::ai; + let inst = |name: &str, m: &str| format!("/SymbolInstance :\n{name} /SymbolRef ,\n{m} /RTransformMatrix\n;\n"); + let def = |name: &str, art: &str| format!("%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%AI10_EndSymbol\n"); + let mut nested = String::new(); + for i in 0..400 { + nested.push_str(&format!("%AI14_BeginSymbol\n(N{i})\n0 Ae\nu\n")); + } + for _ in 0..400 { + nested.push_str("U\n%AI10_EndSymbol\n"); + } + let mut chain = String::new(); + for i in 0..300 { + chain.push_str(&def(&format!("C{i}"), &inst(&format!("(C{})", i + 1), "1 0 0 -1 0 0"))); + } + let cases = [ + format!("%AI14_BeginSymbol\n(Open)\n0 Ae\nu\n{}", ai::layer("L", &inst("(Open)", "1 0 0 -1 20 50"))), + format!("%AI24_BeginSymbolList\n(A)\n(B)\n{}", ai::layer("L", "")), + format!( + "{}{}", + def("S", "-2 -2 m\n2 2 L\nS\n"), + ai::layer("L", &(inst("", "1 0 0 -1 20 50") + &inst("/SymbolRef", "1 0 0 -1 20 50") + &inst("(S)", ""))) + ), + format!( + "{}{}", + def("S", "-2 -2 m\n2 2 L\nS\n"), + ai::layer( + "L", + &(inst("(S)", "1 0 0") + &inst("(S)", "1 0 0 -1 20 50 7") + &inst("(S)", "1e400 0 0 -1 20 50") + &inst("(S)", "0 0 0 0 20 50")) + ) + ), + format!("{nested}{}", ai::layer("L", &inst("(N0)", "1 0 0 -1 20 50"))), + format!("{chain}{}", ai::layer("L", &inst("(C0)", "1 0 0 -1 20 50"))), + format!( + "{}{}{}", + def("S1", &inst("(S2)", "1 0 0 -1 0 0")), + def("S2", &inst("(S1)", "1 0 0 -1 0 0")), + ai::layer("L", &inst("(S1)", "1 0 0 -1 20 50")) + ), + format!("{}{}", def("S1", &inst("(S2)", "1 0 0 -1 0 0")), def("S2", &inst("(S1)", "1 0 0 -1 0 0"))), + ]; + for body in cases { + let data = ai::editing_data(200.0, 100.0, &body).replacen("%%EndComments", "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n%%EndComments", 1); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat(); + survive("hostile .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0)) + .unwrap(); + survive("hostile .ai symbols, trusted", || { + Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0) + }) + .unwrap(); + } } /// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group. @@ -3657,6 +3874,19 @@ proptest! { let text = mutate_text(&fixture, cut, &edits); survive("mutated PostScript-form .ai with placed files", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; } + + /// The same file with linked images in the version 7 form (`XG`, then `XF` with no samples), + /// one with an embedded image between its `XG` and `XF`, damaged. + #[test] + fn ps_form_ai_with_linked_images_never_panics(cut in 0usize..1_400, edits in prop::collection::vec((0usize..1_400, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', 'X', 'F', 'G'])), 0..12)) { + let linked = "%AI5_File:\n%AI5_BeginRaster\n(a.tif) 0 XG\n[ 2 0 0 3 10 80 ] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n\ + %AI5_File:\n%AI5_BeginRaster\n(b.tif) 1 XG\n[ 1 0 0 1 0 100 ] 0 0 1 1 1 1 8 3 0 0 0 0 XI\n%FF0000\n%AI5_EndRaster\n\ + [ 0 1 -1 0 50 50 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n"; + let fixture = NAMED_PROLOG_AI.replacen("0 Ap\nu\n", &format!("0 Ap\n{linked}u\n"), 1); + prop_assert!(fixture.contains("(a.tif)")); + let text = mutate_text(&fixture, cut, &edits); + survive("mutated PostScript-form .ai with linked images", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } } /// A `.ai` in the legacy format without layers (Illustrator 3) whose prolog is included: its @@ -3722,6 +3952,47 @@ proptest! { } } +/// Area type in the version 7 form (§15.5.3) whose story flows through two linked areas: a small +/// one, and one a quarter turn round, each area's characters after its `TP`. +const LINKED_AREAS: &str = "1 To\n1 0 0 1 120 90 0 Tp\n120 60 m\n120 90 L\n180 90 L\n180 60 L\n120 60 L\nn\nTP\n0 Tr\n0 g\n/_Helvetica 9 Tf\n\ + (one two three four five six seven eight nine ten ) Tx\n0 1 -1 0 190 10 0 Tp\n130 10 m\n130 55 L\n190 55 L\n190 10 L\n130 10 L\nn\nTP\n\ + (eleven twelve thirteen fourteen fifteen) Tx\n(\\r) TX\nTO\n"; + +/// [`NAMED_PROLOG_AI`] with `text` on its layer. +fn linked_areas_ai(text: &str) -> String { + NAMED_PROLOG_AI.replace("u\n0.5 g\n", &format!("{text}u\n0.5 g\n")) +} + +/// The fixture, as it is, opens with its area type as two threaded frames, the story flowing from +/// the first into the second. +#[test] +fn the_linked_areas_fixture_opens_as_threaded_frames() { + let l = vectorcraft_engine::cmd::fileio::load("x.ai", linked_areas_ai(LINKED_AREAS).as_bytes()).unwrap(); + let [thread] = &l.doc.text_threads[..] else { panic!("one thread: {:?} {:?}", l.doc.text_threads, l.warnings) }; + let texts: Vec = thread + .iter() + .map(|id| match &l.doc.node(*id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + k => panic!("type: {k:?}"), + }) + .collect(); + let [first, second] = texts.as_slice() else { panic!("two frames: {texts:?}") }; + assert!(!first.is_empty() && !second.is_empty(), "the story flows on into the second frame: {texts:?}"); + assert_eq!(format!("{first}{second}"), "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen"); +} + +proptest! { + #![proptest_config(config())] + + /// That `.ai` with its linked areas damaged (their text paths, frames and characters): read, or + /// refused. + #[test] + fn ps_form_ai_linked_areas_never_panic(cut in 0usize..400, edits in prop::collection::vec((0usize..400, prop::sample::select(vec!['0', '1', '-', '.', ' ', '\n', '(', ')', '\\', 'T', 'p', 'P', 'O', 'o', 'x', 'X', 'm', 'L', 'n'])), 0..12)) { + let text = linked_areas_ai(&mutate_text(LINKED_AREAS, cut, &edits)); + survive("PostScript-form .ai with damaged linked areas", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; + } +} + /// An operand of a layer's options (`Lb`): a flag, a colour index or component, a percentage, or /// anything else. fn arb_layer_operand() -> impl Strategy { @@ -3784,6 +4055,12 @@ fn arb_ai_token() -> impl Strategy { "*U", "q", "Q", + // Several clipping paths in one clipping group or layer clip to their intersection (AI7 spec §5.6.2), each + // nesting a clipping group. + "0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W f", + "q 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n 0 0 m 5 5 L 0 5 L f Q", + "u 0 0 m 9 0 L 9 9 L h W n 1 1 m 8 1 L 8 8 L h W n U", + "q 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n 0 0 m 9 0 L 9 9 L h W n", "LB", "Lb", "Ln", @@ -3816,6 +4093,12 @@ fn arb_ai_token() -> impl Strategy { "\n%AI3_Note:\n", "\n%AI5_NoteMore:more\n", "\n%%Note:old\n", + // Object tags (version 7 §7). + "XT", + "/AdobeURL (https://example.com) XT", + "/tag () XT", + "/ (x) XT", + "(x) (y) XT", "w", "J", "j", @@ -3854,6 +4137,12 @@ fn arb_ai_token() -> impl Strategy { "[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 1 0 1 0", "[ 1 0 0 1 0 0 ] 0 0 3 2 3 2 1 4 1 0 1 0", "[ 1 0 0 1 0 0 ] 0 0 99999 99999 99999 99999 1 1 0 0 0 0", + // A linked image in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF`. + "XG", + "(a.tif) 0 XG", + "XF", + "[ 1 0 0 1 0 0 ] 0 0 2 2 2 2 8 3 0 0 0 0 XF", + "[ 1e308 0 0 1e308 0 0 ] 0 0 1e6 1e6 1e6 1e6 8 3 0 0 0 0 XF", "[", "]", "/Name", @@ -3906,7 +4195,17 @@ fn arb_ai_token() -> impl Strategy { "(\\r) TX", "() Tj", "(x) Tx", + "(\\t) 1 TS", + "() /x TS", + "Te", + "0 0 1e308 -1e308 Te", + "TM", "7 Tr", + "4 Tr", + "9 Tr", + "4.5 Tr", + "*w", + "*W", "-1e308 Ts", "1e308 0 Tz", "1e308 Tt", @@ -3922,10 +4221,23 @@ fn arb_ai_token() -> impl Strategy { "7 Tq", "1 1 1e308 -1e308 4e9 Th", "1 1 (2) 3 4 Th", + "36 2 Xb", + "Xb", + "0 0 4 1e308 Xe", + "0 0 2 -1e308 Xe", + "0 0 3 72 Xe", + "0 0 1e308 72 Xe", + "(x) /y Xe", + "XB", "[39/quotesingle 128/Euro/eacute/nosuch 300/x TE", "[1e308/a -1/b TE", "\n%AI3_BeginEncoding: _Helvetica Helvetica\n[/_Helvetica/Helvetica 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n", "\n%AI3_BeginEncoding:\n", + "[ 39/quotesingle 1e308/a -1/b 200/eacute\n/_Helvetica/Helvetica 0 0 1 [0.5 1e308] TZ", + "/_ 0 TZ", + "[ ] ] [ /a /b (c) TZ", + "\n%AI3_EndEncoding AdobeType\n", + "\n%%BeginEncoding: _x x\n[ 39/grave\n/_x/x 0 1 TZ\n%%EndEncoding\n", "800 Ar", "frobnicate", "\n%AI5_BeginLayer\n", @@ -4125,6 +4437,15 @@ fn arb_ai_token() -> impl Strategy { "\n%\n", "\n%AI5_EndPlace\n", "\n%%PageTrailer\n", + "\n%AI14_BeginSymbol\n(S1)\n0 A 0 Xw 0 Ae\n", + "\n%AI10_EndSymbol\n", + "\n%AI24_BeginSymbolList\n(S1)\n", + "\n%AI24_EndSymbolList\n", + "/SymbolInstance :", + "(S1) /SymbolRef ,", + "/RTransformMatrix", + "5 /Int (AI13PatternRegistrationType) ,", + "; (AI19SymbolAppearanceMap) ,", ]) .prop_map(str::to_string), ] @@ -4343,8 +4664,9 @@ proptest! { /// Art styles with a Distort & Transform effect (Transform, Free Distort, Pucker & Bloat, Roughen, /// Tweak, Twist, Zig Zag) whose dictionary holds any of its entries, and unknown ones, as any kind, - /// with any value (huge, tiny, not a number, a string), repeated or left out, on a path and on type, - /// on the whole object or on its fill. + /// with any value (huge, tiny, not a number, a string), repeated or left out, on a path, on type and + /// on a group nested any number of levels around a curved path, stroked or not, on the whole object + /// or on its fill. #[test] fn ai_distort_effects_never_panic( name in prop::sample::select(vec![ @@ -4371,6 +4693,8 @@ proptest! { ], ), 0..24), on_fill in any::(), + depth in 0usize..300, + stroked in any::(), ) { use vectorcraft_testkit::ai; let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); @@ -4385,10 +4709,15 @@ proptest! { }; let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}%AI9_EndArtStyles\n"); let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let paint = if stroked { "0 0 1 0 K\n2 w\nB\n" } else { "f\n" }; + let curve = format!("0 0 1 0 k\n20 70 m\n20 90 80 90 80 70 c\n80 50 20 50 20 70 c\n{paint}"); + let nested = format!("0 Ae\n{}{curve}{}", "u\n".repeat(depth + 1), "U\n".repeat(depth + 1)).replace('\n', "\n%_"); let art = format!( - "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n", + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n\ + 0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{nested}1 (Fx) XW\n", ai::rect(20.0, 20.0, 80.0, 60.0), - ai::rect(100.0, 20.0, 180.0, 60.0) + ai::rect(100.0, 20.0, 180.0, 60.0), + ai::rect(20.0, 50.0, 80.0, 90.0) ); let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); survive("distort art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; diff --git a/crates/engine/tests/it/clear_commands.rs b/crates/engine/tests/it/clear_commands.rs index 50a6fbd86d..3b7fb79e94 100644 --- a/crates/engine/tests/it/clear_commands.rs +++ b/crates/engine/tests/it/clear_commands.rs @@ -202,3 +202,24 @@ fn cut_direct_selected_anchors_retains_anchor_deletion() { assert_eq!(s.active().unwrap().doc.node(a).unwrap().path_data().unwrap().anchor_count(), 3); assert_eq!(s.active().unwrap().doc.parent_of(b), Some(c)); } + +#[test] +fn clear_explicit_ids_preserves_unrelated_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r1 = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + let r2 = NodeId(s.execute("shape.rectangle", &json!({"x": 50, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [r1.0, r2.0]})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, vec![r1, r2]); + + // Clearing r1 explicitly should remove r1 from doc and from selection, keeping r2 selected. + s.execute("edit.clear", &json!({"ids": [r1.0]})).unwrap(); + assert!(s.active().unwrap().doc.node(r1).is_none()); + assert!(s.active().unwrap().doc.node(r2).is_some()); + assert_eq!(s.active().unwrap().selection.objects, vec![r2]); + + // Parameterless clear clears the rest of the selection. + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(r2).is_none()); + assert!(s.active().unwrap().selection.is_empty()); +} diff --git a/crates/engine/tests/it/copy_direct_selection.rs b/crates/engine/tests/it/copy_direct_selection.rs new file mode 100644 index 0000000000..d34b342934 --- /dev/null +++ b/crates/engine/tests/it/copy_direct_selection.rs @@ -0,0 +1,806 @@ +//! Direct-selection Copy and Cut tests (#2122). + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::FillRule; +use vectorcraft_testkit::invariants::check_session; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()) +} + +#[test] +fn copy_and_paste_direct_selected_segment_of_rect() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select segment 0 of the rectangle. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_none(), "extracted partial path must not retain live shape metadata"); + } + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); +} + +#[test] +fn copy_and_paste_direct_selected_adjacent_anchors_of_rect() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select two adjacent anchors: 0 and 1. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); +} + +#[test] +fn copy_single_anchor_of_rect_copies_three_anchors_with_two_segments() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select only anchor 1 of the closed 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + // Copying a single anchor on a closed path copies the anchor and both its incident segments. + assert_eq!(sp.anchors.len(), 3); + assert_eq!(sp.segment_count(), 2); +} + +#[test] +fn copy_disjoint_segments_does_not_copy_unselected_segment_in_between() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Rectangle has 4 segments (0, 1, 2, 3). Select disjoint segments 0 and 2. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 2]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + // Two separate open path pieces should be created, each with 2 anchors. + assert_eq!(ids.len(), 2); + for id in ids { + let node = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + } +} + +#[test] +fn cut_direct_selected_segment_cuts_source_and_pastes_segment() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select segment 0 and cut it. + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.cut", json!({})); + + // Source rectangle should now have segment 0 removed, turning it into an open path. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 1); + assert!(!src_path.subpaths[0].closed); + + // Paste the cut segment: + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let pasted_path = pasted_node.path_data().unwrap(); + assert_eq!(pasted_path.subpaths.len(), 1); + assert!(!pasted_path.subpaths[0].closed); + assert_eq!(pasted_path.subpaths[0].anchors.len(), 2); +} + +#[test] +fn copy_compound_path_direct_selected_segment_inherits_appearance() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + + // Select segment 0 of the inner member. + run(&mut s, "select.segments", json!({"id": inner.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let compound_node = s.doc().unwrap().doc.node(compound).unwrap(); + assert_eq!(pasted_node.appearance, compound_node.appearance); +} + +#[test] +fn direct_selection_copy_preserves_fill_rule_and_attributes() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + run(&mut s, "path.setFillRule", json!({"rule": "evenOdd"})); + + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + assert!(matches!(pasted_node.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. })); +} + +#[test] +fn pen_tool_drawing_copies_whole_path_not_single_anchor() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Start drawing with Pen tool + s.select_tool("pen", vectorcraft_engine::ViewInfo::default()).unwrap(); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 50})); + + // Pen tool has the last anchor in sel.anchors, but active tool is pen + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + // The whole 3-point path must be copied, not just the last anchor! + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} + +#[test] +fn cut_adjacent_anchors_clipboard_plus_remaining_equals_original() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select two adjacent anchors: 1 and 2 of the 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // Cut placed 1 segment on the clipboard (anchors 1 to 2). + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip_path.subpaths[0].segment_count(), 1); + assert_eq!(clip_path.subpaths[0].anchors.len(), 2); + + // Remaining source path must have the remaining 3 segments (segments 0, 2, 3), not 1. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths[0].segment_count(), 3); + assert_eq!(src_path.subpaths[0].anchors.len(), 4); + assert!(!src_path.subpaths[0].closed); + + // Sum of segments in clipboard + remaining = 1 + 3 = 4 (the original 4 segments). + assert_eq!(clip_path.subpaths[0].segment_count() + src_path.subpaths[0].segment_count(), 4); +} + +#[test] +fn copy_non_adjacent_anchors_on_rect_copies_full_object() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select non-adjacent anchors 1 and 3 of the 4-anchor rectangle. + // Incident segments for anchor 1 are segments 0 and 1; for anchor 3 are segments 2 and 3. + // Together they cover all 4 segments, so the path is copied whole. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1], [0, 3]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_some(), "copying all segments keeps live shape metadata"); + } + let path = pasted_node.path_data().unwrap(); + assert!(path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 4); +} + +#[test] +fn copy_non_adjacent_anchors_on_five_point_path_extracts_selected_segments() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 50})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 30, "y": 80})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 10, "y": 50})); + run(&mut s, "path.close", json!({"id": id.0})); + + // Path has 5 anchors (0..4) and 5 segments (0..4). + // Select non-adjacent anchors 1 and 3. + // Anchor 1 gives segments 0, 1. Anchor 3 gives segments 2, 3. Segment 4 is unselected. + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 1], [0, 3]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 4); + assert_eq!(path.subpaths[0].anchors.len(), 5); +} + +#[test] +fn copy_when_all_segments_selected_preserves_live_shape() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Select all 4 segments explicitly (like Select > Object > Direction Handles). + run(&mut s, "select.segments", json!({"id": r.0, "segments": [[0, 0], [0, 1], [0, 2], [0, 3]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + if let NodeKind::Path { live, .. } = &pasted_node.kind { + assert!(live.is_some(), "all segments selected preserves live shape"); + } +} + +#[test] +fn compound_member_selected_whole_with_direct_selection_promotes_member() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + let standalone = rect(&mut s, 120.0, 10.0, 50.0, 50.0); + + // Select outer compound member whole, and direct-select anchor 0 on standalone. + let outer_anchors: Vec> = (0..4).map(|i| vec![0, i]).collect(); + run( + &mut s, + "select.anchorsMany", + json!({ + "items": [ + {"id": outer.0, "anchors": outer_anchors}, + {"id": standalone.0, "anchors": [[0, 0]]} + ] + }), + ); + + // outer is selected whole, standalone is partially selected. + assert!(s.active().unwrap().selection.partial(outer).is_none()); + assert!(s.active().unwrap().selection.partial(standalone).is_some()); + + run(&mut s, "edit.copy", json!({})); + // Clipboard should have: + // 1. The compound path (outer promoted to compound #786) + // 2. The extracted segment piece from standalone + let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); + assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); + assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); +} + +#[test] +fn cut_whole_compound_member_with_direct_selection_cuts_compound_and_extracted_piece() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + let standalone = NodeId(run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + + let outer_anchors = (0..4).map(|i| vec![0, i]).collect::>(); + run( + &mut s, + "select.anchorsMany", + json!({ + "items": [ + {"id": outer.0, "anchors": outer_anchors}, + {"id": standalone.0, "anchors": [[0, 0]]} + ] + }), + ); + + run(&mut s, "edit.cut", json!({})); + let clip_ids: Vec = s.clipboard.nodes.iter().map(|n| n.id).collect(); + assert_eq!(clip_ids.len(), 2, "promoted compound plus the extracted standalone piece"); + assert!(clip_ids.contains(&compound), "whole compound member must be promoted to compound parent"); + + // Compound was removed because member was selected whole + let doc = &s.doc().unwrap().doc; + assert!(doc.node(compound).is_none(), "compound path must be removed on cut"); + // Standalone has cut pieces remaining + assert!(doc.node(standalone).is_some(), "partially cut standalone path remains"); +} + +#[test] +fn cut_direct_selected_only_path_in_layer_preserves_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + // Create a new layer + let layer_id = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); + // Create a path inside the layer + let rect = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].as_u64().unwrap()); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(rect), Some(layer_id)); + + // Direct-select all 4 anchors of rect and cut + let all_anchors = (0..4).map(|i| vec![0, i]).collect::>(); + run(&mut s, "select.anchors", json!({"id": rect.0, "anchors": all_anchors, "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // The rect was cut, but the layer must NOT be deleted + let doc = &s.doc().unwrap().doc; + assert!(doc.node(rect).is_none(), "rect was cut"); + assert!(doc.node(layer_id).is_some(), "layer must remain even when empty"); + assert_eq!(doc.node(layer_id).unwrap().children().unwrap().len(), 0); +} + +#[test] +fn copy_and_paste_path_in_compound_path_isolation_adds_member_to_compound() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Enter isolation mode on the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + assert_eq!(s.doc().unwrap().isolation, Some(compound)); + + // In isolation mode, select member `inner` whole. + run(&mut s, "select.set", json!({"ids": [inner.0]})); + run(&mut s, "edit.copy", json!({})); + + // Clipboard copies the selected member path, NOT the entire compound path. + assert_eq!(s.clipboard.nodes.len(), 1); + assert_eq!(s.clipboard.nodes[0].id, inner); + + // Paste in isolation mode: the pasted path must be inserted into the compound path, + // not as a new path beside the compound path. + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_id = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_id), Some(compound), "pasted path must be added to the compound path"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 3, "compound path now has 3 member paths"); +} + +#[test] +fn cut_and_paste_direct_selected_anchors_in_compound_path_isolation() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = NodeId(run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}))["id"].as_u64().unwrap()); + let inner = NodeId(run(&mut s, "shape.rectangle", json!({"x": 30, "y": 30, "width": 40, "height": 40}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Enter isolation mode on the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + + // Direct-select anchor 0 of `inner` and cut. + run(&mut s, "select.anchors", json!({"id": inner.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.cut", json!({})); + + // Clipboard holds the cut segment piece. + assert_eq!(s.clipboard.nodes.len(), 1); + + // Paste inside isolation mode: + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_id = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_id), Some(compound), "cut and pasted anchors must be inserted into compound path"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 3); + check_session(&s).unwrap(); +} + +#[test] +fn paste_non_path_in_compound_path_isolation_inserts_into_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let a = rect(&mut s, 10.0, 10.0, 40.0, 40.0); + let b = rect(&mut s, 60.0, 10.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let _group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + + // Copy the group to the clipboard. + run(&mut s, "edit.copy", json!({})); + + // Create a compound path on the layer. + let c1 = rect(&mut s, 10.0, 100.0, 80.0, 80.0); + let c2 = rect(&mut s, 30.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [c1.0, c2.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let layer_id = s.doc().unwrap().doc.parent_of(compound).unwrap(); + + // Isolate the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + assert_eq!(s.doc().unwrap().isolation, Some(compound)); + + // Generic insertion parent inside compound isolation resolves to the layer, not the compound. + assert_eq!(s.doc().unwrap().insertion_parent(), Some(layer_id)); + + // Paste the group while in compound path isolation. + // The group cannot be inserted into the compound path; it must be pasted into the layer beside the compound. + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + let pasted_group = NodeId(ids[0]); + + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(pasted_group), Some(layer_id), "pasted group must be added to layer, not compound"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 2, "compound path must keep only its 2 path children"); + + // All document invariants (including compound children being paths only) must hold. + check_session(&s).unwrap(); +} + +#[test] +fn shape_creation_in_compound_path_isolation_inserts_into_layer() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let outer = rect(&mut s, 10.0, 10.0, 80.0, 80.0); + let inner = rect(&mut s, 30.0, 30.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [outer.0, inner.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Isolate the compound path. + run(&mut s, "object.isolate", json!({"id": compound.0})); + + // Draw a new rectangle while isolating the compound path. + let new_rect = rect(&mut s, 40.0, 40.0, 20.0, 20.0); + + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.parent_of(new_rect), Some(compound), "new shape path is placed outside compound path in layer"); + let compound_node = doc.node(compound).unwrap(); + assert_eq!(compound_node.children().unwrap().len(), 2, "compound path maintains original member paths"); + + check_session(&s).unwrap(); +} + +#[test] +fn paste_compound_into_isolated_compound_preserves_child_order() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 300, "height": 300})); + let r1 = rect(&mut s, 10.0, 10.0, 10.0, 10.0); + let r2 = rect(&mut s, 30.0, 10.0, 10.0, 10.0); + let r3 = rect(&mut s, 50.0, 10.0, 10.0, 10.0); + run(&mut s, "select.set", json!({"ids": [r1.0, r2.0, r3.0]})); + let src_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Copy src_compound (contains [r1, r2, r3] in order) + run(&mut s, "select.set", json!({"ids": [src_compound.0]})); + run(&mut s, "edit.copy", json!({})); + + // Create target compound + let t1 = rect(&mut s, 100.0, 100.0, 80.0, 80.0); + let t2 = rect(&mut s, 120.0, 120.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [t1.0, t2.0]})); + let target_compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + + // Isolate target compound and select member t1 so paste-in-front targets index 1 + run(&mut s, "object.isolate", json!({"id": target_compound.0})); + run(&mut s, "select.set", json!({"ids": [t1.0]})); + + // Paste in front of t1 + let pasted = run(&mut s, "edit.pasteInFront", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 3, "unpacked all 3 children"); + + let doc = &s.doc().unwrap().doc; + let target_node = doc.node(target_compound).unwrap(); + let children = target_node.children().unwrap(); + assert_eq!(children.len(), 5); + + // Verify the 3 pasted children appear in children in exact forward order [r1_copy, r2_copy, r3_copy] + let child_ids: Vec = children.iter().map(|c| c.id.0).collect(); + let pos0 = child_ids.iter().position(|&id| id == ids[0]).unwrap(); + let pos1 = child_ids.iter().position(|&id| id == ids[1]).unwrap(); + let pos2 = child_ids.iter().position(|&id| id == ids[2]).unwrap(); + assert_eq!(pos1, pos0 + 1, "child 1 must immediately follow child 0"); + assert_eq!(pos2, pos1 + 1, "child 2 must immediately follow child 1"); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_and_paste_direct_selected_segment_of_open_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 20}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 60, "y": 20})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 100, "y": 80})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"weight": 4.0})); + + // Select segment 0 of the open path (from (10, 20) to (60, 20)). + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + + // Paste in place: position and appearance must be preserved. + let pasted = run(&mut s, "edit.pasteInPlace", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let src_node = s.doc().unwrap().doc.node(id).unwrap(); + assert_eq!(pasted_node.appearance, src_node.appearance, "appearance (stroke & fill) must match source"); + + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.segment_count(), 1); + assert_eq!(sp.anchors.len(), 2); + assert_eq!(sp.anchors[0].p.x, 10.0); + assert_eq!(sp.anchors[0].p.y, 20.0); + assert_eq!(sp.anchors[1].p.x, 60.0); + assert_eq!(sp.anchors[1].p.y, 20.0); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_two_non_adjacent_segments_of_open_path_pastes_two_paths() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 300, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 40, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 120, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 160, "y": 10})); + + // Path has 5 anchors (0..4) and 4 segments (0..3). + // Select disjoint/non-adjacent segments 0 and 2. + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 0], [0, 2]]})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 2, "two non-adjacent segments paste as two independent paths"); + + for node_id in ids { + let node = s.doc().unwrap().doc.node(NodeId(node_id)).unwrap(); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 1); + assert_eq!(path.subpaths[0].anchors.len(), 2); + } + + check_session(&s).unwrap(); +} + +#[test] +fn copy_all_anchors_of_open_path_copies_whole_path() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 80, "y": 40})); + + // Select all 3 anchors. + run(&mut s, "select.anchors", json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted = run(&mut s, "edit.paste", json!({})); + let ids: Vec = pasted["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 1); + + let pasted_node = s.doc().unwrap().doc.node(NodeId(ids[0])).unwrap(); + let path = pasted_node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(!path.subpaths[0].closed); + assert_eq!(path.subpaths[0].segment_count(), 2); + assert_eq!(path.subpaths[0].anchors.len(), 3); + + check_session(&s).unwrap(); +} + +#[test] +fn copy_single_anchor_on_open_path_and_lone_point_states_what_is_pasted() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + + // 1. Single interior anchor of an open path: + // Path: (10, 10) -> (50, 10) -> (90, 50). + // Selecting interior anchor 1 selects both incident segments (0 and 1). + // Stated behavior: pasting pastes an open path containing the anchor and both its incident segments (3 anchors, 2 segments). + let p1 = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": p1.0, "x": 90, "y": 50})); + run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 1]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted1 = run(&mut s, "edit.paste", json!({})); + let ids1: Vec = pasted1["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids1.len(), 1); + let path1 = s.doc().unwrap().doc.node(NodeId(ids1[0])).unwrap().path_data().unwrap(); + assert!(!path1.subpaths[0].closed); + assert_eq!(path1.subpaths[0].anchors.len(), 3); + assert_eq!(path1.subpaths[0].segment_count(), 2); + + // 2. Single endpoint anchor of an open path: + // Selecting endpoint anchor 0 selects its single incident segment (segment 0). + // Stated behavior: pasting pastes an open path for that segment (2 anchors, 1 segment). + run(&mut s, "select.anchors", json!({"id": p1.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted2 = run(&mut s, "edit.paste", json!({})); + let ids2: Vec = pasted2["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids2.len(), 1); + let path2 = s.doc().unwrap().doc.node(NodeId(ids2[0])).unwrap().path_data().unwrap(); + assert!(!path2.subpaths[0].closed); + assert_eq!(path2.subpaths[0].anchors.len(), 2); + assert_eq!(path2.subpaths[0].segment_count(), 1); + + // 3. A lone point path (a path with only 1 anchor and 0 segments): + // Selecting the lone anchor on a single-point path copies the object whole. + // Stated behavior: pasting pastes a standalone lone-point path (1 anchor, 0 segments). + let p_lone = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 100, "y": 100}]}))["id"].as_u64().unwrap()); + run(&mut s, "select.anchors", json!({"id": p_lone.0, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "edit.copy", json!({})); + let pasted_lone = run(&mut s, "edit.paste", json!({})); + let ids_lone: Vec = pasted_lone["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids_lone.len(), 1); + let path_lone = s.doc().unwrap().doc.node(NodeId(ids_lone[0])).unwrap().path_data().unwrap(); + assert_eq!(path_lone.subpaths[0].anchors.len(), 1); + assert_eq!(path_lone.subpaths[0].segment_count(), 0); + + check_session(&s).unwrap(); +} + +#[test] +fn cut_anchor_of_closed_path_opens_it_with_single_undo_step() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let r = rect(&mut s, 10.0, 10.0, 100.0, 50.0); + + // Direct-select anchor 1 of the closed 4-anchor rectangle. + run(&mut s, "select.anchors", json!({"id": r.0, "anchors": [[0, 1]], "mode": "set"})); + let undo_before = s.doc().unwrap().history.undo.len(); + + // Cut the anchor. + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step"); + + // Source rectangle opens: 1 open subpath with 3 anchors remaining. + let src_node = s.doc().unwrap().doc.node(r).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 1); + assert!(!src_path.subpaths[0].closed, "cutting anchor of closed path opens the path"); + assert_eq!(src_path.subpaths[0].anchors.len(), 3); + assert_eq!(src_path.subpaths[0].segment_count(), 2); + + // Clipboard holds the cut portion (the anchor and its two incident segments: 3 anchors). + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert!(!clip_path.subpaths[0].closed); + assert_eq!(clip_path.subpaths[0].anchors.len(), 3); + assert_eq!(clip_path.subpaths[0].segment_count(), 2); + + // Verify undo restores the closed path in one step. + run(&mut s, "edit.undo", json!({})); + let restored_node = s.doc().unwrap().doc.node(r).unwrap(); + let restored_path = restored_node.path_data().unwrap(); + assert_eq!(restored_path.subpaths.len(), 1); + assert!(restored_path.subpaths[0].closed, "undo restores closed path"); + assert_eq!(restored_path.subpaths[0].anchors.len(), 4); + assert_eq!(restored_path.subpaths[0].segment_count(), 4); + + // Verify redo re-applies the cut. + run(&mut s, "edit.redo", json!({})); + let redone_node = s.doc().unwrap().doc.node(r).unwrap(); + let redone_path = redone_node.path_data().unwrap(); + assert!(!redone_path.subpaths[0].closed); + assert_eq!(redone_path.subpaths[0].anchors.len(), 3); + + check_session(&s).unwrap(); +} + +#[test] +fn cut_middle_segment_of_open_path_splits_into_two_open_paths_with_single_undo_step() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let id = NodeId(run(&mut s, "path.create", json!({"anchors": [{"x": 10, "y": 10}]}))["id"].as_u64().unwrap()); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 50, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 90, "y": 10})); + run(&mut s, "path.appendAnchor", json!({"id": id.0, "x": 130, "y": 10})); + + // Open path has 4 anchors (0, 1, 2, 3) and 3 segments (0, 1, 2). + // Direct-select middle segment 1 (between anchor 1 and 2). + run(&mut s, "select.segments", json!({"id": id.0, "segments": [[0, 1]]})); + let undo_before = s.doc().unwrap().history.undo.len(); + + // Cut the middle segment. + run(&mut s, "edit.cut", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "cut is recorded as one undo step"); + + // Source path should now be split into two surviving open runs. + let src_node = s.doc().unwrap().doc.node(id).unwrap(); + let src_path = src_node.path_data().unwrap(); + assert_eq!(src_path.subpaths.len(), 2, "two open paths/subpaths remain after cutting middle segment"); + assert!(!src_path.subpaths[0].closed); + assert_eq!(src_path.subpaths[0].anchors.len(), 2); + assert_eq!(src_path.subpaths[0].anchors[0].p.x, 10.0); + assert_eq!(src_path.subpaths[0].anchors[1].p.x, 50.0); + + assert!(!src_path.subpaths[1].closed); + assert_eq!(src_path.subpaths[1].anchors.len(), 2); + assert_eq!(src_path.subpaths[1].anchors[0].p.x, 90.0); + assert_eq!(src_path.subpaths[1].anchors[1].p.x, 130.0); + + // Clipboard holds the cut middle segment: + assert_eq!(s.clipboard.nodes.len(), 1); + let clip_path = s.clipboard.nodes[0].path_data().unwrap(); + assert_eq!(clip_path.subpaths[0].anchors.len(), 2); + assert_eq!(clip_path.subpaths[0].anchors[0].p.x, 50.0); + assert_eq!(clip_path.subpaths[0].anchors[1].p.x, 90.0); + + // Verify undo restores the original intact path in one step: + run(&mut s, "edit.undo", json!({})); + let restored_node = s.doc().unwrap().doc.node(id).unwrap(); + let restored_path = restored_node.path_data().unwrap(); + assert_eq!(restored_path.subpaths.len(), 1, "undo restores single subpath"); + assert_eq!(restored_path.subpaths[0].anchors.len(), 4, "undo restores all 4 anchors"); + + // Redo re-applies the split: + run(&mut s, "edit.redo", json!({})); + let redone_path = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap(); + assert_eq!(redone_path.subpaths.len(), 2); + + check_session(&s).unwrap(); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5b9dc39c6c..f17d27e4da 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,6 +13,7 @@ mod artboard_click; mod beyond_canvas; mod clear_commands; mod compound_attributes; +mod copy_direct_selection; mod dimensions; mod eyedropper_sources; mod find_replace_paras; diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 43b82f1272..26293842cc 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -18,11 +18,16 @@ //! `%AI5_ArtFlags`, `%AI5_TargetResolution`, `%AI5_NumLayers`, `%AI5_OpenViewLayers` (a digit for //! each layer, 7 shown and 6 hidden), `%AI7_GridSettings` (§2.1.1), and the version comment //! `%%AI8_CreatorVersion` ([`CREATOR_VERSION`]). -//! - Setup: `0 Bn` (no gradient definitions, §3), the color swatches (`%AI5_BeginPalette`, -//! `0 0 Pb`, the Registration swatch, each swatch's color operator and `(name) Pc`, a color group as `0 (name) count Pg` -//! before its swatches, `PB`), then the artboards as the `ArtboardArray` of the `/Document` -//! dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on `%_` -//! lines. +//! - Setup: the gradients the art uses as `n Bn` and a definition of each (§3.5: `%AI5_BeginGradient: +//! (name)`, `(name) type stops Bd`, `[`, each stop on a `%_` line as `color style opacity 6 midpoint +//! rampPoint Bs`, `BD`, `%AI5_EndGradient`), those only the swatches use in a non-printing block +//! (§14: `%AI5_Begin_NonPrinting`, `Np`, `%AI5_End_NonPrinting--`); the patterns the same way +//! (§3.4: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury`, the tile's art on `%_` lines, `E`, +//! `%AI3_EndPattern`); the swatches (`%AI5_BeginPalette`, `0 0 Pb`, the Registration swatch, each +//! swatch's color operator, gradient instance or pattern operator and `(name) Pc`, a color group as +//! `0 (name) count Pg` before its swatches, `PB`), then the artboards as the `ArtboardArray` of the +//! `/Document` dictionary's `/Recorded` part and the canvas size as its `AIDocumentCanvasSize`, on +//! `%_` lines. //! - Layers: `%AI5_BeginLayer`, `visible preview unlocked printing dimmed 0 1 colorIndex r g b 0 //! dimPercent clipping Lb` (14 operands; a color that isn't one of the preset layer colors has the //! index -1; `clipping` is 1 for a clipping layer), `(name) Ln`, the layer's name as an XML id in an @@ -30,10 +35,22 @@ //! - Colors: `g` gray, `k` CMYK, `c m y k r g b Xa` RGB (Lab is written as RGB); a spot color //! `c m y k (name) tint x` (CMYK) or `c m y k r g b|L a b (name) tint 1|2 Xx` (RGB or Lab); a //! global process color `… (name) tint model Xk`; Registration `1 1 1 1 ([Registration]) tint -//! Xs`. Upper case paints the stroke. +//! Xs`; a pattern `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P`), the matrix taking the pattern's +//! space (its tile's lower left corner the origin) to art space. Upper case paints the stroke. +//! - Gradients (§3.5.3): around the painting operator of a path (of a compound path's last path), +//! `Bb` (`1 Bb` for the stroke), a radial gradient's focal point `x y angle fraction Bh`, then +//! `flag (name) x y angle length a b c d tx ty 1 Bg`, which places the gradient on the path: a +//! linear one with the identity matrix, `x` the start and `length` the length as fractions of the +//! path's extent along `angle`; a radial one with the matrix taking the unit circle onto its +//! extent ellipse, `x` and `y` its center as fractions of the path's bounds there and `length` its +//! radius as a multiple of the one the bounds give (`writer::paints::placement`). The imaging data +//! follows (a linear gradient's `a b c d tx ty Xm`, its caps `Bc` and a `Bm` for each pair of +//! stops; a radial one's `Bm`), then the operator and `0 BB` (`2 BB` or `1 BB` when the path is +//! stroked too; a fill's instance ends `2 BB` before a stroke's). In a pattern's tile the matrices +//! are in the canvas's space (y down, from art space's origin there). //! - State before each object: locked `A`, hidden `Xw` (`1` or `0`). An object's name follows it as -//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are `(N) *`, the -//! path, `(N) *` (`(n) *` when closed). +//! an `/ArtDictionary` whose `AI10_ArtUID` is the name as an XML id. Guides are the path +//! followed by `(N) *` (`(n) *` when closed), without the `(N) *` that §6 also puts before it. //! - Transparency: `mode opacity isolate knockout shape Xy` (the blending mode's number, Knockout //! Group 0 off, 1 on, 2 neutral), written when it changes: in a path's paint after its colors, //! before a guide, and after a group's end (`U` or `Q`) followed by `0 0 Xd` and `6 () XW`; a @@ -45,19 +62,42 @@ //! - Opacity masks: an `AI9_Mask` entry in the object's `/ArtDictionary`, a `/Mask` dictionary //! holding the mask's art between `X=` and `X+` on `%_` lines, `(Art) ,`, and `Clipping`, //! `Inverted`, `Disabled` and `Linked` as `/Bool` entries. +//! - Embedded images (§8): `%AI5_File:`, `%AI5_BeginRaster`, `() 1 XG`, the color space +//! (`/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`) with `XN`, `[matrix] w h 0 Xh`, `[matrix] 0 0 +//! w h w h 8 type alpha flags 1 0 4 4 0 0` (type 1 gray, 3 RGB, 4 CMYK; alpha 1 with an alpha +//! channel; flags 0 gray, 1 RGB, 2 CMYK, 16 more with an alpha channel), `%%BeginData:` counting +//! `XI`, its line end and the color samples, `XI`, the samples in binary (8 bits, rows from the +//! top, CMYK images with their ink amounts) followed by the alpha channel, `%%EndData`, `XH`, +//! `%AI5_EndRaster`, `N`. The matrix (to ten decimals) is an art-space matrix applied to the +//! pixels with their rows running downwards. In a part on `%_` lines, `XI` and the samples are +//! not, and `%_%%EndData` ends them. +//! - Linked images (version 7 specification §16, with the newer sections): `%AI5_BeginPlace`, +//! `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and `(path)` with `` ` ``, `%%IncludeFile:`, +//! the folder relative to the document's between `%AI28_BeginPlacedRelativePath` and its end, +//! a preview of at most 256 pixels a side between `%AI26_BeginPlacedObjectPreview` and its end +//! (`w h rowBytes 32 17 `, then rows of premultiplied ARGB), each in versioned content, `~`, +//! `%AI5_EndPlace`. The box is the file's pixels at art space's origin on the canvas; the matrix +//! takes it into art space. In opacity masks and pattern tiles, linked images are embedded. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the //! artboards together are centered; each artboard's `RulerOrigin` is its top-left corner there, and //! `%AI3_TemplateBox` holds the canvas's center in art space. What the form above can't hold is written as plain filled and stroked paths, each such -//! loss a warning: type as its outlines and its inline graphics' art, gradients as their average color, pattern fills as their -//! tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path, +//! loss a warning: type as its outlines and its inline graphics' art, freeform gradients, gradients +//! along or across a stroke and gradients without stops, with more than 256 stops or without extent +//! as their average color +//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked +//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past +//! the tile or is painted with patterns as their tiles cut to the shape, clipping groups and clipping layers whose clipping object isn't a path, //! and the clipping groups inside them, as their art cut to that object (its fill cut too, its -//! stroke not), images as their outlines filled with -//! their average color, symbols and live objects as their art (symbol art past +//! stroke not; an image in a clipping group of the region it is cut to), images that can't be +//! decoded or have more than 33,554,432 pixels as their outlines filled mid gray, images of 16 bits +//! a channel at 8 bits, linked images in opacity masks and pattern tiles as embedded images, +//! symbols and live objects (placed documents included) as their art (symbol art past //! [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects in all left out), strokes a plain line can't draw -//! as their filled outlines, several fills or strokes as a group of a path for each, gradient and -//! pattern swatches, the opacity and blending modes of single fills and strokes, opacity masks on +//! as their filled outlines, several fills or strokes as a group of a path for each, freeform +//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as +//! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on //! layers and opacity masks nested too deep, and live effects other than geometry effects left out. //! //! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with @@ -160,10 +200,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result Result Vec { s.replace('\n', "\r\n").into_bytes() } +/// `text` with each payload's mark (`\u{1}`, its index in `payloads`, `\u{1}`) replaced by its +/// bytes. Strings are written with that byte escaped, so a mark is never part of one. +fn splice(text: &[u8], payloads: &[Vec]) -> Vec { + let mark = writer::PAYLOAD as u8; + if payloads.is_empty() { + return text.to_vec(); + } + let mut out = Vec::with_capacity(text.len() + payloads.iter().map(Vec::len).sum::()); + let mut parts = text.split(|b| *b == mark); + if let Some(first) = parts.next() { + out.extend_from_slice(first); + } + // The parts alternate: an index, then the text up to the next mark. + while let (Some(index), Some(rest)) = (parts.next(), parts.next()) { + let payload = std::str::from_utf8(index).ok().and_then(|i| i.parse::().ok()).and_then(|i| payloads.get(i)); + if let Some(p) = payload { + out.extend_from_slice(p); + } + out.extend_from_slice(rest); + } + out +} + /// `doc` with its geometry effects and group paint baked ([`vectorcraft_effects::bake_document`]), /// in its symbols' art and its patterns' tile art too (which instances and pattern fills are /// written as); `None` when nothing changes. @@ -305,7 +373,7 @@ fn header(doc: &Document, o: &AiEditingOptions, w: &Writer, art: Rect, first: Re s.push('\n'); s.push_str("%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); s.push_str("%AI5_FileFormat 14.0\n%AI3_ColorUsage: Color\n"); - // Linked images aren't embedded (the data holds no images). + // Linked files aren't included (their previews are). s.push_str("%AI7_ImageSettings: 0\n"); let spots = w.spot_swatches(); for (i, (name, _)) in spots.iter().enumerate() { diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index dcf928df56..529c54a5fa 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -602,8 +602,8 @@ fn hidden_layers_open_hidden() { assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); } -/// A 200 × 100 document of what the data holds as plain paths: a gradient fill, a compound path, -/// an image, type and a symbol instance. +/// A 200 × 100 document of a gradient fill, a compound path and an image, and what the data holds +/// as plain paths: type and a symbol instance. fn unsupported() -> Document { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; @@ -665,7 +665,7 @@ fn paths(nodes: &[Arc], out: &mut Vec) { fn art_the_slice_does_not_cover_is_written_as_plain_paths() { let doc = unsupported(); let out = export_ai_editing(&doc, &opts()).unwrap(); - for w in [writer::GRADIENTS, writer::IMAGES, writer::TYPE, writer::LIVE] { + for w in [writer::TYPE, writer::LIVE] { assert!(out.warnings.iter().any(|x| x == w), "{w}: {:?}", out.warnings); } let back = read_back(&doc); @@ -676,17 +676,19 @@ fn art_the_slice_does_not_cover_is_written_as_plain_paths() { NodeKind::Path { .. } => "path", NodeKind::Group { .. } => "group", NodeKind::Compound { .. } => "compound", + NodeKind::Image(_) => "image", _ => "other", }) .collect(); - assert_eq!(kinds, ["path", "compound", "path", "group", "group"]); + assert_eq!(kinds, ["path", "compound", "image", "group", "group"]); let mut all = vec![]; - paths(layer, &mut all); + paths(&layer[3..], &mut all); assert!(all.iter().all(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }))); - // The gradient as its average color. - assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); - // The image's outline filled with its pixels' average. - assert_eq!(paint(layer[2].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.0, 0.5)))); + // The gradient as a gradient, drawing as it did. + let bounds = Rect::new(10.0, 10.0, 30.0, 30.0); + let original = doc.layers[0].children().unwrap()[0].appearance.items[0].paint(); + assert_eq!(drawn(&back, layer[0].appearance.items[0].paint(), bounds), drawn(&doc, original, bounds)); + // The image as an image. assert_eq!(layer[2].visual_bounds().map(|b| (r3(b.x0), r3(b.y0), r3(b.x1), r3(b.y1))), Some((r3(100.0), r3(10.0), r3(120.0), r3(20.0)))); } @@ -914,11 +916,10 @@ fn an_adjusted_image_in_a_symbol_is_written_in_its_adjusted_color() { let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Picture".into(), xf: Affine::translate((50.0, 20.0)) }); doc.insert(Some(layer), usize::MAX, instance).unwrap(); let back = read_back(&doc); - let mut all = vec![]; - paths(back.layers[0].children().unwrap(), &mut all); - let fill = paint(all[0].appearance.items[0].paint()); - assert_ne!(fill, paint(&solid(Color::gray(0.5))), "the adjusted image is found"); - assert_ne!(fill, paint(&solid(Color::rgb(0.0, 0.0, 0.0))), "the image is adjusted"); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert_eq!(found.len(), 1, "the adjusted image is found"); + assert!(!found[0].ends_with("rgba [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]"), "the image is adjusted: {found:?}"); } #[test] @@ -937,19 +938,24 @@ fn a_group_fill_in_a_pattern_tile_is_written() { doc.insert(Some(layer), usize::MAX, filled).unwrap(); let back = read_back(&doc); let mut all = vec![]; - paths(back.layers[0].children().unwrap(), &mut all); + paths(&back.pattern("Dots").unwrap().art, &mut all); let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); - assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "the tiles keep their group's fill"); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "the tile keeps its group's fill"); } -/// A pattern fill that would place more tiles than a fill places is written as the shape filled -/// gray, as a pattern that isn't found is, instead of as nothing. +/// A pattern fill written as its tiles (its tiles aren't a grid) that would place more tiles than +/// a fill places is written as the shape filled gray, as a pattern that isn't found is, instead of +/// as nothing. #[test] fn a_pattern_fill_of_too_many_tiles_is_written_gray() { let mut doc = Document::new(1200.0, 1200.0); let layer = doc.layers[0].id; let dot = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 0.5, 0.5)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); - let tiny = vectorcraft_doc::PatternDef { tile: Rect::new(0.0, 0.0, 1.0, 1.0), ..vectorcraft_doc::PatternDef::new("Tiny", vec![Arc::new(dot)]) }; + let tiny = vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 1.0, 1.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Tiny", vec![Arc::new(dot)]) + }; doc.patterns.push(tiny); let filled = Node::path( doc.alloc_id(), @@ -978,6 +984,24 @@ fn artboard_display_marks_are_written() { assert!(ab.show_center_mark && !ab.show_cross_hairs && ab.show_video_safe_areas); } +/// A guide is its path followed by `(n) *` (closed) or `(N) *` (open), with no `(N) *` before +/// it, and reads back as the same guide. +#[test] +fn guides_are_their_path_then_the_guide_operator() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let line = shapes::line(vectorcraft_geom::Point::new(10.0, 80.0), vectorcraft_geom::Point::new(150.0, 80.0)); + for path in [shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), line] { + let g = Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + } + let p = program(&doc); + let (closed, open) = (p.matches("\n(n) *\n").count(), p.matches("\n(N) *\n").count()); + assert_eq!((closed, open), (1, 1), "{p}"); + assert!(p.contains("0 Xw\n10 -10 m\n") && p.contains("10 -10 L\n(n) *\n10 -80 m\n150 -80 L\n(N) *\nLB\n"), "{p}"); + assert_eq!(lines(&read_back(&doc)), lines(&doc)); +} + #[test] fn effects_on_a_fill_are_reported_left_out() { let mut doc = Document::new(200.0, 100.0); @@ -992,26 +1016,15 @@ fn effects_on_a_fill_are_reported_left_out() { } #[test] -fn images_too_large_to_average_are_mid_gray() { +fn images_of_more_pixels_than_the_reader_reads_are_mid_gray() { let mut png = vec![]; - image::GrayImage::new(5000, 4000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - assert_eq!(image_average_of(&png), paint(&solid(Color::gray(0.5)))); - let mut small = vec![]; - image::GrayImage::new(50, 40).write_to(&mut std::io::Cursor::new(&mut small), image::ImageFormat::Png).unwrap(); - assert_eq!(image_average_of(&small), paint(&solid(Color::rgb(0.0, 0.0, 0.0)))); -} - -/// The fill an image of `png` is written with, as the reader reads it. -fn image_average_of(png: &[u8]) -> String { + image::GrayImage::new(6000, 6000).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; - let blob = ImageBlob::new("image/png", png.to_vec()); - let key = blob.content_key(); - doc.images.insert(key.clone(), blob); - let im = ImageObject { key, width: 10, height: 10, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; - let im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + let im = image_node(&mut doc, ImageBlob::png(png), (10, 10), Affine::IDENTITY, None); doc.insert(Some(layer), usize::MAX, im).unwrap(); - paint(read_back(&doc).layers[0].children().unwrap()[0].appearance.items[0].paint()) + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::IMAGES]); + assert_eq!(paint(read_back(&doc).layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); } #[test] @@ -1368,11 +1381,9 @@ fn a_clipping_paths_other_paint_keeps_its_opacity() { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); - let g = Gradient::new( - GradientKind::Linear, - vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], - ); - clip.appearance = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0).into(); + // Two fills: a path paints one. + let fills = [Color::rgb(0.5, 0.5, 0.5), Color::rgb(1.0, 0.0, 0.0)].map(|c| AppearanceItem::Fill(FillLayer::new(solid(c)))); + clip.appearance = Appearance { items: fills.to_vec(), ..Appearance::default() }.into(); clip.opacity = 0.5; let inside = square(&mut doc, Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(0.0, 0.0, 1.0)); let g = group(&mut doc, vec![clip, inside], true); @@ -1391,21 +1402,42 @@ fn a_clipping_paths_other_paint_keeps_its_opacity() { let out = export_ai_editing(&masked, &opts()).unwrap(); assert!(out.warnings.iter().any(|w| w == writer::CLIP_PAINT_MASKS), "{:?}", out.warnings); // Two fills at the clipping path's 50% are a group at 50% of the two at 100%, as the canvas - // draws them together. - let mut two = doc.clone(); - if let Some(c) = Arc::make_mut(&mut two.layers[0]).children_mut() - && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) - { - let clip = Arc::make_mut(&mut children[0]); - let mut items = clip.appearance.items.clone(); - items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(1.0, 0.0, 0.0))))); - clip.appearance = Appearance { items, ..Appearance::default() }.into(); - } - let back = read_back(&two); + // draws them together, under the art. + let back = read_back(&doc); let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; let fills = &children[1]; assert!(matches!(fills.kind, NodeKind::Group { clip: false, .. }) && fills.opacity == 0.5, "{fills:?}"); assert_eq!(fills.children().unwrap().iter().map(|c| c.opacity).collect::>(), [1.0, 1.0]); + let colors: Vec = fills.children().unwrap().iter().map(|c| paint(c.appearance.items[0].paint())).collect(); + assert_eq!(colors, [paint(&solid(Color::rgb(0.5, 0.5, 0.5))), paint(&solid(Color::rgb(1.0, 0.0, 0.0)))]); + assert!(matches!(children[2].kind, NodeKind::Path { .. }) && children.len() == 3, "the art over the fills"); + // One fill a path can't paint (a brick pattern, written as its tiles) is written under the art + // at the clipping path's opacity. + let mut brick = doc.clone(); + let dot = square(&mut brick, Rect::new(0.0, 0.0, 2.0, 2.0), Color::rgb(1.0, 0.0, 0.0)); + brick.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 4.0, 4.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Brick", vec![Arc::new(dot)]) + }); + if let Some(c) = Arc::make_mut(&mut brick.layers[0]).children_mut() + && let Some(NodeKind::Group { children, .. }) = c.first_mut().map(|g| &mut Arc::make_mut(g).kind) + { + let fill = Paint::Pattern { pattern: "Brick".into(), xf: Affine::IDENTITY }; + Arc::make_mut(&mut children[0]).appearance = Appearance::basic(fill, Paint::None, 0.0).into(); + } + let out = export_ai_editing(&brick, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS) && out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + let back = read_back(&brick); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + assert_eq!(children.len(), 3, "the clipping path, its fill, the art"); + assert_eq!(children[1].opacity, 0.5); + let mut tiles = vec![]; + paths(std::slice::from_ref(&children[1]), &mut tiles); + let painted: Vec<&Node> = tiles.iter().filter(|t| !t.appearance.items.is_empty()).collect(); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(!painted.is_empty() && painted.iter().all(|t| t.opacity == 1.0 && paint(t.appearance.items[0].paint()) == red), "{painted:?}"); + assert_eq!(paint(children[2].appearance.items[0].paint()), paint(&solid(Color::rgb(0.0, 0.0, 1.0))), "the art over the fill"); // A locked clipping path's fill is locked too, the art it clips not. let mut locked = doc.clone(); if let Some(c) = Arc::make_mut(&mut locked.layers[0]).children_mut() @@ -1416,12 +1448,6 @@ fn a_clipping_paths_other_paint_keeps_its_opacity() { let back = read_back(&locked); let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; assert_eq!(children.iter().map(|c| c.locked).collect::>(), [true, true, false]); - let back = read_back(&doc); - let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; - // The clipping path, its fill as a path under the art, the art. - let fill = &children[1]; - assert!(matches!(fill.kind, NodeKind::Path { clipping: false, .. })); - assert_eq!((fill.opacity, paint(fill.appearance.items[0].paint())), (0.5, paint(&solid(Color::rgb(0.5, 0.5, 0.5))))); } /// A clipping path's stroke that a plain line can't draw goes over the clipped art, its fill under it. @@ -1430,14 +1456,10 @@ fn a_clipping_paths_other_stroke_goes_over_the_art() { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; let mut clip = clipping(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0))); - let g = Gradient::new( - GradientKind::Linear, - vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))], - ); let mut stroke = StrokeLayer::new(solid(Color::rgb(1.0, 0.0, 0.0)), 4.0); stroke.dash = Some(Dash { pattern: vec![2.0, 2.0], offset: 0.0, align_corners: true }); clip.appearance = Appearance { - items: vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(g))))), AppearanceItem::Stroke(stroke)], + items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.5, 0.5, 0.5)))), AppearanceItem::Stroke(stroke)], ..Appearance::default() } .into(); @@ -1447,7 +1469,7 @@ fn a_clipping_paths_other_stroke_goes_over_the_art() { let back = read_back(&doc); let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; let colors: Vec = children.iter().skip(1).map(|c| paint(c.appearance.items.first().map_or(&Paint::None, |i| i.paint()))).collect(); - // The fill (its average) under the blue art, the red stroke's dots over it. + // The fill under the blue art, the red stroke's dots over it. assert_eq!(colors.first(), Some(&paint(&solid(Color::rgb(0.5, 0.5, 0.5)))), "{colors:?}"); assert_eq!(colors.get(1), Some(&paint(&solid(Color::rgb(0.0, 0.0, 1.0)))), "{colors:?}"); assert!(colors.len() > 2 && colors.iter().skip(2).all(|c| *c == paint(&solid(Color::rgb(1.0, 0.0, 0.0)))), "{colors:?}"); @@ -1674,3 +1696,1351 @@ fn transparency_of_single_fills_and_layer_masks_is_reported_left_out() { let out = export_ai_editing(&doc, &opts()).unwrap(); assert!(out.warnings.iter().any(|x| x == writer::ITEM_TRANSPARENCY), "{:?}", out.warnings); } + +// ---------- gradients and patterns ---------- + +const INK: Color = Color::Cmyk { c: 0.0, m: 0.6, y: 1.0, k: 0.0 }; + +/// A gradient of `kind` through `stops` (offset, color, opacity, midpoint). +fn ramp(kind: GradientKind, stops: &[(f32, Color, f32, f32)]) -> Gradient { + let stops = + stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect(); + Gradient::new(kind, stops) +} + +/// The three-stop linear gradient of the `Sunset` swatch: its middle stop half opaque, its first +/// midpoint at 30%. +fn sunset() -> Gradient { + ramp( + GradientKind::Linear, + &[(0.0, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.3), (0.4, Color::rgb(0.0, 1.0, 0.0), 0.5, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)], + ) +} + +fn gradient_paint(g: Gradient, geom: Option, swatch: Option<&str>) -> Paint { + Paint::Gradient(Box::new(GradientPaint { geom, swatch: swatch.map(Into::into), ..GradientPaint::new(g) })) +} + +fn painted(doc: &mut Document, path: PathData, items: Vec) -> Node { + Node::path(doc.alloc_id(), path, Appearance { items, ..Appearance::default() }) +} + +/// A 300 × 200 document of gradients and patterns. Swatches: the linear gradient `Sunset`, the radial +/// gradient `Glow` that nothing uses, the spot color `Ink`, the pattern `Dots` (a 10-point grid tile of +/// a red square and a circle filled with a gradient) and `Checks`, which nothing uses. Art, bottom +/// first: a rectangle filled with `Sunset` +/// placed at 30° over part of it and stroked black; an ellipse filled with a radial gradient half as +/// high as wide whose focal point is off its center; a rectangle filled yellow and stroked with a +/// gradient; one filled and stroked with gradients; an even-odd compound path filled with a +/// gradient; an open path filled with a gradient; a rectangle filled with a gradient of a gray, a +/// CMYK color and `Ink` at 70%; a rectangle filled with `Dots` turned, scaled and moved; and a +/// rectangle stroked 8 points with `Dots`. +fn gradients_and_patterns() -> Document { + use vectorcraft_color::gradient::GradientGeom; + let mut doc = Document::new(300.0, 200.0); + let glow = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.1, 0.2, 0.8), 1.0, 0.5)]); + let two = ramp(GradientKind::Linear, &[(0.0, Color::rgb(1.0, 1.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + // The pattern art. + let red = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + let ball = painted( + &mut doc, + shapes::ellipse(Rect::new(5.0, 5.0, 9.0, 9.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(two.clone(), None, None)))], + ); + let mut dots = vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(red), Arc::new(ball)]); + dots.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut checks = vectorcraft_doc::PatternDef::new("Checks", vec![Arc::new(check)]); + checks.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.extend([dots, checks]); + let swatch = |name: &str, paint: Paint, spot: bool| Swatch { name: name.into(), paint, global: spot, spot }; + let mut swatches: Vec = doc.swatches.iter().filter(|s| matches!(s.paint, Paint::None)).cloned().collect(); + swatches.extend([ + swatch("Sunset", gradient_paint(sunset(), None, None), false), + swatch("Glow", gradient_paint(glow.clone(), None, None), false), + swatch("Ink", solid(INK), true), + swatch("Dots", Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, false), + swatch("Checks", Paint::Pattern { pattern: "Checks".into(), xf: Affine::IDENTITY }, false), + ]); + doc.swatches = swatches.into(); + doc.swatch_groups = Default::default(); + let layer = doc.layers[0].id; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w)); + let placed = GradientGeom { start: (20.0, 40.0).into(), end: (60.0, 17.0).into(), aspect: 1.0, focal: None }; + let mut oval = GradientGeom { start: (140.0, 30.0).into(), end: (180.0, 30.0).into(), aspect: 0.5, focal: None }; + oval.set_focal(Some((150.0, 25.0).into())); + let mut nodes = vec![ + painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![fill(gradient_paint(sunset(), Some(placed), Some("Sunset"))), stroke(solid(Color::BLACK), 2.0)], + ), + painted(&mut doc, shapes::ellipse(Rect::new(100.0, 10.0, 180.0, 50.0)), vec![fill(gradient_paint(glow.clone(), Some(oval), None))]), + painted( + &mut doc, + shapes::rectangle(Rect::new(190.0, 10.0, 280.0, 50.0)), + vec![fill(solid(Color::rgb(1.0, 1.0, 0.0))), stroke(gradient_paint(two.clone(), None, None), 6.0)], + ), + painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 110.0)), + vec![fill(gradient_paint(sunset(), None, Some("Sunset"))), stroke(gradient_paint(two.clone(), None, None), 6.0)], + ), + ]; + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 70.0, 180.0, 110.0)), Appearance::default()); + let hole = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(120.0, 80.0, 160.0, 100.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance { items: vec![fill(gradient_paint(two.clone(), None, None))], ..Appearance::default() }.into(); + nodes.push(ring); + let mut open = shapes::line((190.0, 110.0).into(), (280.0, 70.0).into()); + if let Some(sp) = open.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((200.0, 70.0).into())); + sp.closed = false; + } + nodes.push(painted(&mut doc, open, vec![fill(gradient_paint(two, None, None))])); + let mixed = ramp( + GradientKind::Linear, + &[(0.0, Color::gray(0.2), 1.0, 0.5), (0.5, Color::cmyk(1.0, 0.0, 0.0, 0.0), 1.0, 0.5), (1.0, INK.tinted(0.7), 1.0, 0.5)], + ); + let mut mixed_paint = gradient_paint(mixed, None, None); + if let Paint::Gradient(g) = &mut mixed_paint + && let Some(s) = g.gradient.stops.last_mut() + { + s.set_color(INK.tinted(0.7), Some(("Ink".into(), 0.7))); + } + nodes.push(painted(&mut doc, shapes::rectangle(Rect::new(10.0, 130.0, 90.0, 170.0)), vec![fill(mixed_paint)])); + let turned = Affine::translate((103.0, 127.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(0.5); + nodes.push(painted( + &mut doc, + shapes::rectangle(Rect::new(100.0, 130.0, 180.0, 170.0)), + vec![fill(Paint::Pattern { pattern: "Dots".into(), xf: turned })], + )); + nodes.push(painted( + &mut doc, + shapes::rectangle(Rect::new(195.0, 135.0, 235.0, 165.0)), + vec![stroke(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 8.0)], + )); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// A gradient paint's swatch link in `doc`: the gradient swatch it names, `-` for none, and +/// `not a gradient swatch: name` when it names a swatch of other paint. A link that names no swatch +/// of `doc` at all is `-` too: the reader links every gradient instance to its definition's name, +/// and a definition of a gradient that isn't a swatch has a name no swatch has. +fn link(doc: &Document, swatch: &Option) -> String { + match swatch.as_deref().map(|s| (s, doc.swatch(s))) { + Some((s, Some(w))) if matches!(w.paint, Paint::Gradient(_)) => s.to_string(), + Some((s, Some(_))) => format!("not a gradient swatch: {s}"), + Some((_, None)) | None => "-".into(), + } +} + +/// Paint `p` as it draws on `bounds`: a gradient by its kind, stops (place, color, opacity, +/// midpoint, link) and its parameter at the corners, edge midpoints and center of `bounds`; a +/// pattern by its name and matrix. +fn drawn(doc: &Document, p: &Paint, bounds: Rect) -> String { + match p { + Paint::Gradient(g) => { + let geom = g.resolve(bounds); + let stops: Vec = g + .gradient + .stops + .iter() + .map(|s| { + format!( + "{} {} {} {} {:?}", + r3(f64::from(s.offset)), + color(&s.color), + r3(f64::from(s.opacity)), + r3(f64::from(s.midpoint)), + s.swatch + ) + }) + .collect(); + let (x, y) = ([bounds.x0, bounds.center().x, bounds.x1], [bounds.y0, bounds.center().y, bounds.y1]); + let at: Vec = + x.iter().flat_map(|x| y.iter().map(move |y| (*x, *y))).map(|(x, y)| r3(geom.param_at(g.gradient.kind, (x, y).into()))).collect(); + format!("{:?} [{}] link={} at {}", g.gradient.kind, stops.join(", "), link(doc, &g.swatch), at.join(" ")) + } + Paint::Pattern { pattern, xf } => format!("pattern {pattern} {:?}", xf.as_coeffs().map(r3)), + other => paint(other), + } +} + +/// What each object of `nodes` draws: its kind, bounds and paint. +fn paints_of(doc: &Document, nodes: &[Arc], depth: usize, out: &mut Vec) { + for n in nodes { + let bounds = n.geometric_bounds().unwrap_or(Rect::ZERO); + let mut s = format!("{depth} {} {:?}", n.kind_label(), [bounds.x0, bounds.y0, bounds.x1, bounds.y1].map(r3)); + // Items that paint nothing aren't written. + for it in n.appearance.items.iter().filter(|i| !i.paint().is_none()) { + s += &match it { + AppearanceItem::Fill(f) => format!(" fill({})", drawn(doc, &f.paint, bounds)), + AppearanceItem::Stroke(st) => format!(" stroke({} w={})", drawn(doc, &st.paint, st.paint_bounds(bounds)), r3(st.width)), + }; + } + out.push(s); + // A compound path's paint is its own, not its members'. + if !matches!(n.kind, NodeKind::Compound { .. }) { + paints_of(doc, n.children().map(Vec::as_slice).unwrap_or_default(), depth + 1, out); + } + } +} + +/// What `doc`'s art, patterns and gradient and pattern swatches draw. +fn gradient_looks(doc: &Document) -> Vec { + let mut out = vec![]; + paints_of(doc, &doc.layers, 0, &mut out); + for p in doc.patterns.iter() { + out.push(format!("pattern {} tile {:?}", p.name, [p.tile.x0, p.tile.y0, p.tile.x1, p.tile.y1].map(r3))); + paints_of(doc, &p.art, 1, &mut out); + } + for s in doc.swatches_iter() { + match &s.paint { + Paint::Gradient(g) => { + out.push(format!("swatch {} {}", s.name, drawn(doc, &Paint::Gradient(Box::new(GradientPaint::new(g.gradient.clone()))), Rect::ZERO))) + } + Paint::Pattern { pattern, .. } => out.push(format!("swatch {} pattern {pattern}", s.name)), + _ => {} + } + } + out +} + +#[test] +fn gradients_and_patterns_are_read_back() { + let doc = gradients_and_patterns(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +#[test] +fn gradients_and_patterns_write_the_same_bytes_again() { + let doc = gradients_and_patterns(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap(); + same_lines( + &String::from_utf8(again.program).unwrap().lines().map(str::to_string).collect::>(), + &String::from_utf8(first.program).unwrap().lines().map(str::to_string).collect::>(), + ); +} + +#[test] +fn gradients_and_patterns_are_written_in_their_forms() { + let text = program(&gradients_and_patterns()); + // The gradients the art uses, then the one only the palette uses; then the patterns. + let setup = text.split("%%BeginSetup\n").nth(1).and_then(|s| s.split("%AI5_BeginPalette").next()).unwrap(); + let markers: Vec<&str> = setup.lines().filter(|l| l.starts_with("%AI") || l.ends_with(" Bn")).collect(); + assert_eq!( + markers, + [ + "4 Bn", + "%AI5_BeginGradient: (Sunset)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient 2)", + "%AI5_EndGradient", + "%AI5_BeginGradient: (Gradient 3)", + "%AI5_EndGradient", + "%AI5_Begin_NonPrinting", + "1 Bn", + "%AI5_BeginGradient: (Glow)", + "%AI5_EndGradient", + "%AI5_End_NonPrinting--", + "%AI3_BeginPattern: (Dots)", + "%AI3_EndPattern", + "%AI5_Begin_NonPrinting", + "%AI3_BeginPattern: (Checks)", + "%AI3_EndPattern", + "%AI5_End_NonPrinting--", + ] + ); + // A linear gradient's stops from the last; RGB with its CMYK equivalent, style 2, opacity, 6, + // midpoint, place on the ramp. + assert!(text.contains("(Sunset) 0 3 Bd\n[\n%_"), "{setup}"); + assert!( + setup.contains(" 0 0 1 2 1 6 50 100 Bs\n") && setup.contains(" 0 1 0 2 0.5 6 50 40 Bs\n") && setup.contains(" 1 0 0 2 1 6 30 0 Bs\n"), + "{setup}" + ); + // Gray, CMYK, and a spot color at 70%. + assert!( + setup.contains("%_0.8 0 1 6 50 0 Bs\n%_1 0 0 0 1 1 6 50 50 Bs\n") + || setup.contains("(Ink) 0.3 3 1 6 50 100 Bs\n%_1 0 0 0 1 1 6 50 50 Bs\n%_0.8 0 1 6 50 0 Bs\n"), + "{setup}" + ); + // The tile in the pattern's space, y up, the art on `%_` lines. + assert!(setup.contains("%AI3_BeginPattern: (Dots)\n(Dots) 0 -10 10 0\n%_"), "{setup}"); + assert!(!setup.contains("%_E\n") && setup.contains("\nE\n%AI3_EndPattern\n"), "{setup}"); + // The swatches. + assert!(text.contains("Bb\n2 (Sunset) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sunset) Pc\n"), "{text}"); + assert!(text.contains("Bb\n0 0 0 0 Bh\n2 (Glow) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Glow) Pc\n"), "{text}"); + assert!(text.contains("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots) Pc\n"), "{text}"); + // The instances: the stroked rectangle's fill placed at 29.9° from 0.15 of the rectangle's extent + // that way, 0.52 of it long, with `Xm`, caps and a `Bm` for each pair of stops, `b` and `2 BB`; the + // stroke's `1 Bb`; the radial's focal point and `Bm`. + let art = text.split("%AI5_BeginLayer").nth(1).unwrap(); + assert!(art.contains("Bb\n1 (Sunset) 0.1529 0 29.8989 0.5167 1 0 0 1 0 0 1 Bg\n") && art.contains(" Xm\n"), "{art}"); + let sunset_instance = art.split("Bb\n1 (Sunset)").nth(1).unwrap(); + let ops: Vec<&str> = sunset_instance.lines().take(7).map(|l| l.rsplit(' ').next().unwrap_or(l)).collect(); + assert_eq!(ops, ["Bg", "Xm", "Bc", "Bm", "Bm", "Bc", "b"], "{sunset_instance}"); + assert!(sunset_instance.contains("\nb\n2 BB\n"), "{sunset_instance}"); + assert!(art.contains("1 Bb\n1 (Gradient 2) "), "{art}"); + assert!(art.contains("2 BB\n1 Bb\n"), "fill and stroke: {art}"); + // The radial (40 wide, 20 high) as the unit circle through its matrix: the focal point 10 right of + // the center and 5 up, at 45° and 0.35 of the radius on that circle. + assert!(art.contains("Bb\n10 5 45 0.3536 Bh\n1 (Gradient) 0 0 0 1 40 0 0 20 0 0 1 Bg\n40 0 0 -20 140 -30 Bm\nf\n0 BB\n"), "{art}"); + // The tile's box first in a pattern's definition. + assert!(setup.contains("(Dots) 0 -10 10 0\n%_0 A\n%_0 Xw\n%_0 XR\n%_0 0 m\n"), "{setup}"); + assert!(setup.contains("%_n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n"), "{setup}"); + assert!(art.contains("F\n0 BB\n"), "the open path: {art}"); + assert!(art.contains(" p\n") && art.contains(" P\n"), "{art}"); +} + +/// A clipping path filled with a gradient keeps it: the reader reads it as the clipping path and +/// its fill as a path of its own under the art. +#[test] +fn a_clipping_path_keeps_its_gradient() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0))); + clip.appearance = Appearance::basic(gradient_paint(sunset(), None, None), Paint::None, 0.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 50.0, 40.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::CLIP_PAINT), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("h\nW\nBb\n0 (Gradient) "), "{text}"); + let back = read_back(&doc); + let NodeKind::Group { children, clip: true } = &back.layers[0].children().unwrap()[0].kind else { panic!("a clipping group") }; + let fill = &children[1]; + let bounds = Rect::new(10.0, 10.0, 90.0, 60.0); + let want = drawn(&doc, &gradient_paint(sunset(), None, None), bounds); + assert_eq!(drawn(&back, fill.appearance.items[0].paint(), bounds), want); +} + +#[test] +fn freeform_gradients_are_written_as_their_average_color() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let g = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + let back = read_back(&doc); + assert_eq!(paint(back.layers[0].children().unwrap()[0].appearance.items[0].paint()), paint(&solid(Color::rgb(0.5, 0.5, 0.5)))); +} + +/// A gradient that dithers or mixes perceptually is written as a classic one; a stop linked to a +/// global process color is written as its color; each with a warning. +#[test] +fn gradient_options_and_links_the_data_cant_hold_are_reported() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut g = sunset(); + g.dither = true; + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_MIX]); + // A swatch of such a gradient that nothing uses. + let mut swatch_only = Document::new(200.0, 100.0); + let mut dithered = sunset(); + dithered.dither = true; + let mut swatches: Vec = swatch_only.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Dithered".into(), paint: gradient_paint(dithered, None, None), global: false, spot: false }); + swatch_only.swatches = swatches.into(); + let out = export_ai_editing(&swatch_only, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENT_MIX), "{:?}", out.warnings); + // A gradient along a stroke: the stroke's outline in its average color. + let mut along = Document::new(200.0, 100.0); + let layer = along.layers[0].id; + let mut st = StrokeLayer::new(gradient_paint(sunset(), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along; + let n = painted(&mut along, shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), vec![AppearanceItem::Stroke(st)]); + along.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&along, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.push(Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false }); + doc.swatches = swatches.into(); + let mut g = sunset(); + g.method = vectorcraft_color::gradient::GradientMethod::Perceptual; + if let Some(s) = g.stops.first_mut() { + s.set_color(BRAND, Some(("Brand".into(), 1.0))); + } + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_MIX, writer::STOP_LINKS]); + let back = read_back(&doc); + let Paint::Gradient(g) = back.layers[0].children().unwrap()[0].appearance.items[0].paint() else { panic!("a gradient") }; + assert_eq!((color(&g.gradient.stops[0].color), g.gradient.stops[0].swatch.as_deref()), (color(&BRAND), None)); +} + +/// A pattern whose art reaches past its tile is written as its tiles cut to the shape: a definition +/// would cut its art off at the tile's edge. +#[test] +fn a_pattern_whose_art_reaches_past_its_tile_is_written_as_its_tiles() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let big = square(&mut doc, Rect::new(-2.0, -2.0, 6.0, 6.0), Color::rgb(1.0, 0.0, 0.0)); + let mut over = vectorcraft_doc::PatternDef::new("Over", vec![Arc::new(big)]); + over.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(over); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Over".into(), xf: Affine::IDENTITY }))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + assert!(!program(&doc).contains("%AI3_BeginPattern")); +} + +/// A pattern fill in another pattern's tile is written there as its tiles cut to the shape; the +/// outer pattern is defined and fills the shape. +#[test] +fn a_pattern_fill_in_a_pattern_tile_is_written_as_its_tiles() { + let mut doc = gradients_and_patterns(); + let layer = doc.layers[0].id; + let inner = painted( + &mut doc, + shapes::rectangle(Rect::new(2.0, 2.0, 18.0, 18.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }))], + ); + let mut nest = vectorcraft_doc::PatternDef::new("Nest", vec![Arc::new(inner)]); + nest.tile = Rect::new(0.0, 0.0, 20.0, 20.0); + doc.patterns.push(nest); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(250.0, 130.0, 290.0, 170.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Nest".into(), xf: Affine::IDENTITY }))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("%AI3_BeginPattern: (Nest)") && text.contains("%AI3_BeginPattern: (Dots)")); + let back = read_back(&doc); + let filled = back.layers[0].children().unwrap().last().unwrap(); + assert!(matches!(filled.appearance.items[0].paint(), Paint::Pattern { pattern, .. } if pattern == "Nest")); + // Nest's tile: the dots' tiles (a red square, a gradient circle) cut to its square. + let mut all = vec![]; + paths(&back.pattern("Nest").unwrap().art, &mut all); + assert!(all.len() > 2, "{}", all.len()); + assert!(all.iter().all(|p| !matches!(p.appearance.items[0].paint(), Paint::Pattern { .. }))); + assert!(all.iter().any(|p| paint(p.appearance.items[0].paint()) == paint(&solid(Color::rgb(1.0, 0.0, 0.0))))); +} + +/// A 200 × 100 document with one object of `items` on `path`, and only the None swatch. +fn one_object(path: PathData, items: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + doc.swatches = doc.swatches.iter().filter(|s| matches!(s.paint, Paint::None)).cloned().collect::>().into(); + doc.swatch_groups = Default::default(); + let layer = doc.layers[0].id; + let n = painted(&mut doc, path, items); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// What `doc`'s art draws (a palette of only the None swatch reads back as the default swatches). +fn art_looks(doc: &Document) -> Vec { + let mut out = vec![]; + paints_of(doc, &doc.layers, 0, &mut out); + out +} + +fn swatches_plus(doc: &mut Document, more: Vec) { + let mut swatches: Vec = doc.swatches.iter().cloned().collect(); + swatches.extend(more); + doc.swatches = swatches.into(); +} + +/// `Bg` places each gradient on its path: a radial one 30 right of and 10 above the middle of a +/// 120 × 60 rectangle, 20 in radius, by its unit circle's matrix, its center's place as fractions of +/// the bounds and its radius as a multiple of √((1.5² + 2²) / 2) (the center's distances to the +/// right side and to the bottom in that circle's units); and a linear one at −45° on a triangle, +/// from a quarter of the triangle's extent that way, half of it long. In a pattern's tile the same +/// two are placed mirrored top to bottom: the radial's center 10 below the middle, its radius a +/// multiple of √((1.5² + 1²) / 2), and the linear one at 45°. +#[test] +fn bg_places_gradients_on_their_paths() { + use vectorcraft_color::gradient::GradientGeom; + let radial = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)]); + let off_center = GradientGeom { start: (90.0, 20.0).into(), end: (110.0, 20.0).into(), aspect: 1.0, focal: None }; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let mut doc = one_object(shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 60.0)), vec![fill(gradient_paint(radial.clone(), Some(off_center), None))]); + let layer = doc.layers[0].id; + let mut triangle = shapes::line((130.0, 10.0).into(), (190.0, 10.0).into()); + if let Some(sp) = triangle.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((130.0, 40.0).into())); + sp.closed = true; + } + let turned = GradientGeom { start: (145.0, 10.0).into(), end: (160.0, 25.0).into(), aspect: 1.0, focal: None }; + let n = painted(&mut doc, triangle.clone(), vec![fill(gradient_paint(sunset(), Some(turned), None))]); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let in_tile = painted(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 120.0, 60.0)), vec![fill(gradient_paint(radial, Some(off_center), None))]); + let slant = painted(&mut doc, triangle, vec![fill(gradient_paint(sunset(), Some(turned), None))]); + let mut tile = vectorcraft_doc::PatternDef::new("Tile", vec![Arc::new(in_tile), Arc::new(slant)]); + tile.tile = Rect::new(0.0, 0.0, 200.0, 60.0); + doc.patterns.push(tile); + swatches_plus( + &mut doc, + vec![Swatch { name: "Tile".into(), paint: Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }, global: false, spot: false }], + ); + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(130.0, 50.0, 190.0, 90.0)), + vec![fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY })], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + let art = text.split("%AI5_BeginLayer").nth(1).unwrap(); + assert!(art.contains("Bb\n0 0 0 0 Bh\n1 (Gradient) 0.25 -0.1667 0 0.5657 20 0 0 20 0 0 1 Bg\n"), "{art}"); + assert!(art.contains("Bb\n1 (Gradient 2) 0.25 0 -45 0.5 1 0 0 1 0 0 1 Bg\n"), "{art}"); + let setup = text.split("%AI3_BeginPattern: (Tile)").nth(1).unwrap(); + assert!(setup.contains("%_Bb\n%_0 0 0 0 Bh\n%_1 (Gradient) 0.25 0.1667 0 0.7845 20 0 0 20 0 0 1 Bg\n"), "{setup}"); + assert!(setup.contains("%_Bb\n%_1 (Gradient 2) 0.25 0 45 0.5 1 0 0 1 0 0 1 Bg\n"), "{setup}"); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// A definition of a gradient that isn't a swatch takes a name that no swatch and no pattern has, +/// so that its instances don't read back linked to another swatch. +#[test] +fn gradient_definitions_skip_the_names_of_swatches_and_patterns() { + let mut doc = gradients_and_patterns(); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut taken = vectorcraft_doc::PatternDef::new("Gradient 2", vec![Arc::new(check)]); + taken.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(taken); + swatches_plus( + &mut doc, + vec![ + Swatch { name: "Gradient".into(), paint: solid(Color::rgb(0.0, 0.5, 0.0)), global: false, spot: false }, + Swatch { + name: "Gradient 2".into(), + paint: Paint::Pattern { pattern: "Gradient 2".into(), xf: Affine::IDENTITY }, + global: false, + spot: false, + }, + ], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + assert_eq!(names, ["(Sunset)", "(Gradient 3)", "(Gradient 4)", "(Gradient 5)", "(Glow)"]); + same_lines(&gradient_looks(&read_back(&doc)), &gradient_looks(&doc)); +} + +/// Each search for a new gradient name starts after the last name given, so naming many gradients +/// tries each name once. +#[test] +fn gradient_names_are_searched_from_the_last_one_given() { + let mut taken: std::collections::HashSet = ["Gradient 2", "Gradient 5"].map(String::from).into(); + let (mut next, mut tries) = (1, 0); + let mut names = vec![]; + for _ in 0..1000 { + let name = writer::free_gradient_name(&mut next, |name| { + tries += 1; + taken.contains(name) + }); + taken.insert(name.clone()); + names.push(name); + } + assert_eq!(names[..4], ["Gradient", "Gradient 3", "Gradient 4", "Gradient 6"]); + assert_eq!(names.last().map(String::as_str), Some("Gradient 1002")); + assert_eq!(tries, 1002); + assert_eq!(next, 1003); +} + +/// Many gradients that no swatch names each get their own name, in order, skipping the names of +/// swatches and patterns, and the same names when the document is written again. +#[test] +fn many_gradient_definitions_take_distinct_names_in_order() { + let mut doc = one_object(shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), vec![]); + let check = square(&mut doc, Rect::new(0.0, 0.0, 5.0, 5.0), Color::BLACK); + let mut taken = vectorcraft_doc::PatternDef::new("Gradient 7", vec![Arc::new(check)]); + taken.tile = Rect::new(0.0, 0.0, 10.0, 10.0); + doc.patterns.push(taken); + swatches_plus(&mut doc, vec![Swatch { name: "Gradient 3".into(), paint: solid(Color::rgb(0.0, 0.5, 0.0)), global: false, spot: false }]); + let layer = doc.layers[0].id; + for i in 0..300u16 { + let shade = f32::from(i) / 300.0; + let g = ramp(GradientKind::Linear, &[(0.0, Color::rgb(shade, 0.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.5)]); + let x = f64::from(i % 20) * 10.0; + let y = f64::from(i / 20) * 6.0; + let n = painted( + &mut doc, + shapes::rectangle(Rect::new(x, y, x + 8.0, y + 5.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(g, None, None)))], + ); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let text = program(&doc); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + let expected: Vec = + std::iter::once("(Gradient)".to_string()).chain((2..=302).filter(|&i| i != 3 && i != 7).map(|i| format!("(Gradient {i})"))).collect(); + assert_eq!(names, expected); + assert_eq!(text, program(&doc)); +} + +/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, +/// and reads back with each stop on its side. +#[test] +fn a_linear_gradient_with_every_stop_at_one_place_keeps_its_sides() { + let edge = ramp(GradientKind::Linear, &[(0.3, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.4), (0.3, Color::rgb(0.0, 0.0, 1.0), 1.0, 0.7)]); + let doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(edge, None, None)))], + ); + let text = program(&doc); + let (blue, red) = (text.find(" 0 0 1 2 1 6 70 30 Bs\n").unwrap(), text.find(" 1 0 0 2 1 6 40 30 Bs\n").unwrap()); + assert!(blue < red, "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// Gradients without stops or with more than 256, without a ramp's length or flattened to a line +/// are written as their average color with a warning that says so, not the one for freeform +/// gradients. +#[test] +fn gradients_that_cant_be_placed_are_reported_as_such() { + use vectorcraft_color::gradient::GradientGeom; + let point = GradientGeom { start: (20.0, 20.0).into(), end: (20.0, 20.0).into(), aspect: 1.0, focal: None }; + let flat = GradientGeom { start: (20.0, 20.0).into(), end: (40.0, 20.0).into(), aspect: 0.0, focal: None }; + let radial = ramp(GradientKind::Radial, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + // More stops than the `.ai` reader reads. + let many: Vec<(f32, Color, f32, f32)> = (0..257).map(|i| (i as f32 / 256.0, Color::gray(i as f32 / 256.0), 1.0, 0.5)).collect(); + for p in [ + gradient_paint(sunset(), Some(point), None), + gradient_paint(radial, Some(flat), None), + gradient_paint(Gradient::new(GradientKind::Linear, vec![]), None, None), + gradient_paint(ramp(GradientKind::Linear, &many), None, None), + ] { + let doc = one_object(shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), vec![AppearanceItem::Fill(FillLayer::new(p.clone()))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::GRADIENT_SHAPES], "{p:?}"); + let back = read_back(&doc); + assert!(matches!(back.layers[0].children().unwrap()[0].appearance.items[0].paint(), Paint::Solid { .. }), "{p:?}"); + } +} + +/// A gradient across a stroke is written as the stroke's outline in its average color, with the +/// warning. +#[test] +fn a_gradient_across_a_stroke_is_its_average_color() { + let mut st = StrokeLayer::new(gradient_paint(sunset(), None, None), 4.0); + st.gradient_mode = vectorcraft_doc::StrokeGradientMode::Across; + let doc = one_object(shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), vec![AppearanceItem::Stroke(st)]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::GRADIENTS), "{:?}", out.warnings); + assert!(!program(&doc).contains("Bb\n")); + let mut all = vec![]; + paths(read_back(&doc).layers[0].children().unwrap(), &mut all); + assert!(!all.is_empty() && all.iter().all(|p| p.appearance.items.iter().all(|i| matches!(i.paint(), Paint::Solid { .. }))), "{all:?}"); +} + +/// Patterns whose tiles are hexagons or bricks are written as their tiles cut to the shape, with the +/// warning, and aren't defined. +#[test] +fn hex_and_brick_patterns_are_written_as_their_tiles() { + for tile_type in [ + vectorcraft_doc::TileType::HexByRow, + vectorcraft_doc::TileType::HexByColumn, + vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + vectorcraft_doc::TileType::BrickByColumn { offset: 0.5 }, + ] { + let mut doc = one_object( + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + vec![AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: "Cells".into(), xf: Affine::IDENTITY }))], + ); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 10.0, 10.0), + tile_type, + ..vectorcraft_doc::PatternDef::new("Cells", vec![Arc::new(dot)]) + }); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::PATTERNS), "{tile_type:?}: {:?}", out.warnings); + assert!(!program(&doc).contains("%AI3_BeginPattern"), "{tile_type:?}"); + let mut all = vec![]; + paths(read_back(&doc).layers[0].children().unwrap(), &mut all); + let red = paint(&solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(all.iter().any(|p| p.appearance.items.iter().any(|i| paint(i.paint()) == red)), "{tile_type:?}"); + } +} + +/// An open path filled and stroked with gradients: the fill's instance ends `1 BB`, the stroke's +/// `1 Bb` follows, and the open path's `B` ends `1 BB`. +#[test] +fn an_open_path_keeps_its_gradient_fill_and_stroke() { + let two = ramp(GradientKind::Linear, &[(0.0, Color::rgb(1.0, 1.0, 0.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let mut open = shapes::line((20.0, 80.0).into(), (100.0, 20.0).into()); + if let Some(sp) = open.subpaths.first_mut() { + sp.anchors.push(vectorcraft_geom::Anchor::corner((150.0, 70.0).into())); + sp.closed = false; + } + let doc = one_object( + open, + vec![ + AppearanceItem::Fill(FillLayer::new(gradient_paint(sunset(), None, None))), + AppearanceItem::Stroke(StrokeLayer::new(gradient_paint(two, None, None), 3.0)), + ], + ); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("\n1 BB\n1 Bb\n1 (Gradient 2) ") && text.contains("\nB\n1 BB\n"), "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// A clipping path stroked with a gradient keeps it. +#[test] +fn a_clipping_path_keeps_its_gradient_stroke() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut clip = clipping(&mut doc, shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0))); + clip.appearance = Appearance::basic(Paint::None, gradient_paint(sunset(), None, None), 3.0).into(); + let inside = square(&mut doc, Rect::new(0.0, 0.0, 50.0, 40.0), Color::rgb(0.0, 0.0, 1.0)); + let g = group(&mut doc, vec![clip, inside], true); + doc.insert(Some(layer), usize::MAX, g).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("h\nW\n1 Bb\n0 (Gradient) "), "{text}"); + let back = read_back(&doc); + let mut want = vec![]; + paints_of(&doc, doc.layers[0].children().unwrap(), 0, &mut want); + let mut got = vec![]; + paints_of(&back, back.layers[0].children().unwrap(), 0, &mut got); + let strokes = |v: &[String]| { + v.iter().filter(|l| l.contains(" stroke(Linear")).map(|l| l.split(" stroke(").nth(1).unwrap_or_default().to_string()).collect::>() + }; + assert_eq!(strokes(&got), strokes(&want), "{got:#?}"); +} + +/// In a CMYK document the gradient's CMYK stops are written as CMYK and read back the same. +#[test] +fn a_cmyk_documents_gradients_keep_their_stops() { + let cmyk = ramp(GradientKind::Linear, &[(0.0, Color::cmyk(0.0, 0.6, 1.0, 0.0), 1.0, 0.5), (1.0, Color::cmyk(1.0, 0.0, 0.0, 0.2), 0.5, 0.25)]); + let mut doc = one_object( + shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 50.0)), + vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(cmyk, None, None)))], + ); + doc.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let text = program(&doc); + assert!(text.contains("%AI9_ColorModel: 2\n"), "{text}"); + assert!(text.contains("%_1 0 0 0.2 1 0.5 6 25 100 Bs\n%_0 0.6 1 0 1 1 6 50 0 Bs\n"), "{text}"); + same_lines(&art_looks(&read_back(&doc)), &art_looks(&doc)); +} + +/// A compound path's gradient instance is on its last subpath only. +#[test] +fn a_compound_paths_gradient_is_on_its_last_subpath() { + let text = program(&gradients_and_patterns()); + let compound = text.split("*u\n").nth(1).and_then(|s| s.split("*U\n").next()).unwrap(); + assert_eq!(compound.matches("Bb\n").count(), 1, "{compound}"); + let last_subpath = compound.rfind(" m\n").unwrap(); + assert!(compound.find("Bb\n").unwrap() > last_subpath, "{compound}"); + assert_eq!(compound.matches(" m\n").count(), 2, "{compound}"); +} + +/// Freeform gradient swatches and swatches of patterns that can't be defined are left out with the +/// warning; a color group counts only the swatches written. +#[test] +fn swatches_the_data_cant_hold_are_left_out() { + let mut doc = gradients_and_patterns(); + let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0)); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 10.0, 10.0), + tile_type: vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, + ..vectorcraft_doc::PatternDef::new("Brick", vec![Arc::new(dot)]) + }); + let free = ramp(GradientKind::Freeform, &[(0.0, Color::rgb(1.0, 1.0, 1.0), 1.0, 0.5), (1.0, Color::rgb(0.0, 0.0, 0.0), 1.0, 0.5)]); + let swatch = |name: &str, paint: Paint| Swatch { name: name.into(), paint, global: false, spot: false }; + doc.swatch_groups = vec![SwatchGroup { + name: "Mixed".into(), + swatches: vec![ + swatch("Free", gradient_paint(free.clone(), None, None)), + swatch("Dawn", gradient_paint(sunset(), None, None)), + swatch("Brick", Paint::Pattern { pattern: "Brick".into(), xf: Affine::IDENTITY }), + swatch("Dots 2", Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }), + ], + }] + .into(); + swatches_plus(&mut doc, vec![swatch("Free 2", gradient_paint(free, None, None))]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SWATCHES], "{:?}", out.warnings); + let text = program(&doc); + assert!(text.contains("0 (Mixed) 2 Pg\n"), "{text}"); + for name in ["(Free) Pc", "(Free 2) Pc", "(Brick) Pc", "%AI3_BeginPattern: (Brick)"] { + assert!(!text.contains(name), "{name}"); + } + let back = read_back(&doc); + let group = back.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(group.swatches.iter().map(|s| s.name.as_str()).collect::>(), ["Dawn", "Dots 2"]); +} + +/// A pattern swatch that moves, turns or scales its pattern is written with its pattern, and the +/// placement is reported left out. +#[test] +fn a_pattern_swatchs_own_placement_is_reported_left_out() { + let mut doc = gradients_and_patterns(); + let moved = Paint::Pattern { pattern: "Dots".into(), xf: Affine::scale(2.0) }; + swatches_plus(&mut doc, vec![Swatch { name: "Big Dots".into(), paint: moved, global: false, spot: false }]); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SWATCH_PLACEMENT]); + assert!(program(&doc).contains("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Big Dots) Pc\n")); +} + +// ---------- images and placed files ---------- + +/// `img` as PNG bytes. +fn png_of(img: image::DynamicImage) -> Vec { + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + png +} + +/// An image object of `blob`'s pixels (`w` × `h`) placed by `xf`, its blob kept in `doc`. +fn image_node(doc: &mut Document, blob: ImageBlob, (w, h): (u32, u32), xf: Affine, link: Option) -> Node { + let key = blob.content_key(); + doc.images.insert(key.clone(), blob); + let im = ImageObject { key, width: w, height: h, xf, link, placement: Default::default(), pixels: None }; + Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))) +} + +/// A 3 × 2 RGB image, every pixel a different color. +fn rgb_png() -> Vec { + let px = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 255, 255], [12, 34, 56]]; + png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb(px[(y * 3 + x) as usize])))) +} + +/// A 200 × 100 document of images: on a layer `Pictures`, an RGB image `Photo` turned, scaled and +/// moved, at half opacity in Multiply; a locked RGBA image whose pixels are see-through in part; a +/// hidden gray image; a CMYK image; a clipping group of the RGB image cut by a rectangle; a square +/// whose opacity mask is a gray image. On a layer `Links`, a linked image in a folder next to the +/// document's. +fn images_doc() -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let turned = Affine::translate((40.0, 30.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(8.0, 6.0); + let mut photo = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), turned, None); + photo.name = Some("Photo".into()); + photo.opacity = 0.5; + photo.blend = BlendMode::Multiply; + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + let alpha = [0, 128, 255, 200]; + let rgba = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([200, 100, (x * 50) as u8, alpha[(y * 2 + x) as usize]])); + let mut see = image_node(&mut doc, ImageBlob::png(png_of(rgba.into())), (2, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 60.0, 10.0]), None); + see.locked = true; + doc.insert(Some(layer), usize::MAX, see).unwrap(); + let gray = image::GrayImage::from_fn(4, 1, |x, _| image::Luma([(x * 60) as u8])); + let mut gray = image_node(&mut doc, ImageBlob::png(png_of(gray.into())), (4, 1), Affine::new([5.0, 0.0, 0.0, 5.0, 90.0, 60.0]), None); + gray.visible = false; + doc.insert(Some(layer), usize::MAX, gray).unwrap(); + let inks = vectorcraft_doc::cmyk::Inks::new(2, 1, vec![255, 0, 0, 0, 10, 20, 30, 40]).unwrap(); + let cmyk = image_node(&mut doc, ImageBlob::cmyk_tiff(&inks).unwrap(), (2, 1), Affine::new([10.0, 0.0, 0.0, 10.0, 120.0, 10.0]), None); + doc.insert(Some(layer), usize::MAX, cmyk).unwrap(); + let clip = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 170.0, 25.0)), Appearance::default()); + let inside = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 145.0, 5.0]), None); + let group = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(inside)], clip: true }); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let ramp = image::GrayImage::from_fn(3, 3, |x, y| image::Luma([(x * 100 + y * 20) as u8])); + let mask_art = image_node(&mut doc, ImageBlob::png(png_of(ramp.into())), (3, 3), Affine::new([10.0, 0.0, 0.0, 10.0, 10.0, 60.0]), None); + let mut square = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(10.0, 60.0, 40.0, 90.0)), + Appearance::basic(solid(Color::rgb(0.0, 0.5, 1.0)), Paint::None, 0.0), + ); + // A mask's art is read into a group. + let mask_art = Node::group(doc.alloc_id(), vec![Arc::new(mask_art)]); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let links = Node::layer(doc.alloc_id(), "Links", LayerColor::Preset(1)); + let links_id = links.id; + doc.layers.push(Arc::new(links)); + let pic = image::RgbaImage::from_fn(3, 3, |x, y| image::Rgba([(x * 80) as u8, (y * 80) as u8, 30, 255])); + let mut link = vectorcraft_doc::LinkInfo::new("/Users/someone/Job (1)/art/pic.png"); + link.relative = Some("art/pic.png".into()); + let placed = image_node(&mut doc, ImageBlob::png(png_of(pic.into())), (3, 3), Affine::new([4.0, 1.0, -1.0, 4.0, 60.0, 50.0]), Some(link)); + doc.insert(Some(links_id), usize::MAX, placed).unwrap(); + doc +} + +/// Each image in `nodes` (opacity masks' art included), in order: where it is, its state, size, +/// placement, link and pixels (RGBA, or a CMYK image's ink amounts). +fn pictures(doc: &Document, nodes: &[Arc], path: &str, out: &mut Vec) { + for (i, n) in nodes.iter().enumerate() { + let at = format!("{path}/{i}"); + if let NodeKind::Image(im) = &n.kind { + let blob = doc.image_blob(im).unwrap(); + let pixels = match blob.cmyk() { + Some(inks) if blob.is_cmyk() => format!("cmyk {:?}", inks.data), + _ => format!("rgba {:?}", image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw()), + }; + let xf: Vec = im.xf.as_coeffs().iter().map(|v| r3(*v)).collect(); + let link = im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())); + out.push(format!( + "{at} {:?} shown={} locked={} opacity={} {:?} {}x{} [{}] {link:?} {pixels}", + n.name, + n.visible, + n.locked, + r3(f64::from(n.opacity)), + n.blend, + im.width, + im.height, + xf.join(" ") + )); + } + if let Some(m) = &n.extras().mask { + pictures(doc, std::slice::from_ref(&m.art), &format!("{at}/mask"), out); + } + if let Some(c) = n.children() { + pictures(doc, c, &at, out); + } + } +} + +fn images_of(doc: &Document) -> Vec { + let mut out = vec![]; + pictures(doc, &doc.layers, "", &mut out); + out +} + +#[test] +fn images_come_back_with_their_pixels_and_places() { + let doc = images_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + let back = read_back(&doc); + let want = images_of(&doc); + let got = images_of(&back); + assert_eq!(want.len(), 7); + for (g, w) in got.iter().zip(&want) { + assert_eq!(g, w); + } + assert_eq!(got.len(), want.len(), "{got:?}"); + // The clipping group and the masked square are there as themselves. + assert_eq!(lines(&back).len(), lines(&doc).len(), "{:?}", lines(&back)); +} + +#[test] +fn images_are_written_again_as_the_same_bytes() { + let mut doc = images_doc(); + // The default swatches' RGB colors come back a ten-thousandth off in their CMYK equivalents. + doc.swatches.retain(|s| matches!(s.paint, Paint::None)); + doc.swatches.push(Swatch { name: "Gold".into(), paint: solid(GOLD), global: false, spot: false }); + doc.swatch_groups = Default::default(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = export_ai_editing(&read_back(&doc), &opts()).unwrap().program; + for (a, b) in shown(&again).lines().zip(shown(&first.program).lines()) { + assert_eq!(a, b); + } + assert_eq!(again, first.program); +} + +/// The program of `doc` with LF line ends, and each image's samples (from after `XI` and its line +/// end to `%%EndData`, a `%_` before it kept) and each preview's rows (from after `32 17 ` to the +/// line end before `%AI26_EndPlacedObjectPreview`) shown as ``. +fn program_shown(doc: &Document) -> String { + shown(&export_ai_editing(doc, &opts()).unwrap().program) +} + +/// Program `p` as [`program_shown`] shows it. +fn shown(p: &[u8]) -> String { + let find = |from: usize, what: &[u8]| p.get(from..).and_then(|r| r.windows(what.len()).position(|w| w == what)).map(|i| i + from); + let mut out = Vec::new(); + let mut at = 0; + loop { + let xi = find(at, b"\r\nXI\r\n").map(|i| (i + 6, b"%%EndData".as_slice())); + let pv = find(at, b" 32 17 ").map(|i| (i + 7, b"\r\n%AI26_EndPlacedObjectPreview".as_slice())); + let Some((start, end)) = [xi, pv].into_iter().flatten().min_by_key(|(s, _)| *s) else { break }; + let mut stop = find(start, end).unwrap(); + if end.starts_with(b"%%") && p.get(stop - 2..stop) == Some(b"%_") { + stop -= 2; + } + out.extend_from_slice(&p[at..start]); + out.extend_from_slice(format!("<{} bytes>", stop - start).as_bytes()); + at = stop; + } + out.extend_from_slice(&p[at..]); + String::from_utf8(out).unwrap().replace("\r\n", "\n") +} + +#[test] +fn an_image_is_a_raster_with_binary_samples() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 30.0]), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let p = export_ai_editing(&doc, &opts()).unwrap().program; + // `XI`, CR LF and the 18 samples, which are counted, follow the count's line. + let at = p.windows(17).position(|w| w == b"%%BeginData: 22\r\n").unwrap(); + let samples: Vec = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0, 0, 255, 255, 12, 34, 56]; + let mut want = b"XI\r\n".to_vec(); + want.extend_from_slice(&samples); + want.extend_from_slice(b"%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\r\n"); + assert_eq!(p.get(at + 17..at + 17 + want.len()), Some(want.as_slice())); + let text = program_shown(&doc); + // Art space is y up from the artboard's top-left corner, the pixels' rows run downwards. + assert!( + text.contains( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n[10 0 0 10 20 -30] 3 2 0 Xh\n[10 0 0 10 20 -30] 0 0 3 2 3 2 8 3 0 1 1 0 4 4 0 0\n" + ), + "{text}" + ); +} + +#[test] +fn see_through_gray_and_cmyk_images_have_their_flags() { + let doc = images_doc(); + let text = program_shown(&doc); + // RGBA: the alpha channel follows the color samples, which the count doesn't take in. + assert!(text.contains(" 0 0 2 2 2 2 8 3 1 17 1 0 4 4 0 0\n%%BeginData: 16\nXI\n<16 bytes>%%EndData\n"), "{text}"); + assert!(text.contains("/DeviceGray XN\n"), "{text}"); + assert!(text.contains(" 0 0 4 1 4 1 8 1 0 0 1 0 4 4 0 0\n"), "{text}"); + assert!(text.contains("/DeviceCMYK XN\n"), "{text}"); + assert!(text.contains(" 0 0 2 1 2 1 8 4 0 2 1 0 4 4 0 0\n%%BeginData: 12\nXI\n<8 bytes>%%EndData\n"), "{text}"); + // In an opacity mask: on `%_` lines but for `XI` and its samples. + assert!(text.contains("%_%%BeginData: 13\nXI\n<9 bytes>%_%%EndData\n%_XH\n%_%AI5_EndRaster\n%_N\n"), "{text}"); +} + +#[test] +fn a_linked_image_is_a_placed_file_with_a_preview() { + let doc = images_doc(); + let text = program_shown(&doc); + let begin = text.find("%AI5_BeginPlace\n").unwrap(); + let place = &text[begin..text[begin..].find("%AI5_EndPlace\n").unwrap() + begin]; + let lines: Vec<&str> = place.lines().collect(); + assert_eq!(lines[1], "%%FileType: 1"); + assert!(lines[2].ends_with("] 8091 8141 8094 8144 4 4 0"), "{place}"); + assert_eq!(lines[3], "(/Users/someone/Job \\(1\\)/art/pic.png)`"); + assert_eq!(lines[4], "%%IncludeFile:/Users/someone/Job (1)/art/pic.png"); + assert_eq!( + &lines[5..10], + [ + "%AI17_Begin_Content_if_version_gt:24 12", + "%AI28_BeginPlacedRelativePath", + "(art/)", + "%AI28_EndPlacedRelativePath", + "%AI17_Alternate_Content" + ] + ); + assert_eq!(&lines[11..13], ["%AI17_Begin_Content_if_version_gt:24 5", "%AI26_BeginPlacedObjectPreview"]); + // 3 × 3 pixels of premultiplied ARGB. + assert_eq!(lines[13], "3 3 12 32 17 <36 bytes>"); + assert_eq!(&lines[14..], ["%AI26_EndPlacedObjectPreview", "%AI17_End_Versioned_Content", "~"]); +} + +/// The relative folder goes with the path's file name, so a relative path to a file of another +/// name isn't written. +#[test] +fn a_relative_path_to_a_file_of_another_name_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("/old/original.png"); + link.relative = Some("assets/current.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(!program_shown(&doc).contains("%AI28_BeginPlacedRelativePath")); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + let link = im.link.as_ref().unwrap(); + assert_eq!((link.path.as_str(), link.relative.as_deref()), ("/old/original.png", None)); + // Names that differ only in letter case keep the folder where file names ignore case. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("C:\\Job\\art\\PHOTO.PNG"); + link.relative = Some("art/photo.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let kept = program_shown(&doc).contains("%AI28_BeginPlacedRelativePath\n(art/)\n"); + assert_eq!(kept, cfg!(any(windows, target_os = "macos"))); + // A relative path with `\` separators keeps its folder. + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut link = vectorcraft_doc::LinkInfo::new("C:\\Job\\art\\photo.png"); + link.relative = Some("art\\photo.png".into()); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), Some(link)); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(program_shown(&doc).contains("%AI28_BeginPlacedRelativePath\n(art/)\n")); +} + +#[test] +fn a_large_linked_image_has_a_smaller_preview_over_its_pixels() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let big = image::RgbaImage::from_fn(1024, 512, |x, y| image::Rgba([(x / 4) as u8, (y / 2) as u8, 0, 255])); + let xf = Affine::new([0.1, 0.0, 0.0, 0.1, 20.0, 30.0]); + let im = image_node(&mut doc, ImageBlob::png(png_of(big.into())), (1024, 512), xf, Some(vectorcraft_doc::LinkInfo::new("/tmp/big.png"))); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + assert!(program_shown(&doc).contains("\n256 128 1024 32 17 <131072 bytes>\n")); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + assert_eq!((im.width, im.height), (256, 128)); + let bounds = im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 256.0, 128.0)); + assert_eq!((r3(bounds.x0), r3(bounds.y0), r3(bounds.x1), r3(bounds.y1)), (r3(20.0), r3(30.0), r3(122.4), r3(81.2))); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("/tmp/big.png")); +} + +/// Samples that hold the bytes of `%%EndData` without a line end after them are read whole. +#[test] +fn samples_holding_the_end_marker_are_read_whole() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // The color samples end `%%En` and the alpha channel starts `dData`. + let rgb = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, b'%'], *b"%En"]; + let alpha = *b"dData"; + let img = image::RgbaImage::from_fn(5, 1, |x, _| { + let [r, g, b] = rgb[x as usize]; + image::Rgba([r, g, b, alpha[x as usize]]) + }); + let im = image_node(&mut doc, ImageBlob::png(png_of(img.into())), (5, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // The alpha channel holds the marker, a line end and the operator that follows the samples. + let alpha = *b"%%EndData\r\nXH\r\nZZ"; + let img = image::RgbaImage::from_fn(17, 1, |x, _| image::Rgba([x as u8, 9, 9, alpha[x as usize]])); + let marked = ImageBlob::png(png_of(img.into())); + let im = image_node(&mut doc, marked.clone(), (17, 1), Affine::translate((0.0, 20.0)), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + // The same image as an opacity mask's art, on `%_` lines. + let art = image_node(&mut doc, marked, (17, 1), Affine::translate((0.0, 40.0)), None); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 17.0, 41.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::group(doc.alloc_id(), vec![Arc::new(art)]), false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let back = read_back(&doc); + assert_eq!(images_of(&back), images_of(&doc)); +} + +/// A preview scaled down mixes no color from pixels that don't show. +#[test] +fn a_smaller_preview_takes_no_color_from_see_through_pixels() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let half = image::RgbaImage::from_fn(511, 3, |x, _| if x % 2 == 0 { image::Rgba([255, 0, 0, 0]) } else { image::Rgba([0, 0, 255, 255]) }); + let im = image_node( + &mut doc, + ImageBlob::png(png_of(half.into())), + (511, 3), + Affine::scale(0.2), + Some(vectorcraft_doc::LinkInfo::new("/tmp/half.png")), + ); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let back = read_back(&doc); + let NodeKind::Image(im) = &back.layers[0].children().unwrap()[0].kind else { panic!("not an image") }; + assert_eq!(im.width, 256); + let px = image::load_from_memory(&back.image_blob(im).unwrap().bytes).unwrap().to_rgba8(); + assert!(px.pixels().all(|p| p.0[0] == 0), "{:?}", px.pixels().take(4).collect::>()); + assert!(px.pixels().filter(|p| p.0[3] > 0).count() > 400); +} + +#[test] +fn linked_images_in_masks_and_tiles_are_embedded() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let link = Some(vectorcraft_doc::LinkInfo::new("/tmp/ramp.png")); + let art = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), link); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false))); + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]); + let text = program_shown(&doc); + assert!(!text.contains("BeginPlace") && text.contains("%_%AI5_BeginRaster"), "{text}"); +} + +/// An image in an opacity mask's art inside a pattern's tile is hidden once: its samples end +/// `%_%%EndData`. +#[test] +fn an_image_in_a_mask_in_a_pattern_tile_ends_its_samples_once() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let art = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(10.0), None); + let mut square = + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), Appearance::basic(solid(Color::BLACK), Paint::None, 0.0)); + square.extras_mut().mask = Some(Box::new(OpacityMask::new(Node::group(doc.alloc_id(), vec![Arc::new(art)]), false))); + doc.patterns.push(vectorcraft_doc::PatternDef::new("Masked", vec![Arc::new(square)])); + let filled = Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(40.0, 40.0, 100.0, 80.0)), + Appearance::basic(Paint::Pattern { pattern: "Masked".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + doc.insert(Some(layer), usize::MAX, filled).unwrap(); + let text = program_shown(&doc); + assert!(text.contains("XI\n<18 bytes>%_%%EndData\n%_XH\n"), "{text}"); + assert!(!text.contains("%_%_%%EndData"), "{text}"); +} + +#[test] +fn an_image_in_art_cut_to_a_clipping_object_is_clipped_by_that_region() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + // Type clips: its art is cut to the glyphs' region, which can't cut an image. + let ring = Node::new( + doc.alloc_id(), + NodeKind::Compound { + children: vec![ + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Appearance::default())), + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance::default())), + ], + rule: FillRule::EvenOdd, + }, + ); + let ring = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(ring)], clip: false }); + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(20.0), None); + let group = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(ring), Arc::new(im)], clip: true }); + doc.insert(Some(layer), usize::MAX, group).unwrap(); + let back = read_back(&doc); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert_eq!(found.len(), 1, "{:?}", lines(&back)); + let text = program_shown(&doc); + let at = text.find("%AI5_EndRaster\nN\n").unwrap(); + assert!(text[at..].contains("h\nW\nn\n") && text[..at].contains("q\n"), "{text}"); + // The ring's two subpaths clip as one compound path, not as one cut by the other. + let tail = &text[at..]; + assert!(tail.contains("0 XR\n*u\n") && tail.contains("h\nW\nn\n*U\n"), "{text}"); + fn clipping(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + if let NodeKind::Group { children, clip: true } = &n.kind { + out.extend(children.first().map(|c| match &c.kind { + NodeKind::Path { path, .. } => path.subpaths.len(), + NodeKind::Compound { children, .. } => children.len(), + _ => 0, + })); + } + clipping(n.children().map(Vec::as_slice).unwrap_or_default(), out); + } + } + let mut subpaths = vec![]; + clipping(&back.layers, &mut subpaths); + assert_eq!(subpaths, [2], "{:?}", lines(&back)); +} + +/// Art cut to a region with nothing left in it (two clipping objects that don't overlap) leaves the +/// image out. +#[test] +fn an_image_cut_to_nothing_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let boxed = |doc: &mut Document, r: Rect| { + let p = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + Arc::new(Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(p)], clip: false })) + }; + let im = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::scale(20.0), None); + let far = boxed(&mut doc, Rect::new(50.0, 0.0, 60.0, 10.0)); + let inner = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![far, Arc::new(im)], clip: true }); + let near = boxed(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0)); + let outer = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![near, Arc::new(inner)], clip: true }); + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + assert!(!program_shown(&doc).contains("%AI5_BeginRaster")); +} + +#[test] +fn images_that_cant_be_decoded_are_mid_gray_boxes() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let im = image_node(&mut doc, ImageBlob::png(b"not an image".to_vec()), (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGES]); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); +} + +#[test] +fn sixteen_bit_images_are_written_at_eight_bits() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let deep = image::ImageBuffer::, Vec>::from_fn(2, 1, |x, _| image::Rgb([65535 * x as u16, 257 * 10, 0])); + let im = image_node(&mut doc, ImageBlob::png(png_of(image::DynamicImage::ImageRgb16(deep))), (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGE_DEPTH]); + let back = read_back(&doc); + let mut found = vec![]; + pictures(&back, &back.layers, "", &mut found); + assert!(found[0].ends_with("rgba [0, 10, 0, 255, 255, 10, 0, 255]"), "{found:?}"); +} + +/// A little-endian, uncompressed CMYK TIFF of 16 bits a sample, `w` × 1 pixels, each pixel's inks +/// `inks[x]`. +fn cmyk16_tiff(inks: &[[u16; 4]]) -> Vec { + let w = inks.len() as u32; + let data: Vec = inks.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + // Tags: width, height, bits (an offset), compression, photometric, strip offset, samples, rows, + // strip bytes, planar configuration. + let bits_at = 8 + 2 + 12 * 10 + 4; + let data_at = bits_at + 8; + let entries: [(u16, u16, u32, u32); 10] = [ + (256, 4, 1, w), + (257, 4, 1, 1), + (258, 3, 4, bits_at), + (259, 3, 1, 1), + (262, 3, 1, 5), + (273, 4, 1, data_at), + (277, 3, 1, 4), + (278, 4, 1, 1), + (279, 4, 1, data.len() as u32), + (284, 3, 1, 1), + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&10u16.to_le_bytes()); + for (tag, kind, count, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..4 { + out.extend_from_slice(&16u16.to_le_bytes()); + } + out.extend_from_slice(&data); + out +} + +#[test] +fn sixteen_bit_cmyk_images_are_written_at_eight_bits() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let blob = ImageBlob::new("image/tiff", cmyk16_tiff(&[[65535, 0, 0, 0], [0, 0x8000, 0, 0x1234]])); + assert!(blob.is_cmyk() && blob.is_cmyk16()); + let im = image_node(&mut doc, blob, (2, 1), Affine::scale(10.0), None); + doc.insert(Some(layer), usize::MAX, im).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGE_DEPTH]); + assert!(program_shown(&doc).contains("/DeviceCMYK XN\n")); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 99f8cb607d..78602b9391 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -9,29 +9,32 @@ use vectorcraft_color::swatch::{REGISTRATION, Swatch}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LAYER_COLORS, LayerColor, Node, NodeKind, OpacityMask, StrokeLayer}; use vectorcraft_effects::stroke; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, SubPath}; +use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath}; use vectorcraft_pathops::BoolOp; -use crate::ai_ops::{self, average, unit}; +use crate::ai_ops::{self, unit}; use crate::ps; +mod images; +mod paints; + +pub(super) use images::PAYLOAD; +#[cfg(test)] +pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; +#[cfg(test)] +pub(super) use paints::{GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; + /// How deep symbols, live objects and pattern tiles may nest in one another (deeper art is left /// out). Groups and layers need no limit of their own: a document is never deeper than /// [`vectorcraft_doc::MAX_DEPTH`]. const MAX_NEST: u32 = 8; -/// The side of the image whose pixels are averaged (larger ones are scaled down to it first). -const AVERAGE_SIDE: u32 = 64; -/// Most pixels an image may have to be decoded and averaged (more: mid gray). -const MAX_AVERAGED_PIXELS: u64 = 1 << 24; pub(super) const TYPE: &str = "type is written as its outlines in the editing data for other apps"; -pub(super) const GRADIENTS: &str = "gradients are written as their average color in the editing data for other apps"; -const PATTERNS: &str = "pattern fills are written as their tiles cut to the shape in the editing data for other apps"; +pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const IMAGES: &str = "images are written as their outlines filled with their average color in the editing data for other apps"; pub(super) const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; @@ -43,7 +46,7 @@ pub(super) const DEEP_MASKS: &str = const GROUPED_LAYER: &str = "the transparency and opacity masks of layers that an effect made into a group are left out of the editing data for other apps"; pub(super) const EFFECTS: &str = "live effects other than geometry effects are left out of the editing data for other apps"; -const SWATCHES: &str = "gradient and pattern swatches are left out of the editing data for other apps"; +pub(super) const SWATCHES: &str = "freeform gradient swatches, gradient swatches of more than 256 stops, and pattern swatches whose patterns the data can't define, are left out of the editing data for other apps"; pub(super) const SYMBOL_LIMIT: &str = "symbol instances past 16,000,000 objects of symbol art in all are left out of the editing data for other apps"; const TEMPLATES: &str = "template layers are written as dimmed layers that don't print in the editing data for other apps"; @@ -127,13 +130,52 @@ pub(super) struct Writer<'a> { brushes: Option>, /// The objects of the symbol art written so far, within [`vectorcraft_doc::MAX_SYMBOL_NODES`]. symbol_nodes: u64, + /// The document → the space gradients' matrices (`Xm`, `Bm`, `Bc`) and focal points are + /// written in: art space, and in a pattern's definition [`Self::tile_grad_space`]. + grad_space: Affine, + /// The pattern's space (y down) → the space a pattern's definition writes gradients' matrices + /// in: the canvas's (y down), from art space's origin there. + tile_grad_space: Affine, + /// The document → the canvas (y down), the space of a gradient's transformation in `Bg`; in a + /// pattern's definition, the pattern's space turned y up. + canvas: Affine, + /// The gradient definitions, in the order they are first used. + gradients: Vec, + /// The number the next new gradient definition's name tries first (1 is `Gradient`). + next_gradient: u64, + /// The pattern definitions written, each after those its art uses. + patterns: Vec, + /// The patterns whose definitions are being written. + defining: Vec, + /// Writing the palette: the definitions it adds are for its swatches only. + in_palette: bool, + /// Art space's origin on the canvas (y down), where a placed file's box starts. + canvas_origin: (f64, f64), + /// The binary parts of the program (images' samples, placed files' previews), each in the + /// text as a mark ([`PAYLOAD`], its index, [`PAYLOAD`]). + pub(super) payloads: Vec>, + /// How many parts of the data written on `%_` lines (opacity masks' art, patterns' tiles) the + /// art being written is in. + hidden: u32, } impl<'a> Writer<'a> { - pub(super) fn new(doc: &'a Document, to_art: Affine) -> Self { + /// A writer of `doc`'s art through `to_art`; `origin` is art space's origin on the canvas. + pub(super) fn new(doc: &'a Document, to_art: Affine, origin: (f64, f64)) -> Self { Self { doc, to_art, + grad_space: to_art, + tile_grad_space: Affine::translate((-origin.0, origin.1)), + canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, + gradients: vec![], + next_gradient: 1, + patterns: vec![], + defining: vec![], + in_palette: false, + canvas_origin: origin, + payloads: vec![], + hidden: 0, cms: vectorcraft_color::cms::active(), body: String::new(), warnings: vec![], @@ -358,12 +400,7 @@ impl<'a> Writer<'a> { } NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), NodeKind::Text(_) => self.text(n, xy), - NodeKind::Image(im) => { - let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); - let color = image_average(self.doc.image_blob(im).map(|b| b.bytes.as_slice())); - self.warn(IMAGES); - self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(color)), xy); - } + NodeKind::Image(im) => self.image(im, xy), NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); self.line("u"); @@ -498,19 +535,15 @@ impl<'a> Writer<'a> { _ => std::slice::from_ref(art), }; self.nest += 1; + self.hidden += 1; for c in members { self.node(c); } + self.hidden -= 1; self.nest -= 1; let lines = std::mem::replace(&mut self.body, outer); self.body.push_str("%_/Mask :\n%_X=\n"); - for l in lines.lines() { - if !l.starts_with("%_") { - self.body.push_str("%_"); - } - self.body.push_str(l); - self.body.push('\n'); - } + hide(&lines, &mut self.body); self.body.push_str("%_X+\n%_(Art) ,\n"); for (key, on) in [("Clipping", m.clip), ("Inverted", m.invert), ("Disabled", m.disabled), ("Linked", m.linked)] { let _ = writeln!(self.body, "%_{} /Bool ({key}) ,", u8::from(on)); @@ -560,16 +593,17 @@ impl<'a> Writer<'a> { self.warn_cut(Some(first)); return self.clip_contents(children); }; - let painted = plain_paint(first); - if visible_items(first).iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { + let items = self.items(first, path.to_bezpath().bounding_box()); + let painted = self.plain_paint(&items); + if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { self.warn(ITEM_TRANSPARENCY); } // Paint the clipping path can't carry: its fills under the others, its strokes over them. let (fills, strokes): (Vec<&AppearanceItem>, Vec<&AppearanceItem>) = - if painted.is_none() { visible_items(first).into_iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) }; + if painted.is_none() { items.iter().partition(|i| matches!(i, AppearanceItem::Fill(_))) } else { (vec![], vec![]) }; if painted.is_none() { self.warn(CLIP_PAINT); - if first.extras().mask.is_some() && !visible_items(first).is_empty() { + if first.extras().mask.is_some() && !items.is_empty() { self.warn(CLIP_PAINT_MASKS); } } @@ -588,10 +622,13 @@ impl<'a> Writer<'a> { if several { self.line("*u"); } - for sp in subpaths { + let last = subpaths.len().saturating_sub(1); + let outline = path.to_bezpath(); + for (i, sp) in subpaths.into_iter().enumerate() { ai_ops::subpath(&mut self.body, self.to_art, sp); - let op = if sp.closed { op } else { op.to_ascii_uppercase() }; - let _ = writeln!(self.body, "{}\nW\n{op}", if sp.closed { 'h' } else { 'H' }); + let _ = writeln!(self.body, "{}\nW", if sp.closed { 'h' } else { 'H' }); + let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) }; + self.painted(op, sp.closed, gradients, stroke.is_some(), true, &outline); } if several { self.line("*U"); @@ -658,11 +695,11 @@ impl<'a> Writer<'a> { if path.is_empty() { return; } - let items = visible_items(n); + let items = self.items(n, path.to_bezpath().bounding_box()); if items.iter().any(|i| i.opacity() < 1.0 || i.blend() != BlendMode::Normal) { self.warn(ITEM_TRANSPARENCY); } - match (plain_paint(n), items.as_slice()) { + match (self.plain_paint(&items), items.as_slice()) { (Some((fill, stroke)), _) => self.path_object(path, rule, fill, stroke, xy), (None, [one]) => self.item(path, rule, one, xy), (None, items) => { @@ -679,7 +716,7 @@ impl<'a> Writer<'a> { fn item(&mut self, path: &PathData, rule: FillRule, item: &AppearanceItem, xy: Xy) { match item { AppearanceItem::Fill(f) => self.fill_object(path, rule, f, xy), - AppearanceItem::Stroke(s) if direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), + AppearanceItem::Stroke(s) if self.direct_stroke(s) => self.path_object(path, rule, None, Some(s), xy), AppearanceItem::Stroke(s) => { self.warn(STROKES); if self.brush_art(path, s, xy) { @@ -716,15 +753,17 @@ impl<'a> Writer<'a> { true } - /// A fill as an object of its own, of transparency `xy`: a gradient as its average color, a - /// pattern as its tiles cut to the path. + /// A fill as an object of its own, of transparency `xy`: a color, a placed gradient or a + /// pattern the data can define as the path's fill, another pattern as its tiles cut to the path. fn fill_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, xy: Xy) { + if !matches!(f.paint, Paint::None) && self.direct(&f.paint) { + return self.path_object(path, rule, Some(f), None, xy); + } match &f.paint { - Paint::Solid { .. } => self.path_object(path, rule, Some(f), None, xy), - Paint::Gradient(g) => { - self.warn(GRADIENTS); - let flat = FillLayer { paint: Paint::solid(average(&g.gradient)), ..f.clone() }; - self.path_object(path, rule, Some(&flat), None, xy); + // A gradient not placed yet: placed on the path, or its average color. + Paint::Solid { .. } | Paint::Gradient(_) => { + let flat = self.placed(&f.paint, path.to_bezpath().bounding_box()); + self.path_object(path, rule, Some(&FillLayer { paint: flat, ..f.clone() }), None, xy); } Paint::Pattern { pattern, xf } => { self.warn(PATTERNS); @@ -826,11 +865,13 @@ impl<'a> Writer<'a> { if several { self.line("*u"); } - for sp in subpaths { + // A gradient's instance paints the last subpath; the compound path takes its paint. + let last = subpaths.len().saturating_sub(1); + let outline = path.to_bezpath(); + for (i, sp) in subpaths.into_iter().enumerate() { ai_ops::subpath(&mut self.body, self.to_art, sp); - let op = if sp.closed { op } else { op.to_ascii_uppercase() }; - self.body.push(op); - self.body.push('\n'); + let gradients = if i == last { (gradient(fill.map(|f| &f.paint)), gradient(stroke.map(|s| &s.paint))) } else { (None, None) }; + self.painted(op, sp.closed, gradients, stroke.is_some(), false, &outline); } if several { self.line("*U"); @@ -899,11 +940,15 @@ impl<'a> Writer<'a> { // ---------- color ---------- - /// Set the fill (or with `stroke`, the stroke) color to solid paint `p`: a spot or global - /// swatch by its name, Registration, else the color itself. + /// Set the fill (or with `stroke`, the stroke) to paint `p`: a spot or global swatch by its + /// name, Registration, the color itself, or a pattern ([`Self::pattern_paint`]). A gradient sets + /// nothing: its instance paints ([`Self::painted`]). fn color(&mut self, p: &Paint, stroke: bool) { - let Paint::Solid { color, swatch, tint } = p else { - return self.plain_color(Color::gray(1.0), stroke); + let (color, swatch, tint) = match p { + Paint::Solid { color, swatch, tint } => (color, swatch, tint), + Paint::Pattern { pattern, xf } => return self.pattern_paint(pattern, *xf, stroke), + Paint::Gradient(_) => return, + Paint::None => return self.plain_color(Color::gray(1.0), stroke), }; if swatch.as_deref() == Some(REGISTRATION) { let mut s = String::from("1 1 1 1 "); @@ -989,6 +1034,7 @@ impl<'a> Writer<'a> { /// (the ungrouped ones first, then each color group's after `0 (name) count Pg`), `PB`, /// `%AI5_EndPalette`. pub(super) fn palette(&mut self, s: &mut String) { + self.in_palette = true; s.push_str("%AI5_BeginPalette\n0 0 Pb\n"); self.registration_cell(s); let doc = self.doc; @@ -996,13 +1042,13 @@ impl<'a> Writer<'a> { self.swatch(s, sw); } for g in doc.swatch_groups.iter() { - let colors: Vec<&Swatch> = g.swatches.iter().filter(|sw| writable(sw)).collect(); - let _ = writeln!(s, "0 {} {} Pg", ps::bytes(g.name.as_bytes()), colors.len()); - for sw in &g.swatches { - self.swatch(s, sw); - } + let mut cells = String::new(); + let count = g.swatches.iter().filter(|sw| self.swatch(&mut cells, sw)).count(); + let _ = writeln!(s, "0 {} {count} Pg", ps::bytes(g.name.as_bytes())); + s.push_str(&cells); } s.push_str("PB\n%AI5_EndPalette\n"); + self.in_palette = false; } /// The Registration swatch, which every palette in the files users sent starts with: in a @@ -1021,24 +1067,31 @@ impl<'a> Writer<'a> { let _ = writeln!(s, "{name} Pc"); } - /// One swatch of the palette: a color swatch's color and `(name) Pc`; gradient and pattern - /// swatches are left out. - fn swatch(&mut self, s: &mut String, sw: &Swatch) { + /// One swatch of the palette: a color swatch's color, a gradient swatch's or pattern swatch's + /// paint ([`Self::swatch_paint`]), then `(name) Pc`. False when it isn't written: Registration + /// (written first), the None swatch, and paint the data can't hold (with a warning). + fn swatch(&mut self, s: &mut String, sw: &Swatch) -> bool { if sw.name == REGISTRATION || matches!(sw.paint, Paint::None) { - return; + return false; } - if !writable(sw) { - return self.warn(SWATCHES); - } - let Paint::Solid { color, swatch, .. } = &sw.paint else { return }; - if swatch.is_none() && (sw.global || sw.spot) { - self.named(s, &sw.name, *color, 1.0, sw.spot, false); - } else { - let body = std::mem::take(&mut self.body); - self.plain_color(*color, false); - s.push_str(&std::mem::replace(&mut self.body, body)); + match &sw.paint { + Paint::Solid { color, swatch, .. } => { + if swatch.is_none() && (sw.global || sw.spot) { + self.named(s, &sw.name, *color, 1.0, sw.spot, false); + } else { + let body = std::mem::take(&mut self.body); + self.plain_color(*color, false); + s.push_str(&std::mem::replace(&mut self.body, body)); + } + } + _ if self.swatch_paint(s, sw) => {} + _ => { + self.warn(SWATCHES); + return false; + } } let _ = writeln!(s, "{} Pc", ps::bytes(sw.name.as_bytes())); + true } /// The spot color swatches, with their full colors' CMYK equivalents, for the header. @@ -1057,14 +1110,12 @@ impl<'a> Writer<'a> { } } -/// Is `sw` a color swatch the palette writes? -fn writable(sw: &Swatch) -> bool { - matches!(sw.paint, Paint::Solid { .. }) && sw.name != REGISTRATION -} - -/// Does a plain line of one color draw `s` (the line style operators can write it)? -fn direct_stroke(s: &StrokeLayer) -> bool { - matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) +/// The gradient of paint `p`, when it has one. +fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> { + match p { + Some(Paint::Gradient(g)) => Some(g), + _ => None, + } } /// `n`'s fills and strokes that paint. @@ -1079,19 +1130,6 @@ fn visible_items(n: &Node) -> Vec<&AppearanceItem> { .collect() } -/// `n`'s paint as one path object paints: no paint, a fill of a color, a plain line of a color, -/// or both, the line over the fill; `None` when it has other paint. -fn plain_paint(n: &Node) -> Option<(Option<&FillLayer>, Option<&StrokeLayer>)> { - let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); - match visible_items(n).as_slice() { - [] => Some((None, None)), - [AppearanceItem::Fill(f)] if solid(&f.paint) => Some((Some(f), None)), - [AppearanceItem::Stroke(s)] if direct_stroke(s) => Some((None, Some(s))), - [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if solid(&f.paint) && direct_stroke(s) => Some((Some(f), Some(s))), - _ => None, - } -} - /// The painting operator of a closed subpath (§5.3.3): `b` fill and stroke, `f` fill, `s` /// stroke, `n` neither; an open one's is upper case. fn paint_op(fill: bool, stroke: bool) -> char { @@ -1124,42 +1162,43 @@ fn clip_path(n: &Node) -> Option<(PathData, FillRule)> { path.subpaths.iter().any(|sp| !sp.anchors.is_empty()).then_some((path, rule)) } -/// The image `bytes` decoded, when its header gives at most [`MAX_AVERAGED_PIXELS`] pixels; the -/// decoder may allocate at most 8 bytes a pixel. -fn decode_bounded(bytes: &[u8]) -> Option { +/// `text`'s lines on `%_` lines, as a part of the data that readers of the printed form skip (an +/// opacity mask's art, a pattern's tile) has them. An image's samples stay as they are after an +/// `XI` without `%_`, and `%_%%EndData` ends them, as in the files users sent. Samples hidden +/// already (an opacity mask's art in a pattern's tile) keep their one `%_`. +pub(super) fn hide(text: &str, out: &mut String) { + for l in text.lines() { + if l.starts_with(images::SAMPLES_LINE) { + match l.strip_suffix("%%EndData") { + Some(samples) if !samples.ends_with("%_") => { + out.push_str(samples); + out.push_str("%_%%EndData"); + } + _ => out.push_str(l), + } + } else { + if !l.starts_with("%_") { + out.push_str("%_"); + } + out.push_str(l); + } + out.push('\n'); + } +} + +/// The image `bytes` decoded, when its header gives at most `max` pixels; the decoder may allocate +/// at most 8 bytes a pixel. +fn decode_bounded(bytes: &[u8], max: u64) -> Option { let reader = || -> image::ImageResult>> { let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; let mut limits = image::Limits::default(); - limits.max_alloc = Some(MAX_AVERAGED_PIXELS * 8); + limits.max_alloc = Some(max * 8); r.limits(limits); Ok(r) }; let (w, h) = reader().and_then(|r| r.into_dimensions()).ok()?; - if u64::from(w) * u64::from(h) > MAX_AVERAGED_PIXELS { + if u64::from(w) * u64::from(h) > max { return None; } reader().and_then(|r| r.decode()).ok() } - -/// The average color of the image `bytes` (scaled down first), transparent pixels over white; -/// mid gray when it can't be decoded or has more than [`MAX_AVERAGED_PIXELS`] pixels. -fn image_average(bytes: Option<&[u8]>) -> Color { - let Some(img) = bytes.and_then(decode_bounded) else { return Color::gray(0.5) }; - let img = if img.width() > AVERAGE_SIDE || img.height() > AVERAGE_SIDE { img.thumbnail(AVERAGE_SIDE, AVERAGE_SIDE) } else { img }; - let rgba = img.to_rgba8(); - let mut sum = [0u64; 3]; - let mut n = 0u64; - for px in rgba.pixels() { - let [r, g, b, a] = px.0; - let over = |c: u8| (u64::from(c) * u64::from(a) + 255 * (255 - u64::from(a))) / 255; - sum[0] += over(r); - sum[1] += over(g); - sum[2] += over(b); - n += 1; - } - if n == 0 { - return Color::gray(0.5); - } - let c = |v: u64| (v as f32 / n as f32 / 255.0).clamp(0.0, 1.0); - Color::rgb(c(sum[0]), c(sum[1]), c(sum[2])) -} diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs new file mode 100644 index 0000000000..6ef2ccaa3a --- /dev/null +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -0,0 +1,326 @@ +//! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview +//! (see [`crate::ai_editing`] for the form). + +use std::fmt::Write; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{FillLayer, ImageBlob, ImageObject, LinkInfo}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape}; + +use super::{Writer, Xy}; +use crate::ps; + +pub(in crate::ai_editing) const IMAGES: &str = "images that can't be decoded or have more than 33,554,432 pixels are written as their outlines filled mid gray in the editing data for other apps"; +pub(in crate::ai_editing) const IMAGE_DEPTH: &str = "images of 16 bits a channel are written at 8 bits a channel in the editing data for other apps"; +pub(in crate::ai_editing) const LINKS_EMBEDDED: &str = + "linked images in opacity masks and pattern tiles are written as embedded images in the editing data for other apps"; + +/// The most pixels an image is written with: as many as the reader reads. +pub(super) const MAX_PIXELS: u64 = 1 << 25; +/// The longer side of a placed file's preview at most (a smaller image's preview is its own +/// pixels): the files users sent have previews 256 pixels wide. +const PREVIEW_SIDE: u32 = 256; +/// What marks a binary payload in the program text: `\u{1}`, its index, `\u{1}` +/// ([`super::super::splice`] puts the bytes in its place). Strings never hold the byte unescaped. +pub(in crate::ai_editing) const PAYLOAD: char = '\u{1}'; +/// What starts the line of an image's samples: `XI` and its payload, then `%%EndData`. +pub(super) const SAMPLES_LINE: &str = "XI\u{1}"; + +/// An image's pixels as the data holds them. +struct Samples { + /// `/DeviceGray`, `/DeviceRGB` or `/DeviceCMYK`. + space: &'static str, + /// The image type of `XI` (§8.1): 1 gray, 3 RGB, 4 CMYK. + kind: u8, + width: u32, + height: u32, + /// The color samples, 8 bits each, rows from the top. + color: Vec, + /// The alpha channel, a byte a pixel, when a pixel isn't opaque. + alpha: Option>, +} + +impl Samples { + /// The pixels of `blob`: a CMYK image's ink amounts, else gray samples when every pixel is gray + /// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than + /// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel. + fn of(blob: &ImageBlob) -> Option<(Samples, bool)> { + // The header's size is checked before the inks are decoded. + if blob.is_cmyk() + && blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS) + && let Some(inks) = blob.cmyk() + && u64::from(inks.width) * u64::from(inks.height) <= MAX_PIXELS + { + let s = Samples { space: "/DeviceCMYK", kind: 4, width: inks.width, height: inks.height, color: inks.data, alpha: None }; + return Some((s, blob.is_cmyk16())); + } + let img = super::decode_bounded(&blob.bytes, MAX_PIXELS)?; + let deep = matches!( + img.color(), + image::ColorType::L16 + | image::ColorType::La16 + | image::ColorType::Rgb16 + | image::ColorType::Rgba16 + | image::ColorType::Rgb32F + | image::ColorType::Rgba32F + ); + let rgba = img.to_rgba8(); + // Gray when every pixel is, whatever the file's color type (an image read back from the data + // is RGBA): the same pixels are written the same way. + let gray = rgba.pixels().all(|p| p.0[0] == p.0[1] && p.0[1] == p.0[2]); + let (width, height) = rgba.dimensions(); + if width == 0 || height == 0 { + return None; + } + let opaque = rgba.pixels().all(|p| p.0[3] == 255); + let alpha = (!opaque).then(|| rgba.pixels().map(|p| p.0[3]).collect()); + let color = if gray { rgba.pixels().map(|p| p.0[0]).collect() } else { rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect() }; + let (space, kind) = if gray { ("/DeviceGray", 1) } else { ("/DeviceRGB", 3) }; + Some((Samples { space, kind, width, height, color, alpha }, deep)) + } + + /// `XI`'s fourth flag as the files users sent have it: 0 gray, 1 RGB, 2 CMYK, 16 more with an + /// alpha channel. + fn reserved(&self) -> u8 { + let space = match self.kind { + 1 => 0, + 4 => 2, + _ => 1, + }; + space + if self.alpha.is_some() { 16 } else { 0 } + } +} + +impl Writer<'_> { + /// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a + /// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on + /// `%_` lines. One whose pixels can't be read is its outline filled mid gray. Where the art is + /// cut to a clipping path, the image is in a clipping group of that path. + pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) { + let doc = self.doc; + let Some((samples, deep)) = doc.image_blob(im).and_then(Samples::of) else { + let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); + self.warn(IMAGES); + return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + }; + // A region that has nothing left hides the image. + if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) { + return; + } + if deep { + self.warn(IMAGE_DEPTH); + } + let cut = self.clip.take(); + let at_q = (self.state, self.gs); + if cut.is_some() { + self.line("q"); + } + self.set_xy(xy.object()); + // 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(im.width.max(1)) / f64::from(samples.width), f64::from(im.height.max(1)) / f64::from(samples.height)); + match &im.link { + Some(link) if self.hidden == 0 => self.placed_file(link, &samples, (im.width.max(1), im.height.max(1)), im.xf), + other => { + if other.is_some() { + self.warn(LINKS_EMBEDDED); + } + self.raster(&samples, im.xf * fit); + } + } + if let Some(region) = &cut { + self.line("0 XR"); + // Several subpaths clip as one compound path (`*u` … `*U`), as a clipping group's do. + let subpaths: Vec<_> = region.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).collect(); + let several = subpaths.len() > 1; + if several { + self.line("*u"); + } + for sp in subpaths { + crate::ai_ops::subpath(&mut self.body, self.to_art, sp); + self.line("h\nW\nn"); + } + if several { + self.line("*U"); + } + (self.state, self.gs) = at_q; + self.end_group("Q", Xy::PLAIN); + } + self.clip = cut; + } + + /// An embedded image whose pixels `xf` places in the document: `%AI5_File:`, + /// `%AI5_BeginRaster`, `() 1 XG` (no file), the color space `XN`, `[matrix] w h 0 Xh`, + /// `[matrix] 0 0 w h w h 8 type alpha reserved 1 0 4 4 0 0`, `%%BeginData:` counting `XI`, its + /// line end and the color samples, `XI`, the color samples then the alpha channel in binary, + /// `%%EndData`, `XH`, `%AI5_EndRaster`, `N`. The matrix is an art-space matrix applied to the + /// pixels with their rows running downwards, `(u, -v)`, as §8.1's image matrix. + fn raster(&mut self, s: &Samples, xf: Affine) { + let m = matrix(self.to_art * xf * Affine::FLIP_Y); + let (w, h) = (s.width, s.height); + let alpha = u8::from(s.alpha.is_some()); + let mut payload = Vec::with_capacity(2 + s.color.len() + s.alpha.as_ref().map_or(0, Vec::len)); + payload.extend_from_slice(b"\r\n"); + payload.extend_from_slice(&s.color); + if let Some(a) = &s.alpha { + payload.extend_from_slice(a); + } + let mark = self.payload(payload); + let _ = writeln!( + self.body, + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n{} XN\n{m} {w} {h} 0 Xh\n{m} 0 0 {w} {h} {w} {h} 8 {} {alpha} {} 1 0 4 4 0 0\n%%BeginData: {}\nXI{mark}%%EndData\nXH\n%AI5_EndRaster\nN", + s.space, + s.kind, + s.reserved(), + // `XI`, CR LF. + 4 + s.color.len(), + ); + } + + /// A linked image whose pixels `xf` places in the document: `%AI5_BeginPlace`, + /// `%%FileType: 1`, `[matrix] llx lly urx ury 4 4 0` and the file's path with `` ` ``, + /// `%%IncludeFile:` and the path, the folder relative to the document's between + /// `%AI28_BeginPlacedRelativePath` and its end (`()` for the document's own folder), the preview between + /// `%AI26_BeginPlacedObjectPreview` and its end (`w h rowBytes 32 17 ` and rows of + /// premultiplied ARGB, the top one first, of the pixels `s`), `~`, `%AI5_EndPlace`. The box is + /// as large as the file has pixels (`w` × `h`, the object's pixel grid, which `xf` places in the + /// document), at art space's origin on the canvas (y down); the matrix takes it from there into + /// art space. Each marked part newer releases read is in versioned content, as in the files + /// users sent. + fn placed_file(&mut self, link: &LinkInfo, s: &Samples, (w, h): (u32, u32), xf: Affine) { + let (x, y) = self.canvas_origin; + let m = matrix(self.to_art * xf * Affine::translate((-x, -y))); + let (w, h) = (f64::from(w), f64::from(h)); + let path = ps::bytes(link.path.as_bytes()); + let _ = write!(self.body, "%AI5_BeginPlace\n%%FileType: 1\n{m} "); + ps::push_nums(&mut self.body, &[x, y, x + w, y + h, 4.0, 4.0, 0.0]); + self.body.pop(); + let _ = writeln!(self.body, "\n{path}`"); + if !link.path.chars().any(char::is_control) { + let _ = writeln!(self.body, "%%IncludeFile:{}", link.path); + } + // The section holds a folder only, the file's name comes from the path: a relative path to a + // file of another name isn't written. On Windows and macOS, whose file names ignore letter + // case, names that differ only in case are the same file. + let same_name = |r: &&str| r.rsplit(['/', '\\']).next().is_some_and(|n| same_file_name(n, link.name())); + if let Some(folder) = link.relative.as_deref().filter(same_name).map(relative_folder) { + let _ = writeln!( + self.body, + "%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n{}\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content", + ps::bytes(folder.as_bytes()) + ); + } + let (pw, ph, rows) = preview(s); + let mark = self.payload(rows); + let _ = writeln!( + self.body, + "%AI17_Begin_Content_if_version_gt:24 5\n%AI26_BeginPlacedObjectPreview\n{pw} {ph} {} 32 17 {mark}\n%AI26_EndPlacedObjectPreview\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace", + pw * 4 + ); + } + + /// Keep `bytes` to go in the program where the mark this returns is. + fn payload(&mut self, bytes: Vec) -> String { + self.payloads.push(bytes); + format!("{PAYLOAD}{}{PAYLOAD}", self.payloads.len() - 1) + } +} + +/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four). +fn matrix(m: Affine) -> String { + let n: Vec = m.as_coeffs().iter().map(|v| precise(*v)).collect(); + format!("[{}]", n.join(" ")) +} + +/// `v` rounded to ten decimals, without trailing zeros (0 when not finite). +fn precise(v: f64) -> String { + let r = (v * 1e10).round() / 1e10; + if !r.is_finite() { + return if v.is_finite() { format!("{}", v + 0.0) } else { "0".into() }; + } + format!("{}", r + 0.0) +} + +/// The folder of a path relative to the document's (`src/checker.png` → `src/`); empty when the file +/// is in the document's own folder. `\` separators are read as `/`. +fn relative_folder(relative: &str) -> String { + match relative.replace('\\', "/").rsplit_once('/') { + Some((folder, _)) if !folder.is_empty() => format!("{folder}/"), + _ => String::new(), + } +} + +/// Do file names `a` and `b` name the same file in one folder: equal, or on Windows and macOS equal +/// but for letter case? +fn same_file_name(a: &str, b: &str) -> bool { + a == b || (cfg!(any(windows, target_os = "macos")) && a.to_lowercase() == b.to_lowercase()) +} + +/// A placed file's preview of `s`: its width, height and rows of premultiplied ARGB, the top one +/// first; the image's own pixels when neither side is longer than [`PREVIEW_SIDE`], else scaled +/// down to it, each preview pixel the average of the premultiplied pixels it covers. +fn preview(s: &Samples) -> (u32, u32, Vec) { + let (w, h) = (u64::from(s.width), u64::from(s.height)); + let longer = s.width.max(s.height); + let (pw, ph) = if longer > PREVIEW_SIDE { + let k = f64::from(PREVIEW_SIDE) / f64::from(longer); + let side = |v: u32| ((f64::from(v) * k).round() as u32).clamp(1, PREVIEW_SIDE); + (side(s.width), side(s.height)) + } else { + (s.width, s.height) + }; + let n = usize::from(channels(s.kind)); + let cmyk_memo = std::cell::RefCell::new(std::collections::HashMap::new()); + // Pixel `i` premultiplied: r, g, b, a. + let pixel = |i: usize| -> [u64; 4] { + let c = |k: usize| s.color.get(i * n + k).copied().unwrap_or(0); + let rgb = match s.kind { + 1 => [c(0); 3], + 4 => { + let mut memo = cmyk_memo.borrow_mut(); + if memo.len() > 1 << 16 { + memo.clear(); + } + *memo.entry([c(0), c(1), c(2), c(3)]).or_insert_with(|| { + let f = |v: u8| f32::from(v) / 255.0; + let [r, g, b, _] = Color::cmyk(f(c(0)), f(c(1)), f(c(2)), f(c(3))).to_rgba8(1.0); + [r, g, b] + }) + } + _ => [c(0), c(1), c(2)], + }; + let a = u64::from(s.alpha.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(255)); + let pre = |v: u8| (u64::from(v) * a + 127) / 255; + [pre(rgb[0]), pre(rgb[1]), pre(rgb[2]), a] + }; + let (pw64, ph64) = (u64::from(pw), u64::from(ph)); + let mut rows = Vec::with_capacity((pw64 * ph64 * 4) as usize); + for py in 0..ph64 { + let (y0, y1) = (py * h / ph64, ((py + 1) * h / ph64).max(py * h / ph64 + 1)); + for px in 0..pw64 { + let (x0, x1) = (px * w / pw64, ((px + 1) * w / pw64).max(px * w / pw64 + 1)); + let mut sum = [0u64; 4]; + for y in y0..y1.min(h) { + for x in x0..x1.min(w) { + let p = pixel((y * w + x) as usize); + for (t, v) in sum.iter_mut().zip(p) { + *t += v; + } + } + } + let count = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1); + let [r, g, b, a] = sum.map(|t| ((t + count / 2) / count).min(255) as u8); + rows.extend_from_slice(&[a, r, g, b]); + } + } + (pw, ph, rows) +} + +/// The samples a pixel of image type `kind` has. +fn channels(kind: u8) -> u8 { + match kind { + 1 => 1, + 4 => 4, + _ => 3, + } +} diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs new file mode 100644 index 0000000000..d805d9d0e5 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -0,0 +1,565 @@ +//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the +//! pattern operators (see [`crate::ai_editing`] for the form). + +use std::fmt::Write; + +use vectorcraft_color::gradient::GradientGeom; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType}; +use vectorcraft_effects::stroke; +use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; + +use super::{MAX_NEST, Writer, Xy}; +use crate::ai_ops::{average, unit}; +use crate::ps; + +pub(in crate::ai_editing) const GRADIENTS: &str = + "freeform gradients, and gradients along or across strokes, are written as their average color in the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps"; +pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str = + "the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps"; +pub(in crate::ai_editing) const GRADIENT_MIX: &str = + "gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps"; +pub(in crate::ai_editing) const STOP_LINKS: &str = + "gradient stops linked to global process colors are written as their colors in the editing data for other apps"; +/// The length of a linear gradient's caps (`Bc`): the canvas's side. +const CAP: f64 = super::super::CANVAS_SIZE as f64; + +/// A gradient definition: its name, its gradient, whether it is a gradient swatch's (named after +/// the swatch) and whether the art uses it (else only the palette does). +pub(super) struct GradientDef { + name: String, + gradient: Gradient, + swatch: bool, + used: bool, +} + +/// A pattern definition written: its name, its text (`%AI3_BeginPattern` to `%AI3_EndPattern`) +/// and whether the art uses it. +pub(super) struct PatternOut { + name: String, + text: String, + used: bool, +} + +/// Can `g` be written as a gradient (a linear or radial one with stops, no more than the `.ai` +/// reader reads)? +fn writable_gradient(g: &Gradient) -> bool { + g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS +} + +/// The first name of `Gradient`, `Gradient 2`, `Gradient 3`, … numbered `next` or higher for +/// which `taken` returns false (`Gradient` is number 1); `next` is set past it. +pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl FnMut(&str) -> bool) -> String { + loop { + let name = if *next <= 1 { String::from("Gradient") } else { format!("Gradient {next}") }; + *next = next.saturating_add(1); + if !taken(&name) { + return name; + } + } +} + +/// The stops of `g` in order of their place on the ramp. +fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> { + let mut stops: Vec<&GradientStop> = g.stops.iter().collect(); + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + stops +} + +impl Writer<'_> { + /// Each gradient swatch's definition, named after the swatch, before the art is written. + pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) { + let doc = self.doc; + for sw in doc.swatches_iter() { + if let Paint::Gradient(g) = &sw.paint + && writable_gradient(&g.gradient) + && !self.gradients.iter().any(|d| d.name == sw.name) + { + self.gradients.push(GradientDef { name: sw.name.clone(), gradient: g.gradient.clone(), swatch: true, used: false }); + } + } + } + + /// The name of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else a definition of the same gradient that no swatch names, else a + /// new one ([`free_gradient_name`]: `Gradient`, numbered when taken by another definition, a + /// swatch or a pattern). + fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { + let used = !self.in_palette; + let found = swatch + .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) + .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); + if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + d.used |= used; + return d.name.clone(); + } + let (doc, gradients) = (self.doc, &self.gradients); + let name = free_gradient_name(&mut self.next_gradient, |name| { + gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() + }); + self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); + name + } + + /// `p` as the paint of a fill or stroke whose gradient is placed on `bounds`: a gradient is + /// placed there (it then no longer depends on the shape it paints, which may be cut); one the + /// data can't hold is its average color, with a warning. + pub(super) fn placed(&mut self, p: &Paint, bounds: Rect) -> Paint { + let Paint::Gradient(g) = p else { return p.clone() }; + let geom = g.resolve(bounds); + let finite = [geom.start.x, geom.start.y, geom.end.x, geom.end.y, geom.aspect].iter().all(|v| v.is_finite()); + let radial = g.gradient.kind == GradientKind::Radial; + if g.gradient.kind == GradientKind::Freeform { + self.warn(GRADIENTS); + return Paint::solid(average(&g.gradient)); + } + if !writable_gradient(&g.gradient) || !finite || geom.length() < 1e-9 || (radial && geom.aspect <= 1e-9) { + self.warn(GRADIENT_SHAPES); + return Paint::solid(average(&g.gradient)); + } + Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..(**g).clone() })) + } + + /// The fills and strokes of `n` that paint (outline `bounds`), their gradients placed + /// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints. A gradient + /// along or across a stroke is its average color (the stroke is written as its outline). + pub(super) fn items(&mut self, n: &vectorcraft_doc::Node, bounds: Rect) -> Vec { + super::visible_items(n) + .into_iter() + .map(|i| match i { + AppearanceItem::Fill(f) => AppearanceItem::Fill(FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() }), + AppearanceItem::Stroke(s) => { + let paint = match s.path_gradient() { + Some(g) => { + self.warn(GRADIENTS); + Paint::solid(average(&g.gradient)) + } + None => self.placed(&s.paint, s.paint_bounds(bounds)), + }; + AppearanceItem::Stroke(StrokeLayer { paint, ..s.clone() }) + } + }) + .collect() + } + + /// Can paint `p` be written as the paint of a path object: a color, a placed gradient, or a + /// pattern [`Self::pattern_writable`]? + pub(super) fn direct(&self, p: &Paint) -> bool { + match p { + Paint::Solid { .. } => true, + Paint::Gradient(g) => g.geom.is_some() && writable_gradient(&g.gradient), + Paint::Pattern { pattern, .. } => self.pattern_writable(pattern), + Paint::None => false, + } + } + + /// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can + /// write it)? + pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool { + self.direct(&s.paint) && stroke::is_plain(s) + } + + /// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the + /// line over the fill; `None` when it has other paint. + pub(super) fn plain_paint<'i>(&self, items: &'i [AppearanceItem]) -> Option<(Option<&'i FillLayer>, Option<&'i StrokeLayer>)> { + match items { + [] => Some((None, None)), + [AppearanceItem::Fill(f)] if self.direct(&f.paint) => Some((Some(f), None)), + [AppearanceItem::Stroke(s)] if self.direct_stroke(s) => Some((None, Some(s))), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] if self.direct(&f.paint) && self.direct_stroke(s) => Some((Some(f), Some(s))), + _ => None, + } + } + + /// The painting operator `op` of a subpath (`closed` or open), with the gradient instances of + /// the fill (`fill`) and the stroke (`stroke`) around it when it is the last subpath of its + /// object: `Bb` … `op` `flag BB`, the stroke's `1 Bb` … after the fill's `BB`; the flag is 0, or + /// with a stroke 2 (closed) or 1 (open). `stroked`: the object has a stroke. A clipping path's + /// instances (`clip`) don't issue a clip of their own. `path`: the path the operator paints (all + /// its subpaths), in the document. + pub(super) fn painted( + &mut self, + op: char, + closed: bool, + gradients: (Option<&GradientPaint>, Option<&GradientPaint>), + stroked: bool, + clip: bool, + path: &BezPath, + ) { + let op = if closed { op } else { op.to_ascii_uppercase() }; + let flag = match (stroked, closed) { + (false, _) => "0 BB", + (true, true) => "2 BB", + (true, false) => "1 BB", + }; + let (fill, stroke) = gradients; + if let Some(f) = fill { + self.instance(f, false, clip, path); + if stroke.is_some() { + self.line(if closed { "2 BB" } else { "1 BB" }); + } + } + if let Some(s) = stroke { + self.instance(s, true, clip, path); + } + self.body.push(op); + self.body.push('\n'); + if fill.is_some() || stroke.is_some() { + self.line(flag); + } + } + + /// A gradient instance's start (placed gradient `g`, on the stroke when `stroke`, on `path` in + /// the document), before its painting operator: `Bb` (`1 Bb` on the stroke); a radial + /// gradient's focal point `x y angle fraction Bh` (its offset from the center in the space of the + /// gradient's matrices, then its angle and fraction as [`placement`] gives them; `0 0 0 0 Bh` at + /// the center); `flag (name) x y angle length a b c d tx ty 1 Bg` (flag 1, or 0 for a clipping + /// path; the rest as [`placement`] gives them); then the gradient's place: a linear one's `a b c d tx ty Xm` (the + /// unit vector onto its whole ramp), its cap before the first stop `… Bc`, a `… Bm` for each pair + /// of stops next to each other (the unit vector onto the part between them) and its cap past the + /// last stop; a radial one's `… Bm` (the unit circle onto its extent ellipse). + fn instance(&mut self, g: &GradientPaint, stroke: bool, clip: bool, path: &BezPath) { + let Some(geom) = g.geom else { return }; + let name = self.define_gradient(&g.gradient, g.swatch.as_deref()); + self.line(if stroke { "1 Bb" } else { "Bb" }); + let m = self.grad_space; + let u = geom.end - geom.start; + let radial = g.gradient.kind == GradientKind::Radial; + let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas); + if radial { + let c = m * geom.start; + let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c); + let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) }; + let off = if fraction > 0.0 { off } else { Vec2::ZERO }; + ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]); + self.line("Bh"); + } + let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes())); + ps::push_nums(&mut self.body, &place.bg); + ps::push_nums(&mut self.body, &place.transform.as_coeffs()); + self.line("1 Bg"); + // The unit vector along the gradient, and across it as long. + let frame = |from: f64, to: f64| { + let p = geom.start + u * from; + m * Affine::new([u.x * (to - from), u.y * (to - from), -u.y, u.x, p.x, p.y]) + }; + let mut matrix = |a: Affine, op: &str| { + ps::push_nums(&mut self.body, &a.as_coeffs()); + self.body.push_str(op); + self.body.push('\n'); + }; + if radial { + matrix(m * geom.unit_frame().unwrap_or(Affine::new([u.x, u.y, -u.y, u.x, geom.start.x, geom.start.y])), "Bm"); + return; + } + matrix(frame(0.0, 1.0), "Xm"); + let offsets: Vec = sorted_stops(&g.gradient).iter().map(|s| f64::from(s.offset)).collect(); + let len = u.hypot().max(1e-9); + let (first, last) = (offsets.first().copied().unwrap_or(0.0), offsets.last().copied().unwrap_or(1.0)); + matrix(frame(first - CAP / len, first), "Bc"); + for pair in offsets.windows(2) { + if let [a, b] = pair { + matrix(frame(*a, *b), "Bm"); + } + } + matrix(frame(last, last + CAP / len), "Bc"); + } + + /// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd` (type 0 linear, + /// 1 radial), `[`, each stop on a `%_` line (`color style opacity 6 midpoint rampPoint Bs`), a + /// linear gradient's from the last to the first and a radial one's from the first to the last, + /// `BD`, `%AI5_EndGradient`. + fn gradient_def(&mut self, s: &mut String, d: &GradientDef) { + if d.gradient.dither || !d.gradient.method.is_classic() { + self.warn(GRADIENT_MIX); + } + let name = ps::bytes(d.name.as_bytes()); + let radial = d.gradient.kind == GradientKind::Radial; + let _ = writeln!(s, "%AI5_BeginGradient: {name}\n{name} {} {} Bd\n[", u8::from(radial), d.gradient.stops.len()); + let mut stops = sorted_stops(&d.gradient); + if !radial { + stops.reverse(); + } + for stop in stops { + s.push_str("%_"); + self.stop_color(s, stop); + ps::push_nums(s, &[f64::from(unit(stop.opacity)), 6.0, f64::from(stop.midpoint) * 100.0, f64::from(stop.offset) * 100.0]); + s.push_str("Bs\n"); + } + s.push_str("BD\n%AI5_EndGradient\n"); + } + + /// A stop's color and its style: gray `lightness 0`, CMYK `c m y k 1`, RGB (and Lab, as RGB) + /// `c m y k r g b 2` with its CMYK equivalent; a spot color its full color's CMYK equivalent, + /// then its RGB values when it isn't CMYK, its name and how much lighter than the full color, + /// then `3` (CMYK), or `1 4` (RGB, and Lab as RGB). + fn stop_color(&mut self, s: &mut String, stop: &GradientStop) { + let doc = self.doc; + let intent = self.cms.settings().intent; + if let Some(name) = stop.swatch.as_deref().filter(|n| *n != REGISTRATION) + && let Some(sw) = doc.swatch(name) + && let Paint::Solid { color: full, swatch: None, .. } = sw.paint + { + if sw.spot { + let cmyk = self.cms.to_cmyk(&doc.linked_color(full, true), intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + let rgb = !matches!(full, Color::Cmyk { .. }); + if rgb { + ps::push_nums(s, &full.to_rgb().map(|v| f64::from(unit(v)))); + } + s.push_str(&ps::bytes(name.as_bytes())); + s.push(' '); + ps::push_num(s, f64::from(1.0 - unit(stop.tint))); + s.push_str(if rgb { " 1 4 " } else { " 3 " }); + return; + } + if sw.global { + self.warn(STOP_LINKS); + } + } + match stop.color { + Color::Gray { k } => { + ps::push_num(s, f64::from(1.0 - unit(k))); + s.push_str(" 0 "); + } + Color::Cmyk { c, m, y, k } => { + ps::push_nums(s, &[c, m, y, k].map(|v| f64::from(unit(v)))); + s.push_str("1 "); + } + color @ (Color::Rgb { .. } | Color::Lab { .. }) => { + let cmyk = self.cms.to_cmyk(&color, intent).map(unit); + ps::push_nums(s, &cmyk.map(f64::from)); + ps::push_nums(s, &color.to_rgb().map(|v| f64::from(unit(v)))); + s.push_str("2 "); + } + } + } + + // ---------- patterns ---------- + + /// Can pattern `name` be written as a definition and painted with from here: the document has + /// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used + /// in another pattern's tile or nested more than [`MAX_NEST`] deep? + pub(super) fn pattern_writable(&self, name: &str) -> bool { + if !self.defining.is_empty() || self.nest >= MAX_NEST { + return false; + } + if self.patterns.iter().any(|p| p.name == name) { + return true; + } + self.doc.pattern(name).is_some_and(tile_holds_art) + } + + /// Write pattern `name`'s definition, once: `%AI3_BeginPattern: (name)`, `(name) llx lly urx + /// ury` (the tile, y up), the tile's box (an unpainted path whose dictionary marks it, + /// `AIPattern_Editor_Backing_Tile_Rect`) and the art on `%_` lines, `E`, `%AI3_EndPattern`. + /// False when it can't be ([`Self::pattern_writable`]). + fn define_pattern(&mut self, name: &str) -> bool { + if !self.pattern_writable(name) { + return false; + } + let used = !self.in_palette; + if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + p.used |= used; + return true; + } + let doc = self.doc; + let Some(def) = doc.pattern(name) else { return false }; + self.defining.push(name.to_string()); + // The art is written in the pattern's space, y up, from the state a definition starts in. + let saved = ( + std::mem::take(&mut self.body), + (self.to_art, self.grad_space, self.canvas), + self.state.take(), + self.gs.replace(Xy::OPAQUE), + self.clip.take(), + self.block_end, + ); + // `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its + // placement is worked out in the tile's space turned y up. + (self.to_art, self.grad_space, self.canvas, self.block_end) = (Affine::FLIP_Y, self.tile_grad_space, Affine::FLIP_Y, usize::MAX); + // The tile's box first, unpainted and marked as the box: the tile is that box. + self.state(false, false); + self.line("0 XR"); + if let Some(sp) = vectorcraft_geom::shapes::rectangle(def.tile).subpaths.first() { + crate::ai_ops::subpath(&mut self.body, self.to_art, sp); + } + self.line("n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_"); + self.nest += 1; + self.hidden += 1; + for a in &def.art { + self.node(a); + } + self.hidden -= 1; + self.nest -= 1; + let art; + (art, (self.to_art, self.grad_space, self.canvas), self.state, self.gs, self.clip, self.block_end) = saved; + let art = std::mem::replace(&mut self.body, art); + self.defining.pop(); + let tile = Affine::FLIP_Y.transform_rect_bbox(def.tile); + let quoted = ps::bytes(name.as_bytes()); + let mut text = format!("%AI3_BeginPattern: {quoted}\n{quoted} "); + ps::push_nums(&mut text, &[tile.x0, tile.y0, tile.x1, tile.y1]); + text.pop(); + text.push('\n'); + super::hide(&art, &mut text); + text.push_str("E\n%AI3_EndPattern\n"); + self.patterns.push(PatternOut { name: name.to_string(), text, used }); + true + } + + /// Set the fill (or with `stroke`, the stroke) to pattern `name` placed by `xf` (the pattern's + /// space → the document): `(name) 0 0 1 1 0 0 0 0 0 [matrix] p` (`P` for the stroke), the + /// matrix taking the pattern's space (y up, the tile's lower left corner its origin) to the + /// art's. A pattern that can't be defined paints mid gray. + pub(super) fn pattern_paint(&mut self, name: &str, xf: Affine, stroke: bool) { + let height = self.doc.pattern(name).map(|d| d.tile.height()); + let Some(h) = height.filter(|_| self.define_pattern(name)) else { + self.warn(super::PATTERNS); + return self.plain_color(Color::gray(0.5), stroke); + }; + let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y; + let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' }); + } + + /// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then + /// each), those only the palette uses between `%AI5_Begin_NonPrinting`, `Np` and + /// `%AI5_End_NonPrinting--`, then the patterns in the same way (a pattern after those its art + /// uses). + pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { + let defs = std::mem::take(&mut self.gradients); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let _ = writeln!(s, "{} Bn", used.len()); + for d in &used { + self.gradient_def(s, d); + } + if !unused.is_empty() { + let _ = writeln!(s, "%AI5_Begin_NonPrinting\nNp\n{} Bn", unused.len()); + for d in &unused { + self.gradient_def(s, d); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + self.gradients = defs; + for p in self.patterns.iter().filter(|p| p.used) { + s.push_str(&p.text); + } + if self.patterns.iter().any(|p| !p.used) { + s.push_str("%AI5_Begin_NonPrinting\nNp\n"); + for p in self.patterns.iter().filter(|p| !p.used) { + s.push_str(&p.text); + } + s.push_str("%AI5_End_NonPrinting--\n"); + } + } + + /// A gradient swatch's or pattern swatch's paint in the palette: `Bb`, a radial gradient's + /// `0 0 0 0 Bh`, `2 (name) 0 0 0 1 1 0 0 1 0 0 1 Bg`, `0 BB`; a pattern's + /// `(name) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p`. False for other paint, and for paint that can't + /// be written. + pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool { + match &sw.paint { + Paint::Gradient(g) if writable_gradient(&g.gradient) => { + let swatch = Some(sw.name.as_str()); + let name = self.define_gradient(&g.gradient, swatch); + s.push_str("Bb\n"); + if g.gradient.kind == GradientKind::Radial { + s.push_str("0 0 0 0 Bh\n"); + } + let _ = writeln!(s, "2 {} 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB", ps::bytes(name.as_bytes())); + true + } + Paint::Pattern { pattern, xf } if self.define_pattern(pattern) => { + if *xf != Affine::IDENTITY { + self.warn(SWATCH_PLACEMENT); + } + let _ = writeln!(s, "{} 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p", ps::bytes(pattern.as_bytes())); + true + } + _ => false, + } + } +} + +/// Where `Bg` places a gradient: its `x y angle length` operands, its matrix, and a radial +/// gradient's focal point as `Bh`'s angle and fraction ([`placement`]). +struct Placement { + bg: [f64; 4], + transform: Affine, + focal: (f64, f64), +} + +impl Placement { + /// The gradient's place on the path before it is moved: `0 0 0 1`, the identity. + const UNMOVED: Placement = Placement { bg: [0.0, 0.0, 0.0, 1.0], transform: Affine::IDENTITY, focal: (0.0, 0.0) }; +} + +/// The `Bg` operands that place gradient `geom` (`radial` or linear) on `path`, both in the canvas's +/// space (y down; `canvas` takes the document there; in a pattern's tile, the tile's space turned y +/// up). `Bg` places a gradient in the space its matrix takes to the canvas's, on the path as it lies +/// there: +/// +/// - a linear one's ramp runs at `angle` degrees (counterclockwise, y up) from `x` times the path's +/// extent along that angle past where the path starts along it, `length` times that extent long +/// (`y` doesn't move it); +/// - a radial one's center lies `x` times the width and `y` times the height (y down) of the path's +/// bounds from their center, and its radius is `length` times √((dx² + dy²) / 2), `dx` and `dy` the +/// center's distances to the right side and to the bottom of the bounds, whether or not those are +/// the nearer sides; its focal point lies at `Bh`'s angle (y up), its distance from the center a +/// fraction of the radius. +/// +/// A linear gradient is written with the identity, a radial one with the matrix that takes the +/// unit circle onto its extent ellipse at the origin (so that its circle there is the unit circle). +/// [`Placement::UNMOVED`] when the path has no extent along the gradient or the gradient has none. +fn placement(geom: &GradientGeom, radial: bool, path: &BezPath, canvas: Affine) -> Placement { + let s = canvas * geom.start; + let u = canvas * geom.end - s; + if !radial { + let turn = Affine::rotate(-u.atan2()); + let along = (turn * path.clone()).bounding_box(); + let extent = along.width(); + if !(extent > 1e-9 && extent.is_finite() && u.hypot() > 1e-9) { + return Placement::UNMOVED; + } + let bg = [((turn * s).x - along.x0) / extent, 0.0, (-u.y).atan2(u.x).to_degrees(), u.hypot() / extent]; + return Placement { bg, ..Placement::UNMOVED }; + } + // The unit circle's image: `u` along the vector, `v` across it (the aspect ratio), turning the same way. + let across = geom.end - geom.start; + let mut v = canvas * (geom.start + Vec2::new(-across.y, across.x) * geom.aspect) - s; + if u.cross(v) < 0.0 { + v = -v; + } + let m = Affine::new([u.x, u.y, v.x, v.y, 0.0, 0.0]); + let det = m.determinant().abs(); + if det.is_nan() || det <= 1e-12 { + return Placement::UNMOVED; + } + let back = m.inverse(); + let b = (back * path.clone()).bounding_box(); + let c = back * s; + let (dx, dy) = (b.x1 - c.x, b.y1 - c.y); + let unit = ((dx * dx + dy * dy) / 2.0).sqrt(); + if !(b.width() > 1e-9 && b.height() > 1e-9 && unit > 1e-9 && unit.is_finite()) { + return Placement::UNMOVED; + } + let off = geom.focal.map_or(Vec2::ZERO, |f| back * (canvas * f) - c); + let focal = if off.hypot() > 1e-9 { ((-off.y).atan2(off.x).to_degrees(), off.hypot()) } else { (0.0, 0.0) }; + let bg = [(c.x - b.center().x) / b.width(), (c.y - b.center().y) / b.height(), 0.0, 1.0 / unit]; + Placement { bg, transform: m, focal } +} + +/// Do `def`'s tiles make a grid, with its art (something) within the tile? Art past the tile would +/// be cut off at the tile's edge. +fn tile_holds_art(def: &PatternDef) -> bool { + let t = def.tile; + let tile_ok = [t.x0, t.y0, t.x1, t.y1].iter().all(|v| v.is_finite()) && t.width() > 0.0 && t.height() > 0.0; + tile_ok + && def.tile_type == TileType::Grid + && def.art_bounds().is_some_and(|b| { + let room = t.inflate(1e-6, 1e-6); + b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 + }) +} diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index cfa3928eca..a22c94de53 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -49,13 +49,16 @@ pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) { } } -/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`; with `closing`, a closed -/// subpath ends `(n) *` (the painting operator that closes it first). -pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, closing: bool) { +/// A guide (§6): for each subpath, `(N) *`, its points, `(N) *`. In `editing` data (see +/// [`crate::ai_editing`]) a subpath is its points and `(N) *` alone, `(n) *` when closed (the +/// painting operator that closes it first). +pub(crate) fn guide(s: &mut String, xf: Affine, path: &PathData, editing: bool) { for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) { - s.push_str("(N) *\n"); + if !editing { + s.push_str("(N) *\n"); + } subpath(s, xf, sp); - s.push_str(if closing && sp.closed { "(n) *\n" } else { "(N) *\n" }); + s.push_str(if editing && sp.closed { "(n) *\n" } else { "(N) *\n" }); } } diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index aefb80ccb1..1b0ad86049 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -70,6 +70,7 @@ use graphics::{GState, Out}; use interp::{Fault, Interp}; use obj::PsError; +pub(crate) use ai::MAX_GRADIENT_STOPS; pub(crate) use native::scale_document; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, is_loss, layered_ai, layered_ai_from}; pub use text::family_style; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index e413f6ec8e..21c6a62aa0 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -36,8 +36,10 @@ use crate::ps; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use frames::text_frames; +pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS; pub use read::{ - BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, palette, read, read_beside, variables, + BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, graphic_styles, palette, read, read_beside, + variables, }; pub(crate) use read::{join_and, slot_frame, slot_of}; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index 3904e6aabe..4c9bda1b10 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -7,8 +7,18 @@ //! - One object, the brush manager's order, has the order of the Brushes panel: its parameters //! are the plug-in name and brush name of each brush, each one after a `/` and a space. //! - A Calligraphic brush's parameters are 11 numbers: the first is 1; the diameter, roundness and -//! angle as (low, high) pairs; how the diameter, roundness and angle vary (0 Fixed, 1 Random, 2 -//! Pressure, other codes the pen's other channels); a last number. +//! angle as (low, high) pairs; how the diameter, roundness and angle vary; a last number. The +//! codes follow the order of the Brush Options menu: 0 Fixed, 1 Random, 2 Pressure, 3 Stylus +//! Wheel, 4 Tilt, 5 Bearing, 6 Rotation. A user's 6D Art Pen brushes (#372) vary the diameter +//! with 2, the roundness with 5 and the angle with 6, the angle over a whole turn, as the barrel +//! rotation turns the nib. VectorCraft reads no stylus wheel: 3 is read as Random when the value +//! varies, as an unknown code is. +//! - A path with a Calligraphic brush is a stroke in its art style ([`super::style`]): the filter +//! `(Adobe Calligraphic Brush Tool)`, its stroke's paint and weight (the weight scales the brush: +//! 1 pt draws it at its own size), the brush by name (`/GObjRef : (name) (plug-in) +//! /PluginObject`), and the brush's settings for this path as entries: `Diameter`, `Roundness`, +//! `Angle`, their `…Variation` either side and `…DependsOn` codes, and `AngleRelativeTo` (0 the +//! page). //! - A Scatter, Art or Pattern brush's parameters are fields split by `/`: a number, the art's //! section names (one for Scatter, five for Art and Pattern, empty where there is none, each //! after a space for Art and Pattern), more fields, and last 15 numbers. @@ -168,12 +178,15 @@ fn numbers(s: &str) -> Option> { s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() } -/// How a value varies, by its code: `None` for a code that isn't Fixed, Random or Pressure. +/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known. fn variation(code: f64) -> Option { match code { 0.0 => Some(Variation::Fixed), 1.0 => Some(Variation::Random), 2.0 => Some(Variation::Pressure), + 4.0 => Some(Variation::Tilt), + 5.0 => Some(Variation::Bearing), + 6.0 => Some(Variation::Rotation), _ => None, } } @@ -183,6 +196,27 @@ fn mode(code: f64, varies: bool) -> Variation { variation(code).unwrap_or(if varies { Variation::Random } else { Variation::Fixed }) } +/// A Calligraphic brush of angle, roundness and size `values`, each varying `variation` either side +/// as its code in `codes` says. +pub(super) fn calligraphic(values: [f64; 3], variation: [f64; 3], codes: [f64; 3]) -> Calligraphic { + let [angle, roundness, size] = values; + let modes = [0, 1, 2].map(|i| mode(codes[i], variation[i] != 0.0)); + Calligraphic { angle, roundness, size, variation, modes: Some(modes) } +} + +/// Does the brush `draft` draw as `c`, the settings a path's art style gives it? A path whose +/// settings differ (Options of Selected Object) keeps its drawn look: a stroke names a brush, and +/// has no settings of its own. +pub(super) fn draws_as(draft: &BrushDraft, c: &Calligraphic) -> bool { + let DraftKind::Calligraphic(d) = &draft.kind else { return false }; + let close = |a: f64, b: f64| (a - b).abs() <= 1e-3 * a.abs().max(b.abs()).max(1.0); + close(d.angle, c.angle) + && close(d.roundness, c.roundness) + && close(d.size, c.size) + && d.variation.iter().zip(&c.variation).all(|(a, b)| close(*a, *b)) + && d.modes() == c.modes() +} + /// The brush named `name` of kind `kind` from its parameters `params`. pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result { let kind = match kind { @@ -191,15 +225,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result< let [_, d0, d1, r0, r1, a0, a1, dm, rm, am, ..] = n.as_slice() else { return Err(BrushError::Values) }; let mid = |a: f64, b: f64| (a + b) / 2.0; let half = |a: f64, b: f64| (b - a).abs() / 2.0; - let variation = [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)]; - let modes = [mode(*am, variation[0] != 0.0), mode(*rm, variation[1] != 0.0), mode(*dm, variation[2] != 0.0)]; - DraftKind::Calligraphic(Calligraphic { - angle: mid(*a0, *a1), - roundness: mid(*r0, *r1), - size: mid(*d0, *d1), - variation, - modes: Some(modes), - }) + DraftKind::Calligraphic(calligraphic( + [mid(*a0, *a1), mid(*r0, *r1), mid(*d0, *d1)], + [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)], + [*am, *rm, *dm], + )) } Tool::Scatter | Tool::Art | Tool::Pattern => { let fields: Vec<&str> = params.split('/').collect(); diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 17590b3203..04e181ed48 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -1,69 +1,209 @@ //! Type in the legacy format (version 7 specification §15): text objects `type To` … `TO`, their -//! text path (`a b c d tx ty startPt Tp`, an area's frame or the path type runs along, `TP`), the -//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's -//! letter and word spacing `TC TW`, hanging punctuation `Tq` and hyphenation `Th`), the paint style, and -//! the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Final-form operators (the +//! text paths (`a b c d tx ty startPt Tp`, an area's frame, one for each linked area, or the path +//! type runs along, `TP`), the modal character and paragraph attributes +//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging +//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`), the paint style, and the characters (`Tx`, `Tj`, +//! overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the +//! text object clips the objects of its clipping group. Final-form operators (the //! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the -//! file's `TE` encoding, else as Windows-1252; a re-encoded font `/_name` is the font its -//! `%AI3_BeginEncoding` names (else `name`). +//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s +//! `useDefault` is 0, else as Windows-1252; a re-encoded font `/_name` is the font its `%AI3_BeginEncoding` or `TZ` names +//! (else `name`). use kurbo::{Affine, BezPath, ParamCurve, ParamCurveArclen}; use vectorcraft_color::Paint; -use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, Justify, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject, TextRun}; use vectorcraft_geom::AnchorKind; use super::super::obj::V; use super::art::path_data; -use super::{FLIP, GState, Reader}; +use super::{FLIP, GState, HashSet, Kind, Node, NodeId, Reader}; use crate::latin; /// Most characters of type read in one file. const MAX_CHARS: usize = 1 << 22; /// Largest type size and indent read (points). const MAX_SIZE: f64 = 1e4; +/// Most re-encoded fonts read in one file, for their names and for their encodings each. +const MAX_FONTS: usize = 4096; +/// Most tab stops read in one tab definition. +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, +/// with a warning. +const MAX_TEXT_PATHS: usize = 4096; +/// Most frames of linked areas times characters of their story: the story is laid out again +/// through its frames when the file opens. The frames of the areas past it are left out, with a +/// warning. +const MAX_THREAD_WORK: usize = MAX_CHARS; +/// The warning when [`MAX_TEXT_PATHS`] or [`MAX_THREAD_WORK`] leaves frames of linked areas out. +const LINKED_AREAS_LEFT_OUT: &str = "linked type areas past VectorCraft's limits were left out"; +/// The warning when type set in a mask rendering mode can't be a clipping path: type in linked +/// areas (several frames), in wraparound text or in a compound path doesn't clip. +const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip"; + +/// A text path (`Tp` … `TP`). +#[derive(Debug, Default)] +struct TextPath { + /// `Tp`'s matrix: text space (y up) → art space. + matrix: Option, + /// Where type on a path starts: a segment's index plus how far along it. + start: f64, + /// The frame or path, in art space, and the kind of the anchor each of its segments ends on. + path: Option<(BezPath, Vec)>, +} + +/// 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 { /// `To`'s type: 0 point type, 1 area type, 2 type on a path. kind: i64, - /// `Tp`'s matrix: text space (y up) → art space. - matrix: Option, - /// Where type on a path starts: a segment's index plus how far along it. - start: f64, + /// Its text paths in file order: area type has one for each linked area (§15.5.3). + paths: Vec, /// Between `Tp` and `TP`: the path read is the text path. in_path: bool, - /// The frame or path, in art space, and the kind of the anchor each of its segments ends on. - path: Option<(BezPath, Vec)>, + /// It has more than [`MAX_TEXT_PATHS`] text paths: the paths read past them are left out. + past_limit: bool, + /// The story: the characters after every text path, in file order. runs: Vec, - /// Each paragraph's attributes, as they were at its first character. - paras: Vec, + /// The paragraphs' attributes, as they were at the first character of each, by runs of + /// paragraphs with the same attributes. + paras: Vec, + /// 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. pending_break: bool, + /// Characters were set in a mask rendering mode (`Tr` 4 to 7): the text object is a clipping + /// path (§5.7). + clips: bool, /// The state when it began (lock, visibility), and whether it began on a `%_` line. gs: GState, 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, copied: &mut usize, left_out: &mut bool) -> Vec { + 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. encoding: Vec>, - /// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`). + /// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s). fonts: Vec<(String, String)>, + /// Re-encoded fonts' own encodings (`TZ`), by the new font's name: what its encoding pairs + /// change, by code (None where they say nothing), and whether `TE`'s encoding applies to it. + font_encodings: Vec<(String, Vec>, bool)>, + /// The font `Tf` set last, as the file names it. + font: Option, + /// Between `Xb` and `XB`: the tab stops of the tab definition read so far. + tabs: Option>, chars: usize, } impl Default for TypeState { fn default() -> Self { - Self { style: CharStyle::default(), para: ParaStyle::default(), render: 0, encoding: vec![None; 256], fonts: vec![], chars: 0 } + Self { + style: CharStyle::default(), + para: ParaStyle::default(), + tabs_version: 0, + render: 0, + encoding: vec![None; 256], + fonts: vec![], + font_encodings: vec![], + font: None, + tabs: None, + chars: 0, + } } } @@ -72,10 +212,51 @@ impl TypeState { pub(super) fn encoding_comment(&mut self, line: &str) { let Some((_, names)) = line.split_once(':') else { return }; let mut words = names.split_whitespace(); - if let (Some(new), Some(old)) = (words.next(), words.next()) - && self.fonts.len() < 4096 - { - self.fonts.push((new.trim_start_matches('/').to_string(), old.trim_start_matches('/').to_string())); + if let (Some(new), Some(old)) = (words.next(), words.next()) { + self.font_names(new.trim_start_matches('/'), old.trim_start_matches('/')); + } + } + + /// Re-encoded font `new` is font `old`. The first statement for a name is used. + fn font_names(&mut self, new: &str, old: &str) { + if self.fonts.len() < MAX_FONTS && !self.fonts.iter().any(|(n, _)| n == new) { + self.fonts.push((new.to_string(), old.to_string())); + } + } + + /// A string's bytes, in the current font. + fn decode(&self, bytes: &[u8]) -> String { + let own = self.font.as_ref().and_then(|f| self.font_encodings.iter().find(|(n, _, _)| n == f)); + let (own, te) = own.map_or((None, true), |(_, e, te)| (Some(e.as_slice()), *te)); + bytes + .iter() + .map(|&b| { + if b == b'\r' { + return '\n'; + } + own.and_then(|e| e.get(usize::from(b)).copied().flatten()) + .or_else(|| if te { self.encoding.get(usize::from(b)).copied().flatten() } else { None }) + .unwrap_or_else(|| latin::decode(b)) + }) + .collect() + } +} + +/// Encoding pairs (§3.3.1): codes, each followed by the glyph names from it on, into `table`. +fn encoding_pairs(table: &mut [Option], vals: &[V]) { + let mut code: Option = None; + for v in vals { + match v { + V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize), + V::Name(name) => { + if let Some(c) = code { + if let (Some(slot), Ok(b)) = (table.get_mut(c), u8::try_from(c)) { + *slot = latin::glyph(b, name); + } + code = Some(c + 1); + } + } + _ => {} } } } @@ -102,19 +283,86 @@ fn flag(v: f64) -> Option { impl Reader<'_> { /// `[encodingPairs TE`: codes, each followed by the glyph names from it on (§3.3.1). pub(super) fn te(&mut self, vals: &[V]) { - let mut code: Option = None; - for v in vals { - match v { - V::Num(n) if n.is_finite() && (0.0..256.0).contains(n) => code = Some(*n as usize), - V::Name(name) => { - if let Some(c) = code { - if let (Some(slot), Ok(b)) = (self.type_state.encoding.get_mut(c), u8::try_from(c)) { - *slot = latin::glyph(b, name); - } - code = Some(c + 1); + encoding_pairs(&mut self.type_state.encoding, vals); + } + + /// `[encodingPairs newFontName oldFontName direction fontScript useDefault TZ`, with a Multiple + /// Master weight vector `[w0 … wn]` after it, and without the encoding pairs or the direction + /// in some versions (§3.3.1): the new font's own encoding pairs, which strings in it are + /// decoded by first. `useDefault` 1 (or no number after the names) decodes the codes the pairs + /// leave out by `TE`'s encoding, and 0 leaves `TE`'s encoding out for the font. The font names + /// are the last two names; only numbers and the weight vector follow them. The first `TZ` for + /// a font is used. + pub(super) fn tz(&mut self, vals: &[V]) { + let mut names = vals.iter().enumerate().filter_map(|(i, v)| if let V::Name(n) = v { Some((i, n)) } else { None }).rev(); + let (Some((old_at, old)), Some((new_at, new))) = (names.next(), names.next()) else { return }; + if new_at + 1 != old_at { + return; + } + let tail = vals.get(old_at + 1..).unwrap_or_default(); + let weights = matches!(tail.last(), Some(V::Arr(_))); + let numbers = tail.get(..tail.len() - usize::from(weights)).unwrap_or_default(); + if !numbers.iter().all(|v| matches!(v, V::Num(_))) { + return; + } + let te = !matches!(numbers.last(), Some(V::Num(n)) if *n == 0.0); + let st = &mut self.type_state; + st.font_names(new, old); + if st.font_encodings.iter().any(|(n, _, _)| n == new) || st.font_encodings.len() >= MAX_FONTS { + return; + } + // The pairs start after the `[` that opens them. + let pairs = vals.get(..new_at).unwrap_or_default(); + let pairs = pairs.iter().rposition(|v| matches!(v, V::Mark)).map_or(pairs, |m| pairs.get(m + 1..).unwrap_or_default()); + let mut table = vec![None; 256]; + encoding_pairs(&mut table, pairs); + st.font_encodings.push((new.clone(), table, te)); + } + + /// What is between `%AI3_BeginEncoding` and `%AI3_EndEncoding` (§3.3): its `TZ` is read, and + /// every other operator is skipped with its operands. + pub(super) fn encoding_section(&mut self, section: &[u8]) { + let mut lex = super::Lexer::new(section); + let mut vals: Vec = Vec::new(); + let mut marks: Vec = Vec::new(); + // `[`s past the value limit, which are not kept: as many `]`s after them are skipped. + let mut dropped: usize = 0; + while let Some(t) = lex.next_token() { + let v = match t.tok { + super::Tok::Num(n) => V::Num(n), + super::Tok::Name(n) => V::Name(super::obj::text(n)), + super::Tok::Str(s) | super::Tok::Hex(s) => V::Str(s), + super::Tok::Word(b"[") => { + // Each `[` kept is a value, so the open arrays are no more than the values. + if vals.len() >= MAX_ENCODING_VALUES { + dropped = dropped.saturating_add(1); + continue; } + marks.push(vals.len()); + V::Mark } - _ => {} + super::Tok::Word(b"]") => { + if dropped > 0 { + dropped -= 1; + continue; + } + let Some(m) = marks.pop() else { continue }; + let items: Vec = vals.split_off(m.min(vals.len())).into_iter().skip(1).collect(); + V::Arr(items) + } + super::Tok::Word(w) => { + if w == b"TZ" { + self.tz(&vals); + } + vals.clear(); + marks.clear(); + dropped = 0; + continue; + } + _ => continue, + }; + if vals.len() < MAX_ENCODING_VALUES { + vals.push(v); } } } @@ -131,6 +379,8 @@ impl Reader<'_> { self.unreadable("type in a pattern", false); } let kind = nums::<1>(vals).map_or(0, |[k]| k as i64); + // A tab definition left open by an earlier text object (an `Xb` with no `XB`) ends here. + self.type_state.tabs = None; self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() }); } @@ -144,27 +394,28 @@ impl Reader<'_> { 6 => (nums::<6>(vals), None), _ => (None, None), }; - if let Some(m) = m { - let m = Affine::new(m); + let matrix = m.map(Affine::new).filter(|m| { let det = m.determinant(); - if det.is_finite() && det.abs() > 1e-12 { - t.matrix = Some(m); - } + det.is_finite() && det.abs() > 1e-12 + }); + let start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + t.past_limit |= t.paths.len() >= MAX_TEXT_PATHS; + if !t.past_limit { + t.paths.push(TextPath { matrix, start, path: None }); } - t.start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); t.in_path = true; } - /// The path painted (or `TP`, ending the text path): the text object's frame or path. + /// The path painted (or `TP`, ending the text path): the text path's frame or path. pub(super) fn text_path(&mut self) { let path = std::mem::take(&mut self.path); let kinds = std::mem::take(&mut self.path_kinds); self.end_path_quietly(); - if let Some(t) = self.text.as_mut() - && t.path.is_none() + if let Some(p) = self.text.as_mut().filter(|t| !t.past_limit).and_then(|t| t.paths.last_mut()) + && p.path.is_none() && !path.elements().is_empty() { - t.path = Some((path, kinds)); + p.path = Some((path, kinds)); } } @@ -182,8 +433,9 @@ impl Reader<'_> { let st = &mut self.type_state; let n0 = nums::<1>(vals).map(|[v]| v); match w { + // `render Tr`: a mode from 0 to 9 (§15.4.5.1). "Tr" => { - if let Some(v) = n0 { + if let Some(v) = n0.filter(|v| v.fract() == 0.0 && (0.0..=9.0).contains(v)) { st.render = v as i64; } } @@ -191,6 +443,7 @@ impl Reader<'_> { // `/name size Tf`, or `/name size ascent descent Tf`. let Some(at) = vals.iter().position(|v| matches!(v, V::Name(_))) else { return }; if let Some(V::Name(name)) = vals.get(at) { + st.font = Some(name.clone()); let name = st.fonts.iter().find(|(new, _)| new == name).map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); let (family, style) = super::super::super::text::family_style(&name); @@ -293,6 +546,38 @@ impl Reader<'_> { h.before_last = letters(tail, 1.0, 15.0); h.hyphen_limit = if limit { letters(max, 0.0, 25.0) } else { 0 }; } + // A tab definition (§22.6): `numDots numTabs Xb` begins it, each + // `leader decimal tabType tabPosition Xe` describes one tab stop, and `XB` ends it. The + // stops it describes replace the paragraph's tab stops, sorted by position, one stop at + // each position; a definition with none (or whose descriptions were all skipped) leaves + // the default stops. The dot-leader distance, the count and the two reserved operands are + // not read. A description whose type is not 1 to 4 (left, center, right, decimal) or + // whose position is not a number from 0 to [`MAX_TAB_POSITION`] is skipped, and so is one + // outside a tab definition or past the first [`MAX_TABS`] of one. A text object's `To` + // ends a definition that an earlier object left open. + "Xb" => st.tabs = Some(vec![]), + "Xe" => { + let Some(tabs) = st.tabs.as_mut().filter(|t| t.len() < MAX_TABS) else { return }; + let Some([kind, position]) = nums::<2>(vals) else { return }; + let align = match kind { + 1.0 => TabAlign::Left, + 2.0 => TabAlign::Center, + 3.0 => TabAlign::Right, + 4.0 => TabAlign::Decimal, + _ => return, + }; + if (0.0..=MAX_TAB_POSITION).contains(&position) { + tabs.push(TabStop { position, align, leader: String::new(), align_on: '.' }); + } + } + "XB" => { + if let Some(mut tabs) = st.tabs.take() { + 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); + } + } _ => {} } } @@ -302,10 +587,7 @@ impl Reader<'_> { let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return }; let st = &mut self.type_state; let Some(t) = self.text.as_mut() else { return }; - let decoded: String = bytes - .iter() - .map(|&b| if b == b'\r' { '\n' } else { st.encoding.get(usize::from(b)).copied().flatten().unwrap_or_else(|| latin::decode(b)) }) - .collect(); + let decoded = st.decode(&bytes); if decoded.is_empty() { return; } @@ -323,6 +605,9 @@ impl Reader<'_> { st.chars += decoded.chars().count(); let gs = &self.gs; let mut style = st.style.clone(); + // Characters in modes 4 to 7 make the whole text object the mask, not each run (§5.7); 7 + // paints nothing, nor does 3 (invisible). + t.clips |= (4..=7).contains(&st.render); let (fill, stroke) = match st.render { 0 | 4 => (true, false), 1 | 5 => (false, true), @@ -341,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; } @@ -358,35 +643,124 @@ impl Reader<'_> { } } - /// `TO`: the text object ends. + /// `TO`: the text object ends. Area type with several linked areas becomes one frame for each + /// area, threaded in file order: the first frame holds the story, and the flow from area to + /// area (final-form, §15.1) is laid out again. The frames are added last to first, so the + /// object's dictionary that follows names the first one ([`Reader::each_linked_frame`]). + /// 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(()); } - let m = t.matrix.unwrap_or(Affine::IDENTITY); let to_doc = self.space(); - // Art space → text space (y down). - let to_text = FLIP * m.inverse(); - let kind = match (t.kind, &t.path) { - (1, Some((p, kinds))) => TextKind::Area { frame: path_data(&(to_text * p.clone()), kinds) }, - (2, Some((p, kinds))) => { - TextKind::OnPath { path: path_data(&(to_text * p.clone()), kinds), start: start_fraction(p, t.start), end: None } - } - _ => TextKind::Point, + let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum(); + let most = (MAX_THREAD_WORK / chars.max(1)).max(1); + let all_areas = t.paths.iter().filter(|p| p.path.is_some()).count(); + // Area type with linked areas, also when the limits leave one frame of it. + let linked = t.kind == 1 && (all_areas > 1 || t.past_limit); + let areas: Vec<&TextPath> = t.paths.iter().filter(|p| p.path.is_some()).take(most).collect(); + let placed: Vec<(Affine, TextKind)> = match t.kind { + 1 if areas.len() > 1 => areas.into_iter().map(|p| placed(1, Some(p))).collect(), + 0 => vec![placed(0, t.paths.first())], + kind => vec![placed(kind, areas.first().copied().or(t.paths.first()))], }; - let mut obj = TextObject::point(kurbo::Point::ZERO, "", CharStyle::default()); - obj.kind = kind; - obj.xf = to_doc * m * FLIP; - obj.runs = t.runs; - let mut paras = t.paras; - if paras.is_empty() { - paras.push(self.type_state.para.clone()); + if t.kind == 1 && (t.past_limit || all_areas > placed.len()) { + self.warn(LINKED_AREAS_LEFT_OUT); } - obj.set_paragraph_styles(paras); - let node = self.new_node(NodeKind::Text(Box::new(obj)), &t.gs); - self.add(node, t.hidden || hidden) + let mut paras = std::mem::take(&mut t.paras); + if paras.is_empty() { + paras.push(ParaRun { style: self.type_state.para.clone(), count: 1, tabs_version: 0 }); + } + 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((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()); + obj.kind = kind; + obj.xf = to_doc * m * FLIP; + match story.take() { + Some((runs, paras)) => { + obj.runs = runs; + // 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_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 = 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 + // objects with type, so the frames of linked areas and type in those don't clip, with a + // warning. The frames up to the clipping group or opacity mask's art are checked, a group in + // either included. + let in_wrap_or_compound = self + .frames + .iter() + .rev() + .take_while(|f| !matches!(f.kind, Kind::Clip | Kind::Mask | Kind::Layer(_))) + .any(|f| matches!(f.kind, Kind::Wrap | Kind::Compound)); + let can_clip = !linked && nodes.len() == 1 && !in_wrap_or_compound; + if t.clips && !can_clip { + self.warn(MASK_NOT_CLIPPED); + } + for node in nodes.into_iter().rev() { + if t.clips + && can_clip + && let Some(f) = self.frames.last_mut() + { + f.clips.push(f.children.len()); + } + self.add(node, t.hidden || hidden)?; + } + if frames.len() > 1 { + self.doc.text_threads.push(frames); + } + Ok(()) } + + /// Call `f` on the other frames of the threaded text object just read, whose first frame is + /// the last object ([`Reader::end_text`]): the opacity mask and text wrap of the object's + /// dictionary apply to every frame. + pub(super) fn each_linked_frame(&mut self, mut f: impl FnMut(&mut Node)) { + if !self.after_object { + return; + } + let Some(first) = self.frames.last().and_then(|fr| fr.children.last()).map(|n| n.id) else { return }; + let Some(thread) = self.doc.text_threads.last().filter(|t| t.first() == Some(&first)) else { return }; + let rest: HashSet = thread.iter().skip(1).copied().collect(); + let Some(fr) = self.frames.last_mut() else { return }; + for n in fr.children.iter_mut().rev().skip(1).take(rest.len()).filter(|n| rest.contains(&n.id)) { + f(n); + } + } +} + +/// A text object of type `kind` on text path `p` (none: at the origin): the matrix from text space +/// (y up) to art space, and the kind of type with its frame or path in text space (y down). +fn placed(kind: i64, p: Option<&TextPath>) -> (Affine, TextKind) { + let m = p.and_then(|p| p.matrix).unwrap_or(Affine::IDENTITY); + // Art space → text space (y down). + let to_text = FLIP * m.inverse(); + let kind = match (kind, p.and_then(|p| p.path.as_ref().map(|path| (path, p.start)))) { + (1, Some(((path, kinds), _))) => TextKind::Area { frame: path_data(&(to_text * path.clone()), kinds) }, + (2, Some(((path, kinds), start))) => { + TextKind::OnPath { path: path_data(&(to_text * path.clone()), kinds), start: start_fraction(path, start), end: None } + } + _ => TextKind::Point, + }; + (m, kind) } /// Where type on `path` starts (`index.fraction`: a segment and how far along it, §15.5.2), as a diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index eb8841e0db..b96b85c068 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -55,6 +55,56 @@ const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlace /// A document included whole: (begin, end) markers. const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); +/// The line of `src` before the one that starts at `at`, without its line end, when it ends within +/// [`OPERAND_LINE`] bytes of `at` and is no longer than that. +fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> { + let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?; + let end = before.iter().rposition(|b| !is_eol(*b))? + 1; + let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1; + before.get(start..end) +} + +/// The longest line of an image's `XI` operands looked at. +const OPERAND_LINE: usize = 1024; + +/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix] +/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when +/// the alpha count isn't 0, else none (or when the operands aren't of that shape). +fn alpha_bytes(line: &[u8]) -> usize { + let line = line.strip_prefix(b"%_").unwrap_or(line); + let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 }; + let nums: Vec = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect(); + match (nums.get(4), nums.get(5), nums.get(8)) { + // At most the pixels the reader reads an image with. + (Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize, + _ => 0, + } +} + +/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose +/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line +/// end, or the end of `w`, follows. +fn end_data(w: &[u8]) -> Option { + const MARK: &[u8] = b"%%EndData"; + let mut first = None; + let mut at = 0; + while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) { + let i = at + i; + let rest = w.get(i + MARK.len()..).unwrap_or_default(); + if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) { + let next = rest.strip_prefix(b"\r").unwrap_or(rest); + let next = next.strip_prefix(b"\n").unwrap_or(next); + let next = next.strip_prefix(b"%_").unwrap_or(next); + if next.starts_with(b"XH") { + return Some(i); + } + first = first.or(Some(i)); + } + at = i + 1; + } + first +} + fn is_space(b: u8) -> bool { matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') } @@ -232,12 +282,18 @@ impl<'a> Lexer<'a> { (Some(b'\r' | b'\n'), _) => data += 1, _ => {} } - // The count leaves out an alpha channel: the data ends where `%%EndData` starts. + // The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one + // that a line end or the end of the data follows (samples can hold the marker's bytes). let declared = from.saturating_add(n).min(self.src.len()).max(data); - let window = - self.src.get(declared.saturating_sub(4).max(data)..declared.saturating_add(n.saturating_mul(2)).saturating_add(64).min(self.src.len())); - let end = match window.and_then(|w| find(w, b"%%EndData")) { - Some(i) => declared.saturating_sub(4).max(data) + i, + // The alpha channel the line before gives the image (its `XI` operands) follows the counted + // samples: the marker is looked for after it. + let line_start = self.pos.saturating_sub(line.len()); + let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start }; + let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes); + let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data); + let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len()); + let end = match self.src.get(start..stop).and_then(end_data) { + Some(i) => start + i, None => declared, }; self.pos = end; diff --git a/crates/eps/src/import/ai/paint.rs b/crates/eps/src/import/ai/paint.rs index b624a22475..178238dc15 100644 --- a/crates/eps/src/import/ai/paint.rs +++ b/crates/eps/src/import/ai/paint.rs @@ -18,19 +18,24 @@ //! `Bm` for each pair in the order of the ramp (`Bc`, around them, are the caps past the first and //! last stops). Without `Xm`, a radial gradient's one `Bm` takes the unit circle onto it. //! +//! - The name shown for a gradient's or a pattern's name in the file is the part before its first +//! newline (`\n`) ([`ShownNames`]). +//! //! "AI7 spec": Adobe Illustrator File Format Specification, version 7.0 (1998), listed by PRONOM at -//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators. +//! https://www.nationalarchives.gov.uk/PRONOM/fmt/423; §3.5 documents the gradient operators and §4 +//! the names of global objects. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use kurbo::{Affine, Point, Vec2}; use vectorcraft_color::gradient::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; use vectorcraft_color::{Color, Paint}; +use super::lex::{Lexer, Tok}; use super::obj::V; /// Largest number of stops read in one gradient. -const MAX_STOPS: usize = 256; +pub(crate) const MAX_STOPS: usize = 256; /// A colour read with the swatch it names (spot and global colours). #[derive(Clone, Debug, PartialEq)] @@ -172,7 +177,16 @@ impl GradientDef { } // Stops are listed along the ramp from either end: listed downwards they're reversed, so // stops sharing a ramp point keep their order (and each its midpoint, to the next stop). - if self.gradient.stops.first().zip(self.gradient.stops.last()).is_some_and(|(first, last)| first.offset > last.offset) { + // When every stop shares one ramp point, a linear gradient's are taken as listed from the + // last, as newer files list a linear gradient's stops. + let linear = self.gradient.kind == GradientKind::Linear; + if self + .gradient + .stops + .first() + .zip(self.gradient.stops.last()) + .is_some_and(|(first, last)| first.offset > last.offset || (linear && self.gradient.stops.len() > 1 && first.offset == last.offset)) + { self.gradient.stops.reverse(); } self.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); @@ -180,6 +194,157 @@ impl GradientDef { } } +/// The names of the named colors in the tokens [`Self::token`] is given: those the color operators +/// (`x`, `Xx`, `Xk` and their stroke forms) and gradient stops (`Bs` between `Bd` and `BD`) use, +/// also in the color and tile strings of patterns in the version 7 form (`(…) @`, `(…) &`). It +/// also keeps the names of the gradients `BD` finishes ([`GradientDef::finish`]). +#[derive(Default)] +pub(super) struct ColorNames { + pub names: HashSet, + pub gradients: Vec, + vals: Vec, + def: Option, + spots: Vec, +} + +impl ColorNames { + pub fn token(&mut self, tok: Tok<'_>) { + self.take(tok, true); + } + + /// [`Self::token`], with the names in the strings of a version 7 pattern's layer when `outer`. + fn take(&mut self, tok: Tok<'_>, outer: bool) { + let w = match tok { + Tok::Num(n) => { + if self.vals.len() < MAX_STOPS { + self.vals.push(V::Num(n)); + } + return; + } + Tok::Str(s) | Tok::Hex(s) => { + if self.vals.len() < MAX_STOPS { + self.vals.push(V::Str(s)); + } + return; + } + Tok::Word(w) => w, + _ => return, + }; + let vals = std::mem::take(&mut self.vals); + match w { + b"Bd" => self.def = GradientDef::begin(&vals), + b"BD" => { + if let Some((name, _)) = self.def.take().and_then(GradientDef::finish) { + self.gradients.push(name); + } + } + b"Bs" => { + if let Some(d) = self.def.as_mut() { + d.stop(&vals, &mut self.spots); + } + } + b"x" | b"X" | b"Xx" | b"XX" | b"Xk" | b"XK" => { + if let Some((_, Some(n))) = std::str::from_utf8(w).ok().and_then(|op| color_op(op, &vals)) { + self.spots.push(n); + } + } + b"@" | b"&" if outer => { + for v in &vals { + if let V::Str(s) = v { + let mut inner = ColorNames::default(); + let mut lex = Lexer::new(s); + while let Some(t) = lex.next_token() { + inner.take(t.tok, false); + } + self.names.extend(inner.names); + } + } + } + _ => {} + } + self.names.extend(self.spots.drain(..).map(|n| n.name)); + } +} + +/// A kind of global object. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Global { + Gradient, + Pattern, +} + +/// The names the gradients and patterns get in the document, by their kind and names in the file. +/// The name shown for a name in the file is the part before its first newline (AI7 spec §4): +/// `(Sky\n1)` is shown as "Sky". Gradients and patterns share their swatches' names. A name with a +/// newline is shown as the part before it unless that name is reserved (a custom color's, or a +/// gradient's or pattern's name without a newline) or an object defined earlier (of either kind) +/// got it; then it is the first free "Sky 2", "Sky 3"… A name shown as nothing (`(\n3)`) is shown +/// as "Gradient" or "Pattern", numbered the same way. A name without a newline is kept. An object +/// defined again under the same name in the file keeps the name it got. +#[derive(Debug, Default)] +pub(super) struct ShownNames { + gradients: HashMap, + patterns: HashMap, + taken: HashSet, + /// The number to try first for each shown name already taken. + next: HashMap, +} + +impl ShownNames { + fn by_file(&self, kind: Global) -> &HashMap { + match kind { + Global::Gradient => &self.gradients, + Global::Pattern => &self.patterns, + } + } + + /// The name the object of `kind` defined as `name` in the file got ([`Self::define`]), or + /// `name` for one not defined. + pub fn get<'n>(&'n self, kind: Global, name: &'n str) -> &'n str { + self.by_file(kind).get(name).map_or(name, String::as_str) + } + + /// Keep `name` from the objects defined after. + pub fn reserve(&mut self, name: &str) { + self.taken.insert(name.to_string()); + } + + /// The name the object of `kind` defined as `name` in the file gets. + pub fn define(&mut self, kind: Global, name: &str) -> String { + if let Some(shown) = self.by_file(kind).get(name) { + return shown.clone(); + } + let shown = match name.split_once('\n') { + None => name.to_string(), + Some((base, _)) => { + let base = match (base.is_empty(), kind) { + (false, _) => base, + (true, Global::Gradient) => "Gradient", + (true, Global::Pattern) => "Pattern", + }; + if self.taken.contains(base) { + // The first free number from the one after the last number this base got. Of + // the numbers `from..=tries`, at least one is free. + let from = self.next.get(base).copied().unwrap_or(2); + let tries = from.saturating_add(self.taken.len()); + let i = (from..tries).find(|i| !self.taken.contains(&format!("{base} {i}"))).unwrap_or(tries); + self.next.insert(base.to_string(), i.saturating_add(1)); + format!("{base} {i}") + } else { + base.to_string() + } + } + }; + self.taken.insert(shown.clone()); + let by_file = match kind { + Global::Gradient => &mut self.gradients, + Global::Pattern => &mut self.patterns, + }; + by_file.insert(name.to_string(), shown.clone()); + shown + } +} + /// A gradient instance on an object, between `Bb` and `BB`. #[derive(Clone, Debug, Default)] pub(super) struct Instance { @@ -258,8 +423,9 @@ impl Instance { self.xm.is_some() || self.bm.is_some() } - /// The paint, through `to_doc` (art space → the document), when the gradient is defined. - pub fn paint(&self, defs: &HashMap, to_doc: Affine) -> Option { + /// The paint, through `to_doc` (art space → the document), when the gradient is defined, linked + /// to the gradient's swatch by the name `shown` gave it. + pub fn paint(&self, defs: &HashMap, shown: &ShownNames, to_doc: Affine) -> Option { let name = self.name.as_ref()?; let gradient = defs.get(name)?.clone(); let radial = gradient.kind == GradientKind::Radial; @@ -310,7 +476,8 @@ impl Instance { let focal = (self.hilight.hypot() > 1e-9).then_some(focal).filter(|p| p.is_finite()); let geom = GradientGeom { start, end, aspect, focal: if radial { focal } else { None } }; let angle = -(end - start).atan2().to_degrees(); - Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch: Some(name.clone()), ..GradientPaint::new(gradient) }))) + let swatch = Some(shown.get(Global::Gradient, name).to_string()); + Some(Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle, swatch, ..GradientPaint::new(gradient) }))) } } @@ -406,22 +573,59 @@ mod tests { bg.extend(nums(&[100.0, 100.0, 0.0, 50.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); i.bg(&bg); i.bm(&nums(&[50.0, 0.0, 0.0, -50.0, 100.0, 100.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let shown = ShownNames::default(); + let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() }; + assert_eq!(gp.swatch.as_deref(), Some("G")); let geom = gp.geom.unwrap(); assert_eq!(geom.start, Point::new(100.0, 100.0)); assert_eq!(geom.end, Point::new(150.0, 100.0)); assert!((geom.aspect - 1.0).abs() < 1e-9); - assert!(i.paint(&HashMap::new(), Affine::IDENTITY).is_none()); + assert!(i.paint(&HashMap::new(), &shown, Affine::IDENTITY).is_none()); // Newer files give the matrix with `Xm`; the `Bm`s after it are bands of a cached ramp. let mut i = Instance::begin(&[]); i.bg(&bg); i.xm(&nums(&[40.0, 0.0, 0.0, -40.0, 10.0, 10.0])); i.bm(&nums(&[5.0, 0.0, 0.0, -40.0, 30.0, 10.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let Some(Paint::Gradient(gp)) = i.paint(&defs, &shown, Affine::IDENTITY) else { panic!() }; let geom = gp.geom.unwrap(); assert_eq!((geom.start, geom.end), (Point::new(10.0, 10.0), Point::new(50.0, 10.0))); } + /// A name is shown up to its first newline, numbered when a reserved name or an earlier object + /// of either kind has it; a name defined again keeps the name it got, and a blank one gets its + /// kind's stand-in. A name without a newline is kept. + #[test] + fn global_names_are_shown_up_to_their_newline() { + let mut shown = ShownNames::default(); + // A color's name, and the names without a newline the file defines. + for name in ["Ink", "Sky", "Sky 2", "Sea"] { + shown.reserve(name); + } + let got: Vec = [ + (Global::Gradient, "Sky\n1"), + (Global::Gradient, "Sky\n2"), + (Global::Gradient, "Sky"), + (Global::Gradient, "Sky\n1"), + (Global::Pattern, "Sky\n1"), + (Global::Gradient, "Sea\nA\nB"), + (Global::Gradient, "\n3"), + (Global::Pattern, "\n4"), + (Global::Gradient, "Sky 2"), + (Global::Pattern, "Ink\n1"), + (Global::Gradient, "Ink"), + (Global::Pattern, "Sea"), + (Global::Pattern, "Tide\n1"), + (Global::Pattern, ""), + ] + .iter() + .map(|(kind, n)| shown.define(*kind, n)) + .collect(); + assert_eq!(got, ["Sky 3", "Sky 4", "Sky", "Sky 3", "Sky 5", "Sea 2", "Gradient", "Pattern", "Sky 2", "Ink 2", "Ink", "Sea", "Tide", ""]); + assert_eq!(shown.get(Global::Gradient, "Sky\n2"), "Sky 4"); + assert_eq!(shown.get(Global::Pattern, "Sky\n1"), "Sky 5"); + assert_eq!(shown.get(Global::Pattern, "Sky\n2"), "Sky\n2", "not a pattern's name"); + } + #[test] fn gradient_stops_beyond_the_cap_are_ignored() { let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)]).unwrap(); @@ -434,6 +638,24 @@ mod tests { assert_eq!(g.stops.len(), MAX_STOPS); } + /// A hard edge: every stop at one ramp point. A linear gradient's are listed from the last, a + /// radial one's from the first. + #[test] + fn stops_at_one_ramp_point_keep_their_sides() { + for (kind, listed) in [(0.0, [0.75, 0.25]), (1.0, [0.25, 0.75])] { + let mut d = GradientDef::begin(&[V::Str(b"E".to_vec()), V::Num(kind), V::Num(2.0)]).unwrap(); + for (gray, mid) in listed.into_iter().zip([40.0, 70.0]) { + d.stop(&nums(&[gray, 0.0, 1.0, 6.0, mid, 30.0]), &mut vec![]); + } + let (_, g) = d.finish().unwrap(); + let lightness: Vec = g.stops.iter().map(|s| (s.color.to_rgb()[0] * 100.0).round() / 100.0).collect(); + let first_mid = if kind == 0.0 { 0.7 } else { 0.4 }; + assert_eq!(lightness, vec![0.25, 0.75], "kind {kind}"); + assert!((g.stops[0].midpoint - first_mid).abs() < 1e-6, "kind {kind}: {:?}", g.stops); + assert!(g.stops.iter().all(|s| (s.offset - 0.3).abs() < 1e-6)); + } + } + /// A linear gradient of three stops as newer files place it: `Bg` with numbers that aren't in /// art space, `Xm` for the whole ramp and a `Bm` for each pair of stops. #[test] @@ -454,7 +676,7 @@ mod tests { // From the stop at 20 to the one at 60, then on to the one at 100. i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 260.0])); i.bm(&nums(&[0.0, -80.0, -30.0, 0.0, 10.0, 180.0])); - let Some(Paint::Gradient(gp)) = i.paint(&defs, Affine::IDENTITY) else { panic!() }; + let Some(Paint::Gradient(gp)) = i.paint(&defs, &ShownNames::default(), Affine::IDENTITY) else { panic!() }; gp.geom.unwrap() }; for xm in [true, false] { diff --git a/crates/eps/src/import/ai/palette.rs b/crates/eps/src/import/ai/palette.rs index 9a4ba72ebc..e816c5d6c0 100644 --- a/crates/eps/src/import/ai/palette.rs +++ b/crates/eps/src/import/ai/palette.rs @@ -63,6 +63,14 @@ impl Palette { pub fn is_empty(&self) -> bool { self.swatches.is_empty() && self.groups.iter().all(|(_, s)| s.is_empty()) } + + /// The names the palette gives its color groups and swatches, except the name a swatch takes + /// from its gradient or pattern. + pub fn own_names(&self) -> impl Iterator { + let named = |e: &Entry| !matches!(&e.cell, Cell::Gradient(n) | Cell::Pattern(n) if *n == e.name); + let swatches = self.swatches.iter().chain(self.groups.iter().flat_map(|(_, s)| s)).filter(move |e| named(e)); + self.groups.iter().map(|(name, _)| name.as_str()).chain(swatches.map(|e| e.name.as_str())) + } } /// The palette of `data`: what follows `%AI5_BeginPalette`, up to its end. diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index a3eda140e5..2cf9dc736e 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -35,6 +35,11 @@ //! and the samples after `XI`. 8-bit CMYK samples keep their ink amounts in a CMYK TIFF, and //! an alpha channel that hides part of such an image becomes its opacity mask; other samples //! become an RGBA PNG. +//! - Linked images in the version 7 form (§8.2, §8.3): `(path) modified XG`, then `XF` with the +//! operands `XI` takes and no samples. Each is a linked image of that file showing a placeholder +//! over the image's place until its file is found. An `XF` without a file name before it, or +//! with operands `XI` couldn't read, is left out with a warning. An `XI` after `XG` (newer files +//! write `() 1 XG` before their embedded images) stays an embedded image. //! - Placed (linked) files, as written in files users sent: `%AI5_BeginPlace`, `[matrix] llx lly urx //! ury … (path)` and the operator `` ` ``, the file's preview between `%AI26_BeginPlacedObjectPreview` //! and its end (`w h rowBytes 32 n `, then rows of premultiplied ARGB, the top one first), `~`. The @@ -52,7 +57,9 @@ //! lines and `1 (style) XW`: the drawn look is kept, named after the object. //! - Patterns: `%AI3_BeginPattern: (name)`, `(name) llx lly urx ury` (the tile, in the pattern's //! space, y up), the tile's art (on `%_` lines in newer files), `E`, `%AI3_EndPattern`; each is -//! read by a reader of its own and becomes a pattern swatch. In the version 7 form (§3.4) a list +//! read by a reader of its own and becomes a pattern swatch. An unpainted path whose dictionary +//! marks it as the tile's box (`AIPattern_Editor_Backing_Tile_Rect`) is left out of the art. In +//! the version 7 form (§3.4) a list //! of layers follows the tile, `[ (colors) @ (tile) & … ] E`, each layer's tile read from its //! string with the colors' state (`_ &`: the tile's box filled). A fill or stroke with one: //! `(name) x y scaleX scaleY angle reflect axis shear shearAxis [matrix] p` (`P`), the matrix @@ -80,8 +87,18 @@ //! style's appearance and transparency is linked to it. A `1` naming a style the list doesn't //! have is the object's own appearance, not a link. //! -//! Sections the reader doesn't need (symbols, styles, filters) are skipped; -//! type, symbols, fills with a pattern it can't read, placed files without a preview and operators +//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the +//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration +//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of +//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names +//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx +//! ty /RTransformMatrix ;`, the matrix taking the symbol's art to art space; in a symbol's art, +//! it takes it to art space about the canvas point of art space's origin, as a pattern's +//! gradients are. Its hide and lock come before it (`Xw`, `A`) and its transparency (`Xy`) after +//! it. +//! +//! Sections the reader doesn't need (styles, filters) are skipped; type, instances of symbols it +//! can't read, fills with a pattern it can't read, placed files without a preview and operators //! it doesn't know are errors. So is data that ends inside a layer, a group or a compound path. use std::collections::{BTreeSet, HashMap, HashSet}; @@ -103,7 +120,7 @@ use super::super::ate::CANVAS_CENTRE; use super::super::graphics::HAIRLINE; use super::lex::{Lexer, Tok}; use super::obj::{self, Obj, V}; -use super::paint::{self, GradientDef, Instance, Named}; +use super::paint::{self, Global, GradientDef, Instance, Named, ShownNames}; use crate::ps; mod art; @@ -117,12 +134,12 @@ mod types; pub(crate) use art::join_and; use art::preview_png; -pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, palette, variables}; +pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, graphic_styles, palette, variables}; pub(crate) use document::{slot_frame, slot_of}; pub use types::IMAGE_TOO_LARGE; -use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster}; +use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster, SymbolHead}; #[cfg(test)] -pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; +pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; pub(super) use types::{blend_mode, blend_name}; #[path = "legacy_text.rs"] @@ -153,6 +170,10 @@ pub struct Structure { /// Where the drawn looks lay that objects read with their art style took the place of (the /// document's coordinates): the page draws Illustrator's rendering of those styles there. pub restyled: Vec, + /// Where linked images whose pixels the data doesn't keep (`XF`) show a placeholder (the + /// document's coordinates). A PostScript page doesn't draw them there; a PDF part draws the + /// image's pixels. + pub placeholders: Vec, /// Placed files whose pixels the file puts at another point too: their image's id and the /// move, in its pixels, that places them there (the corner of the box they are written with, /// in place of the canvas point of art space's origin). @@ -199,7 +220,7 @@ pub(super) fn remember_xml_id(xml_ids: &mut HashMap>, byt /// when `large_canvas` is set: an EPS's page is drawn at the full size, but a `.ai`'s PDF part may /// keep the reduced one, which the PDF import reads as it is (#2031). pub fn read(data: &[u8], large_canvas: bool) -> Result { - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); r.large_canvas = large_canvas.then_some(1.0); r.run()?; r.finish() @@ -209,13 +230,129 @@ pub fn read(data: &[u8], large_canvas: bool) -> Result { /// data): the program's header gives the author and the custom colors the editing data's header /// doesn't. pub fn read_beside(data: &[u8], large_canvas: bool, ps: &[u8]) -> Result { - let mut r = Reader::new(data); + let header = Reader::header_of(ps); + let mut r = Reader::with_names(data); r.large_canvas = large_canvas.then_some(1.0); + // The program's custom colors have swatches of their names, which no gradient or pattern takes. + for n in &header.custom_colors { + r.global_names.reserve(&n.name); + } r.run()?; - r.program_header(ps); + r.program_header(header); r.finish() } +/// The names the gradients and patterns of the editing data `data` get in the document +/// ([`ShownNames`]), with the names its other swatches can have reserved first: Registration, the +/// default swatches of both color modes when the palette the reader keeps is missing or empty, the +/// names that palette gives, the named colors, and the names without a newline of the gradients +/// and patterns. Names come only from what the reader reads: not from the alternates of versioned +/// content, the prolog, resources, sections it skips (such as symbols and the text document) or +/// what follows the trailer. The palette the reader keeps is the last one outside those and the +/// sections it reads on their own. +fn swatch_names(data: &[u8]) -> ShownNames { + /// The sections the reader reads on their own whose definitions and colors it keeps. + const READ_APART: &[&str] = &["BeginPattern", "BeginBrushPattern", "BeginPluginObject", "BeginArtStyles", "BeginArtStyleList"]; + /// Whether the marker `m` ends what began with `begin` and ends with `end`, `depth` of its kind + /// open inside it. + fn closes(begin: &str, end: &str, depth: &mut usize, m: &str) -> bool { + if !begin.is_empty() && m == begin { + *depth += 1; + } else if m == end { + match depth.checked_sub(1) { + Some(d) => *depth = d, + None => return true, + } + } + false + } + let mut names = ShownNames::default(); + names.reserve(vectorcraft_color::swatch::REGISTRATION); + let mut colors = paint::ColorNames::default(); + let mut lex = Lexer::new(data); + // What the reader skips wherever it is (the marker of one of its kind nested in it, its end + // marker, how many are open inside it, and where reading goes on when it doesn't end), the + // top-level section being passed over (the first three, and whether the reader reads it on its + // own), and where the palette being found starts. + let mut skip: Option<(&str, &str, usize, Option)> = None; + let mut section: Option<(&str, &str, usize, bool)> = None; + let (mut palette_at, mut palette) = (None, None); + // A pattern's name is the first string of its definition. + let mut head = false; + loop { + let before = lex.offset(); + let Some(t) = lex.next_token() else { + // Versioned content that doesn't end is read whole, as the reader reads it. + match skip.take() { + Some((.., Some(at))) => { + lex.seek(at); + continue; + } + _ => break, + } + }; + match &t.tok { + Tok::Comment(c) => { + let line = String::from_utf8_lossy(c); + let m = marker(&line); + if let Some((begin, end, depth, _)) = skip.as_mut() { + if closes(begin, end, depth, m) { + skip = None; + } + } else if let Some(at) = palette_at { + if m == "EndPalette" { + palette = Some(lex.slice(at, before)); + palette_at = None; + } + } else if m.starts_with("Alternate_Content") && section.is_none_or(|s| s.3) { + skip = Some(("Begin_Content_if_version_gt", "End_Versioned_Content", 0, Some(lex.offset()))); + } else if m == "%BeginProlog" { + skip = Some(("", "%EndProlog", 0, None)); + } else if m == "%BeginResource" { + skip = Some(("", "%EndResource", 0, None)); + } else if let Some((begin, end, depth, _)) = section.as_mut() { + if closes(begin, end, depth, m) { + section = None; + } + } else if m == "BeginPalette" { + palette_at = Some(lex.offset()); + } else if let Some((begin, end)) = types::SKIPPED.iter().find(|(b, _)| *b == m) { + section = Some((begin, end, 0, READ_APART.contains(begin))); + head = m == "BeginPattern"; + } else if matches!(m, "%PageTrailer" | "%Trailer") { + break; + } + continue; + } + // A palette's names are those of the palette kept, as the palette reads them. + _ if skip.is_some() || palette_at.is_some() || section.is_some_and(|s| !s.3) => continue, + Tok::Str(s) | Tok::Hex(s) if std::mem::take(&mut head) => { + let text = obj::text(s); + if !text.contains('\n') { + names.reserve(&text); + } + } + _ => {} + } + colors.token(t.tok); + } + colors.gradients.iter().filter(|n| !n.contains('\n')).for_each(|n| names.reserve(n)); + let palette = palette.map(super::palette::palette).unwrap_or_default(); + if palette.is_empty() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk] { + let (swatches, groups) = vectorcraft_color::default_swatches(mode.model()); + for g in &groups { + names.reserve(&g.name); + g.swatches.iter().for_each(|s| names.reserve(&s.name)); + } + swatches.iter().for_each(|s| names.reserve(&s.name)); + } + } + palette.own_names().for_each(|n| names.reserve(n)); + colors.names.iter().for_each(|n| names.reserve(n)); + names +} + struct Reader<'a> { lex: Lexer<'a>, stack: Vec, @@ -234,6 +371,8 @@ struct Reader<'a> { to_doc: Option, cropmarks: Option, artboards: Vec, + /// The index in `artboards` of the active artboard (`CropAreaActive`). + active_board: Option, /// The user the header's `%%For` names. author: Option, /// The custom colors the header's `%%CMYKCustomColor` and `%%RGBCustomColor` define. @@ -247,6 +386,8 @@ struct Reader<'a> { /// The Objects on Path records of the `/Document` dictionary and the ids of the objects. on_path: on_path::OnPath, gradients: HashMap, + /// The names the gradients and patterns get in the document, by their names in the file. + global_names: ShownNames, gradient_def: Option, instance: Option, pending_fill: Option, @@ -257,10 +398,15 @@ struct Reader<'a> { /// a global process colour, so these make swatches only for names no colour operator defines. stop_spots: Vec, raster: Option, + /// The file `XG` names for the image after it (`XF`), until an image is read. + image_link: Option, /// The placed file being read (`%AI5_BeginPlace` … `~`). place: Option, /// The last object read is the last child of the innermost frame, and nothing started since. after_object: bool, + /// The last object read is an image, and only the operators that end its raster (`XH`, `Xr`, + /// `N`) came since: its name and opacity mask still follow. + image_tail: bool, nodes: usize, /// What layers that show have that this reader doesn't read (errors). unsupported: BTreeSet, @@ -269,7 +415,24 @@ struct Reader<'a> { /// What layers that don't show have that this reader doesn't read. hidden_unread: BTreeSet, unread: Vec<(NodeId, Vec)>, + /// The art boxes (symbol space) of symbols whose definition can be measured but not read + /// whole, by their name in the file: their instances come in as the page draws them. symbol_bounds: HashMap, + /// The symbols read, by their name in the file → their name in the document. + symbol_names: HashMap, + /// The names the symbols read have in the document, and for each name read more than once, + /// the number its next copy is tried with. + symbol_taken: HashSet, + symbol_suffix: HashMap, + /// The art boxes (symbol space) of symbols read, by their name in the file, once measured for + /// an instance that comes in as the page draws it. + symbol_art_bounds: HashMap>, + /// The symbol list's names, in the Symbols panel's order (`%AI24_BeginSymbolList`). + symbol_list: Option>, + /// The symbols read were checked for instances of symbols the file doesn't have. + symbols_checked: bool, + /// This reader reads a symbol's definition (see [`Reader::define_symbol`]). + symbol: Option, /// Depth shared by pattern and symbol readers. subreader_depth: usize, pending_unread_fill: bool, @@ -341,6 +504,8 @@ struct Reader<'a> { palette: super::palette::Palette, /// See [`Structure::restyled`]. restyled: Vec, + /// See [`Structure::placeholders`]. + placeholders: Vec, /// See [`Structure::placed_elsewhere`]. placed_elsewhere: Vec<(NodeId, Affine)>, unread_elsewhere: Vec<(NodeId, Rect)>, @@ -410,6 +575,14 @@ pub(crate) fn is_look_slot(name: Option<&str>) -> bool { } impl<'a> Reader<'a> { + /// A reader of the editing data `data` as a whole, with the names its gradients and patterns + /// get in the document found first ([`swatch_names`]). + fn with_names(data: &'a [u8]) -> Self { + let mut r = Self::new(data); + r.global_names = swatch_names(data); + r + } + fn new(data: &'a [u8]) -> Self { let mut doc = Document::new(1.0, 1.0); doc.layers.clear(); @@ -427,6 +600,7 @@ impl<'a> Reader<'a> { to_doc: None, cropmarks: None, artboards: Vec::new(), + active_board: None, author: None, custom_colors: Vec::new(), custom_more: None, @@ -434,6 +608,7 @@ impl<'a> Reader<'a> { variables: VariableRead::default(), on_path: on_path::OnPath::default(), gradients: HashMap::new(), + global_names: ShownNames::default(), gradient_def: None, instance: None, pending_fill: None, @@ -441,15 +616,24 @@ impl<'a> Reader<'a> { spots: Vec::new(), stop_spots: Vec::new(), raster: None, + image_link: None, place: None, foreign_data: None, after_object: false, + image_tail: false, nodes: 0, unsupported: BTreeSet::new(), unknown: BTreeSet::new(), hidden_unread: BTreeSet::new(), unread: Vec::new(), symbol_bounds: HashMap::new(), + symbol_names: HashMap::new(), + symbol_taken: HashSet::new(), + symbol_suffix: HashMap::new(), + symbol_art_bounds: HashMap::new(), + symbol_list: None, + symbols_checked: false, + symbol: None, subreader_depth: 0, pending_unread_fill: false, pending_unread_stroke: false, @@ -485,6 +669,7 @@ impl<'a> Reader<'a> { style_links: vec![], palette: super::palette::Palette::default(), restyled: vec![], + placeholders: vec![], placed_elsewhere: vec![], unread_elsewhere: vec![], mesh: None, diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 1df1b2d9c1..7eb55ad114 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -1,13 +1,14 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::types::{ - FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, + FLIP, Frame, IMAGE_TOO_LARGE, Kind, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, Place, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, }; +use vectorcraft_doc::links::missing_placeholder; impl<'a> Reader<'a> { /// A text object (`/AI11Text`): an empty group standing for it, named after its story. @@ -15,6 +16,7 @@ impl<'a> Reader<'a> { if self.pattern.is_some() { self.unreadable("type in a pattern", false); } + self.left_out_of_symbol(); // `1 /FreeUndo`: type in a drawn look. Its story is one of another text document // (`/AI11UndoFreeTextDocument`), which counts its stories on its own, so its slot has none. // In the look of a text object that has an appearance, the object itself follows the look, @@ -45,6 +47,11 @@ impl<'a> Reader<'a> { /// group. Without data, or with a PDF that can't be read, nothing is drawn. pub(super) fn foreign_art(&mut self, o: &Obj) -> Result<(), String> { let Some(text) = self.foreign_data.take() else { return Ok(()) }; + // Where a symbol's art puts it isn't known. + if self.symbol.is_some() { + self.left_out_of_symbol(); + return Ok(()); + } // One `%` starts each line; the rest, `_` included, is data. let mut encoded = String::with_capacity(text.len()); for line in text.split(|b| matches!(b, b'\r' | b'\n')) { @@ -164,6 +171,9 @@ impl<'a> Reader<'a> { self.path_kinds.clear(); self.points = 0; self.clip_next = false; + if let Some(head) = self.symbol.as_mut() { + (head.missing_fill, head.missing_stroke) = (false, false); + } } /// Paint the current path (`op`), as a guide when `guide`. @@ -176,6 +186,7 @@ impl<'a> Reader<'a> { self.set_instance(&i); } let (fill_paint, stroke_paint) = (self.pending_fill.take(), self.pending_stroke.take()); + let missing = self.symbol.as_mut().map_or((false, false), |h| (std::mem::take(&mut h.missing_fill), std::mem::take(&mut h.missing_stroke))); if bp.elements().is_empty() { return Ok(()); } @@ -195,6 +206,10 @@ impl<'a> Reader<'a> { "b" => (true, true), _ => (false, false), }; + // A symbol's art painted with a gradient the file doesn't define is left out. + if (missing.0 && fill) || (missing.1 && stroke) { + self.left_out_of_symbol(); + } // A gradient instance's paint replaces the missing pattern. let unread = (fill && self.pending_unread_fill && fill_paint.is_none()) || (stroke && self.pending_unread_stroke && stroke_paint.is_none()); let mut items = Vec::new(); @@ -352,15 +367,20 @@ impl<'a> Reader<'a> { pub(super) fn set_instance(&mut self, i: &Instance) { let mut to_doc = self.space(); // In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's - // origin, as the file's PDF part draws them. - if self.pattern.is_some() + // origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are. + if (self.pattern.is_some() || self.symbol.is_some()) && i.has_matrix() && let Some(t) = self.template { let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]); } - match i.paint(&self.gradients, to_doc) { + let paint = i.paint(&self.gradients, &self.global_names, to_doc); + if let Some(head) = self.symbol.as_mut() { + let missing = if i.stroke { &mut head.missing_stroke } else { &mut head.missing_fill }; + *missing = paint.is_none(); + } + match paint { Some(p) if i.stroke => self.pending_stroke = Some(p), Some(p) => self.pending_fill = Some(p), None => { @@ -383,25 +403,59 @@ impl<'a> Reader<'a> { self.image_from(vals, data) } + /// The matrix and the numbers of an image's operands (`[a b c d tx ty] llx lly urx ury w h bits + /// ImageType AlphaChannelCount reserved bin-ascii ImageMask`, as `XI` and `XF` take them); `None` + /// without a matrix or with fewer numbers than up to the encoding (bin-ascii). + fn image_operands(vals: &[V]) -> Option<(Vec, Vec)> { + let m = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None })?; + let n = Self::nums(vals); + (n.len() >= 11).then_some((m, n)) + } + + /// `XG` (`w`, which names the file of the image after it) or `XF` (that image), with their + /// operands `vals`. Before the art, the setup's procedures run: there they do nothing. + pub(super) fn image_link_op(&mut self, w: &str, vals: Vec, hidden: bool) -> Result<(), String> { + if self.frames.is_empty() { + return Ok(()); + } + if w == "XG" { + self.image_link = Self::image_link(&vals); + return Ok(()); + } + self.linked_image(vals, hidden) + } + + /// The file `XG`'s operands (`(path) modified`) name; `None` for operands of another shape or + /// an empty path. + fn image_link(vals: &[V]) -> Option { + match vals { + [.., V::Str(path), V::Num(_)] if !path.is_empty() => Some(super::obj::text(path)), + _ => None, + } + } + /// An image of operands `vals` and samples `data`. pub(super) fn image_from(&mut self, vals: Vec, data: &[u8]) -> Result<(), String> { + // A file `XG` named before this image isn't the file of a later `XF`. + self.image_link = None; let space = self.raster.as_ref().and_then(|r| r.space.clone()).unwrap_or_default(); - let Some(m) = vals.iter().find_map(|v| if let V::Arr(a) = v { Some(Self::nums(a)) } else { None }) else { - self.warn("an image VectorCraft can't read was left out"); + let Some((m, n)) = Self::image_operands(&vals) else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let n = Self::nums(&vals); - let [_, _, _, _, w, h, bits, kind, alpha, _, binary, ..] = n.as_slice() else { - self.warn("an image VectorCraft can't read was left out"); + let [_, _, _, _, w, h, bits, kind, alpha, _, binary, rest @ ..] = n.as_slice() else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; + // ImageMask 1: the image is transparent and takes a color (version 7 specification §8.1). + let image_mask = rest.first() == Some(&1.0); let (w, h) = (*w as u64, *h as u64); if w.saturating_mul(h) > MAX_PIXELS { - self.warn(IMAGE_TOO_LARGE); + self.image_left_out(IMAGE_TOO_LARGE); return Ok(()); } if w == 0 || h == 0 || ![1.0, 8.0].contains(bits) { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } let channels: usize = match space.as_str() { @@ -427,7 +481,7 @@ impl<'a> Reader<'a> { // An alpha channel follows the colour samples, one byte a pixel. let alpha_len = if *alpha > 0.0 { (w * h) as usize } else { 0 }; let (Some(samples), opacity) = (data.get(..need), data.get(need..need.saturating_add(alpha_len))) else { - self.warn("an image whose data is cut short was left out"); + self.image_left_out("an image whose data is cut short was left out"); return Ok(()); }; let opacity = opacity.filter(|_| alpha_len > 0); @@ -437,7 +491,10 @@ impl<'a> Reader<'a> { && *bits == 8.0 && let Some(blob) = Inks::new(w as u32, h as u32, samples.to_vec()).and_then(|i| ImageBlob::cmyk_tiff(&i)) { - return self.add_raster(blob, opacity, &m, (w as u32, h as u32)); + return self.add_raster(blob, opacity, &m, (w as u32, h as u32), None); + } + if image_mask && channels == 1 && *bits == 1.0 { + return self.colorized_raster(samples, row, opacity, &m, (w as u32, h as u32)); } let mut rgba = Vec::with_capacity((w * h * 4) as usize); for y in 0..h as usize { @@ -465,38 +522,145 @@ impl<'a> Reader<'a> { } } let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, rgba) else { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; let mut png = vec![]; if img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } - self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32)) + self.add_raster(ImageBlob::new("image/png", png), None, &m, (w as u32, h as u32), None) + } + + /// A 1-bit gray image whose ImageMask is 1 (`samples`, `row` bytes a row): a grayscale image + /// colorized with the fill color. Its 0 bits, which open black with ImageMask 0, take that color, + /// and its 1 bits are transparent. A fill that isn't a solid color colorizes it black. + fn colorized_raster(&mut self, samples: &[u8], row: usize, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + let mut gray = Vec::with_capacity(w as usize * h as usize); + for y in 0..h as usize { + let line = samples.get(y * row..(y + 1) * row).unwrap_or_default(); + for x in 0..w as usize { + let v = line.get(x / 8).map_or(0, |b| ((b >> (7 - x % 8)) & 1) * 255); + gray.push(v); + } + } + let mut png = vec![]; + let written = image::GrayImage::from_raw(w, h, gray).map(|img| img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)); + if !matches!(written, Some(Ok(()))) { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let paint = self.mask_paint(); + self.add_raster(ImageBlob::new("image/png", png), alpha, m, (w, h), Some(paint)) + } + + /// The color that colorizes an image mask: the fill color, or black when the fill isn't a + /// solid color. + fn mask_paint(&self) -> Paint { + match &self.gs.fill { + p @ Paint::Solid { .. } => p.clone(), + _ => Paint::solid(vectorcraft_color::Color::BLACK), + } + } + + /// `XF` (§8.2): an image whose pixels are in the file the `XG` before it names becomes a linked + /// image of that file, of its `w` × `h` pixels placed as the matrix maps them, as `XI` places an + /// image. The data keeps no pixels or preview of it, so a placeholder is spread over those pixels + /// until its file is found. A 1-bit image mask is colorized as `XI` colorizes one. One without + /// that file name, or whose operands `XI` couldn't read (no + /// matrix, too few numbers, no pixels, or samples of other than 1 or 8 bits), is left out with a + /// warning. No pixels are read, so its size isn't held to the limit on `XI`'s samples. + fn linked_image(&mut self, vals: Vec, hidden: bool) -> Result<(), String> { + let path = self.image_link.take(); + let operands = Self::image_operands(&vals); + let (Some(path), Some((m, n))) = (path, operands) else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let (&[a, b, c, d, tx, ty], &[_, _, _, _, w, h, bits, ..]) = (m.as_slice(), n.as_slice()) else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + if !(1.0..=MAX_SIDE).contains(&w) || !(1.0..=MAX_SIDE).contains(&h) || ![1.0, 8.0].contains(&bits) { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let (w, h) = (w as u32, h as u32); + let Some(to_doc) = self.image_space() else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let xf = to_doc * Affine::new([a, b, c, d, tx, ty]) * FLIP; + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + } + let Some(png) = missing_placeholder() else { + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + // The placeholder is all the document has of the file: what a missing link shows. + let bytes = Arc::new(png); + let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; + let key = linked_key(&blob, &path); + self.doc.images.entry(key.clone()).or_insert(blob); + self.warn(LINKED_PLACEHOLDERS); + // A PostScript page doesn't draw the placeholder: there its pixels are left out of the + // comparisons with the page. + if !hidden && !self.gs.hidden && self.shown() { + self.placeholders.push(xf.transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)))); + } + let im = ImageObject { key, width: w, height: h, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None }; + // A 1-bit image mask (ImageMask 1) keeps the color that colorizes it once its file is relinked. + let image_mask = bits == 1.0 && n.get(7) == Some(&1.0) && n.get(11) == Some(&1.0); + let colorize = image_mask.then(|| self.mask_paint()); + self.add_image_colorized(im, None, colorize, hidden) } /// Add the image `blob` (`w` × `h` pixels), which the matrix `m` maps into art space, with /// `alpha` (its alpha channel, one byte a pixel) as its opacity mask when it hides part of the - /// image. - fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32)) -> Result<(), String> { + /// image, and `colorize` as the color that colorizes it. + fn add_raster(&mut self, blob: ImageBlob, alpha: Option<&[u8]>, m: &[f64], (w, h): (u32, u32), colorize: Option) -> Result<(), String> { // The matrix is an art-space matrix (y up) applied to the pixels with their rows running // downwards, (u, -v): pixels → (u, -v) → art space. Flipping the matrix's result instead // gives the same place only when the image isn't rotated (b = c = 0). let [a, b, c, d, tx, ty] = m else { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); + return Ok(()); + }; + let Some(to_doc) = self.image_space() else { + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let to_doc = self.space(); let xf = to_doc * Affine::new([*a, *b, *c, *d, *tx, *ty]) * FLIP; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { - self.warn("an image VectorCraft can't read was left out"); + self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); } let mask = alpha.and_then(|a| self.alpha_mask(a, w, h, xf)); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); - self.add_image_masked(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }, mask, false) + let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }; + self.add_image_colorized(im, mask, colorize, false) + } + + /// An image that isn't read is left out, with `warning`; in a symbol's art, the symbol isn't + /// read whole, so its instances come in as the page draws them. + fn image_left_out(&mut self, warning: &str) { + if self.symbol.is_some() { + self.left_out_of_symbol(); + } else { + self.warn(warning); + } + } + + /// Note art of a symbol's definition that is left out: the symbol isn't kept, and its + /// instances come in as the page draws them, within the box of the art that is read. + pub(super) fn left_out_of_symbol(&mut self) { + if let Some(head) = self.symbol.as_mut() { + head.left_out = true; + } } /// An image's alpha channel (`w` × `h` bytes) as a grayscale image over the image (`xf`): its @@ -524,18 +688,33 @@ impl<'a> Reader<'a> { /// Add an image object with the state's transparency and `mask` as its opacity mask. fn add_image_masked(&mut self, im: ImageObject, mask: Option, hidden: bool) -> Result<(), String> { + self.add_image_colorized(im, mask, None, hidden) + } + + /// Add an image object with the state's transparency, `mask` as its opacity mask and + /// `colorize` as the color that colorizes it. + fn add_image_colorized(&mut self, im: ImageObject, mask: Option, colorize: Option, hidden: bool) -> Result<(), String> { let gs = self.gs.clone(); let mut node = self.new_node(NodeKind::Image(Box::new(im)), &gs); node.opacity = gs.opacity; node.blend = gs.blend; node.extras_mut().mask = mask.map(Box::new); - self.add(node, hidden) + node.extras_mut().colorize = colorize.map(Box::new); + self.add(node, hidden)?; + self.image_tail = self.after_object; + Ok(()) } /// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that /// shows the preview the data keeps of it, as a linked image whose file is missing does. One /// without a preview, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { + // Where a symbol's art puts a placed file's pixels isn't known. + if self.symbol.is_some() { + self.place = None; + self.left_out_of_symbol(); + return Ok(()); + } let (m, b, path, png, w, h, folder) = match self.place.take() { Some(Place { broken: true, .. }) => { self.unreadable("placed files", hidden); @@ -597,7 +776,7 @@ impl<'a> Reader<'a> { // The preview is all the document has of the file: what a missing link shows. let bytes = Arc::new(png); let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }; - let key = blob.content_key(); + let key = linked_key(&blob, &path); self.doc.images.entry(key.clone()).or_insert(blob); self.warn(LINKED_PREVIEWS); if let Some(shift) = elsewhere @@ -712,17 +891,28 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { } /// A placed file's path relative to the document's folder (`/` separators): its relative `folder` -/// (`src/`, `..\art`) followed by its file `name`. `None` when the folder is empty, absolute, or -/// holds control characters, or when there is no name. +/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the +/// document's own folder). `None` when the folder is absolute or holds control characters, or +/// when there is no name. pub(super) fn relative_path(folder: &str, name: &str) -> Option { let folder = folder.replace('\\', "/"); let absolute = folder.starts_with('/') || folder.as_bytes().get(1) == Some(&b':') || folder.contains("://"); - if folder.is_empty() || absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) { + if absolute || name.is_empty() || folder.chars().chain(name.chars()).any(char::is_control) { return None; } + if folder.is_empty() { + return Some(name.to_string()); + } Some(format!("{}/{name}", folder.trim_end_matches('/'))) } +/// The image key of a linked image of the file at `path` that shows `blob` (its preview or a +/// placeholder): the blob's own key and the path's. Images of other files that show the same pixels +/// have keys of their own, and reading one file's pixels in changes that file's images only. +fn linked_key(blob: &ImageBlob, path: &str) -> String { + format!("{}-{}", blob.content_key(), vectorcraft_doc::links::hash_bytes(path.as_bytes())) +} + pub(super) fn sane(r: Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_SIDE) } diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 2273f087ba..f6ac4a00ae 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -1,7 +1,9 @@ use super::document::slot_of; use super::ops::{paints_apart, path_rule}; use super::types::{Frame, GState, Kind, MAX_DEPTH, MAX_NODES, PendingEnvelope}; -use super::{AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj}; +use super::{ + AppearanceItem, Arc, BezPath, BlendMode, FillRule, HashMap, HashSet, LayerColor, Node, NodeId, NodeKind, Obj, Paint, PathEl, Rc, Reader, V, obj, +}; use vectorcraft_doc::TextWrap; impl<'a> Reader<'a> { @@ -13,6 +15,7 @@ impl<'a> Reader<'a> { } if matches!(kind, Kind::Layer(_)) { self.ensure_space(); + self.check_symbols(); } let base = if matches!(kind, Kind::Obj(_)) { self.stack.len() } else { self.frames.last().map_or(0, |f| f.base) }; self.frames.push(Frame { @@ -133,7 +136,7 @@ impl<'a> Reader<'a> { // Some files mark every group so, the plain one holding the subpaths too (#980): one // paint for all its paths keeps it one compound path, its holes cut. Kind::Compound if kids.iter().any(|k| self.looks.contains(&k.id) && paints_apart(k)) => { - let (children, clip) = self.clip_first(kids, &clips); + let (children, clip) = self.clip_first(kids, &clips, true, self.nesting() + 1)?; self.new_node(NodeKind::Group { children, clip }, &gs) } Kind::Compound => { @@ -153,7 +156,7 @@ impl<'a> Reader<'a> { } // A group with a clipping path (`q` … `Q`, or a `W` path in a group) is a clipping group. _ => { - let (children, clip) = self.clip_first(kids, &clips); + let (children, clip) = self.clip_first(kids, &clips, false, self.nesting() + 1)?; self.new_node(NodeKind::Group { children, clip }, &gs) } }; @@ -200,9 +203,76 @@ impl<'a> Reader<'a> { Some(n) } + /// How deep in the document the objects the open frames hold are, less one: a dictionary adds no level, and an + /// opacity mask's art is two under the frames around the object it masks. + fn nesting(&self) -> usize { + self.frames + .iter() + .map(|f| match f.kind { + Kind::Obj(_) => 0, + Kind::Mask => 2, + _ => 1, + }) + .sum() + } + + /// `kids` with the clipping paths among them (indexes `clips`) first → the children and whether they clip. + /// + /// Several clipping paths in a clipping group or a layer clip to their intersection, as each `W` reduces the clip + /// set by the ones before it: each clipping path after the first clips a clipping group nested in the one before + /// it, and the innermost one holds the art. As with one clipping path, every object in the group is clipped by all + /// of them, wherever it is written. A clipping path's painted fill stays at its path's level. In a compound path + /// (`union`), several clipping paths are one compound path. `at`: how deep the group or layer made of them is in the + /// document. + fn clip_first(&mut self, kids: Vec, clips: &[usize], union: bool, at: usize) -> Result<(Vec>, bool), String> { + if union || clips.len() < 2 { + return Ok(self.clip_union(kids, clips)); + } + let clips: std::collections::HashSet = clips.iter().copied().collect(); + let (clip, rest): (Vec, Vec) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i)); + let innermost = clip.len() - 1; + // A painted fill follows its clipping path; the art goes in the innermost level. + let level = |i: usize, n: &Node| { + if self.clip_fills.contains(&n.id) { clip.iter().rposition(|(c, _)| *c < i).unwrap_or(0) } else { innermost } + }; + // Each nested clipping group adds a level over the nodes placed in it, the clipping paths included. Past the + // reader's limit, or past the document's when the nodes fit in it without those levels (the document would merge + // the deepest groups and drop their clipping paths), the editing data isn't read. + let deepest = + rest.iter().map(|(i, n)| level(*i, n) + depth(n)).chain(clip.iter().enumerate().map(|(k, (_, n))| k + depth(n))).max().unwrap_or(0); + let flat = rest.iter().map(|(_, n)| depth(n)).chain(clip.iter().map(|(_, n)| depth(n))).max().unwrap_or(0); + if at + deepest > MAX_DEPTH || (at + deepest > vectorcraft_doc::MAX_DEPTH && at + flat <= vectorcraft_doc::MAX_DEPTH) { + return Err("its clipping masks are nested too deeply".into()); + } + // Each level: its clipping path, the clipping paths' own fills, which paint under the art they clip, then the + // art. + let mut fills_at: Vec> = clip.iter().map(|_| Vec::new()).collect(); + let mut art_at: Vec> = clip.iter().map(|_| Vec::new()).collect(); + for (i, n) in rest { + let k = level(i, &n); + let at = if self.clip_fills.contains(&n.id) { &mut fills_at } else { &mut art_at }; + if let Some(v) = at.get_mut(k) { + v.push(n); + } + } + let mut children: Vec> = Vec::new(); + let mut levels = clip.into_iter().map(|(_, n)| n).zip(fills_at.into_iter().zip(art_at)).rev().peekable(); + while let Some((path, (fills, art))) = levels.next() { + let mut inner: Vec> = Vec::with_capacity(fills.len() + art.len() + children.len() + 1); + inner.push(Arc::new(path)); + inner.extend(fills.into_iter().chain(art).map(Arc::new)); + inner.append(&mut children); + if levels.peek().is_none() { + return Ok((inner, true)); + } + children = vec![Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children: inner, clip: true }))]; + } + Ok((children, false)) + } + /// `kids` with the clipping paths among them (indexes `clips`) first, several as one compound /// path → the children and whether they clip. - fn clip_first(&mut self, kids: Vec, clips: &[usize]) -> (Vec>, bool) { + fn clip_union(&mut self, kids: Vec, clips: &[usize]) -> (Vec>, bool) { let clips: std::collections::HashSet = clips.iter().copied().collect(); let (mut clip, rest): (Vec, Vec) = kids.into_iter().enumerate().partition(|(i, _)| clips.contains(i)); let clip_node = match clip.len() { @@ -245,7 +315,7 @@ impl<'a> Reader<'a> { (mesh.opacity, mesh.blend, mesh.isolate, mesh.knockout) = before; } let Kind::Layer(a) = f.kind else { return Ok(()) }; - let (children, clip) = self.clip_first(f.children, &f.clips); + let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 1)?; let color = a.color.unwrap_or(LayerColor::Preset(0)); let mut layer = Node::new( self.doc.alloc_id(), @@ -307,7 +377,8 @@ impl<'a> Reader<'a> { pub(super) fn end_mask(&mut self) -> Result<(), String> { self.end_path_quietly(); let f = self.close("X+", |k| matches!(k, Kind::Mask))?; - let (children, clip) = self.clip_first(f.children, &f.clips); + // The mask's art is one level under the object it masks. + let (children, clip) = self.clip_first(f.children, &f.clips, false, self.nesting() + 2)?; let art = self.new_node(NodeKind::Group { children, clip }, &f.gs); self.gs = f.gs; self.pending_unread_fill = f.pending_unread_fill; @@ -480,24 +551,141 @@ impl<'a> Reader<'a> { Ok(Some(id)) } + /// A symbol instance (`/SymbolInstance`): the symbol its `SymbolRef` names, placed by its + /// `RTransformMatrix`, hidden and locked as the state says. In a symbol's art the matrix is + /// written about the canvas point of art space's origin, and the name is the file's until the + /// symbols are checked ([`Self::check_symbols`]). An instance of a symbol that wasn't read, one + /// whose appearance differs from its symbol's, or one placed only by a `Matrix` or `Transform`, + /// comes in as the page draws it, within the symbol's box placed by the matrix when the box is + /// known. fn symbol_instance(&mut self, o: &Obj) -> Result<(), String> { - let bounds = o.get("SymbolRef").and_then(|v| v.iter().find_map(V::text)).and_then(|name| self.symbol_bounds.get(&name).copied()); - let matrix = o - .get("Matrix") - .or_else(|| o.get("Transform")) - .map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v))); - let box_at_canvas = match (bounds, matrix.as_deref()) { - (Some(b), Some([a, c, d, e, x, y])) if [*a, *c, *d, *e, *x, *y].iter().all(|n| n.is_finite()) => { - Some(self.space().transform_rect_bbox(super::Affine::new([*a, *c, *d, *e, *x, *y]).transform_rect_bbox(b))) - } + let name = o.text("SymbolRef"); + let affine = |n: &[f64]| match n { + [a, b, c, d, e, f] if [a, b, c, d, e, f].iter().all(|v| v.is_finite()) => Some(super::Affine::new([*a, *b, *c, *d, *e, *f])), _ => None, }; - match box_at_canvas { - Some(b) => self.unread_box("symbols", b, self.obj_hidden).map(|_| ()), - None => { - self.unreadable("symbols", self.obj_hidden); - Ok(()) + let live = affine(&o.nums("RTransformMatrix")); + let boxed_only = live.is_none(); + let matrix = live.or_else(|| { + o.get("Matrix") + .or_else(|| o.get("Transform")) + .map(|v| v.iter().find_map(|item| if let V::Arr(a) = item { Some(Self::nums(a)) } else { None }).unwrap_or_else(|| Self::nums(v))) + .and_then(|n| affine(&n)) + }); + let hidden = self.obj_hidden; + let place = if self.symbol.is_some() { + self.canvas_origin().map(|o| super::Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y])) + } else { + Some(self.space()) + }; + let (Some(name), Some(m), Some(place)) = (name, matrix, place) else { + self.unreadable("symbols", hidden); + return Ok(()); + }; + let xf = place * m; + let usable = xf.determinant().abs() >= 1e-12 && xf.as_coeffs().iter().all(|v| v.is_finite()); + let symbol = if self.symbol.is_some() { Some(name.clone()) } else { self.symbol_names.get(&name).cloned() }; + match symbol.filter(|_| usable && !boxed_only && !overrides(o)) { + Some(symbol) => { + // Its transparency is the `Xy` after it, as a group's is. + let gs = self.gs.clone(); + let node = self.new_node(NodeKind::SymbolInstance { symbol, xf }, &gs); + self.add(node, hidden) } + None => { + let bounds = self.symbol_art_bounds(&name).or_else(|| self.symbol_bounds.get(&name).copied()); + match bounds.map(|b| xf.transform_rect_bbox(b)).filter(|_| usable && self.symbol.is_none()) { + Some(b) => self.unread_box("symbols", b, hidden).map(|_| ()), + None => { + self.unreadable("symbols", hidden); + Ok(()) + } + } + } + } + } + + /// The art box (symbol space) of the symbol read under `name` (its name in the file), measured + /// once. + fn symbol_art_bounds(&mut self, name: &str) -> Option { + if let Some(b) = self.symbol_art_bounds.get(name) { + return *b; + } + let named = self.symbol_names.get(name)?; + let boxes = self.doc.symbol_boxes(); + let b = self.doc.symbols.iter().find(|s| &s.name == named).and_then(|s| s.art.visual_bounds_with(&boxes)); + drop(boxes); + self.symbol_art_bounds.insert(name.to_string(), b); + b + } + + /// Check the symbols read for instances in their art of symbols the file doesn't have, before + /// the first layer: a symbol with one isn't kept, and so on for the symbols holding its + /// instances. The instances in the art kept then name the symbols as the document does. + pub(super) fn check_symbols(&mut self) { + if std::mem::replace(&mut self.symbols_checked, true) { + return; + } + // Each symbol's name in the file (none for one named as an earlier one), and the names its + // instances use. + let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect(); + let defs: Vec<(Option, Vec)> = self + .doc + .symbols + .iter() + .map(|s| { + let mut uses = vec![]; + symbol_uses(&s.art, &mut uses, 0); + (files.get(s.name.as_str()).map(|f| f.to_string()), uses.into_iter().map(str::to_string).collect()) + }) + .collect(); + // A symbol goes when one of its instances names a symbol that isn't kept: first those + // naming one the file doesn't have, then, one at a time, those using a symbol that went. + let mut kept: Vec = vec![true; defs.len()]; + let mut users: HashMap<&str, Vec> = HashMap::new(); + let mut going: Vec = vec![]; + for (i, (_, uses)) in defs.iter().enumerate() { + for u in uses { + users.entry(u.as_str()).or_default().push(i); + } + if uses.iter().any(|u| !self.symbol_names.contains_key(u)) { + going.push(i); + } + } + while let Some(i) = going.pop() { + match kept.get_mut(i) { + Some(k) if *k => *k = false, + _ => continue, + } + if let Some(file) = defs.get(i).and_then(|(file, _)| file.as_deref()) { + going.extend(users.get(file).into_iter().flatten().copied().filter(|j| kept.get(*j).copied().unwrap_or(false))); + } + } + drop(users); + if kept.iter().any(|k| !k) { + let left: Vec<(Option, String)> = defs + .iter() + .zip(&self.doc.symbols) + .zip(&kept) + .filter(|(_, k)| !**k) + .map(|(((file, _), s), _)| (file.clone(), s.name.clone())) + .collect(); + let mut i = 0; + self.doc.symbols.retain(|_| { + i += 1; + kept.get(i - 1).copied().unwrap_or(false) + }); + // Their art's box isn't known (the instances that made them go have none), so their + // instances have no box either. + for (file, named) in left { + self.doc.set_symbol_registration(&named, vectorcraft_doc::SymbolRegistration::CENTER); + let Some(file) = file else { continue }; + self.symbol_names.remove(&file); + } + } + let names = self.symbol_names.clone(); + for s in &mut self.doc.symbols { + rename_uses(Arc::make_mut(&mut s.art), &names, 0); } } @@ -573,6 +761,8 @@ impl<'a> Reader<'a> { let mut blend = Node::new(self.doc.alloc_id(), kind); (blend.name, blend.visible, blend.locked) = (steps.name.take(), steps.visible, steps.locked); (blend.opacity, blend.blend, blend.isolate, blend.knockout) = (steps.opacity, steps.blend, steps.isolate, steps.knockout); + // Its note, URL and data (object tags) too. + blend.extras_mut().attrs = steps.extras_mut().attrs.take(); f.children.push(blend); } None => { @@ -723,6 +913,68 @@ pub(super) fn drop_commented_copies(layers: &mut [Arc], hidden: &HashSet(node: &'n Node, out: &mut Vec<&'n str>, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + out.push(symbol); + } + if let Some(m) = &node.extras().mask { + symbol_uses(&m.art, out, depth + 1); + } + for c in node.children().into_iter().flatten() { + symbol_uses(c, out, depth + 1); + } +} + +/// The instances in `node`, and in the art of its opacity masks, named by `names` (a name in the +/// file → the symbol's in the document). +fn rename_uses(node: &mut Node, names: &HashMap, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &mut node.kind + && let Some(named) = names.get(symbol.as_str()) + { + symbol.clone_from(named); + } + if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) { + rename_uses(Arc::make_mut(&mut m.art), names, depth + 1); + } + for c in node.children_mut().into_iter().flatten() { + rename_uses(Arc::make_mut(c), names, depth + 1); + } +} + +/// Whether a symbol instance's dictionary carries appearance of its own (a dynamic symbol's +/// edits), which isn't read. +fn overrides(o: &Obj) -> bool { + const KEYS: [&str; 5] = [ + "AI19SymbolAppearanceMap", + "AI19SymbolOverriddenSymbolMap", + "AI Local Art of Symbol Instance", + "AI15 Layer In Symbol", + "AI15 Color Of Layer In Symbol", + ]; + // In a dictionary or array nested in it, as a keyed entry's value, in an array or among the + // values closed without a key. + fn has(o: &Obj, depth: usize) -> bool { + depth <= 8 + && (o.entries.iter().any(|(k, v)| k.as_deref().is_some_and(|k| KEYS.contains(&k)) || v.iter().any(|v| in_value(v, depth + 1))) + || o.content.iter().any(|v| in_value(v, depth + 1))) + } + fn in_value(v: &V, depth: usize) -> bool { + match v { + V::Obj(c) => has(c, depth), + V::Arr(items) => depth <= 8 && items.iter().any(|v| in_value(v, depth + 1)), + _ => false, + } + } + has(o, 0) +} + /// Close the subpath `bp` ends with, if it has one open. pub(super) fn close(bp: &mut BezPath) { if bp.elements().last().is_some_and(|e| !matches!(e, PathEl::ClosePath)) { @@ -730,6 +982,20 @@ pub(super) fn close(bp: &mut BezPath) { } } +/// How many levels of nodes `n` holds, itself included, its opacity masks' art included. +fn depth(n: &Node) -> usize { + let mut deepest = 0; + let mut todo = vec![(n, 1)]; + while let Some((n, d)) = todo.pop() { + deepest = deepest.max(d); + todo.extend(n.children().into_iter().flatten().map(|c| (c.as_ref(), d + 1))); + if let Some(m) = n.extras().mask.as_ref() { + todo.push((m.art.as_ref(), d + 1)); + } + } + deepest +} + /// The fill rule of a path or compound node. /// `kids` with the members of each plain group among them in the group's place, at any depth. fn ungrouped(kids: Vec) -> Vec { diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index b1c9db39d3..2bd94479db 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,10 +1,13 @@ +use std::collections::HashMap; + use super::super::brush; use super::art::{four, sane, two}; use super::types::{ - FLIP, GState, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, - VERSIONED_UNENDED, + FLIP, GState, Kind, MAX_DEPTH, MAX_HEX, MAX_LISTED, MAX_NODES, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, MAX_SYMBOLS, + PatternHead, Place, Raster, SKIPPED, SymbolHead, VERSIONED_UNENDED, }; -use super::{Arc, Lexer, Node, PatternDef, Reader, Rect, Tok, V, marker, obj}; +use super::{Arc, Global, Lexer, Node, NodeKind, PatternDef, Reader, Rect, Tok, V, marker, obj}; +use vectorcraft_doc::{NodeId, Symbol, SymbolRegistration}; impl<'a> Reader<'a> { pub(super) fn push(&mut self, v: V) -> Result<(), String> { @@ -85,7 +88,7 @@ impl<'a> Reader<'a> { } let m = marker(line); // A pattern's definition. One inside another's isn't read, and the outer tile is then incomplete. - if m == "BeginPattern" { + if m == "BeginPattern" && self.symbol.is_none() { let section = self.section("EndPattern")?; if self.pattern.is_some() { self.unsupported.insert("patterns inside patterns".into()); @@ -96,7 +99,12 @@ impl<'a> Reader<'a> { } if m == "BeginSymbol" { let section = self.section("EndSymbol")?; - self.symbol_bounds(section); + self.define_symbol(section); + return Ok(()); + } + if m == "BeginSymbolList" { + let section = self.section("EndSymbolList")?; + self.symbol_list(section); return Ok(()); } // Brushes and their art (those in a pattern's or a brush's art aren't read). @@ -127,6 +135,9 @@ impl<'a> Reader<'a> { } if m == "BeginEncoding" { self.type_state.encoding_comment(line); + let section = self.section("EndEncoding")?; + self.encoding_section(section); + return Ok(()); } // Versioned content holds alternatives of the same art, the newest first: the first is // read, and the next one (`%AI17_Alternate_Content`, or `…_if_version_gt:` for a version @@ -160,8 +171,12 @@ impl<'a> Reader<'a> { return Ok(()); } if line.starts_with("AI5_BeginRaster") { + // An `XG` outside a raster object names no image in it. + self.image_link = None; self.raster = Some(Raster::default()); } else if line.starts_with("AI5_EndRaster") { + // A file `XG` named in this raster object is no later one's. + self.image_link = None; if let Some(Raster { operands: Some(vals), hex, .. }) = self.raster.take() { return self.image_from(vals, &hex); } @@ -303,6 +318,8 @@ impl<'a> Reader<'a> { _ => return, }; if !name.trim().is_empty() && !self.custom_colors.iter().any(|n| n.name == name) { + // A gradient or pattern defined after it does not take its swatch's name. + self.global_names.reserve(&name); self.custom_colors.push(super::Named { name, color, tint: 1.0, spot: true }); } } @@ -355,13 +372,17 @@ impl<'a> Reader<'a> { let mut sub = Reader::new(section); sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead::default()); - // The gradients defined so far, lent (and those it defines kept). + // The gradients defined so far and the names given, lent (and those it defines kept). sub.gradients = std::mem::take(&mut self.gradients); + 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); // Unread art in the definition, hidden or not, leaves the tile incomplete. let whole = read.is_ok() && sub.unsupported.is_empty() @@ -380,8 +401,10 @@ impl<'a> Reader<'a> { sub.subreader_depth = self.subreader_depth + 1; sub.pattern = Some(PatternHead { taken: true, name: def.name.clone(), tile: Some(def.tile) }); sub.gradients = std::mem::take(&mut self.gradients); + 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() { @@ -389,8 +412,10 @@ 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); let whole = read.is_ok() && sub.unsupported.is_empty() && sub.unknown.is_empty() @@ -466,15 +491,17 @@ impl<'a> Reader<'a> { return; }; let art: Vec> = frame.children.iter().map(|n| Arc::new(self.doc.reid(n))).collect(); - let mut def = PatternDef::new(&head.name, art); + // Fills and the tables look the pattern up by its name in the file; the document has it by + // the name it shows. + let mut def = PatternDef::new(&self.global_names.define(Global::Pattern, &head.name), art); def.tile = FLIP.transform_rect_bbox(tile); - if self.pattern_tiles.insert(def.name.clone(), def.tile).is_some() { + if self.pattern_tiles.insert(head.name.clone(), def.tile).is_some() { self.doc.patterns.retain(|p| p.name != def.name); } if v7 { - self.v7_patterns.insert(def.name.clone()); + self.v7_patterns.insert(head.name); } else { - self.v7_patterns.remove(&def.name); + self.v7_patterns.remove(&head.name); } self.doc.patterns.push(def); for (key, blob) in sub.doc.images { @@ -489,32 +516,167 @@ impl<'a> Reader<'a> { } } - /// Read a definition's box for an instance whose art must come from the page. - fn symbol_bounds(&mut self, section: &[u8]) { - if self.symbol_bounds.len() >= MAX_PATTERNS || self.subreader_depth >= MAX_SUBREADERS { + /// A symbol's definition (`section`: what follows `%AI14_BeginSymbol`), read by a reader of its + /// own into a symbol of the document, its art in the symbol's space (y down), named as the file + /// names it unless another symbol has that name. A definition inside another one or inside a + /// pattern's isn't read, nor is one after the first layer (the symbols were checked there, see + /// [`Reader::check_symbols`]). One it can't read whole (an operator it doesn't know, type, unbalanced + /// groups, art it leaves out) isn't kept: its instances come in as the page draws them, within + /// its art's box when that can be measured. + fn define_symbol(&mut self, section: &[u8]) { + if self.symbol.is_some() + || self.pattern.is_some() + || self.symbols_checked + || self.subreader_depth >= MAX_SUBREADERS + || self.doc.symbols.len() + self.symbol_bounds.len() >= MAX_SYMBOLS + { return; } - let mut lex = super::Lexer::new(section); - let name = match lex.next_token().map(|t| t.tok) { - Some(Tok::Str(bytes)) => super::obj::text(&bytes), + let name = match Lexer::new(section).next_token().map(|t| t.tok) { + Some(Tok::Str(bytes)) => obj::text(&bytes), _ => return, }; let mut sub = Reader::new(section); sub.subreader_depth = self.subreader_depth + 1; - sub.cropmarks = self.cropmarks; + sub.symbol = Some(SymbolHead::default()); sub.template = self.template; + // The gradients, art styles and patterns defined so far and the names given, lent. + sub.gradients = std::mem::take(&mut self.gradients); + sub.global_names = std::mem::take(&mut self.global_names); + sub.styles = std::mem::take(&mut self.styles); + 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; - if read.is_err() || !sub.unsupported.is_empty() || !sub.unknown.is_empty() || sub.frames.len() != 1 { + self.gradients = std::mem::take(&mut sub.gradients); + self.global_names = std::mem::take(&mut sub.global_names); + self.styles = std::mem::take(&mut sub.styles); + self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); + // Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or + // gradient still open at the end (as [`Reader::run_string`] checks), isn't whole. + let open = sub.done + || sub.stack.iter().any(|v| matches!(v, V::Mark)) + || !sub.marks.is_empty() + || sub.text.is_some() + || sub.raster.is_some() + || sub.place.is_some() + || sub.mesh.is_some() + || sub.gradient_def.is_some(); + let head = sub.symbol.take().unwrap_or_default(); + let registration = head.registration; + let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; + let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; + let mut kids = frame.children; + // Where a symbol's art puts a pattern's tiles isn't known. + let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0)); + if !whole { + let boxes = self.doc.symbol_boxes(); + let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes))); + drop(boxes); + if let Some(b) = bounds.filter(|b| sane(*b) && b.area() > 0.0) { + self.symbol_bounds.insert(name, b); + } return; } - let Some(frame) = sub.frames.pop() else { return }; - let bounds = frame.children.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds())); - let Some(bounds) = bounds.map(|b| sub.space().inverse().transform_rect_bbox(b)) else { return }; - if sane(bounds) && bounds.area() > 0.0 { - self.symbol_bounds.insert(name, bounds); + let art = match (kids.len(), kids.pop()) { + (1, Some(one)) => one, + (_, last) => Node::group(self.doc.alloc_id(), kids.into_iter().chain(last).map(Arc::new).collect()), + }; + // The group a definition holds its art in, when it holds one object and isn't linked to a + // graphic style. + let linked = sub.style_links.iter().any(|(id, _)| *id == art.id); + let art = match symbol_art_member(&art).filter(|_| !linked).cloned() { + Some(m) => Arc::unwrap_or_clone(m), + None => art, + }; + let read_art = art; + let mut art = self.doc.reid(&read_art); + self.reid_masks(&mut art, 0); + // The objects of the art linked to graphic styles, by their ids in the document. + if !sub.style_links.is_empty() { + let mut ids = HashMap::new(); + pair_ids(&read_art, &art, &mut ids, 0); + for (id, style) in &sub.style_links { + if let Some(new) = ids.get(id) + && self.style_links.len() < MAX_NODES + { + self.style_links.push((*new, style.clone())); + } + } } + let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name }); + self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false }); + if let Some(reg) = registration.and_then(symbol_registration) { + self.doc.set_symbol_registration(&named, reg); + } + self.symbol_names.entry(name).or_insert(named); + for (key, blob) in sub.doc.images { + self.doc.images.entry(key).or_insert(blob); + } + self.spots.extend(sub.spots); + self.stop_spots.extend(sub.stop_spots); + self.cmyk_colors += sub.cmyk_colors; + self.rgb_colors += sub.rgb_colors; + self.drawn_looks += sub.drawn_looks; + for w in &sub.warnings { + self.warn(w); + } + } + + /// `base`, or the first free "`base` N" (N from 2) when a symbol read has that name, as + /// [`vectorcraft_doc::Document::unique_symbol_name`] names it, without looking at every symbol + /// for each N. + fn unique_symbol_name(&mut self, base: &str) -> String { + let mut named = base.to_string(); + if self.symbol_taken.contains(&named) { + let next = self.symbol_suffix.entry(named.clone()).or_insert(2); + while self.symbol_taken.contains(&format!("{base} {next}")) { + *next += 1; + } + named = format!("{base} {next}"); + *next += 1; + } + self.symbol_taken.insert(named.clone()); + named + } + + /// Give the art of the opacity masks in `n` (a copy of a symbol's art with ids of this + /// document, [`vectorcraft_doc::Document::reid`], which leaves masks as they are) ids of this + /// document too. + fn reid_masks(&mut self, n: &mut Node, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + let mut art = self.doc.reid(&m.art); + self.reid_masks(&mut art, depth + 1); + m.art = Arc::new(art); + } + for c in n.children_mut().into_iter().flatten() { + self.reid_masks(Arc::make_mut(c), depth + 1); + } + } + + /// The symbol list (`section`: what follows `%AI24_BeginSymbolList`): the symbols' names in the + /// Symbols panel's order. The first list is kept. + fn symbol_list(&mut self, section: &[u8]) { + if self.symbol.is_some() || self.pattern.is_some() || self.symbol_list.is_some() { + return; + } + let mut lex = Lexer::new(section); + let mut names = vec![]; + while let Some(t) = lex.next_token() { + if let Tok::Str(bytes) = t.tok { + if names.len() >= MAX_LISTED { + break; + } + names.push(obj::text(&bytes)); + } + } + self.symbol_list = Some(names); } /// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's @@ -560,15 +722,21 @@ impl<'a> Reader<'a> { // In a space of its own (y down), with no head to take. sub.pattern = Some(PatternHead { taken: true, ..PatternHead::default() }); sub.subreader_depth = self.subreader_depth + 1; - // The gradients and patterns defined so far, lent. + // The gradients and patterns defined so far, and which patterns are in the version 7 form, lent. sub.gradients = std::mem::take(&mut self.gradients); sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); + sub.v7_patterns = std::mem::take(&mut self.v7_patterns); + 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); + self.v7_patterns = std::mem::take(&mut sub.v7_patterns); + self.global_names = std::mem::take(&mut sub.global_names); // Images aren't kept: the document's images don't count a brush's art among their users. Art // read with a note (something left out of it) isn't kept either. let whole = read.is_ok() @@ -589,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) -> Vec { @@ -769,6 +952,64 @@ fn ps_string(v: &[u8]) -> Option { None } +/// The one member of `n` when `n` is a plain group holding only it (not clipping, unnamed, shown, +/// unlocked, opaque, Normal, not isolated, knockout neutral, no knockout shape, appearance, opacity +/// mask or other extras such as object attributes): a symbol's art written as such a group +/// (definitions hold a group) is that member. +pub(crate) fn symbol_art_member(n: &Node) -> Option<&Arc> { + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + let [one] = children.as_slice() else { return None }; + let plain = n.name.as_deref().is_none_or(str::is_empty) + && n.visible + && !n.locked + && n.opacity == 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::Neutral + && !n.knockout_shape + && n.appearance.items.is_empty() + && n.appearance.effects.is_empty() + && *n.extras() == vectorcraft_doc::NodeExtras::default(); + plain.then_some(one) +} + +/// Whether `n`, an object in it or the art of an opacity mask in it is filled or stroked with a +/// pattern. +fn paints_pattern(n: &Node, depth: usize) -> bool { + if depth > MAX_DEPTH { + return true; + } + let pattern = |p: &super::Paint| matches!(p, super::Paint::Pattern { .. }); + n.appearance.items.iter().any(|item| match item { + super::AppearanceItem::Fill(f) => pattern(&f.paint), + super::AppearanceItem::Stroke(s) => pattern(&s.paint), + }) || n.extras().mask.as_ref().is_some_and(|m| paints_pattern(&m.art, depth + 1)) + || n.children().into_iter().flatten().any(|c| paints_pattern(c, depth + 1)) +} + +/// Each id of `old` and its descendants → the id of the object in its place in `new`, a copy of +/// `old` with new ids ([`vectorcraft_doc::Document::reid`]). +fn pair_ids(old: &Node, new: &Node, ids: &mut HashMap, depth: usize) { + ids.insert(old.id, new.id); + if depth > MAX_DEPTH { + return; + } + if let (Some(a), Some(b)) = (old.extras().mask.as_ref(), new.extras().mask.as_ref()) { + pair_ids(&a.art, &b.art, ids, depth + 1); + } + if let (Some(a), Some(b)) = (old.children(), new.children()) { + for (a, b) in a.iter().zip(b) { + pair_ids(a, b, ids, depth + 1); + } + } +} + +/// The registration point `AI13PatternRegistrationType` `v` gives a symbol: 1 to 9 from the top +/// left, row by row (5 the center); `None` for other numbers. +pub(super) fn symbol_registration(v: f64) -> Option { + (v.fract() == 0.0 && (1.0..=9.0).contains(&v)).then(|| SymbolRegistration(v as u8 - 1)) +} + #[cfg(test)] mod tests { use super::*; @@ -786,9 +1027,11 @@ mod tests { assert_eq!(ps_string(longest.as_bytes()).map(|s| s.len()), Some(MAX_STRING)); } + /// Definitions nested in a definition aren't read, however deep, and none is read past the + /// limit of nested readers. #[test] fn deeply_nested_symbol_definitions_stop_at_subreader_limit() { - let mut definition = String::from("(Outer) 0 Ae\n"); + let mut definition = String::from("(Outer) 0 A 0 Xw 0 Ae\n"); for i in 0..300 { definition.push_str(&format!("%AI14_BeginSymbol\n(S{i}) 0 Ae\n")); } @@ -798,8 +1041,34 @@ mod tests { } let mut reader = Reader::new(b""); reader.subreader_depth = MAX_SUBREADERS; - reader.symbol_bounds(definition.as_bytes()); - assert!(reader.symbol_bounds.is_empty()); + reader.define_symbol(definition.as_bytes()); + assert!(reader.doc.symbols.is_empty()); + reader.subreader_depth = 0; + reader.define_symbol(definition.as_bytes()); + let names: Vec<&str> = reader.doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Outer"]); + } + + /// Definitions past the limit aren't read, however they are named. + #[test] + fn symbol_definitions_stop_at_the_limit_even_with_one_name() { + let mut reader = Reader::new(b""); + for _ in 0..MAX_SYMBOLS + 10 { + reader.define_symbol(b"(Same) 0 A 0 Xw 0 Ae\nu\nU\n"); + } + assert_eq!(reader.doc.symbols.len(), MAX_SYMBOLS); + assert_eq!(reader.doc.symbols.last().map(|s| s.name.as_str()), Some(format!("Same {MAX_SYMBOLS}").as_str())); + } + + /// The registration points 1 to 9 run from the top left, row by row; other numbers give none. + #[test] + fn symbol_registration_numbers_run_row_by_row() { + assert_eq!(symbol_registration(1.0), Some(SymbolRegistration(0))); + assert_eq!(symbol_registration(5.0), Some(SymbolRegistration::CENTER)); + assert_eq!(symbol_registration(9.0), Some(SymbolRegistration(8))); + for v in [0.0, 10.0, 2.5, -1.0, f64::NAN] { + assert_eq!(symbol_registration(v), None); + } } #[test] @@ -861,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 = 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); + } } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 5aebb94dda..2fd918fe64 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -4,10 +4,10 @@ use super::containers::drop_commented_copies; use super::ops::appearance_from_art_style; use super::types::{FLIP, Kind, MAX_DEPTH}; use super::{ - Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, + Affine, Arc, Artboard, CANVAS_CENTRE, ColorMode, Document, Global, HashMap, Node, NodeId, NodeKind, Obj, OpacityMask, Paint, Point, Reader, Rect, Structure, Swatch, Unit, V, obj, }; -use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, TextWrap, Variable, VariableKind, Variables}; +use vectorcraft_doc::{DataSet, DataValue, GraphicStyle, Guide, ImageBlob, PatternDef, Symbol, TextWrap, Variable, VariableKind, Variables}; /// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files). fn ruler_unit(v: u8) -> Option { @@ -22,6 +22,19 @@ fn ruler_unit(v: u8) -> Option { }) } +/// `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, 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)] @@ -128,27 +141,41 @@ pub(crate) const LOOK_SLOT: &str = "\u{0}text:look"; /// The artboards (names, and rects in art space) of the editing data `data` that [`read`] can't /// read as a whole, as far as it gets: where to put the pages of its PDF part instead, and what to -/// call them (#1068). -pub fn artboards(data: &[u8]) -> Vec<(String, Rect)> { +/// call them (#1068); and the index among them of the active artboard (`CropAreaActive`). +pub fn artboards(data: &[u8]) -> (Vec<(String, Rect)>, Option) { let found = artboards_read(data); - if !found.is_empty() { + if !found.0.is_empty() && found.1.is_some() { return found; } - // Reading can stop before the artboards (art kept in the document's data comes first): read - // their array on its own. - artboard_array(data).map_or(found, |array| { - let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec(); - alone.extend_from_slice(array); - alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n"); - artboards_read(&alone) - }) + // Reading can stop before the artboards (art kept in the document's data comes first), or + // between them and the active artboard's entry: read their array on its own. + let Some((array, active)) = artboard_array(data) else { return found }; + let mut alone = b"%_/Document :\n%_/Dictionary :\n".to_vec(); + alone.extend_from_slice(array); + if let Some(active) = active { + alone.push(b'\n'); + alone.extend_from_slice(active); + } + alone.extend_from_slice(b"\n%_; /NotRecorded ,\n%_;\n"); + let (boards, active) = artboards_read(&alone); + if found.0.is_empty() { + (boards, active) + } else if boards == found.0 { + // The same array: its names and rects read alike. + (found.0, active) + } else { + found + } } +/// The key that ends the `ArtboardArray` entry of the editing data. +const ARTBOARD_ARRAY: &[u8] = b"%_; (ArtboardArray) ,"; + /// The `ArtboardArray` entry of the editing data `data`, from its `/Array :` to its key: found -/// from the key back, counting the dictionaries its artboards open and close. -fn artboard_array(data: &[u8]) -> Option<&[u8]> { - const KEY: &[u8] = b"%_; (ArtboardArray) ,"; - let end = data.windows(KEY.len()).rposition(|w| w == KEY)? + KEY.len(); +/// from the key back, counting the dictionaries its artboards open and close; and the +/// `CropAreaActive` entry of the dictionary that holds it ([`crop_area_active`]). +fn artboard_array(data: &[u8]) -> Option<(&[u8], Option<&[u8]>)> { + let end = data.windows(ARTBOARD_ARRAY.len()).rposition(|w| w == ARTBOARD_ARRAY)? + ARTBOARD_ARRAY.len(); let head = data.get(..end)?; let mut depth = 0usize; let mut line_end = head.len(); @@ -160,7 +187,10 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { } else if text.starts_with(b"/") && text.windows(2).any(|w| w == b" :") { depth = depth.checked_sub(1)?; if depth == 0 { - return head.get(line_start..); + let breaks = |b: &u8| *b == b'\n' || *b == b'\r'; + let after = data.get(end..).and_then(|rest| crop_area_active(rest.split(breaks), true)); + let active = after.or_else(|| data.get(..line_start).and_then(|before| crop_area_active(before.rsplit(breaks), false))); + return Some((head.get(line_start..)?, active)); } } } @@ -168,6 +198,33 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { } } +/// The `CropAreaActive` entry (`%_ /Int (CropAreaActive) ,`) among the entries of the dictionary +/// that holds the `ArtboardArray` entry, skipping the dictionaries and arrays inside it: `lines` are +/// the lines after that entry, in order (`forward`), or those before it, last first. +fn crop_area_active<'a>(lines: impl Iterator, forward: bool) -> Option<&'a [u8]> { + const KEY: &[u8] = b" /Int (CropAreaActive) ,"; + let mut depth = 0usize; + for line in lines { + let Some(text) = line.strip_prefix(b"%_") else { continue }; + let closes = text.starts_with(b";") || text.starts_with(b"/Def ;"); + let opens = !closes && text.starts_with(b"/") && text.windows(2).any(|w| w == b" :"); + let (enters, leaves) = if forward { (opens, closes) } else { (closes, opens) }; + if enters { + // Into a dictionary or array inside the holder. + depth += 1; + } else if leaves { + // Out of one, or out of the holder itself. + depth = depth.checked_sub(1)?; + } else if depth == 0 { + let digits = text.iter().take_while(|b| b.is_ascii_digit()).count(); + if digits > 0 && text.get(digits..) == Some(KEY) { + return Some(line); + } + } + } + None +} + /// The palette of a `.ai` file's editing data, as [`palette`] reads it. pub struct PaletteSwatches { pub swatches: Vec, @@ -231,7 +288,7 @@ fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap) { /// editing data defines, which are named apart from `patterns` ([`beside`]); `None` when the /// palette is empty or reading stops before it. pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option { - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); // The palette, the gradients and the patterns it names come before the art, so an error in the // art leaves them read. let _ = r.run(); @@ -281,7 +338,7 @@ pub struct Brushes { pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option { // Brush objects are plug-in objects: data without one isn't read again. memchr::memmem::find(data, b"BeginPluginObject")?; - let mut r = Reader::new(data); + let mut r = Reader::with_names(data); // The brushes come before the art, so an error in the art leaves them read. let _ = r.run(); let (mut lib, unread) = r.brush_library()?; @@ -317,9 +374,25 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option { Some(Brushes { brushes: lib, patterns: added, images, note: (unread > 0).then(|| brush::left_out_note(unread)) }) } +/// The graphic styles of the editing data `data`, for a file whose layers aren't read (a graphic +/// style library has none), as [`read`] makes them, with ids from 1, and the data's declared large +/// canvas scale (1 when it declares none). `large_canvas`: as [`read`] takes it. The styles are +/// those the list names before reading stops, and none when the data has no style list or lists no +/// style this reads. +pub fn graphic_styles(data: &[u8], large_canvas: bool) -> (Vec, f64) { + if crate::import::ai::find(data, b"BeginArtStyleList").is_none() { + return (vec![], 1.0); + } + let mut r = Reader::with_names(data); + r.large_canvas = large_canvas.then_some(1.0); + // The styles come before the art, so an error in the art leaves them read. + let _ = r.run(); + (r.graphic_styles().0, r.canvas_scale) +} + /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and /// those of a `/Document` still open when it stopped (its art can be what stopped it). -fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { +fn artboards_read(data: &[u8]) -> (Vec<(String, Rect)>, Option) { let mut r = Reader::new(data); let _ = r.run(); let open: Vec = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect(); @@ -328,7 +401,8 @@ fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { r.document(o); } } - r.artboards.into_iter().map(|b| (b.name, b.rect)).collect() + let active = r.active_board.filter(|i| *i < r.artboards.len()); + (r.artboards.into_iter().map(|b| (b.name, b.rect)).collect(), active) } /// An object bound to a variable of the library: the variable's name, and the XML id of the object @@ -406,10 +480,23 @@ pub fn variables(data: &[u8]) -> VariableRead { } impl<'a> Reader<'a> { - /// Take the author and custom colors that the header of the program `ps` gives (its comment - /// lines up to `%%EndComments`), where the editing data's own header gives none: the program of - /// an EPS whose editing data is kept apart from it. - pub(super) fn program_header(&mut self, ps: &[u8]) { + /// Take the author and custom colors that the header of a program gives (`outer`, from + /// [`Self::header_of`]), where the editing data's own header gives none: the program of an EPS + /// whose editing data is kept apart from it. + pub(super) fn program_header(&mut self, outer: Reader<'_>) { + if self.author.is_none() { + self.author = outer.author; + } + for n in outer.custom_colors { + if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { + self.custom_colors.push(n); + } + } + } + + /// A reader that has read the header of the program `ps` (its comment lines up to + /// `%%EndComments`). + pub(super) fn header_of(ps: &[u8]) -> Reader<'_> { let mut end = 0; for line in ps.split_inclusive(|&b| b == b'\n' || b == b'\r') { if !line.starts_with(b"%") && !line.trim_ascii().is_empty() { @@ -422,14 +509,7 @@ impl<'a> Reader<'a> { } let mut outer = Reader::new(ps.get(..end).unwrap_or_default()); let _ = outer.run(); - if self.author.is_none() { - self.author = outer.author; - } - for n in outer.custom_colors { - if self.custom_colors.len() < super::directives::MAX_CUSTOM_COLORS && !self.custom_colors.iter().any(|c| c.name == n.name) { - self.custom_colors.push(n); - } - } + outer } } @@ -495,9 +575,27 @@ fn text_wrap(o: &Obj, scale: f64) -> Option { } impl<'a> Reader<'a> { - /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the - /// opacity mask it may carry. + /// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), the opacity + /// mask it may carry, and in a pattern's definition the mark of the tile's box + /// (`AIPattern_Editor_Backing_Tile_Rect`), which leaves that box out of the art. pub(super) fn art_dictionary(&mut self, o: &Obj) { + // The unpainted box that a pattern's definition marks as its tile's box isn't art. + if self.pattern.is_some() + && o.nums("AIPattern_Editor_Backing_Tile_Rect").first().copied() == Some(1.0) + && self.after_object + && let Some(f) = self.frames.last_mut() + && f.children.last().is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }) && n.appearance.items.iter().all(|i| i.paint().is_none())) + { + f.children.pop(); + return; + } + // The dictionary after a symbol's art: its registration point. + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && let Some(r) = o.nums("AI13PatternRegistrationType").first() + { + head.registration = Some(*r); + } self.constraint_art(o); // A blend's key object or spine. if let Some(kind) = o.text("ShapeBlendPathType") @@ -519,7 +617,8 @@ impl<'a> Reader<'a> { let value = OpacityMask { art: art.clone(), clip: on("Clipping"), invert: on("Inverted"), disabled: on("Disabled"), linked: on("Linked") }; if let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) { - n.extras_mut().mask = Some(Box::new(value)); + n.extras_mut().mask = Some(Box::new(value.clone())); + self.each_linked_frame(|n| n.extras_mut().mask = Some(Box::new(value.clone()))); } else if !on("Disabled") { self.unreadable("opacity masks without an owning object", false); } @@ -542,6 +641,7 @@ impl<'a> Reader<'a> { && let Some(n) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })) { n.extras_mut().wrap = Some(wrap); + self.each_linked_frame(|n| n.extras_mut().wrap = Some(wrap)); } // The object's XML id, which the variable library's bindings name it by. if let Some(uid) = o.obj("AI10_ArtUID").and_then(Obj::content_text).filter(|u| !u.is_empty()) @@ -565,8 +665,9 @@ impl<'a> Reader<'a> { } } - /// The `/Document` dictionary: the artboards and their display options, Document Raster Effects - /// Settings, its variable library (the first one read), and its Objects on Path records. + /// The `/Document` dictionary: the artboards and their display options, the active artboard + /// (`CropAreaActive`, `/Int`: its index in the `ArtboardArray`, next to it), Document Raster + /// Effects Settings, its variable library (the first one read), and its Objects on Path records. pub(super) fn document(&mut self, o: &Obj) { if !self.variables.present { self.variables = variable_library(o); @@ -575,7 +676,9 @@ impl<'a> Reader<'a> { if let Some(r) = find_entry(o, "AI Auto Rasterize", 0) { raster_settings(r, &mut self.doc); } - let Some(list) = find_entry(o, "ArtboardArray", 0) else { return }; + let Some(holder) = find_holder(o, "ArtboardArray", 0) else { return }; + let Some(list) = holder.obj("ArtboardArray") else { return }; + let active = typed(holder, "CropAreaActive", "Int"); for (i, ab) in list.items().enumerate().take(1000) { let (p1, p2) = (ab.nums("PositionPoint1"), ab.nums("PositionPoint2")); let ([x0, y0, ..], [x1, y1, ..]) = (p1.as_slice(), p2.as_slice()) else { continue }; @@ -586,6 +689,9 @@ impl<'a> Reader<'a> { let name = ab.text("Name").unwrap_or_else(|| format!("Artboard {}", i + 1)); let mut board = AiArtboard::new(name, r); display_options(ab, &mut board); + if active == Some(i as f64) { + self.active_board = Some(self.artboards.len()); + } self.artboards.push(board); } } @@ -639,9 +745,50 @@ impl<'a> Reader<'a> { } /// Art space → where the art being read goes: the document, or while a pattern's definition is - /// read, the pattern's space (y down). + /// read, the pattern's space (y down). A symbol's definition is written in the symbol's space. pub(crate) fn space(&mut self) -> Affine { - if self.pattern.is_some() { FLIP } else { self.ensure_space() } + if self.pattern.is_some() { + FLIP + } else if self.symbol.is_some() { + Affine::IDENTITY + } else { + self.ensure_space() + } + } + + /// The space an image's matrix is in → where the art being read goes: [`Self::space`], and in a + /// symbol's art (outside a pattern's definition) the canvas's space turned y up about art space's + /// origin there, as an instance's matrix in it is; `None` there without a template box. + pub(super) fn image_space(&mut self) -> Option { + if self.pattern.is_none() && self.symbol.is_some() { + return self.canvas_origin().map(|o| Affine::new([1.0, 0.0, 0.0, -1.0, o.x, o.y])); + } + Some(self.space()) + } + + /// The canvas point of art space's origin, from the template box's center (the canvas's): what + /// a pattern's gradients and the instances in a symbol's art are written about. + pub(super) fn canvas_origin(&self) -> Option { + let t = self.template?; + let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0); + let origin = Point::new(CANVAS_CENTRE - cx, CANVAS_CENTRE + cy); + (origin.x.is_finite() && origin.y.is_finite()).then_some(origin) + } + + /// The symbols in the symbol list's order, those it doesn't name after them as they were + /// defined; names it has twice or that no symbol has don't count. + fn order_symbols(&mut self) { + let Some(list) = self.symbol_list.take() else { return }; + let mut slots: Vec> = std::mem::take(&mut self.doc.symbols).into_iter().map(Some).collect(); + let at: HashMap = slots.iter().enumerate().filter_map(|(i, s)| s.as_ref().map(|s| (s.name.clone(), i))).collect(); + let mut ordered = Vec::with_capacity(slots.len()); + for name in &list { + if let Some(s) = self.symbol_names.get(name).and_then(|named| at.get(named)).and_then(|i| slots.get_mut(*i)).and_then(Option::take) { + ordered.push(s); + } + } + ordered.extend(slots.into_iter().flatten()); + self.doc.symbols = ordered; } /// The swatches of the palette, `[None]` first, in its order, and its color groups; a gradient @@ -652,18 +799,26 @@ impl<'a> Reader<'a> { return None; } let palette = std::mem::take(&mut self.palette); - let swatch = |e: crate::import::ai::palette::Entry| -> Option { + let swatch = |mut e: crate::import::ai::palette::Entry| -> Option { use crate::import::ai::palette::Cell; let (paint, global, spot) = match e.cell { Cell::Color { color, global, spot } => (Paint::solid(color), global, spot), + // A swatch named by its gradient or pattern takes the name that got in the document. Cell::Gradient(g) => { let mut gp = vectorcraft_color::gradient::GradientPaint::new(self.gradients.get(&g)?.clone()); + if e.name == g { + e.name = self.global_names.get(Global::Gradient, &g).to_string(); + } gp.swatch = Some(e.name.clone()); (Paint::Gradient(Box::new(gp)), false, false) } Cell::Pattern(p) => { - patterns.iter().find(|d| d.name == p)?; - (Paint::Pattern { pattern: p, xf: Affine::IDENTITY }, false, false) + let pattern = self.global_names.get(Global::Pattern, &p).to_string(); + patterns.iter().find(|d| d.name == pattern)?; + if e.name == p { + e.name.clone_from(&pattern); + } + (Paint::Pattern { pattern, xf: Affine::IDENTITY }, false, false) } }; Some(Swatch { name: e.name, paint, global, spot }) @@ -678,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 { + 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 = 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 = + 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::>() { + 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 = 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 = 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, usize)> { @@ -740,9 +975,13 @@ impl<'a> Reader<'a> { } let to_doc = self.ensure_space(); let artboard = self.first_board(); + self.check_symbols(); + self.order_symbols(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); super::on_path::apply(&mut self.doc, &self.on_path); let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); + // The active artboard, when it is not the first (the default). + let active = self.active_board.filter(|i| *i > 0 && *i < self.artboards.len()); let boards: Vec = if self.artboards.is_empty() { artboard.or_else(|| self.bbox_board()).map(|r| vec![AiArtboard::new("Artboard 1".to_string(), r)]).unwrap_or_default() } else { @@ -778,6 +1017,7 @@ impl<'a> Reader<'a> { color: None, }]; } + doc.opened_artboard = active.and_then(|i| doc.artboards.get(i)).map(|a| a.id); if !self.ruler_guides.is_empty() { let ids: Vec = doc.artboards.iter().map(|a| a.id).collect(); let (candidates, centre) = (std::mem::take(&mut self.ruler_guides), self.template_center); @@ -810,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 = 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::>() { - 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(); @@ -850,9 +1062,24 @@ impl<'a> Reader<'a> { let links: HashMap = self.style_links.iter().filter_map(|(node, name)| Some((*node, *ids.get(name)?))).collect(); if !links.is_empty() { link_styles(&mut doc.layers, &links, &styles, 0); + for symbol in &mut doc.symbols { + link_styles(std::slice::from_mut(&mut symbol.art), &links, &styles, 0); + } } 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, _: &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); @@ -872,6 +1099,11 @@ impl<'a> Reader<'a> { doc.variables = variables.variables.into(); } let (bindings, bindings_skipped) = (variables.bindings, variables.bindings_skipped); + // Symbols that hold instances of themselves can't be drawn: those instances go before the + // layers are compared with the page. + if !doc.symbols.is_empty() { + doc.limit_depth_noting(&mut warnings); + } Ok(Structure { doc, to_doc, @@ -883,6 +1115,7 @@ impl<'a> Reader<'a> { unread_elsewhere: self.unread_elsewhere, slot_names: self.slot_names, restyled: self.restyled, + placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, envelopes_drawn: self.envelopes_drawn, styles_read, @@ -981,10 +1214,18 @@ fn take_ruler_guides(nodes: &mut [Arc], pick: &dyn Fn(NodeId) -> Option(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { + find_holder(o, key, depth).and_then(|h| h.obj(key)) +} + +/// The dictionary that [`find_entry`] finds the entry `key` in: `o` or one it holds. +fn find_holder<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o Obj> { if depth > 8 { return None; } - o.obj(key).or_else(|| o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_entry(c, key, depth + 1))) + if o.obj(key).is_some() { + return Some(o); + } + o.entries.iter().flat_map(|(_, v)| v.iter()).filter_map(V::obj).find_map(|c| find_holder(c, key, depth + 1)) } // ---- the variable library ----------------------------------------------------------------- diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 5d47ce16fa..dc30890247 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1,9 +1,12 @@ use super::containers::close; use super::document::slot_of; -use super::types::{BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, Place, line_width}; +use super::types::{ + BLENDS, FLIP, Frame, GRAPH_OPS, GRAPH_PLAIN, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, + line_width, +}; use super::{ - Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Gradient, GradientDef, Graph, HashMap, HashSet, Instance, - Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, StrokeLayer, V, obj, paint, + Affine, Appearance, AppearanceItem, Arc, BlendMode, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, Graph, HashMap, HashSet, Instance, + Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint, }; impl<'a> Reader<'a> { @@ -73,6 +76,36 @@ impl<'a> Reader<'a> { } } + /// `/identifier (string) XT` (version 7 specification §7): a tag on the object before it. The + /// `AdobeURL` tag sets the object's URL, and every other tag is added to the object's data in + /// order, up to [`MAX_TAGS`]. A tag with no object before it, with an empty identifier, or with + /// an identifier or string longer than [`MAX_TAG_TEXT`] bytes is ignored, and so are tags in a + /// pattern's or brush's art, which is not an object of the document. A clipping path's tags are + /// its own, not those of the copy that paints its fill. + fn object_tag(&mut self, vals: &[V], hidden: bool) { + let [.., V::Name(id), V::Str(value)] = vals else { + self.note_unknown("XT", hidden); + return; + }; + if id.is_empty() || id.len() > MAX_TAG_TEXT || value.len() > MAX_TAG_TEXT || !self.after_object || self.pattern.is_some() { + return; + } + let (id, value) = (id.clone(), obj::text(value)); + let Some(kids) = self.frames.last_mut().map(|f| &mut f.children) else { return }; + let Some(mut at) = kids.len().checked_sub(1) else { return }; + if at > 0 && kids.get(at).is_some_and(|n| self.clip_fills.contains(&n.id)) { + at -= 1; + } + let Some(n) = kids.get_mut(at) else { return }; + n.edit_attrs(|a| { + if id == URL_TAG { + a.url = value; + } else if a.data.len() < MAX_TAGS { + a.data.push((id, value)); + } + }); + } + pub(super) fn op(&mut self, w: &str, hidden: bool) -> Result<(), String> { if self.blend_record.is_some() { self.end_blend(); @@ -124,6 +157,7 @@ impl<'a> Reader<'a> { "Bs" => d.stop(&vals, &mut self.stop_spots), "BD" => { if let Some((name, g)) = self.gradient_def.take().and_then(GradientDef::finish) { + self.global_names.define(Global::Gradient, &name); self.gradients.insert(name, g); } } @@ -211,6 +245,12 @@ impl<'a> Reader<'a> { Some(0.0) => self.gs.show_center = None, _ => {} }, + // Object tags (§7): `/identifier (string) XT` after the object it tags. The state written + // after a group or a mesh is still theirs after its tags. + "XT" => { + self.object_tag(&vals, hidden); + (self.group_ended, self.mesh_ended) = (group_ended, mesh_ended); + } "w" => { if let Some(v) = Self::nums(&vals).last().filter(|v| v.is_finite() && **v >= 0.0) { self.gs.width = *v; @@ -317,21 +357,28 @@ impl<'a> Reader<'a> { "Tp" => self.begin_text_path(&vals), "TP" => self.end_text_path(), "TO" => self.end_text(hidden)?, - "Tx" | "Tj" | "TX" => self.text_body(w, &vals), - "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" => self.text_attr(w, &vals), + // `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`. + "Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals), + "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "Xb" | "Xe" | "XB" => self.text_attr(w, &vals), // Attributes the reader doesn't keep (kerning pairs, Far-Eastern type) and final-form // positions (§15.3). "Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" | "Tu" | "Xu" => {} - // The hyphenation language and tab rulers, which the reader doesn't keep either (§22): `XL`, - // `Xb`/`XB` a tab definition (and the `Xe` tab descriptions between them). - "XL" | "Xb" | "XB" | "Xe" => {} + // `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the + // reader takes `Te` with any number of operands. + "TM" | "Te" => {} + // The hyphenation language (`XL`), which the reader doesn't keep either (§22). + "XL" => {} "TE" => self.te(&vals), + "TZ" => self.tz(&vals), // An image whose samples follow in comment lines (read at `%AI5_EndRaster`). "XI" if self.raster.is_some() => { if let Some(r) = self.raster.as_mut() { r.operands = Some(vals); } } + // A linked image (§8.2, §8.3): `(path) modified XG` names the file of the `XF` image after + // it, which has `XI`'s operands and no samples. + "XG" | "XF" => self.image_link_op(w, vals, hidden)?, // A plugin group ends; a blend's record follows on `%` lines. "XP" => { let name = vals.iter().find_map(V::text).unwrap_or_default(); @@ -431,7 +478,7 @@ impl<'a> Reader<'a> { self.unread_pattern(w); return; }; - let p = Paint::Pattern { pattern: name.unwrap_or_default(), xf }; + let p = Paint::Pattern { pattern: name.as_deref().map(|n| self.global_names.get(Global::Pattern, n).to_string()).unwrap_or_default(), xf }; if w == "p" { self.pending_unread_fill = false; self.gs.fill = p; @@ -473,10 +520,16 @@ impl<'a> Reader<'a> { self.gs.fill = p; self.pending_fill = None; self.pending_unread_fill = false; + if let Some(head) = self.symbol.as_mut() { + head.missing_fill = false; + } } else { self.gs.stroke = p; self.pending_stroke = None; self.pending_unread_stroke = false; + if let Some(head) = self.symbol.as_mut() { + head.missing_stroke = false; + } } } @@ -496,8 +549,16 @@ impl<'a> Reader<'a> { /// The state block of a layer whose art ended (`Xy`, `Xd`, `XW`, then `LB`) is read at the /// `LB`, and can have the stroke style between its `Xy` and `Xd`: that keeps the layer's state, /// and what a mesh or blend before it had (`mesh_undo`). + /// After an image, the operators that end its raster (`XH`, `Xr` and the `N` after + /// `%AI5_EndRaster`) keep it the object its name and opacity mask go to. fn state_block_continues(&mut self, w: &str) { - if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB") { + if self.image_tail && matches!(w, "XH" | "XT" | "Xr" | "N") { + return; + } + self.image_tail = false; + // An object's tags (`XT`) follow it one after another, and an image's follow the `XH` that + // ends its data. + if matches!(w, "Xy" | "Xd" | "XW" | "BB" | "LB" | "XT" | "XH") { return; } self.after_object = false; @@ -530,14 +591,18 @@ impl<'a> Reader<'a> { let gs = &self.gs; let state = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); let Some(Frame { kind: Kind::Layer(_), children, .. }) = self.frames.last_mut() else { return }; - let Some(n) = children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. })) else { return }; + let Some(n) = + children.last_mut().filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. })) + else { + return; + }; (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = before; self.layer_state = Some(state); } - /// `mode opacity isolate knockout shape Xy`; after a group's end, the group's too, and right - /// after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and `6 () XW`), - /// theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`). + /// `mode opacity isolate knockout shape Xy`; after a group's end or a symbol instance, theirs + /// too, and right after a gradient mesh's `/End X!` or a blend's record (before their `Xd` and + /// `6 () XW`), theirs, unless the layer's `LB` follows: then it is the layer's (see `end_layer`). fn transparency(&mut self, vals: &[V], mesh_ended: bool) { let n = Self::nums(vals); let [mode, opacity, rest @ ..] = n.as_slice() else { return }; @@ -567,6 +632,12 @@ impl<'a> Reader<'a> { // The layer's instead when the layer's `7 () XW` follows (`layer_state_block`). self.container_undo = in_layer.then_some(before); self.layer_state = None; + } else if let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) { + // A symbol instance's, as a group's. + let before = (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape); + (n.opacity, n.blend, n.isolate, n.knockout, n.knockout_shape) = (gs.opacity, gs.blend, gs.isolate, gs.knockout, gs.knockout_shape); + self.container_undo = in_layer.then_some(before); + self.layer_state = None; } else { // After a layer's art and before its `LB`: the layer's own state (#2003). Kept until // an operator that isn't part of the state block (or the `LB` that takes it) says the @@ -652,7 +723,14 @@ impl<'a> Reader<'a> { object, look, st, - &StylePaints { gradients: &self.gradients, patterns: &self.pattern_tiles, v7_patterns: &self.v7_patterns, space }, + &StylePaints { + gradients: &self.gradients, + patterns: &self.pattern_tiles, + names: &self.global_names, + v7_patterns: &self.v7_patterns, + brushes: &self.brush_drafts, + space, + }, ) }) { // Strokes and effects at the document's scale, as the art (a Large Canvas copy's is scaled up). @@ -714,6 +792,23 @@ impl<'a> Reader<'a> { look.name = object.name.clone().or(look.name.take()); look.visible = object.visible; look.locked = object.locked; + // The object's note, Show Center, URL and data (object tags) stay with the look that stands + // for it, in place of the look's own where the object has them. + if let Some(a) = object.extras().attrs.as_deref().cloned() { + look.edit_attrs(|l| { + if a.show_center.is_some() { + l.show_center = a.show_center; + } + if !a.url.is_empty() { + l.url = a.url; + } + if !a.note.is_empty() { + l.note = a.note; + } + let room = MAX_TAGS.saturating_sub(l.data.len()); + l.data.extend(a.data.into_iter().take(room)); + }); + } if !hidden { self.drawn_looks += 1; } @@ -769,12 +864,15 @@ fn pattern_controls(n: &[f64]) -> Option { xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf) } -/// What a style's fills paint with: the file's gradients and pattern tiles, the patterns defined in -/// the version 7 form, and art space → the document. +/// What a style's fills paint with: the file's gradients and pattern tiles with the names they get +/// in the document, the patterns defined in the version 7 form, and art space → the document. struct StylePaints<'a> { gradients: &'a HashMap, patterns: &'a HashMap, + names: &'a ShownNames, v7_patterns: &'a HashSet, + /// The brushes the file defines, which a brushed stroke names. + brushes: &'a [super::super::brush::BrushDraft], space: Affine, } @@ -813,21 +911,88 @@ fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { } } +/// Is `n` a path, a compound path or a group without a clip, with no opacity mask, the objects +/// whose outline the effects that move it (Transform, Twist, Free Distort) are read on? Images, +/// type (and a text object's slot, filled with type placed where the page has it) and live objects +/// draw more than their outline, and a mask stays where it is. +fn outlines_only(n: &Node) -> bool { + matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { clip: false, .. }) + && n.extras().mask.is_none() + && slot_of(n.name.as_deref()).is_none() +} + +/// Does `n`, inside an object whose outline an effect moves, move with it: is it and everything in +/// it [`outlines_only`], painting with no gradient or pattern (which stay where they are placed) +/// and with no effects of its own (drawn after the outer effect, not before)? Deeper than +/// [`MAX_DEPTH`] counts as no. +fn moves_alike(n: &Node, depth: usize) -> bool { + depth <= MAX_DEPTH + && outlines_only(n) + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty() && !matches!(i.paint(), Paint::Gradient(_) | Paint::Pattern { .. })) + && n.children().into_iter().flatten().all(|c| moves_alike(c, depth + 1)) +} + +/// Does `n` or anything in it (to [`MAX_DEPTH`]) have a stroke that paints? +fn strokes(n: &Node, depth: usize) -> bool { + depth > MAX_DEPTH + || n.appearance.items.iter().any(|i| !i.is_fill() && !i.paint().is_none()) + || n.children().into_iter().flatten().any(|c| strokes(c, depth + 1)) +} + +/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? +fn straight(n: &Node) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.h_in == a.p && a.h_out == a.p), + NodeKind::Compound { children, .. } => children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. }) && straight(c)), + _ => false, + } +} + +/// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything +/// in it [`moves_alike`], and the style paints no gradient. Twist is read only on an unstroked path +/// or compound path with straight segments, and Transform that scales, turns or reflects only when +/// nothing is stroked (its reference point lies on the bounds without strokes). +fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { + use crate::import::ai::style::StyleItem; + let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) + || object.children().into_iter().flatten().any(|c| strokes(c, 1)); + !st.items.iter().any(|i| matches!(i, StyleItem::Gradient { .. })) + && outlines_only(object) + && object.children().into_iter().flatten().all(|c| moves_alike(c, 1)) + && st.effects.iter().all(|e| match e.id.as_str() { + "distort.twist" => !stroked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && straight(object), + "distort.transform" => { + let p = &e.params; + !stroked + || (p["scaleH"].as_f64() == Some(100.0) + && p["scaleV"].as_f64() == Some(100.0) + && p["rotate"].as_f64() == Some(0.0) + && p["reflectX"].as_bool() == Some(false) + && p["reflectY"].as_bool() == Some(false)) + } + _ => true, + }) +} + /// What [`placed_paints`] keys a pattern's name with, apart from the gradients' names. const PATTERN_KEY: &str = "\u{1}pattern "; /// `object`'s appearance with style `st`, its drawn look `look`: `None` when the style isn't one -/// this reads, asks a group for fills or strokes, or has Pathfinder effects on anything but a group -/// with no fills or strokes. +/// this reads, asks a group for fills or strokes, has Pathfinder effects on anything but a group +/// with no fills or strokes, or moves the outline of an object it isn't read on ([`moves_with`]). fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, paints: &StylePaints) -> Option { use crate::import::ai::style::StyleItem; // A text object's slot (an empty group standing for it) takes the style as the type will. let slot = slot_of(object.name.as_deref()).is_some(); + // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain + || matches!(object.kind, NodeKind::SymbolInstance { .. }) || (!slot && !st.simple) || (object.is_container() && !slot && !matches!(object.kind, NodeKind::Compound { .. }) && !st.items.is_empty()) || (st.pathfinder && (slot || !st.items.is_empty() || object.is_compound_shape() || !matches!(object.kind, NodeKind::Group { clip: false, .. }))) + || (!slot && st.moves_outline() && !moves_with(object, st)) { return None; } @@ -843,7 +1008,8 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), StyleItem::Gradient { name, angle } => { - let paint = match (name.as_ref().and_then(|n| placed.get(n)), gradients, own_gradient) { + // The drawn look's gradients are keyed by the names they got in the document. + let paint = match (name.as_ref().and_then(|n| placed.get(paints.names.get(Global::Gradient, n))), gradients, own_gradient) { // Other objects than type: the object's own, as they always were. (_, 1, Some(own)) if !slot => own.paint.clone(), (Some(p), ..) => p.clone(), @@ -858,7 +1024,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p }; AppearanceItem::Fill(FillLayer::new(paint)) } - StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{name}")) { + StyleItem::Pattern { name, matrix, controls } => match placed.get(&format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name))) { Some(p) => AppearanceItem::Fill(FillLayer::new(p.clone())), None => { let tile = paints.patterns.get(name).copied()?; @@ -867,10 +1033,20 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p matrix = Some(matrix.unwrap_or(Affine::IDENTITY) * pattern_controls(controls)?); } let xf = pattern_xf(paints.space, matrix, tile)?; - AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: name.clone(), xf })) + AppearanceItem::Fill(FillLayer::new(Paint::Pattern { pattern: paints.names.get(Global::Pattern, name).to_string(), xf })) } }, - StyleItem::Stroke { .. } => stroke_layer(item)?, + StyleItem::Stroke { brush, .. } => { + // A brushed stroke draws as its look only with the brush the file defines (the + // first of its name, as the Brushes panel keeps it) at the object's settings. + if let Some((name, settings)) = brush { + let draft = paints.brushes.iter().find(|d| &d.name == name)?; + if !super::super::brush::draws_as(draft, settings) { + return None; + } + } + stroke_layer(item)? + } }; if let Some(look) = st.looks.get(n) { with_look(&mut layer, look); @@ -896,6 +1072,8 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) for (n, item) in st.items.iter().enumerate() { let mut layer = match item { StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), + // A graphic style's brush isn't checked against the file's brushes: it is left out. + StyleItem::Stroke { brush: Some(_), .. } => return None, StyleItem::Stroke { .. } => stroke_layer(item)?, StyleItem::Gradient { .. } | StyleItem::Pattern { .. } => return None, }; @@ -909,9 +1087,10 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) /// A style's stroke as an appearance item (`None` for a fill). fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option { - let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile } = item else { return None }; + let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, brush } = item else { return None }; let mut layer = StrokeLayer::new(paint.clone(), line_width(*width)); (layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile) = (*cap, *join, *miter, dash.clone(), profile.clone()); + layer.brush = brush.as_ref().map(|(name, _)| name.clone()); Some(AppearanceItem::Stroke(layer)) } @@ -942,3 +1121,71 @@ fn strip(n: &mut Node, hidden: &HashSet) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::ImageObject; + use vectorcraft_geom::shapes; + + fn square(id: u64, fill: Paint) -> Arc { + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) + } + + #[test] + fn only_outlines_without_gradients_move_alike() { + // GUARDS: an image's pixels and a placed gradient stay behind when an effect moves the outline. + let solid = || square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert!(moves_alike(&Node::group(NodeId(1), vec![solid(), solid()]), 1)); + let gradient = square(3, Paint::Gradient(Box::new(vectorcraft_color::gradient::GradientPaint::new(Gradient::default())))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), gradient]), 1)); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image)))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(5), vec![image.clone()]))]), 1)); + assert!(!outlines_only(&image)); + // A text object's slot, and a member with an opacity mask. + let mut slot = Node::group(NodeId(6), vec![]); + slot.name = Some(format!("{}0", super::super::document::TEXT_SLOT)); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(slot)]), 1)); + let mut masked = Node::clone(&solid()); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(masked)]), 1)); + // A member with an effect of its own. + let mut turned = Node::clone(&solid()); + turned.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.twist".into(), + params: serde_json::json!({"angle": 30.0}), + visible: true, + }); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), Arc::new(turned)]), 1)); + // A member painting a pattern, whose tiles stay where they are, and a clipping group. + let tiled = square(8, Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }); + assert!(!moves_alike(&Node::group(NodeId(1), vec![solid(), tiled]), 1)); + let mut clipped = Node::group(NodeId(9), vec![solid(), solid()]); + if let NodeKind::Group { clip, .. } = &mut clipped.kind { + *clip = true; + } + assert!(!moves_alike(&Node::group(NodeId(1), vec![Arc::new(clipped)]), 1)); + } + + #[test] + fn an_outline_moves_with_its_effect_only_on_outlines() { + // GUARDS: a top-level image or masked path took an effect that moves the outline. + use crate::import::ai::style::ArtStyle; + let effect = |id: &str, params| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let style = |e| ArtStyle { effects: vec![e], ..ArtStyle::default() }; + let twist = style(effect("distort.twist", serde_json::json!({"angle": 30.0}))); + let path = square(2, Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))); + assert!(moves_with(&path, &twist)); + let mut masked = Node::clone(&path); + masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(7), vec![]), true))); + assert!(!moves_with(&masked, &twist)); + let image = + ImageObject { key: "a".into(), width: 1, height: 1, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(NodeId(4), NodeKind::Image(Box::new(image))); + let distort = style(effect("distort.freeDistort", serde_json::json!({"corners": [[0.1, 0.0], [1.1, 0.0], [1.0, 1.0], [0.0, 1.0]]}))); + assert!(!moves_with(&image, &distort)); + assert!(moves_with(&path, &distort)); + } +} diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 39b77cf749..09f752db5d 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -40,9 +40,26 @@ pub(crate) const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); /// Most patterns read (others can't fill art). pub(super) const MAX_PATTERNS: usize = 4096; +/// Most symbol definitions read (instances of others come in as the page draws them). +pub(super) const MAX_SYMBOLS: usize = 4096; + +/// Most names a symbol list orders. +pub(super) const MAX_LISTED: usize = 4 * MAX_SYMBOLS; + /// Most characters of a path's note read (the version 7 specification allows 254, §5.3.1). pub(super) const MAX_NOTE: usize = 1024; +/// Most object tags (`XT`) kept in one object's data. SVG import keeps the same number of `data-*` +/// attributes per element. +pub(super) const MAX_TAGS: usize = 64; + +/// The longest identifier or string an object tag (`XT`) may have, in bytes: SVG import keeps +/// another application's attribute values up to the same length. +pub(super) const MAX_TAG_TEXT: usize = 64 * 1024; + +/// The object tag that holds the object's URL (version 7 specification §7). +pub(super) const URL_TAG: &str = "AdobeURL"; + #[derive(Clone, Debug)] pub(crate) struct GState { pub(crate) fill: Paint, @@ -216,6 +233,22 @@ pub(super) struct PatternHead { pub(super) tile: Option, } +/// What a reader of a symbol's definition has read of the symbol besides its art. +#[derive(Debug, Default)] +pub(super) struct SymbolHead { + /// `AI13PatternRegistrationType` in the dictionary after the art. + pub(super) registration: Option, + /// Art the reader left out (type, a placed file, non-native art, an image it can't read or + /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the + /// page draws them, within the box of the rest. + pub(super) left_out: bool, + /// A gradient instance the reader can't make a paint of (a gradient the file doesn't define, + /// or one it can't place) is the next path's fill or stroke: the art is left out when that + /// path paints it. + pub(super) missing_fill: bool, + pub(super) missing_stroke: bool, +} + /// An image's operands, from `XN` and before `XI`. #[derive(Debug, Default)] pub(super) struct Raster { @@ -258,6 +291,11 @@ pub(super) const MAX_PLACED_FOLDER: usize = 4096; pub(super) const LINKED_PREVIEWS: &str = "linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel"; +/// What the open result says of linked images the data keeps no pixels of (`XF`): they show a +/// placeholder. +pub const LINKED_PLACEHOLDERS: &str = + "linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel"; + /// Operators that change nothing the reader keeps. pub(super) const IGNORED: &[&str] = &[ "Ae", @@ -265,12 +303,10 @@ pub(super) const IGNORED: &[&str] = &[ "As", "Xd", "Xr", - "XG", // `/DeviceGray XC` after a linked image's file name (`XG`): its colour space. "XC", "Xh", "XH", - "XF", "Bc", "XP", "Np", @@ -278,7 +314,6 @@ pub(super) const IGNORED: &[&str] = &[ "i", // Path resolution (`Ar`, §12): how finely curves print. "Ar", - "TZ", "Xs", "Xt", // A brushed path's width at each anchor (`(…) Xt n XD`), on its hidden source path. @@ -301,6 +336,8 @@ pub(super) const IGNORED: &[&str] = &[ ]; /// Sections skipped whole, by their markers without the `AI_` prefix: begin → end. +/// Patterns, symbols and the symbol list are read before this list is looked at; their markers +/// stay here for sections of the same kind nested in them to be skipped. pub(super) const SKIPPED: &[(&str, &str)] = &[ ("BeginPattern", "EndPattern"), ("BeginBrushPattern", "EndBrushPattern"), diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e1947bfdaf..0e1a52a6f2 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -32,8 +32,13 @@ //! gradient (`Bb` … `flag (name) x y angle length … Bg` … `BB`); `stroke fill Xd` says whether it //! paints at all. A blend filter's `mode opacity isolate knockout shape Xy` is its transparency. //! +//! A stroke with a Calligraphic brush is its own basic filter, `(Adobe Calligraphic Brush Tool)`, with +//! its stroke's style and the brush's settings for the object as entries (see +//! [`super::brush`]). +//! //! A style is *plain* when every filter in it is one read here: fills and strokes (in a colour; fills -//! with a pattern or gradient too), each with its own transparency and effects, and the effects of +//! with a pattern or gradient too; strokes with a Calligraphic brush too), each with its own +//! transparency and effects, and the effects of //! [`effect`]. Such objects are read as themselves with an appearance of those fills, strokes and //! effects; others keep their drawn look. Effect › Pathfinder effects (`(Adobe Pathfinder)` in the //! object's chain) are read on a group with no fills or strokes of its own, which keeps its members. @@ -72,6 +77,8 @@ const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl"; const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files const PATHFINDER: &str = "Adobe Pathfinder"; // brand-ok: the filter's name in the files +const CALLIGRAPHIC: &str = "Adobe Calligraphic Brush Tool"; // brand-ok: the filter's and plug-in's name in the files + const CHAIN: &str = "Chain Style Filter"; const STACK: &str = "Stack Style Filter"; const FILL: &str = "Fill Style Filter"; @@ -131,7 +138,8 @@ pub(super) struct ArtStyle { pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, - /// Feather, Round Corners, Scribble, Convert to Shape and the Path effects (Offset Path, Outline Object, Outline Stroke) on the object + /// Feather, Round Corners, Scribble, Convert to Shape, the Path effects (Offset Path, Outline Object, Outline Stroke) + /// and some Distort & Transform effects ([`any_object_takes`]) on the object /// (and Pathfinder effects when it has no fills or strokes): what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, @@ -150,6 +158,13 @@ pub(super) struct ArtStyle { pub pathfinder: bool, } +impl ArtStyle { + /// Do its effects move the object's outline (Transform, Twist, Free Distort)? + pub fn moves_outline(&self) -> bool { + self.effects.iter().any(|e| matches!(e.id.as_str(), "distort.transform" | "distort.twist" | "distort.freeDistort")) + } +} + #[derive(Clone, Debug, PartialEq)] pub(super) enum StyleItem { Fill(Paint), @@ -174,6 +189,8 @@ pub(super) enum StyleItem { miter: f64, dash: Option, profile: Option, + /// A Calligraphic brush: its name, and its settings for this object. + brush: Option<(String, vectorcraft_brush::Calligraphic)>, }, } @@ -231,6 +248,9 @@ struct Filter { gradient_of: Option<(Option, f64)>, /// `(name) … [matrix] p`, and the numbers between the name and the matrix. pattern: Option<(String, Option<[f64; 6]>, Vec)>, + /// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and + /// plug-in name. + plugin_object: Option<(String, String)>, /// `mode opacity … Xy`. xy: Option<(usize, f32)>, /// `… isolate knockout … Xy`. @@ -259,6 +279,7 @@ impl Default for Filter { gradient: false, gradient_of: None, pattern: None, + plugin_object: None, xy: None, xy_group: None, } @@ -388,6 +409,13 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } } b"Array" => dict_array = Some(vec![]), + b"PluginObject" if in_basic => { + let mut texts = operands.iter().rev().filter_map(V::text); + if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) { + f.plugin_object = Some((name, plugin)); + } + other_entry = Some(None); + } b"Int" | b"Real" | b"Bool" => { // The number right before the type: an earlier one isn't this value. let value = operands.last().and_then(V::num); @@ -1066,13 +1094,46 @@ fn paint_item(f: &Filter) -> Result, ()> { miter: f.miter, dash: f.dash.clone(), profile: width_profile(&f.arrays), + brush: None, })), _ => Err(()), }, + CALLIGRAPHIC => calligraphic_stroke(f).map(Some).ok_or(()), _ => Err(()), } } +/// A Calligraphic brush's filter `f` as the stroke it paints: `None` when it isn't a stroke in a +/// colour, names no Calligraphic brush, or its settings aren't all there as numbers. An angle +/// relative to the path isn't read. +fn calligraphic_stroke(f: &Filter) -> Option { + let real = |key: &str| entry(f, key, Kind::Real).ok().flatten(); + let code = |key: &str| entry(f, key, Kind::Int).ok().flatten(); + if !f.paints.0 || f.gradient || f.pattern.is_some() || f.repeated { + return None; + } + if entry(f, "AngleRelativeTo", Kind::Int).ok()?.unwrap_or(0.0) != 0.0 { + return None; + } + let (name, plugin) = f.plugin_object.as_ref()?; + if plugin != CALLIGRAPHIC { + return None; + } + let values = [real("Angle")?, real("Roundness")?, real("Diameter")?]; + let variation = [real("AngleVariation")?, real("RoundnessVariation")?, real("DiameterVariation")?].map(f64::abs); + let codes = [code("AngleDependsOn")?, code("RoundnessDependsOn")?, code("DiameterDependsOn")?]; + Some(StyleItem::Stroke { + paint: f.stroke.clone()?, + width: f.width, + cap: f.cap, + join: f.join, + miter: f.miter, + dash: None, + profile: None, + brush: Some((name.clone(), super::brush::calligraphic(values, variation, codes))), + }) +} + /// Builds an [`ArtStyle`] from a style's filter tree. struct Builder<'a> { filters: &'a [Filter], @@ -1113,7 +1174,7 @@ impl Builder<'_> { let c = &filters[k]; match c.name.as_str() { _ if c.compound => {} - FILL | STROKE => match paint_item(c) { + FILL | STROKE | CALLIGRAPHIC => match paint_item(c) { Ok(Some(StyleItem::Stroke { .. })) => under.strokes = true, Ok(Some(StyleItem::Pattern { .. })) => under.patterns = true, _ => {} @@ -1127,7 +1188,7 @@ impl Builder<'_> { let c = &filters[k]; match c.name.as_str() { _ if c.compound => self.plain = false, - FILL | STROKE => { + FILL | STROKE | CALLIGRAPHIC => { paints += 1; look.visible &= c.visible; match paint_item(c) { @@ -1177,6 +1238,52 @@ impl Builder<'_> { } } +/// Is `e`, on the whole object, an effect any object is read with? Of the Distort & Transform +/// effects: Transform without copies (Random is never read), Twist, a Tweak that moves nothing, +/// Pucker & Bloat at 0, and Free Distort when its corners make a parallelogram (an affine map). +/// Zig Zag is left to type. Which objects Transform, Twist and Free Distort are read on is +/// `read::ops`' `moves_with`. +fn any_object_takes(e: &Effect) -> bool { + match e.id.as_str() { + "stylize.dropShadow" + | "stylize.innerGlow" + | "stylize.outerGlow" + | "stylize.feather" + | "stylize.roundCorners" + | "stylize.scribble" + | "convertToShape.rectangle" + | "convertToShape.roundedRectangle" + | "convertToShape.ellipse" + | "path.offsetPath" + | "path.outlineObject" + | "path.outlineStroke" + | "distort.twist" + | "distort.tweak" => true, + // Copies are drawn as one path, its fills under all its strokes, where the file paints each + // copy's fill and stroke in turn. + "distort.transform" => e.params["copies"].as_i64() == Some(0), + "distort.puckerBloat" => e.params["amount"].as_f64() == Some(0.0), + "distort.freeDistort" => affine(&e.params), + id => is_pathfinder(id), + } +} + +/// Do Free Distort params `p`'s corners (top left, top right, bottom right, bottom left) make a +/// parallelogram, so that the bilinear map is affine? +fn affine(p: &serde_json::Value) -> bool { + let Some(c) = p["corners"].as_array() else { return false }; + let at = |i: usize, axis: usize| c.get(i).and_then(|c| c.get(axis)).and_then(serde_json::Value::as_f64); + (0..2).all(|axis| match (at(0, axis), at(1, axis), at(2, axis), at(3, axis)) { + (Some(tl), Some(tr), Some(br), Some(bl)) => { + // The corners are fractions of the object's box, divided out of the file's rounded + // decimals; the tolerance is relative to how far apart they lie, not where. + let (lo, hi) = [tl, tr, br, bl].iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + ((tl + br) - (tr + bl)).abs() <= 1e-5 * (hi - lo).max(1.0) + } + _ => false, + }) +} + fn style(filters: &[Filter]) -> ArtStyle { let mut st = ArtStyle { plain: true, ..ArtStyle::default() }; let Some(root) = filters.iter().position(|f| f.parent.is_none()) else { return st }; @@ -1187,7 +1294,7 @@ fn style(filters: &[Filter]) -> ArtStyle { let f = &filters[id]; match f.name.as_str() { STACK if f.compound => b.stack(id, &mut st), - FILL | STROKE | CHAIN => { + FILL | STROKE | CALLIGRAPHIC | CHAIN => { if let Some((item, look)) = b.item(id) { st.items.push(item); st.looks.push(look); @@ -1221,23 +1328,10 @@ fn style(filters: &[Filter]) -> ArtStyle { && count(false) <= 1 && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Stroke { .. } | StyleItem::Gradient { .. })) && st.looks.iter().all(|l| l.visible && l.opacity >= 1.0 && l.blend == BlendMode::Normal && l.effects.is_empty()) - && st.effects.iter().all(|e| { - matches!( - e.id.as_str(), - "stylize.dropShadow" - | "stylize.innerGlow" - | "stylize.outerGlow" - | "stylize.feather" - | "stylize.roundCorners" - | "stylize.scribble" - | "convertToShape.rectangle" - | "convertToShape.roundedRectangle" - | "convertToShape.ellipse" - | "path.offsetPath" - | "path.outlineObject" - | "path.outlineStroke" - ) || is_pathfinder(&e.id) - }) + && st.effects.iter().all(any_object_takes) + // An effect that moves the outline is drawn on its own: with others, their order and what + // scales with it aren't kept. + && (!st.moves_outline() || st.effects.len() == 1) // Pathfinder effects on a group with no fills or strokes of its own (`styled` checks the group). && (!st.pathfinder || st.items.is_empty()); st diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 2815f589c5..4b6cc1502a 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -891,6 +891,48 @@ fn pucker_and_twist_keep_their_sense() { assert_eq!(read_effect("Adobe Twirl", "4000 /Real (angle) ,\n"), None); } +#[test] +fn any_object_takes_the_distort_effects_that_draw_as_its_drawn_look() { + // GUARDS: `simple` left out every Distort & Transform effect, so only type took them. + let simple = |name: &str, keys: &str| { + let st = distort_effect_style(name, keys); + assert!(st.plain, "{name}: {st:?}"); + st.simple + }; + assert!(simple("Adobe Twirl", "45 /Real (angle) ,\n")); + assert!(simple("Adobe Transform", &format!("0.5 /Real (scaleH_Factor) ,\n{SWITCHES}"))); + assert!(simple("Adobe Scribble and Tweak", "")); + assert!(simple("Adobe Punk and Bloat", "")); + assert!(simple("Adobe Free Distort", "")); + // A slant: the bottom edge moved as far as the top one. + let src = [[0.0, 0.0], [1.0, 0.0], [0.0, -1.0], [1.0, -1.0]]; + assert!(simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.0], [0.0, -1.0], [1.0, -1.0]]))); + assert!(!simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.1], [0.0, -1.0], [1.0, -1.0]]))); + assert!(!simple("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n")); + assert!(!simple("Adobe Zigzag", "")); + assert!(!simple("Adobe Transform", &format!("1 /Int (numCopies) ,\n{SWITCHES}"))); + // With another effect, only type takes it. + let chain = [basic("Adobe Twirl", "45 /Real (angle) ,\n"), basic("Adobe Offset Path", "4 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n")]; + let data = format!("/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &chain)); + let st = art_styles(data.as_bytes()).remove("Fx").unwrap_or_default(); + assert!(st.plain && !st.simple, "{st:?}"); +} + +#[test] +fn affine_corners_are_a_parallelogram_however_far_they_reach() { + assert!(affine(&json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}))); + assert!(affine(&json!({"corners": [[180.0, -310.0], [320.0, -300.0], [330.0, -250.0], [190.0, -260.0]]}))); + assert!(!affine(&json!({"corners": [[180.0, -310.0], [320.0, -300.0], [330.0, -250.01], [190.0, -260.0]]}))); + // Far from the box, a small shape is held to its own size. + assert!(!affine(&json!({"corners": [[9999.0, 0.0], [10000.0, 0.0], [10000.05, 1.0], [9999.0, 1.0]]}))); + // GUARDS: a slant written in rounded decimals, in a frame of 33.333 pt, missed by a hair. + let src = [[0.0, 0.0], [33.333, 0.0], [0.0, -33.333], [33.333, -33.333]]; + let slant = distort_effect_style("Adobe Free Distort", &corners(src, [[6.6667, 0.0], [40.0, 0.0], [0.0, -33.333], [33.333, -33.333]])); + assert!(slant.plain && slant.simple, "{slant:?}"); + assert!(!affine(&json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]}))); + assert!(!affine(&json!({}))); +} + #[test] fn roughen_keeps_the_drawn_look() { // Its outline is random and the file holds no seed; at a size of 0 the effect still redraws the diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index fabf97a5db..c883719e39 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -229,6 +229,163 @@ fn a_note_or_ap_in_a_skipped_section_does_not_reach_the_art_after_it() { assert!(!n.shows_center()); } +/// A node's URL and data (object tags), empty when it has no attributes. +fn tags(n: &Node) -> (String, Vec<(String, String)>) { + n.extras().attrs.as_deref().map(|a| (a.url.clone(), a.data.clone())).unwrap_or_default() +} + +fn tag(id: &str, value: &str) -> (String, String) { + (id.to_string(), value.to_string()) +} + +/// `/identifier (string) XT` tags the object before it (version 7 specification §7): `AdobeURL` +/// is its URL, and other tags go to its data in order, an empty string included. Paths, groups, +/// compound paths, text objects and images take tags. +#[test] +fn object_tags_are_kept_on_the_object_before_them() { + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Hi) Tx\nTO\n"; + let body = format!( + "{a}N\n/part_no (A-12) XT\n/AdobeURL (https://example.com/a) XT\n/part_no (A-13) XT\n\ + u\n{b}f\nU\n/hand () XT\n*u\n{c}f\n{d}f\n*U\n/shape (two \\(parts\\)) XT\n{text}/AdobeURL (https://example.com/t) XT\n{a}f\n" + ); + let r = read(stream7(&layer7("L", &body)).as_bytes()).unwrap(); + let got: Vec<_> = art(&r.doc).iter().map(|n| tags(n)).collect(); + assert_eq!( + got, + [ + ("https://example.com/a".to_string(), vec![tag("part_no", "A-12"), tag("part_no", "A-13")]), + (String::new(), vec![tag("hand", "")]), + (String::new(), vec![tag("shape", "two (parts)")]), + ("https://example.com/t".to_string(), vec![]), + (String::new(), vec![]), + ] + ); + assert!(r.warnings.is_empty() && r.unread.is_empty(), "{:?} {:?}", r.warnings, r.unread); + // The group's and the compound path's paths keep no tags of their own. + for n in &art(&r.doc)[1..3] { + assert!(n.children().unwrap().iter().all(|k| k.extras().attrs.is_none())); + } + // A later `AdobeURL` replaces an earlier one. + let body = format!("{a}f\n/AdobeURL (https://example.com/1) XT\n/AdobeURL (https://example.com/2) XT\n"); + assert_eq!(tags(&art(&read7(&layer7("L", &body)).doc)[0]).0, "https://example.com/2"); +} + +/// A tag with no object right before it (at a layer's start, after a state change, after a group +/// opens) and a tag with an empty identifier tag nothing; one with operands of another kind is an +/// operator the reader doesn't know. +#[test] +fn object_tags_without_an_object_before_them_tag_nothing() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + for body in + [format!("/first (x) XT\n{a}f\n"), format!("{a}f\n1 w\n/late (x) XT\n"), format!("u\n/inside (x) XT\n{a}f\nU\n"), format!("{a}f\n/ (x) XT\n")] + { + let doc = read7(&layer7("L", &body)).doc; + let mut all = art(&doc); + all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::>()); + assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}"); + } + for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] { + let err = read(stream7(&layer7("L", &format!("{a}f\n{bad}"))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{bad}: {err}"); + } + // Outside any layer too. + let err = read(stream7(&format!("(x) (y) XT\n{}", layer7("L", &format!("{a}f\n")))).as_bytes()).unwrap_err(); + assert!(err.contains("operators VectorCraft doesn't know"), "{err}"); +} + +/// A clipping path's tags are its own, not those of the copy that paints its fill, and a clip +/// group's tags after `Q` are the group's. One object keeps at most 64 tags in its data. +#[test] +fn object_tags_on_clipping_paths_and_the_tag_limit() { + let body = format!( + "0 Ae\nq\n{RED}{}W\nf\n/edge (clip) XT\n{}f\nQ\n/group (clipped) XT\n", + rect_path(5.0, 5.0, 25.0, 25.0), + rect_path(0.0, 0.0, 30.0, 30.0) + ); + let doc = read_ok(&layer(&body)).doc; + let top = &art(&doc); + assert_eq!(top.len(), 1); + assert_eq!(tags(&top[0]).1, [tag("group", "clipped")]); + let tagged: Vec<_> = top[0].children().unwrap().iter().filter(|k| !tags(k).1.is_empty()).map(|k| k.kind.clone()).collect(); + assert_eq!(tagged.len(), 1, "{tagged:?}"); + assert!(matches!(tagged[0], NodeKind::Path { clipping: true, .. }), "{tagged:?}"); + let many: String = (0..70).map(|i| format!("/t{i} ({i}) XT\n")).collect(); + let body = format!("{}f\n{many}/AdobeURL (https://example.com) XT\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let (url, data) = tags(&art(&read_ok(&layer(&body)).doc)[0]); + assert_eq!(data.len(), 64); + assert_eq!(data.last(), Some(&tag("t63", "63"))); + assert_eq!(url, "https://example.com", "the URL is kept past the limit"); + // A tag whose identifier or string is longer than 64 KiB is ignored. + let long = "x".repeat(64 * 1024 + 1); + let body = format!("{}f\n/{long} (a) XT\n/b ({long}) XT\n/c (ok) XT\n", rect_path(0.0, 0.0, 10.0, 10.0)); + assert_eq!(tags(&art(&read_ok(&layer(&body)).doc)[0]).1, [tag("c", "ok")]); +} + +/// An image takes the tags after it, as any other object does. +#[test] +fn object_tags_after_an_image_are_its_own() { + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 3); + let at = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap(); + data.splice(at..at, b"/AdobeURL (https://example.com/i) XT\r\n/sku (I-1) XT\r\n".iter().copied()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{a:#?}"); + assert_eq!(tags(&a[0]), ("https://example.com/i".to_string(), vec![tag("sku", "I-1")])); +} + +/// The state written after a group's end or a gradient mesh's `/End X!` is still theirs when the +/// object's tags come first. +#[test] +fn object_tags_before_a_group_or_mesh_state_leave_it_theirs() { + let body = format!("{RED}0 Ae\nu\n0 0.5 0 0 0 Xy\n{}f\nU\n/hand (x) XT\n0 0 Xd\n6 () XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&layer(&body)).doc; + assert_eq!((art(&doc)[0].opacity, tags(&art(&doc)[0]).1), (0.5, vec![tag("hand", "x")])); + let corner = + |x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| format!("%_[1 1 1 1 {x} {y} {} {} 1 {} {} 1] /N X#\n", next.0, next.1, prev.0, prev.1); + let mesh = format!( + "/Mesh X!\n%_(DeviceRGB) /CS X#\n%_[0 0] /P X#\n{}{}{}{}%_0 /E X#\n/End X!\n", + corner(0, 0, (0, 10), (10, 0)), + corner(0, 40, (10, 40), (0, 30)), + corner(40, 40, (40, 30), (30, 40)), + corner(40, 0, (30, 0), (40, 10)), + ); + let doc = read_ok(&layer(&format!("{mesh}/hand (y) XT\n1 0.35 0 0 0 Xy\n0 0 Xd\n6 () XW\n"))).doc; + let (m, l) = (&art(&doc)[0], &doc.layers[0]); + assert!(matches!(m.kind, NodeKind::Mesh(_)), "{m:#?}"); + assert_eq!((m.opacity, m.blend, tags(m).1), (0.35, BlendMode::Multiply, vec![tag("hand", "y")])); + assert_eq!((l.opacity, l.blend), (1.0, BlendMode::Normal), "not the layer's"); +} + +/// The tags of an object whose drawn look stands for it (its style not found) stay with the look. +#[test] +fn a_drawn_look_keeps_its_objects_tags() { + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let body = format!( + "0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_{hidden_rect}n\n%_/AdobeURL (https://example.com/n) XT\n%_/sku (N-1) XT\n1 (Gone style) XW\n", + rect_path(0.0, 0.0, 10.0, 10.0), + ); + let r = read_ok(&layer(&body)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert_eq!(tags(&a[0]), ("https://example.com/n".to_string(), vec![tag("sku", "N-1")])); + // A look with tags of its own keeps them, and takes the object's after them. + let a = art(&read_ok(&layer(&body.replace("U\n0 0 Xd", "U\n/own (L) XT\n0 0 Xd"))).doc); + assert_eq!(tags(&a[0]), ("https://example.com/n".to_string(), vec![tag("own", "L"), tag("sku", "N-1")])); +} + +/// Tags in a brush's art don't keep it from being read, and stay out of the art: it isn't an object +/// of the document. +#[test] +fn a_brushs_art_with_tags_is_read_without_them() { + let art_ = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n0 g\n{}f\n/sku (D-1) XT\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + let r = read_ok(&format!("{art_}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter: {:?}", r.warnings) }; + assert_eq!(s.art.geometric_bounds().map(|b| (b.width(), b.height())), Some((4.0, 4.0))); + assert!(s.art.extras().attrs.is_none(), "{:?}", s.art.extras().attrs); +} + #[test] fn paths_colours_and_strokes() { let art_ = format!( @@ -448,12 +605,82 @@ fn a_gradient_stop_naming_a_process_colour_leaves_its_swatch_process() { assert!(near(sw.paint.color()), "{sw:?}"); } +/// A gradient whose name in the file is shown as the name of a color a later gradient's stop names +/// is numbered: the color keeps its swatch. +#[test] +fn a_gradient_shown_as_a_stops_color_name_is_numbered() { + let first = "%AI5_BeginGradient: (Test Cyan\\n1)\n(Test Cyan\\n1) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let brand = "%AI5_BeginGradient: (Brand)\n(Brand) 0 2 Bd\n[\n\ + %_0.93 0.1 0 0 (Test Cyan) 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 art_ = format!("Bb\n1 (Test Cyan\\n1) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{first}{brand}{}", layer(&art_))).doc; + let Paint::Gradient(g) = fill(&art(&doc)[0]) else { panic!("{:?}", fill(&art(&doc)[0])) }; + assert_eq!(g.swatch.as_deref(), Some("Test Cyan 2")); + let sw = doc.swatch("Test Cyan").unwrap(); + assert!(matches!(sw.paint, Paint::Solid { .. }) && sw.global, "{sw:?}"); +} + +/// A gradient whose name has no newline keeps it when a gradient shown as that name is defined +/// first: the one shown up to its newline is numbered. +#[test] +fn a_gradient_name_without_a_newline_is_kept_whichever_comes_first() { + let gradient = |name: &str| format!("%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"); + let filled = |name: &str| format!("Bb\n1 ({name}) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let doc = read_ok(&format!("{}{}{}", gradient("Sky\\n1"), gradient("Sky"), layer(&format!("{}{}", filled("Sky\\n1"), filled("Sky"))))).doc; + let links: Vec<_> = art(&doc).iter().map(|n| if let Paint::Gradient(g) = fill(n) { g.swatch.clone() } else { None }).collect(); + assert_eq!(links, [Some("Sky 2".to_string()), Some("Sky".to_string())]); + // A gradient without stops isn't kept, and its name stays free. + let empty = "%AI5_BeginGradient: (Sky)\n(Sky) 0 0 Bd\n[\nBD\n%AI5_EndGradient\n"; + let doc = read_ok(&format!("{empty}{}{}", gradient("Sky\\n1"), layer(&filled("Sky\\n1")))).doc; + assert!(matches!(fill(&art(&doc)[0]), Paint::Gradient(g) if g.swatch.as_deref() == Some("Sky"))); +} + /// A pattern's definition (`%AI3_BeginPattern`): its name and tile (8 points square here, y up), /// then its art on `%_` lines (a group of the tile's unpainted box and a dot, a round-capped /// stroke of no length), `E`. const DOTS: &str = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 8 8\n%_0 A\n%_0 Xw\n%_0 Ae\n%_u\n%_0 O\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_n\n\ %_0 R\n%_0 0 0 1 K\n%_1 J 0 j 2 w 4 M []0 d\n%_4 4 m\n%_4 4 L\n%_S\n%_U\n%_/ArtDictionary :\n%_;\n%_\n%_9 () XW\nE\n%AI3_EndPattern\n"; +/// An unpainted box that a pattern's definition marks as its tile's box isn't art; a painted one +/// with the mark stays. +#[test] +fn a_patterns_marked_tile_box_is_not_art() { + let mark = "%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_\n"; + let def = |paint: &str, op: &str| { + format!( + "%AI3_BeginPattern: (Box)\n(Box) 0 0 8 8\n%_0 A\n%_0 Xw\n%_{paint}0 XR\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_{op}\n{mark}\ + %_0 0 0 1 k\n%_2 2 m\n%_6 2 L\n%_6 6 L\n%_2 6 L\n%_f\nE\n%AI3_EndPattern\n" + ) + }; + let layer = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n(Box) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\nLB\n%AI5_EndLayer--\n", + rect_path(10.0, 20.0, 70.0, 80.0) + ); + let s = read_ok(&format!("{}{layer}", def("", "n"))); + let art = &s.doc.pattern("Box").unwrap().art; + assert_eq!(art.len(), 1, "the square only"); + assert_eq!(art[0].geometric_bounds(), Some(Rect::new(2.0, -6.0, 6.0, -2.0))); + let s = read_ok(&format!("{}{layer}", def("1 0 0 0 k\n%_", "f"))); + assert_eq!(s.doc.pattern("Box").unwrap().art.len(), 2, "a painted box is art"); + // The mark after a group or a compound path of an unpainted box leaves it in the art. + for (open, close, kind) in [("u", "U", "group"), ("*u", "*U", "compound path")] { + let def = format!( + "%AI3_BeginPattern: (Box)\n(Box) 0 0 8 8\n%_0 A\n%_0 Xw\n%_{open}\n%_0 8 m\n%_8 8 L\n%_8 0 L\n%_0 0 L\n%_0 8 L\n%_n\n%_{close}\n{mark}\ + %_0 0 0 1 k\n%_2 2 m\n%_6 2 L\n%_6 6 L\n%_2 6 L\n%_f\nE\n%AI3_EndPattern\n" + ); + let s = read_ok(&format!("{def}{layer}")); + assert_eq!(s.doc.pattern("Box").unwrap().art.len(), 2, "after a {kind}"); + } + // Outside a pattern's definition the mark leaves the box in the art. + let marked = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n0 XR\n{}n\n{mark}0 0 0 1 k\n{}f\nLB\n%AI5_EndLayer--\n", + rect_path(10.0, 20.0, 70.0, 80.0), + rect_path(20.0, 30.0, 40.0, 50.0) + ); + let s = read_ok(&marked); + assert_eq!(s.doc.layers[0].children().unwrap().len(), 2, "outside a pattern"); +} + /// Patterns are read into pattern swatches, and `p` fills with one (#1025): the art keeps its /// layers, the fill places the tiles by its matrix. #[test] @@ -491,6 +718,181 @@ fn patterns_are_pattern_swatches_and_fill_with_them() { assert!(s.warnings.is_empty(), "{:?}", s.warnings); } +/// A pattern's name in the file is shown up to its newline (AI7 spec §4): two patterns named +/// `Dots` apart from what follows the newline are "Dots" and "Dots 2", each fill paints with its +/// own, and one defined again under its name in the file replaces the first. +#[test] +fn pattern_names_are_shown_up_to_their_newline() { + let def = |name: &str, tile: u32| DOTS.replace("(Dots)", &format!("({name})")).replace("0 0 8 8\n", &format!("0 0 {tile} {tile}\n")); + 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 body = format!( + "{}{}{}{}", + def("Dots\\n1", 8), + def("Dots\\n2", 8), + def("Dots\\n2", 9), + layer(&format!("{}{}", filled("Dots\\n2"), filled("Dots\\n1"))) + ); + let s = read_ok(&body); + let doc = &s.doc; + let tiles: Vec<_> = doc.patterns.iter().map(|p| (p.name.as_str(), p.tile.width())).collect(); + assert_eq!(tiles, [("Dots", 8.0), ("Dots 2", 9.0)]); + for name in ["Dots", "Dots 2"] { + assert!(matches!(&doc.swatch(name).unwrap().paint, Paint::Pattern { pattern, .. } if pattern == name), "{name}"); + } + let fills: Vec<_> = art(doc).iter().map(|n| if let Paint::Pattern { pattern, .. } = fill(n) { pattern } else { String::new() }).collect(); + assert_eq!(fills, ["Dots 2", "Dots"]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); + // Without a palette (or with an empty one) the document keeps its default swatches, and a named + // color the art uses has its swatch: a pattern takes none of their names. + let empty = "%AI5_BeginPalette\n0 0 Pb\nPB\n%AI5_EndPalette\n"; + let ink = format!("0 1 1 0 (Ink) 0 x\n{}f\n", rect_path(0.0, 0.0, 5.0, 5.0)); + for palette in ["", empty] { + let body = + format!("{}{}{palette}{}", def("Black\\n1", 8), def("Ink\\n1", 8), layer(&format!("{}{}{ink}", filled("Black\\n1"), filled("Ink\\n1")))); + let doc = read_ok(&body).doc; + for (solid, pattern) in [("Black", "Black 2"), ("Ink", "Ink 2")] { + assert!(matches!(&doc.swatch(pattern).unwrap().paint, Paint::Pattern { pattern: p, .. } if p == pattern), "{palette:?}"); + assert!(matches!(doc.swatch(solid).unwrap().paint, Paint::Solid { .. }), "{palette:?}"); + } + 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 == "Black 2" && b == "Ink 2")); + } + // Nor the name of a custom color the program of an EPS gives, or None's. + let ps = b"%!PS-Adobe-3.0\n%%CMYKCustomColor: 0 0 1 0 (Outer Ink)\n%%EndComments\n"; + let data = stream(&format!("{}{}{}", def("Outer Ink\\n1", 8), def("[None]\\n1", 8), layer(&filled("Outer Ink\\n1")))); + let doc = super::read_beside(data.as_bytes(), true, ps).unwrap().doc; + assert_eq!(doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Outer Ink 2", "[None] 2"]); + assert!(matches!(doc.swatch("Outer Ink").unwrap().paint, Paint::Solid { .. })); + assert!(matches!(fill(&art(&doc)[0]), Paint::Pattern { pattern, .. } if pattern == "Outer Ink 2")); +} + +/// A pattern shown as the name of one of the document's other swatches is numbered: a swatch or a +/// color group of the palette the reader keeps (under any version's prefix, a swatch it names by +/// its values too), Registration, and a custom color of the editing data's own header. A pattern +/// whose name has no newline keeps it, whichever is defined first. The default swatches go when a +/// palette replaces them, and their names are free then; a palette only in versioned content that +/// isn't read replaces nothing. +#[test] +fn pattern_names_are_numbered_around_the_documents_swatches() { + let def = |name: &str| DOTS.replace("(Dots)", &format!("({name})")); + let palette = "%AI12_BeginPalette\n0 0 Pb\n0 0 0 0.5 k\n(Mist)\nPc\n1 (Greys) 1 Pg\n0 0 0 0.2 k\nPc\nPB\n%AI12_EndPalette\n"; + let header = "%%CMYKCustomColor: 0 0 1 0 (Head Ink)\n"; + let doc = |defs: &[&str], palette: &str| { + let body = format!("{}{palette}{}", defs.iter().map(|n| def(n)).collect::(), layer("")); + read(stream_with_header(header, &body).as_bytes()).unwrap().doc + }; + let names = |d: &Document| d.patterns.iter().map(|p| p.name.clone()).collect::>(); + let d = doc(&["Mist\\n1", "Greys\\n1", "[Registration]\\n1", "Head Ink\\n1", "Red\\n1", "Sky\\n1", "Sky"], palette); + let generated = d.swatch_groups[0].swatches[0].name.clone(); + let all: Vec<&str> = d.swatches_iter().map(|s| s.name.as_str()).collect(); + assert!(d.swatch("Mist").is_some() && d.swatch("Head Ink").is_some(), "{all:?}"); + assert!(matches!(&d.swatch("Red").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Red"), "{all:?}"); + assert_eq!(names(&d), ["Mist 2", "Greys 2", "[Registration] 2", "Head Ink 2", "Red", "Sky 2", "Sky"]); + let d = doc(&[&format!("{generated}\\n1")], palette); + assert_eq!(names(&d), [format!("{generated} 2")]); + // Without a palette the default swatches stay, and so they do when the only palette is in + // versioned content that isn't read. + let versioned = format!("%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{palette}%AI17_End_Versioned_Content\n"); + for palette in ["", &versioned] { + let d = doc(&["Red\\n1"], palette); + assert!(matches!(d.swatch("Red").unwrap().paint, Paint::Solid { .. }), "{palette:?}"); + assert_eq!(names(&d), ["Red 2"], "{palette:?}"); + } + // A pattern and a color in versioned content that isn't read take no name. + let unread = format!( + "%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{}{}%AI17_End_Versioned_Content\n", + def("Sky"), + layer("0 1 1 0 (Sea) 0 x\n") + ); + let d = doc(&["Sky\\n1", "Sea\\n1"], &unread); + assert_eq!(names(&d), ["Sky", "Sea"]); + // Nor does a color of a palette that a later one replaces, or of a palette's alternate. + let replaced = "%AI5_BeginPalette\n0 0 Pb\n0 1 1 0 (Sky) 0 x\n(Sky)\nPc\nPB\n%AI5_EndPalette\n\ + %AI5_BeginPalette\n0 0 Pb\n%AI17_Begin_Content_if_version_gt:17 1\n0 0 0 1 k\n(Ink)\nPc\n\ + %AI17_Alternate_Content\n0 1 0 0 (Sea) 0 x\n(Sea)\nPc\n%AI17_End_Versioned_Content\nPB\n%AI5_EndPalette\n"; + let d = doc(&["Sky\\n1", "Sea\\n1"], replaced); + assert_eq!(names(&d), ["Sky", "Sea"]); + // Versioned content that doesn't end is read whole, its colors too. + let unended = format!("%AI17_Begin_Content_if_version_gt:17 1\n%AI17_Alternate_Content\n{}", layer("0 1 1 0 (Sea) 0 x\n")); + let d = doc(&["Sea\\n1"], &unended); + 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::>(), ["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() { + let palette = "%AI5_BeginPalette\n0 0 Pb\n(Dots\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\nPc\nPB\n%AI5_EndPalette\n"; + let doc = read_ok(&format!("{}{palette}{}", DOTS.replace("(Dots)", "(Dots\\n1)"), layer(""))).doc; + let names: Vec<&str> = doc.swatches.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["[None]", "Dots"]); + assert!(matches!(&doc.swatch("Dots").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Dots")); +} + /// Where a definition draws its tile doesn't move the fill: the tile's lower left is the pattern's /// origin, so the same dots drawn at 30..38 × 40..48 tile as they do at 0..8 × 0..8. #[test] @@ -658,6 +1060,17 @@ fn a_version_7_patterns_underbar_fills_the_tile_box() { assert!(def.art[1].appearance.stroke().is_some()); } +/// A version 7 pattern shown as the name of a custom color its own layer strings use is numbered: +/// the color keeps its swatch. +#[test] +fn a_version_7_pattern_shown_as_its_colors_name_is_numbered() { + let layers = "(0 O 0 R 0 0 0 1 \\(Ink\\) 0 x) @ (2 2 m 9 2 L 9 9 L f) &\n"; + let s = pattern_read7(&pattern7("Ink\\n1", layers), &pattern_layer7("Art", "")); + assert_eq!(s.doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Ink 2"]); + assert!(matches!(&s.doc.swatch("Ink 2").unwrap().paint, Paint::Pattern { pattern, .. } if pattern == "Ink 2")); + assert!(matches!(s.doc.swatch("Ink").unwrap().paint, Paint::Solid { .. })); +} + /// A layer's strings are read with their escapes undone: `\r`, `\n`, an octal tab, a backslash at /// a line's end, and escaped parentheses around a custom color's name. #[test] @@ -798,6 +1211,20 @@ fn a_style_pattern_fill_is_placed_as_a_direct_one() { } } +/// An art style's pattern fill paints with the pattern under the name it is shown with. +#[test] +fn a_style_pattern_fill_paints_with_the_shown_name() { + let look = "0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nU\n"; + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let defs = format!("{}{}", pattern7("Grid", "(0 g) @ _ &\n"), pattern7("Grid\\n1", "(0 g) @ _ &\n")); + let s = read_ok(&format!("{}{defs}{}", tiled_style("Grid\\n1", "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let pattern = |n: &Node| match fill(n) { + Paint::Pattern { pattern, .. } => pattern, + p => panic!("{p:?} {:?} {:?}", s.unread, s.warnings), + }; + assert_eq!(pattern(&art(&s.doc)[0]), "Grid 2"); +} + #[test] fn compound_paths_and_clipping() { let art_ = format!( @@ -863,18 +1290,132 @@ fn a_clipping_paths_stroke_stays_on_the_clipping_path() { children(&read_ok(&format!("{defs}{}", layer(&gradient))).doc), [(true, None, false, Some((blue, 3.0))), (false, None, true, None), (false, red, false, None)] ); - // Several clipping paths clip as one compound path, which keeps their stroke when they all have the same one. + // Several clipping paths each keep their own stroke, opacity and blend mode: the second one clips a clipping group + // inside the first one's. let inner = rect_path(10.0, 10.0, 20.0, 20.0); - let compound_stroke = |first: &str, second: &str| { + let strokes = |first: &str, second: &str| { let body = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{first}{clip}W\nS\n{second}{inner}W\nS\nQ\n"); let doc = read_ok(&layer(&body)).doc; let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; - assert!(matches!(children[0].kind, NodeKind::Compound { .. }), "{:?}", children[0].kind); - (children[0].appearance.stroke().map(|s| (s.paint.color(), s.width)), children[0].opacity, children[0].blend) + let NodeKind::Group { children: nested, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + [&children[0], &nested[0]].map(|c| { + assert!(matches!(c.kind, NodeKind::Path { clipping: true, .. }), "{:?}", c.kind); + (c.appearance.stroke().map(|s| (s.paint.color(), s.width)), c.opacity, c.blend) + }) }; - assert_eq!(compound_stroke("", ""), (Some((blue, 3.0)), 1.0, BlendMode::Normal)); - assert_eq!(compound_stroke("9 0.5 0 0 0 Xy\n", ""), (Some((blue, 3.0)), 0.5, BlendMode::Lighten)); - assert_eq!(compound_stroke("", "5 w\n"), (None, 1.0, BlendMode::Normal), "strokes that differ"); + let plain = (Some((blue, 3.0)), 1.0, BlendMode::Normal); + assert_eq!(strokes("", ""), [plain, plain]); + assert_eq!(strokes("", "9 0.5 0 0 0 Xy\n"), [plain, (Some((blue, 3.0)), 0.5, BlendMode::Lighten)]); + assert_eq!(strokes("", "5 w\n"), [plain, (Some((blue, 5.0)), 1.0, BlendMode::Normal)], "strokes that differ"); +} + +/// Several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection: each `W` +/// reduces the clip set by the ones before it (AI7 spec §5.6.2). Each clipping path after the first clips a clipping +/// group inside the one before it, and the innermost one holds the art; a clipping path's painted fill stays at its own +/// level. +#[test] +fn several_clipping_paths_clip_to_their_intersection() { + let square = rect_path(0.0, 0.0, 80.0, 80.0); + let (a, b) = (rect_path(20.0, 20.0, 60.0, 60.0), rect_path(25.0, 25.0, 70.0, 55.0)); + // (clipping, fill color, bounds) of a clipping group's children, with a nested clipping group's children listed + // after it. + type Level = Vec<(bool, Option, Option)>; + fn levels(children: &[Arc]) -> Vec { + let mut out = vec![]; + let mut at = children; + loop { + out.push(at.iter().map(|c| (matches!(c.kind, NodeKind::Path { clipping: true, .. }), fill(c).color(), c.geometric_bounds())).collect()); + let Some(NodeKind::Group { children, clip: true }) = at.last().map(|c| &c.kind) else { return out }; + at = children; + } + } + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); + // A rectangle as written, in the document's coordinates (y down from the 100 pt high page's top). + let r = |x0, y0, x1, y1| Some(Rect::new(x0, 100.0 - y1, x1, 100.0 - y0)); + let (ra, rb) = (r(20.0, 20.0, 60.0, 60.0), r(25.0, 25.0, 70.0, 55.0)); + let group = |body: &str| { + let doc = read_ok(&layer(body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + levels(children) + }; + // The art after both clipping paths, in a clipping group of the second inside the first's. + let two = group(&format!("0 Ae\nq\n{a}h\nW\nn\n{b}h\nW\nn\n{RED}{square}f\nQ\n")); + assert_eq!((two.len(), two[0].len()), (2, 2), "{two:?}"); + assert_eq!(two[0][0], (true, None, ra)); + assert_eq!(two[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Three clipping paths nest twice; a filled clipping path's painted copy is clipped by the paths before it only. + let three = + group(&format!("0 Ae\nq\n{a}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{b}h\nW\nf\n{}h\nW\nn\n{RED}{square}f\nQ\n", rect_path(30.0, 10.0, 50.0, 90.0))); + assert_eq!(three.len(), 3, "{three:?}"); + assert_eq!(three[1][..2], [(true, None, rb), (false, blue, rb)]); + assert_eq!(three[2], [(true, None, r(30.0, 10.0, 50.0, 90.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // As with one clipping path, every object in the group is clipped by all of them, in the order written, wherever + // it is written. + let small = rect_path(0.0, 0.0, 10.0, 10.0); + let before = group(&format!("0 Ae\nq\n{RED}{small}f\n{a}h\nW\nn\n{b}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{square}f\nQ\n")); + assert_eq!(before.len(), 2, "{before:?}"); + assert_eq!(before[1], [(true, None, rb), (false, red, r(0.0, 0.0, 10.0, 10.0)), (false, blue, r(0.0, 0.0, 80.0, 80.0))]); + let between = group(&format!("0 Ae\nq\n{RED}{small}f\n{a}h\nW\nn\n0 0 1 0 0 0 1 Xa\n{square}f\n{b}h\nW\nn\n{RED}{square}f\nQ\n")); + assert_eq!((between.len(), between[0].len()), (2, 2), "{between:?}"); + assert_eq!( + between[1], + [(true, None, rb), (false, red, r(0.0, 0.0, 10.0, 10.0)), (false, blue, r(0.0, 0.0, 80.0, 80.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))] + ); + // A compound clipping path and a clipping path after it: their union, then that intersected with the second. + let c = rect_path(30.0, 10.0, 50.0, 90.0); + let mixed = format!("0 Ae\nq\n*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n{c}h\nW\nn\n{RED}{square}f\nQ\n"); + let doc = read_ok(&layer(&mixed)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + assert_eq!(levels(children)[1], [(true, None, r(30.0, 10.0, 50.0, 90.0)), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Clipping paths alone in a group (`u W n W n U`) clip the clipping group around it the same way. + let grouped = group(&format!("0 Ae\nq\n{RED}{square}f\n0 Ae\nu\n{a}h\nW\nn\n{b}h\nW\nn\nU\nQ\n")); + assert_eq!(grouped.len(), 2, "{grouped:?}"); + assert_eq!(grouped[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // A compound path of clipping paths is still one clipping path, their union. + let compound = format!("0 Ae\nq\n*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n{RED}{square}f\nQ\n"); + let doc = read_ok(&layer(&compound)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }) && children.len() == 2, "{children:?}"); + // Two clipping paths in a layer: the layer clips by the first, a clipping group in it by the second. + let doc = read_ok(&layer(&format!("{a}h\nW\nn\n{b}h\nW\nn\n{RED}{square}f\n"))).doc; + let NodeKind::Layer { clip: true, children, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + let in_layer = levels(children); + assert_eq!(in_layer.len(), 2, "{in_layer:?}"); + assert_eq!(in_layer[1], [(true, None, rb), (false, red, r(0.0, 0.0, 80.0, 80.0))]); + // Two clipping paths in an opacity mask's art: the art clips by the first, a clipping group in it by the second. + let mask_art: String = format!("{a}h\nW\nn\n{b}h\nW\nn\n1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let doc = read_ok(&layer(&format!("{RED}{square}f\n{mask}"))).doc; + let m = art(&doc)[0].extras().mask.clone().unwrap(); + let NodeKind::Group { children, clip: true } = &m.art.kind else { panic!("{:?}", m.art.kind) }; + let in_mask = levels(children); + assert_eq!(in_mask.len(), 2, "{in_mask:?}"); + assert_eq!((in_mask[0][0].0, in_mask[0][0].2, in_mask[1][0]), (true, ra, (true, None, rb))); + assert_eq!(in_mask[1].len(), 2, "{in_mask:?}"); + // Clipping paths are nested as far as the document's depth limit allows; past it they are refused rather than + // merged away, in a clipping group, a layer and an opacity mask's art. + let fits = |text: &dyn Fn(usize) -> String| (2..400).take_while(|n| read(stream(&layer(&text(*n))).as_bytes()).is_ok()).last().unwrap(); + let deep = |n: usize, last: &str| format!("0 Ae\nq\n{}{last}{RED}{square}f\nQ\n", format!("{a}h\nW\nn\n").repeat(n)); + // The layer is 1 deep, the clipping group 2, and the art in the innermost of `n` levels `n + 2`. + let in_group = fits(&|n| deep(n, "")); + assert_eq!(in_group, vectorcraft_doc::MAX_DEPTH - 2); + let r = read_ok(&layer(&deep(in_group, ""))); + let NodeKind::Group { children, clip: true } = &art(&r.doc)[0].kind else { panic!("{:?}", art(&r.doc)[0].kind) }; + assert_eq!(levels(children).len(), in_group, "{:?}", r.warnings); + assert!(read(stream(&layer(&deep(400, ""))).as_bytes()).unwrap_err().contains("nested too deeply")); + let in_layer = fits(&|n| format!("{}{RED}{square}f\n", format!("{a}h\nW\nn\n").repeat(n))); + assert_eq!(in_layer, vectorcraft_doc::MAX_DEPTH - 1); + let in_mask = fits(&|n| { + let art: String = format!("{}1 g\n{square}f\n", format!("{a}h\nW\nn\n").repeat(n)).lines().map(|l| format!("%_{l}\n")).collect(); + format!("{RED}{square}f\n%_/ArtDictionary :\n%_/Mask :\n%_X=\n{art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n") + }); + // The masked object is 2 deep and its mask's art 3. + assert_eq!(in_mask, vectorcraft_doc::MAX_DEPTH - 3); + // A compound clipping path holds its subpaths one level down: as the innermost one, it adds a level. + let compound_last = format!("*u\n{a}h\nW\nn\n{b}h\nW\nn\n*U\n"); + assert!(read(stream(&layer(&deep(in_group - 1, &compound_last))).as_bytes()).unwrap_err().contains("nested too deeply")); } /// A clipping group's clipping path can sit alone in a group of its own, after the art it clips (`q … u W n U @@ -1259,6 +1800,35 @@ fn artboards() { assert_eq!(doc.artboards[0].rect, Rect::new(0.0, 0.0, 600.0, 400.0)); } +#[test] +fn the_active_artboard_is_the_one_crop_area_active_names() { + let board = |x: i32, w: i32| { + format!( + "%_/Dictionary :\n%_{x} 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{} 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n", + x + w + ) + }; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + // Four artboards in the array, the second of no width (left out); `entry` follows the array. + let opened = |entry: &str| { + let boards = [board(0, 100), board(200, 0), board(400, 100), board(600, 100)].concat(); + let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n{entry}%_; /NotRecorded ,\n%_;\n{square}"); + let doc = read_ok(&data).doc; + doc.opened_artboard.map(|id| doc.artboards.iter().position(|a| a.id == id)) + }; + // The index counts every entry of the array, the one left out too. + assert_eq!(opened("%_3 /Int (CropAreaActive) ,\n"), Some(Some(2))); + assert_eq!(opened("%_2 /Int (CropAreaActive) ,\n"), Some(Some(1))); + // After another entry of the dictionary that holds the array. + assert_eq!(opened("%_1 /Int (Other) ,\n%_3 /Int (CropAreaActive) ,\n"), Some(Some(2))); + // The first artboard, the one left out, one past the end, a value of another type, or none. + for entry in + ["%_0 /Int (CropAreaActive) ,\n", "%_1 /Int (CropAreaActive) ,\n", "%_4 /Int (CropAreaActive) ,\n", "%_2 /Real (CropAreaActive) ,\n", ""] + { + assert_eq!(opened(entry), None, "{entry}"); + } +} + /// The document data of artboards side by side, 100 points wide, each with the entries `extra`. fn boards_with(extra: &[&str]) -> String { let boards: String = extra @@ -1799,6 +2369,35 @@ fn a_drawn_look_that_is_an_image_stands_for_its_object() { assert!(r.warnings.iter().any(|w| w.contains("drawn look (1)")), "{:?}", r.warnings); } +/// The name and opacity mask after an image follow the operators that end its raster: `XH`, the +/// versioned `Xr` and the `N` after `%AI5_EndRaster`. +#[test] +fn an_images_name_and_mask_follow_the_end_of_its_raster() { + let mask = "%_/ArtDictionary :\r\n%_/Mask :\r\n%_X=\r\n%_0 g\r\n%_0 0 m\r\n%_5 0 l\r\n%_5 5 l\r\n%_f\r\n%_X+\r\n%_ (Art) ,\r\n\ + %_0 /Bool (Clipping) ,\r\n%_0 /Bool (Inverted) ,\r\n%_0 /Bool (Disabled) ,\r\n%_1 /Bool (Linked) ,\r\n%_; (AI9_Mask) ,\r\n\ + %_/XMLUID : (Photo) ; (AI10_ArtUID) ,\r\n%_;\r\n%_\r\n"; + for tail in [ + "XH\r\n%AI5_EndRaster\r\nN\r\n", + "XH\r\n%AI17_Begin_Content_if_version_gt:24 17\r\n72 72 Xr\r\n%AI17_End_Versioned_Content\r\n%AI5_EndRaster\r\nN\r\n", + ] { + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 7); + let at = data.windows(6).position(|w| w == b"XH\r\n%A").unwrap(); + let end = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap() + 3; + data.splice(at..end, [tail, mask].concat().into_bytes()); + let r = read(&data).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{:?}", a[0].kind); + assert_eq!(a[0].name.as_deref(), Some("Photo")); + assert!(a[0].extras().mask.is_some()); + } + // An operator of another kind in between ends the image: the name has no object. + let mut data = image("[ 10 0 0 10 50 90 ]", (1, 1), ("DeviceRGB", 3, 0), &[255, 0, 0], 7); + let end = data.windows(6).position(|w| w == b"N\r\nLB\r").unwrap() + 3; + data.splice(end..end, b"0 A\r\n%_/ArtDictionary :\r\n%_/XMLUID : (Photo) ; (AI10_ArtUID) ,\r\n%_;\r\n%_\r\n".to_vec()); + assert_eq!(art(&read(&data).unwrap().doc)[0].name, None); +} + fn pixels(doc: &Document) -> (image::RgbaImage, kurbo::Affine) { let a = art(doc); let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; @@ -1833,6 +2432,61 @@ fn one_bit_images_read_each_channel() { assert_eq!((0..3).map(|x| img.get_pixel(x, 0).0[0]).collect::>(), [255, 0, 255]); } +/// A gray image `w` × 1 in hex with ImageMask `mask` and `bits` bits a pixel, after the fill `fill`. +fn masked_gray(fill: &str, bits: u32, mask: u32, w: u32, hex: &[u8]) -> Vec { + let text = String::from_utf8(image("[ 1 0 0 1 0 100 ]", (w, 1), ("DeviceGray", 1, 0), hex, hex.len())).unwrap(); + text.replacen(" 8 1 0 0 1 0 ", &format!(" {bits} 1 0 0 0 {mask} "), 1).replacen("(L) Ln\n", &format!("(L) Ln\n{fill}"), 1).into_bytes() +} + +/// ImageMask 1 on a 1-bit gray image: the image is colorized with the fill color, so its black +/// pixels take the color and its white ones are transparent. ImageMask 0 keeps the opaque image. +#[test] +fn image_masks_are_colorized_with_the_fill() { + // 4 × 1 at 1 bit: black, white, white, black (0110). + let r = read(&masked_gray("0 0 1 0 k\n", 1, 1, 4, b"60")).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let a = art(&r.doc); + let Some(Paint::Solid { color, .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!(color.to_rgba8(1.0), Color::cmyk(0.0, 0.0, 1.0, 0.0).to_rgba8(1.0)); + let NodeKind::Image(im) = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let blob = &r.doc.images[&im.key]; + assert!(blob.gray_source().is_some_and(|g| !g.alpha), "an image a fill color can colorize"); + let img = pixels(&r.doc).0; + assert_eq!( + (0..4).map(|x| img.get_pixel(x, 0).0).collect::>(), + [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]] + ); + // How much of the color each pixel shows: the black ones only. + assert_eq!(blob.coverage().map(|c| c.2), Some(vec![255, 0, 0, 255])); + // A spot color keeps its swatch and tint. + let spot = "0 0 1 0 (Ink) 0.5 0 Xx\n"; + let a = art(&read(&masked_gray(spot, 1, 1, 4, b"60")).unwrap().doc); + assert!( + matches!(a[0].extras().colorize.as_deref(), Some(Paint::Solid { swatch: Some(s), tint, .. }) if s == "Ink" && (*tint - 0.5).abs() < 1e-6), + "{:?}", + a[0].extras().colorize + ); + // A fill that isn't a solid color (here a pattern) colorizes it black. + let patterned = String::from_utf8(masked_gray("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n", 1, 1, 4, b"60")).unwrap(); + let doc = read(patterned.replacen("%AI5_BeginLayer", &format!("{DOTS}%AI5_BeginLayer"), 1).as_bytes()).unwrap().doc; + let a = art(&doc); + let Some(Paint::Solid { color, swatch: None, .. }) = a[0].extras().colorize.as_deref() else { panic!("{:?}", a[0].extras().colorize) }; + assert_eq!(color.to_rgba8(1.0), Color::BLACK.to_rgba8(1.0)); + // An 8-bit gray image with ImageMask 1 opens as before, with no color. + let doc = read(&masked_gray("0 1 0 0 k\n", 8, 1, 2, b"00ff")).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(1, 0).0, [255, 255, 255, 255]); + // ImageMask 0: the opaque image, with no color. + let doc = read(&masked_gray("0 0 1 0 k\n", 1, 0, 4, b"60")).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [0, 0, 0, 255]); + // An RGB image can't take a color: ImageMask 1 leaves it as it is. + let text = String::from_utf8(image("[ 1 0 0 1 0 100 ]", (1, 1), ("DeviceRGB", 3, 0), b"ff0000", 6)).unwrap(); + let doc = read(text.replacen(" 8 3 0 0 1 0 ", " 8 3 0 0 0 1 ", 1).as_bytes()).unwrap().doc; + assert!(art(&doc)[0].extras().colorize.is_none()); + assert_eq!(pixels(&doc).0.get_pixel(0, 0).0, [255, 0, 0, 255]); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). @@ -1915,6 +2569,111 @@ fn a_rotated_image_is_placed_as_its_matrix_maps_it() { } } +/// A raster object in the version 7 form (§8): `%AI5_BeginRaster`, `head` (a link's `XG`, or +/// nothing), the operands `[matrix] 0 0 w h w h 8 3 0 0 0 0`, the operator `op` and `tail` (an +/// `XI`'s samples on `%` lines), `%AI5_EndRaster`. +fn raster7(head: &str, matrix: &str, (w, h): (u32, u32), op: &str, tail: &str) -> String { + format!("%AI5_File:\n%AI5_BeginRaster\n{head}{matrix} 0 0 {w} {h} {w} {h} 8 3 0 0 0 0 {op}\n{tail}%AI5_EndRaster\n") +} + +/// A linked 1-bit gray image with ImageMask 1 keeps the fill color as the color that colorizes it, +/// as an embedded one does. Other linked images have no color. +#[test] +fn linked_image_masks_are_colorized_with_the_fill() { + let m = "[ 1 0 0 1 0 0 ]"; + let linked = |bits_kind_mask: &str| { + let xf = raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", &format!(" {bits_kind_mask} XF")); + let r = read(stream7(&layer7("L", &format!("0 0 1 0 (Ink) 0.5 0 Xx\n{xf}"))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[0].kind, NodeKind::Image(im) if im.link.is_some()), "{:?} {:?}", a, r.warnings); + a[0].extras().colorize.as_deref().cloned() + }; + assert!( + matches!(linked("1 1 0 0 0 1"), Some(Paint::Solid { swatch: Some(s), tint, .. }) if s == "Ink" && (tint - 0.5).abs() < 1e-6), + "a 1-bit image mask" + ); + assert_eq!(linked("1 1 0 0 0 0"), None, "ImageMask 0"); + assert_eq!(linked("8 1 0 0 0 1"), None, "8-bit gray"); + assert_eq!(linked("8 3 0 0 0 1"), None, "RGB"); +} + +/// A linked image in the version 7 form (§8.2, §8.3), `(path) modified XG` and then `XF` with no +/// samples, is a linked image of that file. The data keeps no pixels of it, so it shows a +/// placeholder over the place the matrix maps the image's pixels to, as an embedded image (`XI`) +/// of the same operands is placed. +#[test] +fn a_version_7_linked_image_shows_a_placeholder_where_the_image_is() { + let (s, c) = 30f64.to_radians().sin_cos(); + for m in [[2.0, 0.0, 0.0, 3.0, 100.0, 400.0], [3.0 * c, 3.0 * s, -2.0 * s, 2.0 * c, 40.0, 60.0]] { + let matrix = format!("[ {} ]", m.map(|v| v.to_string()).join(" ")); + let linked = raster7("(Macintosh HD:Images:photo.tif) 0 XG\n", &matrix, (10, 20), "XF", ""); + let embedded = raster7("", &matrix, (10, 20), "XI", &"%FF0000\n".repeat(200)); + let r = read(stream7(&layer7("L", &format!("{linked}{embedded}"))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 2, "{:?}", r.warnings); + let (NodeKind::Image(link), NodeKind::Image(emb)) = (&a[0].kind, &a[1].kind) else { panic!("{:?}", a) }; + assert_eq!(link.link.as_ref().map(|l| l.path.as_str()), Some("Macintosh HD:Images:photo.tif")); + assert_eq!(emb.link, None, "an image whose samples follow stays embedded"); + assert!(r.doc.images[&link.key].is_proxy(), "the placeholder is what a missing link shows"); + // The file's pixels, placed as the embedded image's are: relinking keeps that size. + assert_eq!((link.width, link.height, link.xf), (emb.width, emb.height, emb.xf)); + assert_eq!((link.width, link.height), (10, 20)); + assert_eq!(r.warnings.iter().filter(|w| *w == read::LINKED_PLACEHOLDERS).count(), 1, "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); + } + // Images of other files keep images of their own, though each shows the same placeholder; two + // of one file share theirs. + let m = "[ 1 0 0 1 0 100 ]"; + let three = ["(a.tif) 0 XG\n", "(b.tif) 0 XG\n", "(a.tif) 0 XG\n"].map(|xg| raster7(xg, m, (2, 2), "XF", "")).concat(); + let r = read(stream7(&layer7("L", &three)).as_bytes()).unwrap(); + let keys: Vec<_> = art(&r.doc).iter().filter_map(|n| if let NodeKind::Image(im) = &n.kind { Some(im.key.clone()) } else { None }).collect(); + assert!(matches!(&keys[..], [a, b, c] if a != b && a == c), "{keys:?}"); + assert_eq!(r.doc.images.len(), 2); +} + +/// `XG` names the file of the `XF` after it only: an `XF` without a file name before it, after an +/// `XG` with operands of another shape or an empty path, or after an image that took the name, +/// is left out with a warning, as is one whose operands `XI` couldn't read. Of two `XG`s, the +/// second names the file. +#[test] +fn a_version_7_linked_image_without_its_file_name_is_left_out_with_a_warning() { + let m = "[ 1 0 0 1 0 100 ]"; + let embedded = raster7("() 1 XG\n", m, (1, 1), "XI", "%FF0000\n"); + for (what, src) in [ + ("no XG", raster7("", m, (2, 2), "XF", "")), + ("a name, not a string", raster7("/photo 0 XG\n", m, (2, 2), "XF", "")), + ("no modified flag", raster7("(a.tif) XG\n", m, (2, 2), "XF", "")), + ("an empty path", raster7("() 0 XG\n", m, (2, 2), "XF", "")), + ("taken by an embedded image", format!("{}{}", raster7("(a.tif) 0 XG\n", m, (1, 1), "XI", "%FF0000\n"), raster7("", m, (2, 2), "XF", ""))), + ("named in an earlier raster object", format!("%AI5_BeginRaster\n(a.tif) 0 XG\n%AI5_EndRaster\n{}", raster7("", m, (2, 2), "XF", ""))), + ("named outside a raster object", format!("(a.tif) 0 XG\n{}", raster7("", m, (2, 2), "XF", ""))), + ("too few operands", raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", " 8 3 0 XF")), + ("no matrix", raster7("(a.tif) 0 XG\n", "", (2, 2), "XF", "")), + ("a matrix with no area", raster7("(a.tif) 0 XG\n", "[ 0 0 0 0 0 0 ]", (2, 2), "XF", "")), + ("no pixels", raster7("(a.tif) 0 XG\n", m, (0, 2), "XF", "")), + ("a side past the largest", raster7("(a.tif) 0 XG\n", m, (2_000_000, 2), "XF", "")), + ("samples of 7 bits", raster7("(a.tif) 0 XG\n", m, (2, 2), "XF", "").replace(" 8 3 0 0 0 0 XF", " 7 3 0 0 0 0 XF")), + ] { + let body = format!("{embedded}{src}"); + let r = read(stream7(&layer7("L", &body)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), body.matches(" XI\n").count(), "{what}: {:?}", r.warnings); + assert!(a.iter().all(|n| matches!(&n.kind, NodeKind::Image(im) if im.link.is_none())), "{what}: the embedded images only"); + let left_out = r.warnings.iter().filter(|w| *w == "an image VectorCraft can't read was left out").count(); + assert_eq!(left_out, 1, "{what}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{what}: {:?}", r.warnings); + } + // More pixels than an embedded image may have: no pixels are read, so the linked image comes in. + let r = read(stream7(&layer7("L", &raster7("(a.tif) 0 XG\n", m, (100_000, 100_000), "XF", ""))).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[..], [n] if matches!(&n.kind, NodeKind::Image(im) if (im.width, im.height) == (100_000, 100_000))), "{a:?}"); + assert!(!r.warnings.iter().any(|w| w == read::IMAGE_TOO_LARGE), "{:?}", r.warnings); + let twice = raster7("(a.tif) 0 XG\n(b.tif) 0 XG\n", m, (2, 2), "XF", ""); + let r = read(stream7(&layer7("L", &twice)).as_bytes()).unwrap(); + let a = art(&r.doc); + assert!(matches!(&a[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.as_ref().is_some_and(|l| l.path == "b.tif"))), "{a:?}"); +} + /// CMYK images keep their ink amounts, as the file's PDF part keeps them, and an alpha channel /// becomes their opacity mask: a grayscale image over the image. #[test] @@ -2039,10 +2798,11 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() { assert_eq!(relative_of(&placed_in("( art /)", path, &preview)).as_deref(), Some(" art /photo.png"), "spaces are part of names"); // On `%_` lines too. assert_eq!(relative_of(&hide_placed(&placed_in("(src/)", path, &preview))).as_deref(), Some("src/photo.png")); - // No folder, an absolute one, one too long or not a string: the path alone, and the file still - // opens. + // An empty folder is the document's own: the file's name. + assert_eq!(relative_of(&placed_in("()", path, &preview)).as_deref(), Some("photo.png")); + // An absolute folder, one too long or not a string: the path alone, and the file still opens. let long = format!("({})", "a/".repeat(3000)); - for folder in ["()", "(/elsewhere/)", "(C:\\\\art\\\\)", long.as_str(), "12", "/src"] { + for folder in ["(/elsewhere/)", "(C:\\\\art\\\\)", long.as_str(), "12", "/src"] { assert_eq!(relative_of(&placed_in(folder, path, &preview)), None, "{folder}"); } // A section that doesn't end leaves the folder unread. @@ -2285,6 +3045,25 @@ fn xml_ids_stay_within_their_byte_budget() { assert_eq!(bytes, super::read::MAX_XML_ID_BYTES); } +/// Placed files of other paths keep images of their own though their previews are alike; two of +/// one path share theirs. +#[test] +fn placed_files_of_other_paths_keep_images_of_their_own() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let object = |path: &str| { + let data = placed(true, "[5 0 0 -5 0 200]", path, Some(&preview), ""); + let find = |s: &[u8]| data.windows(s.len()).position(|w| w == s).unwrap(); + data[find(b"%AI5_BeginPlace")..find(b"%AI5_EndPlace\r") + 14].to_vec() + }; + let mut data = placed(true, "[5 0 0 -5 0 200]", "a.png", Some(&preview), ""); + let end = data.windows(14).position(|w| w == b"%AI5_EndPlace\r").unwrap() + 14; + data.splice(end..end, [object("b.png"), object("a.png")].concat()); + let r = read(&data).unwrap(); + let keys: Vec<_> = art(&r.doc).iter().filter_map(|n| if let NodeKind::Image(im) = &n.kind { Some(im.key.clone()) } else { None }).collect(); + assert!(matches!(&keys[..], [a, b, c] if a != b && a == c), "{keys:?}"); + assert_eq!(r.doc.images.len(), 2); +} + #[test] fn placed_files_are_linked_images_showing_their_preview() { // A 2×1 preview (premultiplied ARGB, a padded row) of a file of 4×2 pixels. @@ -2417,6 +3196,60 @@ fn legacy_texts(art: &str) -> Vec { art_texts(&doc) } +/// The characters of each text object of a legacy-format file whose setup is `setup` and whose +/// layer holds point type with the string `(chars)` in each font of `fonts`. +fn legacy_chars(setup: &str, fonts: &[&str], chars: &str) -> Vec { + let art: String = fonts.iter().map(|f| point_type("", chars).replace("/_Helvetica 12 Tf", &format!("/{f} 12 Tf"))).collect(); + let data = type_stream7(&art).replace("%%BeginSetup\n%%EndSetup", &format!("%%BeginSetup\n{setup}%%EndSetup")); + let doc = match read(data.as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc).iter().map(|t| t.runs.iter().map(|r| r.text.as_str()).collect()).collect() +} + +/// `TZ` (§3.3.1) gives a re-encoded font encoding pairs of its own: its strings decode by them +/// first, then by `TE`'s encoding when `useDefault` is 1, and other fonts' strings keep `TE`'s. `TZ` is read in an +/// `%AI3_BeginEncoding` section and in an `%%BeginEncoding` one, with a Multiple Master weight +/// vector after it, and without the direction operand. +#[test] +fn a_re_encoded_fonts_own_encoding_pairs_decode_only_its_strings() { + let setup = "[39/quoteright 96/grave 128/Adieresis\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 39/quotesingle 200/eacute\n/_F/F 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %%BeginEncoding: _M M\n[ 39/quotesingle\n/_M/M 0 0 1 [0.5 0.25] TZ\n%%EndEncoding\n\ + %AI3_BeginEncoding: _N N\n[ 39/quotesingle\n/_N/N 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + let got = legacy_chars(setup, &["_F", "_M", "_N", "_G"], "\\047\\140\\200\\310"); + assert_eq!(got, ["'`Äé", "'`ÄÈ", "'`ÄÈ", "’`ÄÈ"]); + // The re-encoded fonts are the fonts they were made from. + let data = type_stream7(&point_type("", "a").replace("/_Helvetica", "/_M")) + .replace("%%BeginSetup\n%%EndSetup", "%%BeginSetup\n%%BeginEncoding: _M Courier\n[/_M/Courier 0 0 1 TZ\n%%EndEncoding\n%%EndSetup"); + let texts = art_texts(&read(data.as_bytes()).unwrap().doc); + assert_eq!(texts[0].runs[0].style.font_family, "Courier"); +} + +/// The reader does not use the pairs of a `TZ` whose font names aren't the last two operands, or +/// are followed by other values. The first `TZ` for a font is used, also when it has no pairs. +#[test] +fn a_tz_of_another_shape_changes_no_encoding() { + let setup = "[39/quoteright\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 39/quotesingle\n/_F/F (x) 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _G G\n[ 39/quotesingle\n/_G 0 /G 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _H H\n[ 39/grave\n/_H/H 0 0 1 TZ\n[ 39/quotesingle\n/_H/H 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _K K\n[/_K/K 0 0 1 TZ\n[ 39/quotesingle\n/_K/K 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F", "_G", "_H", "_K"], "\\047"), ["’", "’", "`", "’"]); +} + +/// A `TZ` whose `useDefault` is 0 leaves `TE`'s encoding out for its font (§3.3.1): the codes its +/// pairs leave out decode as Windows-1252. +#[test] +fn a_tz_with_use_default_0_leaves_te_out() { + let setup = "[39/quoteright 128/Adieresis\nTE\n\ + %AI3_BeginEncoding: _F F\n[ 96/grave\n/_F/F 0 0 0 TZ\n%AI3_EndEncoding TrueType\n\ + %AI3_BeginEncoding: _S S\n[/_S/S 0 0 0 TZ\n%AI3_EndEncoding AdobeType\n\ + %AI3_BeginEncoding: _M M\n[ 96/grave\n/_M/M 0 0 [0.5] TZ\n%AI3_EndEncoding AdobeType\n"; + assert_eq!(legacy_chars(setup, &["_F", "_S", "_M", "_G"], "\\047\\140\\200"), ["'`€", "'`€", "'`€", "’`Ä"]); +} + fn art_texts(doc: &Document) -> Vec { art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() } @@ -2481,6 +3314,119 @@ fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { assert_eq!(bad.xf, good.xf); } +/// `(text) justified TS` (special characters, §22.6) adds its characters to the story like `Tx` +/// and `Tj`, whichever its flag. Without a string, or outside a text object, it adds nothing. +#[test] +fn legacy_special_characters_join_the_story() { + let texts = legacy_texts(&point_type("", "One").replace("TO\n", "(\\t) 0 TS\n(Two\\r) 1 TS\n(Three) Tx\nTO\n")); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.plain_text(), "One\tTwo\nThree"); + let texts = legacy_texts(&format!("(x) 0 TS\n{}", point_type("0 TS", "Hi"))); + let [t] = texts.as_slice() else { panic!("{texts:?}") }; + assert_eq!(t.plain_text(), "Hi"); +} + +/// A tab definition (`Xb`, `Xe`, `XB`, §22.6) sets the paragraph's tab stops, sorted by position +/// with one stop at each position; each paragraph keeps the stops in force at its first character, +/// and they last into the next text object. A definition with no stops leaves the default ones. +#[test] +fn legacy_tab_definitions_set_the_paragraph_tab_stops() { + use vectorcraft_doc::TabAlign; + let stops = |p: &vectorcraft_doc::ParaStyle| p.tabs.iter().map(|t| (t.position, t.align)).collect::>(); + let ruler = "36 5 Xb\n0 0 3 144 Xe\n0 0 1 72 Xe\n0 0 2 200.5 Xe\n0 0 4 250 Xe\n0 0 2 72 Xe\nXB"; + let two_paragraphs = point_type(ruler, "A\\tB\\r").replace("TO\n", "36 0 Xb\nXB\n(C\\tD) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "E"))); + assert_eq!(texts.len(), 2); + let want = vec![(72.0, TabAlign::Left), (144.0, TabAlign::Right), (200.5, TabAlign::Center), (250.0, TabAlign::Decimal)]; + let one = texts[0].para_at(0); + assert_eq!(stops(one), want); + assert!(one.tabs.iter().all(|t| t.leader.is_empty() && t.align_on == '.')); + assert!(texts[0].para_at(1).tabs.is_empty(), "an empty definition leaves the default stops"); + assert!(texts[1].para_at(0).tabs.is_empty(), "the next text object keeps the empty definition"); + let texts = legacy_texts(&format!("{}{}", point_type(ruler, "A"), point_type("", "B"))); + assert_eq!(stops(texts[1].para_at(0)), want, "the next text object keeps the stops"); +} + +/// A tab description whose type is not 1 to 4 or whose position is missing, not a number, +/// negative or past 100,000 pt is skipped; so is one outside a tab definition, and an `XB` without +/// an `Xb` leaves the stops as they were. +#[test] +fn legacy_tab_descriptions_out_of_range_are_skipped() { + let bad = "0 0 5 90 Xe\n0 0 0 90 Xe\n0 0 1.5 90 Xe\n0 0 1 -1 Xe\n0 0 1 100001 Xe\n0 0 1 /x Xe\n1 Xe"; + let texts = legacy_texts(&point_type(&format!("0 0 1 10 Xe\n36 2 Xb\n{bad}\n0 0 3 100000 Xe\n0 0 1 0 Xe\nXB\nXB\n0 0 1 50 Xe"), "Hi")); + let tabs: Vec = texts[0].para_at(0).tabs.iter().map(|t| t.position).collect(); + assert_eq!(tabs, [0.0, 100_000.0]); +} + +/// A tab definition whose descriptions were all skipped leaves the default stops; a definition +/// keeps its first 1024 stops; and a definition left open (an `Xb` with no `XB`) ends at the next +/// text object's `To`, so that object's descriptions outside a definition are skipped. +#[test] +fn legacy_tab_definitions_skipped_capped_and_left_open() { + let positions = |t: &vectorcraft_doc::TextObject| t.para_at(0).tabs.iter().map(|t| t.position).collect::>(); + let all_skipped = format!("{}{}", point_type("36 1 Xb\n0 0 1 72 Xe\nXB", "A"), point_type("36 1 Xb\n0 0 9 90 Xe\nXB", "B")); + let texts = legacy_texts(&all_skipped); + assert_eq!(positions(&texts[0]), [72.0]); + assert!(texts[1].para_at(0).tabs.is_empty(), "a definition with every stop skipped leaves the default stops"); + let many: String = (0..1100).map(|i| format!("0 0 1 {i} Xe\n")).collect(); + let texts = legacy_texts(&point_type(&format!("36 1100 Xb\n{many}XB"), "C")); + assert_eq!(positions(&texts[0]).len(), 1024); + assert_eq!(positions(&texts[0]).last(), Some(&1023.0)); + let open = format!("{}{}", point_type("36 1 Xb\n0 0 1 72 Xe", "D"), point_type("0 0 1 90 Xe\nXB", "E")); + let texts = legacy_texts(&open); + assert!(texts[0].para_at(0).tabs.is_empty(), "an unended definition sets no stops"); + 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(¶graphs_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(¶graphs_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::(), 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] +fn legacy_end_render_and_text_matrix_pop_read() { + for te in ["Te", "0 0 1 36 Te", "36 0 Xb\n0 0 1 36 Te\nXB", "1 0 0 1 10 50 Tm\nTM"] { + let texts = legacy_texts(&point_type(te, "Hi")); + let [t] = texts.as_slice() else { panic!("{te}: {texts:?}") }; + assert_eq!(t.plain_text(), "Hi", "{te}"); + } +} + /// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum /// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges /// `text.setFormat` takes. @@ -2507,6 +3453,378 @@ fn one_long_run_of_legacy_type_stops_at_the_allowance() { assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); } +/// The fill and stroke colors of a text object's first run (None: no paint). +fn run_paint(n: &Node) -> (Option, Option) { + let NodeKind::Text(t) = &n.kind else { panic!("type: {:?}", n.kind) }; + (t.runs[0].style.fill.color(), t.runs[0].style.stroke.color()) +} + +/// Legacy type set in rendering modes 4 to 7 is a mask (§5.7): the text object is the clipping +/// path of its clipping group (`q` … `Q`) and clips the objects with it. Modes 4, 5 and 6 also +/// fill, stroke, or fill and stroke it; 7 paints nothing. +#[test] +fn legacy_type_in_a_mask_rendering_mode_clips_its_clipping_group() { + let (black, red) = (Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Some(Color::rgb(1.0, 0.0, 0.0))); + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let cases = [("4", (black, None)), ("5", (None, red)), ("6", (black, red)), ("7", (None, None))]; + for (mode, paint) in cases { + let text = point_type(&format!("{mode} Tr\n1 0 0 XA\n1 w"), "Hi"); + let doc = legacy_read(&format!("q\n{text}{square}Q\n")).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{mode} Tr"); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{mode} Tr: {:?}", a[0].kind) }; + assert_eq!(children.len(), 2, "{mode} Tr"); + assert_eq!(run_paint(&children[0]), paint, "{mode} Tr"); + assert!(matches!(children[1].kind, NodeKind::Path { clipping: false, .. }), "{mode} Tr"); + // The art takes its shape from the type: it is bounded by the characters, not the square. + let b = a[0].geometric_bounds().unwrap(); + assert!(b.width() < 50.0 && b.height() < 50.0, "{mode} Tr: {b:?}"); + } + // Directly in a layer, the layer clips. As with a `W` path in this reader, the art written before the + // type is clipped too. + let doc = legacy_read(&format!("{square}{}", point_type("7 Tr", "Hi"))).doc; + let NodeKind::Layer { children, clip: true, .. } = &doc.layers[0].kind else { panic!("{:?}", doc.layers[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && matches!(children[1].kind, NodeKind::Path { .. })); + // With a clipping path after it, the art shows where both are: the type clips a clipping group nested in it, and + // keeps its paint. + let doc = legacy_read(&format!("q\n{}{}h\nW\nn\n{square}Q\n", point_type("6 Tr\n1 0 0 XA\n1 w", "Hi"), rect_path(0.0, 0.0, 30.0, 30.0))).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(run_paint(&children[0]), (black, red)); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Path { clipping: true, .. }) && matches!(inner[1].kind, NodeKind::Path { clipping: false, .. })); +} + +/// A filled clipping path (`W` then `f`) beside type used as a mask: its painted fill stays at its own path's level, +/// as beside another clipping path (the reader's rule for `W` paths). Written after the type, it is painted within the +/// type's mask, since a later mask narrows the clip set by the earlier ones (§5.6.2); written before it, the type doesn't +/// clip it. +#[test] +fn a_filled_clipping_path_beside_legacy_type_used_as_a_mask() { + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let filled = format!("0 0 1 Xa\n{}h\nW\nf\n", rect_path(0.0, 0.0, 30.0, 30.0)); + let text = point_type("7 Tr", "Hi"); + let is_fill = |n: &Node| matches!(n.kind, NodeKind::Path { clipping: false, .. }) && fill(n).color() == Some(Color::rgb(0.0, 0.0, 1.0)); + let is_art = |n: &Node| matches!(n.kind, NodeKind::Path { clipping: false, .. }) && fill(n).color() == Some(Color::rgb(1.0, 0.0, 0.0)); + // The type first: the path's fill is in the clipping group the path clips, inside the type's. + let doc = legacy_read(&format!("q\n{text}{filled}{square}Q\n")).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && children.len() == 2, "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Path { clipping: true, .. }), "{inner:?}"); + assert!(is_fill(&inner[1]) && is_art(&inner[2]) && inner.len() == 3, "{inner:?}"); + // The path first: its fill is in the outer clipping group, which only the path clips; the type clips the art. + let doc = legacy_read(&format!("q\n{filled}{text}{square}Q\n")).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }), "{children:?}"); + assert!(is_fill(&children[1]) && children.len() == 3, "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[2].kind else { panic!("{:?}", children[2].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Text(_)) && is_art(&inner[1]) && inner.len() == 2, "{inner:?}"); +} + +/// `Tr` sets the rendering mode of all the type that follows (§15.3.2), in later text objects too: a second text +/// object with no `Tr` of its own is also a mask. +#[test] +fn a_legacy_mask_rendering_mode_lasts_into_the_next_text_object() { + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let second = point_type("", "Yo").replace("0 Tr\n", ""); + let doc = legacy_read(&format!("q\n{}{second}{square}Q\n", point_type("7 Tr", "Hi"))).doc; + let a = art(&doc); + let NodeKind::Group { children, clip: true } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Text(_)), "{children:?}"); + let NodeKind::Group { children: inner, clip: true } = &children[1].kind else { panic!("{:?}", children[1].kind) }; + assert!(matches!(inner[0].kind, NodeKind::Text(_)) && matches!(inner[1].kind, NodeKind::Path { clipping: false, .. }), "{inner:?}"); +} + +/// Type in a mask rendering mode that can't be one clipping path doesn't clip, with a warning: area type with linked +/// areas (threaded frames), the type of wraparound text, and type in a compound path. +#[test] +fn legacy_type_used_as_a_mask_that_cannot_clip_is_left_unclipped() { + const WARNING: &str = "type used as a mask in linked areas, wraparound text or a compound path doesn't clip"; + let square = format!("1 0 0 Xa\n{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let linked = format!( + "1 To\n1 0 0 1 0 40 0 Tp\n{}n\nTP\n7 Tr\n/_Helvetica 12 Tf\n(Linked ) Tx\n1 0 0 1 60 40 0 Tp\n{}n\nTP\n(areas) Tx\nTO\n", + rect_path(0.0, 0.0, 50.0, 40.0), + rect_path(60.0, 0.0, 110.0, 40.0) + ); + let r = legacy_read(&format!("q\n{linked}{square}Q\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 3); + assert_eq!(r.doc.text_threads.len(), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // Also when the reader's limits leave one frame of a long story in linked areas. + let long = linked.replace("(areas) Tx", &format!("({}) Tx", "a".repeat(3_000_000))); + let r = legacy_read(&format!("q\n{long}{square}Q\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + assert_eq!(children.len(), 2); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // Wraparound text: the type is what flows around the other objects, which it doesn't clip. + let area = format!("1 To\n1 0 0 1 0 0 0 Tp\n{}n\nTP\n7 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Around) Tx\nTO\n", rect_path(0.0, 0.0, 100.0, 80.0)); + let r = legacy_read(&format!("q\n*w\n{area}{square}*W\nQ\n")); + let a = art(&r.doc); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let NodeKind::Group { children: wrap, clip: false } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + assert!(matches!(wrap[0].kind, NodeKind::Text(_)) && wrap.len() == 2, "{wrap:?}"); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // A compound path: its type is no clipping subpath, and the compound path doesn't clip the group. + let r = legacy_read(&format!("q\n*u\n{}f\n{}*U\n{square}Q\n", rect_path(0.0, 0.0, 30.0, 30.0), point_type("7 Tr", "Hi"))); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // The same with the type in a group inside the compound path or the wraparound text. + let grouped = format!("u\n{}U\n", point_type("7 Tr", "Hi")); + let r = legacy_read(&format!("q\n*u\n{}f\n{grouped}*U\n{square}Q\n", rect_path(0.0, 0.0, 30.0, 30.0))); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + let grouped = format!("u\n{area}U\n"); + let r = legacy_read(&format!("q\n*w\n{grouped}{square}*W\nQ\n")); + assert_eq!(unclipped_texts(&art(&r.doc)), 1); + assert!(r.warnings.iter().any(|w| w == WARNING), "{:?}", r.warnings); + // An opacity mask's art clips on its own, also on an object in wraparound text. + let mask_art: String = + format!("{}1 g\n{}f\n", point_type("7 Tr", "Hi"), rect_path(0.0, 0.0, 100.0, 100.0)).lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let r = legacy_read(&format!("q\n*w\n{area}{square}{mask}*W\nQ\n")); + assert!(r.warnings.iter().filter(|w| *w == WARNING).count() == 1, "{:?}", r.warnings); + let a = art(&r.doc); + let NodeKind::Group { children, .. } = &a[0].kind else { panic!("{:?}", a[0].kind) }; + let NodeKind::Group { children: wrap, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + let Some(m) = wrap.iter().find_map(|n| n.extras().mask.clone()) else { panic!("{wrap:?}") }; + let NodeKind::Group { children: in_mask, clip: true } = &m.art.kind else { panic!("{:?}", m.art.kind) }; + assert!(matches!(in_mask[0].kind, NodeKind::Text(_)) && in_mask.len() == 2, "{in_mask:?}"); +} + +/// The text objects in `nodes` and the groups and compound paths under them, checking that nothing among them clips. +#[track_caller] +fn unclipped_texts(nodes: &[Arc]) -> usize { + let mut texts = 0; + for n in nodes { + assert!(!matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Path { clipping: true, .. }), "{:?}", n.kind); + texts += usize::from(matches!(n.kind, NodeKind::Text(_))); + texts += n.children().map_or(0, |c| unclipped_texts(c)); + } + texts +} + +/// Legacy type in rendering modes 0 to 3 is no mask (3: invisible, painting nothing). A mode that is not a whole +/// number from 0 to 9 leaves the mode as it was. +#[test] +fn legacy_type_in_other_rendering_modes_does_not_clip() { + let (black, red) = (Some(Color::cmyk(0.0, 0.0, 0.0, 1.0)), Some(Color::rgb(1.0, 0.0, 0.0))); + let square = format!("{}f\n", rect_path(0.0, 0.0, 100.0, 100.0)); + let cases = [("0 Tr", (black, None)), ("3 Tr", (None, None)), ("1 Tr\n4.5 Tr\n10 Tr\n-4 Tr\n/x Tr", (None, red))]; + for (modes, paint) in cases { + let text = point_type(&format!("{modes}\n1 0 0 XA\n1 w"), "Hi"); + let doc = legacy_read(&format!("q\n{text}{square}Q\n")).doc; + let a = art(&doc); + assert_eq!(a.len(), 1, "{modes}"); + let NodeKind::Group { children, clip: false } = &a[0].kind else { panic!("{modes}: {:?}", a[0].kind) }; + assert_eq!(run_paint(&children[0]), paint, "{modes}"); + } +} + +/// A legacy-format file whose layer holds `art`, read. +fn legacy_read(art: &str) -> Structure { + match read(type_stream7(art).as_bytes()) { + Ok(r) => r, + Err(e) => panic!("{e}"), + } +} + +/// The text objects of the first layer, with their ids, top to bottom: a threaded text object's +/// frames in file order. +fn art_frames(doc: &Document) -> Vec<(vectorcraft_doc::NodeId, vectorcraft_doc::TextObject)> { + art(doc).iter().rev().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((n.id, (**t).clone())) } else { None }).collect() +} + +/// An area's frame in the document. +fn frame_in_doc(t: &vectorcraft_doc::TextObject) -> Rect { + let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { panic!("area type: {:?}", t.kind) }; + kurbo::Shape::bounding_box(&(t.xf * frame.to_bezpath())) +} + +/// Do two matrices match? +fn same_matrix(a: Affine, b: Affine) -> bool { + a.as_coeffs().iter().zip(b.as_coeffs()).all(|(p, q)| (p - q).abs() < 1e-9) +} + +/// Area type with linked areas (§15.5.3): each area's `Tp` … `TP` with its own matrix and frame, +/// the characters after each, and overflow text. It opens as one frame for each area, threaded in +/// file order, with the story in the first. +#[test] +fn legacy_area_type_with_linked_areas_is_threaded_frames() { + let text = format!( + "1 To\n1 0 0 1 0 40 0 Tp\n{}n\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Linked ) Tx\n\ + 0 1 -1 0 150 20 0 Tp\n{}n\nTP\n(areas\\r) Tx\n(and more) TX\n(\\r) TX\nTO\n", + rect_path(0.0, 0.0, 50.0, 40.0), + rect_path(110.0, 20.0, 150.0, 80.0) + ); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + let [(a, first), (b, second)] = frames.as_slice() else { panic!("two frames: {frames:?} {:?}", r.warnings) }; + assert_eq!(r.doc.text_threads, [vec![*a, *b]], "threaded in file order"); + let in_doc = |x0, y0, x1, y1| r.to_doc.transform_rect_bbox(Rect::new(x0, y0, x1, y1)); + assert!(near(frame_in_doc(first), in_doc(0.0, 0.0, 50.0, 40.0)), "{:?}", frame_in_doc(first)); + assert!(near(frame_in_doc(second), in_doc(110.0, 20.0, 150.0, 80.0)), "{:?}", frame_in_doc(second)); + // Each frame keeps its own area's matrix: the second's type runs up the page. + let placed = |m: [f64; 6]| r.to_doc * Affine::new(m) * Affine::FLIP_Y; + assert!(same_matrix(first.xf, placed([1.0, 0.0, 0.0, 1.0, 0.0, 40.0])), "{:?}", first.xf); + assert!(same_matrix(second.xf, placed([0.0, 1.0, -1.0, 0.0, 150.0, 20.0])), "{:?}", second.xf); + // The story: the characters after every area and the overflow text, in the first frame. + assert_eq!(first.plain_text(), "Linked areas\nand more"); + assert_eq!(first.paragraph_styles().len(), 2); + assert_eq!(second.plain_text(), ""); +} + +/// A linked area without a path is left out; a single area with a path is area type in no thread. +#[test] +fn legacy_area_type_leaves_out_a_linked_area_without_a_path() { + let area = |m: &str, path: Option, chars: &str| { + let path = path.map(|p| format!("{}n\n", rect_path(p.x0, p.y0, p.x1, p.y1))).unwrap_or_default(); + format!("{m} Tp\n{path}TP\n{chars}") + }; + let style = "0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n"; + let three = format!( + "1 To\n{}{}{}TO\n", + area("1 0 0 1 0 40 0", Some(Rect::new(0.0, 0.0, 50.0, 40.0)), &format!("{style}(One ) Tx\n")), + area("1 0 0 1 60 40 0", None, "(two ) Tx\n"), + area("1 0 0 1 110 40 0", Some(Rect::new(110.0, 0.0, 150.0, 40.0)), "(three) Tx\n"), + ); + let r = legacy_read(&three); + let frames = art_frames(&r.doc); + let [(a, first), (b, second)] = frames.as_slice() else { panic!("two frames: {frames:?} {:?}", r.warnings) }; + assert_eq!(r.doc.text_threads, [vec![*a, *b]]); + assert_eq!((first.plain_text().as_str(), second.plain_text().as_str()), ("One two three", "")); + let one = format!( + "1 To\n{}{}TO\n", + area("1 0 0 1 60 40 0", None, &format!("{style}(x) Tx\n")), + area("1 0 0 1 0 40 0", Some(Rect::new(0.0, 0.0, 50.0, 40.0)), "(y) Tx\n") + ); + let r = legacy_read(&one); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one frame: {frames:?}") }; + assert!(r.doc.text_threads.is_empty()); + assert_eq!(only.plain_text(), "xy"); + // The frame's own matrix, not the pathless area's. + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((0.0, 40.0)) * Affine::FLIP_Y), "{:?}", only.xf); +} + +/// One text object reads at most 4,096 linked areas: the paths of the rest are left out, not read as +/// art, and their characters stay in the story. +#[test] +fn legacy_area_type_reads_up_to_its_limit_of_linked_areas() { + const LIMIT: usize = 4096; + 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\n(a) Tx\n{area}(b) Tx\nTO\n", area.repeat(LIMIT)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), LIMIT); + assert_eq!(art(&r.doc).len(), LIMIT, "no art paths"); + assert_eq!(r.doc.text_threads.iter().map(Vec::len).collect::>(), [LIMIT]); + assert_eq!(frames[0].1.plain_text(), "ab"); + 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 = 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"; + +/// The frames of linked areas times the characters of their story are kept to the reader's +/// allowance of characters: a story of more than half of it gets one frame, and of a third, two. +#[test] +fn legacy_area_type_keeps_its_frames_times_characters_to_the_allowance() { + const ALLOWANCE: usize = 1 << 22; + let area = |x: f64| format!("1 0 0 1 {x} 0 0 Tp\n{}n\nTP\n", rect_path(x, 0.0, x + 50.0, 40.0)); + for (chars, kept) in [(ALLOWANCE / 2 + 1, 1), (ALLOWANCE / 3, 3), (ALLOWANCE / 3 + 1, 2)] { + let text = format!("1 To\n{}0 Tr\n({}) Tx\n{}{}TO\n", area(0.0), "a".repeat(chars), area(60.0), area(120.0)); + let r = legacy_read(&text); + let frames = art_frames(&r.doc); + assert_eq!(frames.len(), kept, "{chars}"); + assert_eq!(r.doc.text_threads.len(), usize::from(kept > 1), "{chars}"); + assert_eq!(frames[0].1.plain_text().len(), chars); + assert_eq!(r.warnings.iter().any(|w| w == LINKED_AREAS_LEFT_OUT), kept < 3, "{chars}"); + } +} + +/// Point type and type on a path have one text path (§15.2): one with more is read at its first. +#[test] +fn legacy_point_and_path_type_with_several_text_paths_use_the_first() { + let point = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 90 20 0 Tp\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(point); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + assert!(matches!(only.kind, vectorcraft_doc::TextKind::Point) && r.doc.text_threads.is_empty()); + assert_eq!(only.plain_text(), "ab"); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((10.0, 50.0)) * Affine::FLIP_Y), "the first text path's matrix: {:?}", only.xf); + let on_path = "2 To\n1 0 0 1 0 0 0.5 Tp\n0 0 m\n100 0 L\nN\nTP\n0 Tr\n(a) Tx\n1 0 0 1 0 0 0 Tp\n0 50 m\n100 50 L\nN\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(on_path); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + let vectorcraft_doc::TextKind::OnPath { path, start, .. } = &only.kind else { panic!("{:?}", only.kind) }; + assert!((start - 0.5).abs() < 1e-9, "the first text path's start: {start}"); + let along = kurbo::Shape::bounding_box(&(only.xf * path.to_bezpath())); + assert!((along.y0 - r.to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, 100.0, 0.0)).y0).abs() < 1e-9, "{along:?}"); + assert!(same_matrix(only.xf, r.to_doc * Affine::FLIP_Y), "{:?}", only.xf); + // Type on a path whose first text path has no path: the first one with a path, its matrix and + // start included. + let later = "2 To\n1 0 0 1 30 30 0.25 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 5 0 0.5 Tp\n0 50 m\n100 50 L\nN\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(later); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + let vectorcraft_doc::TextKind::OnPath { start, .. } = &only.kind else { panic!("{:?}", only.kind) }; + assert!((start - 0.5).abs() < 1e-9, "{start}"); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((5.0, 0.0)) * Affine::FLIP_Y), "{:?}", only.xf); + // Area type with no frame at all: point type at its first text path. + let frameless = "1 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n(a) Tx\n1 0 0 1 90 20 0 Tp\nTP\n(b) Tx\nTO\n"; + let r = legacy_read(frameless); + let frames = art_frames(&r.doc); + let [(_, only)] = frames.as_slice() else { panic!("one object: {frames:?}") }; + assert!(matches!(only.kind, vectorcraft_doc::TextKind::Point), "{:?}", only.kind); + assert!(same_matrix(only.xf, r.to_doc * Affine::translate((10.0, 50.0)) * Affine::FLIP_Y), "{:?}", only.xf); +} + +/// The dictionary that follows a threaded text object (version 9 and later): its opacity mask and +/// text wrap go on every frame, and its name on the first frame, which holds the story. +#[test] +fn the_dictionary_after_linked_area_type_applies_to_its_frames() { + let dict = "%_/ArtDictionary :\n%_(Story) /String (AIArtName) ,\n%_12.5 /Real (AI11TextWrapOffset) ,\n\ + %_0 /Bool (AI11TextWrapInvert) ,\n%_/Mask :\n%_1 /Bool (Linked) ,\n%_0 /Bool (Disabled) ,\n%_X=\n\ + %_0 0 0 1 k\n%_0 0 m\n%_5 0 L\n%_5 5 L\n%_0 5 L\n%_0 0 L\n%_f\n%_X+\n%_ (Art) ,\n%_1 /Bool (Clipping) ,\n\ + %_0 /Bool (Inverted) ,\n%_; (AI9_Mask) ,\n%_;\n"; + let area = |x: f64| format!("1 0 0 1 {x} 40 0 Tp\n{}n\nTP\n", rect_path(x, 0.0, x + 50.0, 40.0)); + let text = format!("1 To\n{}0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(a) Tx\n{}{}(b) Tx\nTO\n{dict}", area(0.0), area(60.0), area(120.0)); + let r = read_ok(&layer(&text)); + let ids: Vec<_> = art_frames(&r.doc).into_iter().map(|(id, _)| id).collect(); + assert_eq!(r.doc.text_threads, std::slice::from_ref(&ids), "{:?}", r.warnings); + let nodes: Vec<&Node> = ids.iter().filter_map(|id| r.doc.node(*id)).collect(); + assert_eq!(nodes.len(), 3); + for n in &nodes { + assert!(n.extras().mask.is_some(), "every frame is masked: {:?}", n.id); + assert_eq!(wrap_of(n), Some(vectorcraft_doc::TextWrap { offset: 12.5, invert: false })); + } + let names: Vec<_> = nodes.iter().map(|n| n.name.as_deref()).collect(); + assert_eq!(names, [Some("Story"), None, None]); +} + #[test] fn what_it_doesnt_read_is_an_error_where_it_shows() { let e = read(stream(&layer("1 2 frobnicate\n")).as_bytes()).unwrap_err(); @@ -2755,6 +4073,362 @@ fn sections_it_skips() { %_/Document :\n%_/Binary : /ASCII85Decode ,\n%_(]<[%\n%;;;~>\n%_; (Profile) ,\n%_;\n"; let doc = read_ok(&format!("{body}{}", layer(&(rect_path(0.0, 0.0, 1.0, 1.0) + "f\n")))).doc; assert_eq!(art(&doc).len(), 1); + // A symbol whose art can't be read isn't kept. + assert!(doc.symbols.is_empty()); +} + +/// Symbol definitions as the editing data writes them, in a section that doesn't print. +fn symbols(defs: &str) -> String { + format!("%AI5_Begin_NonPrinting\n{defs}%AI5_End_NonPrinting--\n") +} + +/// A symbol named `name` whose art is `art` (in the symbol's space, y down), with the registration +/// point `registration` (1 to 9 from the top left, row by row). +fn symbol(name: &str, art: &str, registration: u32) -> String { + format!( + "%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n{art}U\n%_/ArtDictionary :\n%_{registration} /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n" + ) +} + +/// An instance of the symbol named `name`, `m` taking the symbol's art to art space. +fn instance(name: &str, m: [f64; 6]) -> String { + let [a, b, c, d, e, f] = m; + format!("/SymbolInstance :\n({name}) /SymbolRef ,\n{a} {b} {c} {d} {e} {f} /RTransformMatrix\n;\n") +} + +/// A red square of 4 points about the origin, as a symbol's art. +fn dot() -> String { + format!("{RED}{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)) +} + +/// The visual box of `n` in `doc`, its instances measured by their symbols' art. +fn instance_box(doc: &Document, n: &Node) -> Rect { + n.visual_bounds_with(&doc.symbol_boxes()).expect("a box") +} + +#[test] +fn a_symbol_comes_in_once_and_its_instances_stay_live() { + let body = symbols(&symbol("Dot", &dot(), 5)) + + &layer(&(instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]) + &instance("Dot", [2.0, 0.0, 0.0, -2.0, 100.0, 50.0]))); + let mut doc = read_ok(&body).doc; + assert_eq!(doc.symbols.len(), 1); + assert_eq!(doc.symbols[0].name, "Dot"); + assert!(doc.symbol_registration("Dot").is_center()); + let a = art(&doc); + assert_eq!(a.len(), 2); + let xfs: Vec<_> = a + .iter() + .map(|n| if let NodeKind::SymbolInstance { symbol, xf } = &n.kind { (symbol.clone(), *xf) } else { panic!("{:?}", n.kind) }) + .collect(); + assert_eq!(xfs[0].0, "Dot"); + assert_ne!(xfs[0].1, xfs[1].1); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(18.0, 48.0, 22.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(96.0, 46.0, 104.0, 54.0)); + // Editing the symbol's art changes both instances. + let wider = read_ok(&(symbols(&symbol("Dot", &format!("{RED}{}f\n", rect_path(-4.0, -2.0, 4.0, 2.0)), 5)) + &layer(""))).doc; + doc.symbols[0].art = wider.symbols[0].art.clone(); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(16.0, 48.0, 24.0, 52.0)); + assert_eq!(instance_box(&doc, &a[1]), Rect::new(92.0, 46.0, 108.0, 54.0)); +} + +#[test] +fn an_instance_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). + let nested = instance("Dot", [1.0, 0.0, 0.0, -1.0, -8081.0, 8237.0]); + let defs = symbols(&(symbol("Dot", &dot(), 5) + &symbol("Pair", &nested, 1))); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&instance("Pair", [1.0, 0.0, 0.0, -1.0, 50.0, 50.0]))); + let doc = read_ok(&body).doc; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Dot", "Pair"]); + assert_eq!(doc.symbol_registration("Pair"), vectorcraft_doc::SymbolRegistration(0)); + // Dot sits at (10, 5) in Pair's art, which the page instance puts at (50, 50). + let a = art(&doc); + assert_eq!(instance_box(&doc, &a[0]), Rect::new(58.0, 53.0, 62.0, 57.0)); +} + +#[test] +fn an_image_in_a_symbols_art_is_placed_from_the_canvas() { + // The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). The + // image's matrix is in the canvas's space turned y up about that point, as an instance's in a + // symbol's art is: its top left pixel goes to (-5, -2.5) in the symbol's art. + let m = "[ 5 0 0 5 -8096 8244.5 ]"; + let raster = format!( + "%AI5_File:\n%AI5_BeginRaster\n() 1 XG\n/DeviceRGB XN\n{m} 2 1 0 Xh\n{m} 0 0 2 1 2 1 8 3 0 0 1 0 4 4 0 0\n\ + %%BeginData: 6\rXI\nABCDEF%%EndData\r\nXH\r\n%AI5_EndRaster\r\nN\n" + ); + let body = format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Pic", &raster, 5)), layer("")); + let doc = read_ok(&body).doc; + assert_eq!(doc.symbols.len(), 1); + let NodeKind::Image(im) = &doc.symbols[0].art.kind else { panic!("{:?}", doc.symbols[0].art.kind) }; + for ((u, v), want) in [((0.0, 0.0), (-5.0, -2.5)), ((2.0, 0.0), (5.0, -2.5)), ((0.0, 1.0), (-5.0, 2.5))] { + let got = im.xf * Point::new(u, v); + assert!((got - Point::new(want.0, want.1)).hypot() < 1e-9, "pixel ({u}, {v}): {got:?}, want {want:?}"); + } + // A linked image (`XG` and `XF`) is placed the same way. + let linked = raster7("(a.tif) 0 XG\n", m, (2, 1), "XF", ""); + let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Link", &linked, 5)), layer(""))).doc; + let NodeKind::Image(link) = &doc.symbols[0].art.kind else { panic!("{:?}", doc.symbols[0].art.kind) }; + assert!(link.link.is_some()); + assert!((link.xf * Point::new(0.0, 0.0) - Point::new(-5.0, -2.5)).hypot() < 1e-9, "{:?}", link.xf); + // Without a template box the image can't be placed, so the symbol isn't read whole: its + // instance comes in as the page draws it. + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Pic", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Pic", &raster, 5)) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_eq!(r.unread.len(), 1, "{:?}", r.warnings); +} + +#[test] +fn an_instance_keeps_its_hide_lock_transparency_and_clip() { + let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]; + let art_ = format!( + "1 Xw\n{}0 Xw\n1 A\n{}0 A\n{}1 0.5 1 1 1 Xy\n0 0 Xd\n6 () XW\n0 Ae\nq\n{}{}h\nW\nn\nQ\n0 0.25 0 0 0 Xy\n{}", + instance("Dot", m), + instance("Dot", m), + instance("Dot", m), + instance("Dot", m), + rect_path(19.0, 49.0, 21.0, 51.0), + instance("Dot", m), + ); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&art_))).doc; + let a = art(&doc); + assert_eq!(a.len(), 5); + assert!(!a[0].visible && !a[0].locked); + assert!(a[1].visible && a[1].locked); + // An instance's transparency is the `Xy` after it, as a group's is; one set before it isn't its. + assert_eq!((a[2].opacity, a[2].blend, a[2].isolate, a[2].knockout, a[2].knockout_shape), (0.5, BlendMode::Multiply, true, Knockout::On, true)); + assert_eq!((a[1].opacity, a[1].blend, a[1].isolate, a[1].knockout), (1.0, BlendMode::Normal, false, Knockout::Neutral)); + assert_eq!((a[3].opacity, a[4].opacity), (0.25, 1.0)); + let NodeKind::Group { children, clip: true } = &a[3].kind else { panic!("a clipping group: {:?}", a[3].kind) }; + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::SymbolInstance { .. })); +} + +/// The art of an opacity mask in a symbol's art takes ids of the document, as the rest of the art +/// does: no two objects of the document, in its layers or its symbols, share an id. +#[test] +fn a_symbols_opacity_mask_art_takes_ids_of_the_document() { + fn ids(n: &Node, out: &mut Vec) { + out.push(n.id); + if let Some(m) = n.extras().mask.as_ref() { + ids(&m.art, out); + } + for c in n.children().into_iter().flatten() { + ids(c, out); + } + } + let square = rect_path(-2.0, -2.0, 2.0, 2.0); + let mask_art: String = format!("1 g\n{square}f\n").lines().map(|l| format!("%_{l}\n")).collect(); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let defs = symbols(&symbol("Masked", &format!("{RED}{square}f\n{mask}{}", dot()), 5)); + let shapes: String = (0..6).map(|i| format!("{RED}{}f\n", rect_path(f64::from(i) * 10.0, 0.0, f64::from(i) * 10.0 + 4.0, 4.0))).collect(); + let doc = read_ok(&(defs + &layer(&format!("{shapes}{}", instance("Masked", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))))).doc; + let mut all = Vec::new(); + for n in doc.layers.iter().chain(doc.symbols.iter().map(|s| &s.art)) { + ids(n, &mut all); + } + assert!(doc.symbols.iter().any(|s| s.art.children().into_iter().flatten().any(|c| c.extras().mask.is_some())), "the mask is read"); + let unique: std::collections::HashSet<_> = all.iter().copied().collect(); + assert_eq!(unique.len(), all.len(), "{all:?}"); +} + +/// A layer's `Xy` right after its last object, an instance, before the layer's `0 0 Xd` and +/// `7 () XW`, is the layer's; the instance's own state block (`6 () XW`) keeps it the instance's. +#[test] +fn a_layers_state_after_its_last_symbol_instance_is_the_layers() { + let last = instance("Dot", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("{last}1 0.6 0 2 0 Xy\n0 0 Xd\n7 () XW\n")))).doc; + assert_eq!((doc.layers[0].opacity, doc.layers[0].blend), (0.6, BlendMode::Multiply)); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), (1.0, BlendMode::Normal)); + let doc = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("{last}1 0.6 0 2 0 Xy\n0 0 Xd\n6 () XW\n")))).doc; + assert_eq!(doc.layers[0].opacity, 1.0); + assert_eq!((art(&doc)[0].opacity, art(&doc)[0].blend), (0.6, BlendMode::Multiply)); +} + +#[test] +fn the_symbol_list_orders_the_symbols_and_names_stay_apart() { + let defs = symbol("A", &dot(), 5) + &symbol("B", &dot(), 5) + &symbol("A", &dot(), 5) + &symbol("C", &dot(), 9); + for list in [ + "%AI24_BeginSymbolList\n(C)\n(Ghost)\n(B)\n(C)\n%AI24_EndSymbolList\n", + "%AI10_BeginSymbolList\n(C)\n(Ghost)\n(B)\n(C)\n%AI10_EndSymbolList\n", + ] { + let doc = read_ok(&(symbols(&format!("{defs}{list}")) + &layer(&instance("A", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))).doc; + let names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["C", "B", "A", "A 2"], "{list}"); + assert_eq!(doc.symbol_registration("C"), vectorcraft_doc::SymbolRegistration(8)); + // An instance names the first symbol the file gives that name. + assert!(matches!(&art(&doc)[0].kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "A")); + } +} + +/// A symbol whose art is filled with a pattern isn't kept: its instances come in as the page draws +/// them, within the box of its art. The pattern keeps the name it was numbered with. +#[test] +fn a_symbol_with_a_pattern_fill_isnt_kept() { + let pattern = DOTS.replace("(Dots)", "(Red\\n1)"); + let lawn = symbol("Lawn", &format!("(Red\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&format!("{pattern}{}{}", symbols(&lawn), layer(&instance("Lawn", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Red 2"]); + assert!(r.doc.symbols.is_empty()); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0))); + // A pattern chosen and then replaced by a color before the art is painted fills nothing. + let solid = symbol("Solid", &format!("(Red\\n1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{RED}{}f\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&format!("{pattern}{}{}", symbols(&solid), layer(&instance("Solid", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.symbols.len(), 1); + assert!(r.unread.is_empty()); +} + +#[test] +fn an_instance_of_a_symbol_it_doesnt_have_is_the_unread_object() { + let missing = instance("Absent", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]); + // Alone on the layer, the file isn't read: the page has no box for it. + let e = read(stream(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&missing))).as_bytes()).unwrap_err(); + assert!(e.contains("symbols"), "{e}"); + // In a group, the group is the unread object. + let group = format!("0 Ae\nu\n{missing}{RED}{}f\nU\n", rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&group))); + assert_unread(&r, "symbols"); + // Nor is a symbol whose art holds an instance of one the file doesn't have: the page has no box + // for its instances. + let holder = symbol("Holder", &(dot() + &instance("Absent", [1.0, 0.0, 0.0, -1.0, 0.0, 0.0])), 5); + let body = + format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&holder), layer(&instance("Holder", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let e = read(stream(&body).as_bytes()).unwrap_err(); + assert!(e.contains("symbols"), "{e}"); + // An instance whose matrix doesn't have six finite numbers isn't read either. + let bad = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 /RTransformMatrix\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(&format!("0 Ae\nu\n{bad}U\n")))); + assert_unread(&r, "symbols"); +} + +#[test] +fn an_instance_whose_appearance_differs_from_its_symbols_comes_in_as_the_page_draws_it() { + let edited = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 50 /RTransformMatrix\n,\n/Dictionary :\n; (AI19SymbolAppearanceMap) ,\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(edited))); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0)), "the box is the symbol's, placed"); + // The appearance changes are found in a dictionary that an array holds as a value without a key. + let in_array = "/SymbolInstance :\n(Dot) /SymbolRef ,\n1 0 0 -1 20 50 /RTransformMatrix\n,\n\ + /Array :\n/Dictionary :\n/Dictionary :\n; (AI19SymbolAppearanceMap) ,\n;\n;\n; (Edits) ,\n;\n"; + let r = read_ok(&(symbols(&symbol("Dot", &dot(), 5)) + &layer(in_array))); + assert_unread(&r, "symbols"); + // So does an instance of a symbol whose art isn't read whole, within that art's box. + let partial = symbol("Partial", &format!("{}f\n1 Xw\n1 2 frobnicate\n0 Xw\n", rect_path(-2.0, -2.0, 2.0, 2.0)), 5); + let r = read_ok(&(symbols(&partial) + &layer(&instance("Partial", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert!(r.doc.symbols.is_empty()); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0))); +} + +/// A symbol whose art holds an image that is left out (no matrix, a matrix with no area, data cut +/// short) isn't kept, so its instances don't draw it without the image. +#[test] +fn a_symbol_with_an_image_it_leaves_out_isnt_kept() { + for (what, image) in [ + ("no matrix", raster7("", "", (1, 1), "XI", "%FF0000\n")), + ("a matrix with no area", raster7("", "[ 0 0 0 0 0 0 ]", (1, 1), "XI", "%FF0000\n")), + ("data cut short", raster7("", "[ 1 0 0 1 0 0 ]", (2, 2), "XI", "%FF0000\n")), + ("no end", raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n").replace("%AI5_EndRaster\n", "")), + ("art after a trailer", format!("%%PageTrailer\n{}", raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n"))), + ] { + // With a template box, so that the image could be placed. + let defs = symbols(&symbol("Photo", &(dot() + &image), 5)); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Photo", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&group))); + assert!(r.doc.symbols.is_empty(), "{what}"); + assert_eq!(r.unread.len(), 1, "{what}: {:?}", r.warnings); + } +} + +/// A symbol's art written as a group holding one object stays that group when the group is tagged +/// (`XT`), so the tag isn't lost. +#[test] +fn a_symbols_tagged_group_keeps_its_tag() { + let def = format!( + "%AI14_BeginSymbol\n(Tagged)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n/AdobeURL (https://example.com/a) XT\n%_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n", + dot() + ); + let doc = read_ok(&(symbols(&def) + &layer(&instance("Tagged", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))).doc; + let art = &doc.symbols[0].art; + assert!(matches!(art.kind, NodeKind::Group { .. }), "{:?}", art.kind); + assert_eq!(tags(art).0, "https://example.com/a"); +} + +/// A definition whose art a trailer stops isn't kept, though the art before the trailer is whole. +#[test] +fn a_symbol_cut_off_by_a_trailer_isnt_kept() { + let cut = format!("%AI14_BeginSymbol\n(Cut)\n0 A\n0 Xw\n0 Ae\n{}%%PageTrailer\n{}%AI10_EndSymbol\n", dot(), dot()); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Cut", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&(symbols(&cut) + &layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_unread(&r, "symbols"); +} + +/// A symbol whose art holds type, a placed file, non-native art, an image it can't place or a +/// gradient the file doesn't define isn't kept. Its instances come in as the page draws them, within the box of the rest of its art, an +/// instance right on a layer as well as one in a group. +#[test] +fn a_symbols_art_it_leaves_out_gives_its_instances_the_box_of_the_rest() { + let typed = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n".to_string(); + let placed = "%AI5_BeginPlace\n%AI5_EndPlace\n".to_string(); + let foreign = + "/ForeignObject :\n1 /Version ,\n2 0 0 2 10 20 /RTransform ,\n10 20 /Origin ,\n1 2 5 8 /Bounds ,\n/Data ,\n%,u@!!/MSk8%41#ocdN=10d&\n%1H@\n;\n" + .to_string(); + let image = raster7("", "[ 1 0 0 1 0 0 ]", (1, 1), "XI", "%FF0000\n"); + let gradient = format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(-2.0, -2.0, 2.0, 2.0)); + let template = "%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n"; + for (what, left, head) in [ + ("type", typed, template), + ("a placed file", placed, template), + ("non-native art", foreign, template), + ("an image without a template box", image, ""), + ("a gradient the file doesn't define", gradient, template), + ] { + let defs = symbols(&symbol("Mixed", &(dot() + &left), 5)); + let body = format!("{head}{defs}{}", layer(&instance("Mixed", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let r = read(stream(&body).as_bytes()).unwrap_or_else(|e| panic!("{what}: {e}")); + assert!(r.doc.symbols.is_empty(), "{what}"); + assert_unread(&r, "symbols"); + let (id, _) = &r.unread[0]; + assert_eq!(r.doc.node(*id).and_then(|n| n.geometric_bounds()), Some(Rect::new(18.0, 48.0, 22.0, 52.0)), "{what}"); + } + // A gradient the file doesn't define on a path that isn't painted paints nothing. + // Nor does one on a path that a group's start drops, for the paths after it. + let square = rect_path(-2.0, -2.0, 2.0, 2.0); + for (what, unpainted) in [ + ("not painted", format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{square}n\n0 BB\n")), + ("dropped", format!("Bb\n1 (Nowhere) 0 0 0 10 1 0 0 1 0 0 Bg\n{square}0 BB\nu\n{square}f\nU\n")), + ] { + let defs = symbols(&symbol("Kept", &(dot() + &unpainted), 5)); + let r = read_ok(&format!("{template}{defs}{}", layer(&instance("Kept", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0])))); + assert_eq!(r.doc.symbols.len(), 1, "{what}: {:?}", r.warnings); + assert!(r.unread.is_empty(), "{what}"); + } +} + +#[test] +fn symbols_that_hold_each_other_lose_the_instances_that_close_the_loop() { + let m = [1.0, 0.0, 0.0, -1.0, 0.0, 0.0]; + let defs = symbols(&(symbol("S1", &instance("S2", m), 5) + &symbol("S2", &instance("S1", m), 5))); + let r = + read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{defs}{}", layer(&(dot() + &instance("S1", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))))); + assert!(r.warnings.contains(&vectorcraft_doc::depth::symbols_note()), "{:?}", r.warnings); + assert!(!r.doc.clone().limit_depth(), "nothing is left that draws itself"); +} + +/// A definition after the first layer isn't read: the symbols were checked before that layer, and +/// one read later could hold an instance of a symbol the file doesn't have. +#[test] +fn a_symbol_defined_after_the_first_layer_is_not_read() { + let late = symbols(&symbol("Late", &(dot() + &instance("Absent", [1.0, 0.0, 0.0, -1.0, 0.0, 0.0])), 5)); + let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Late", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0)); + let r = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{late}{}", layer(&dot()), layer(&group))); + assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::>()); + assert_unread(&r, "symbols"); } /// A filled square at x = `10 × i` (5 pt wide), to tell the alternatives of versioned content apart. @@ -3160,7 +4834,7 @@ fn artboards_after_what_stops_the_reading() { let array = format!("%_/Array :\n{}{}%_; (ArtboardArray) ,\n", board("one", 0), board("two", 200)); // Art in the document's own data that the reader can't follow comes before the artboards. let data = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n%_/Dictionary :\nLB\n{array}%_; /NotRecorded ,\n%_;\n"); - let boards: Vec<_> = super::artboards(data.as_bytes()).into_iter().map(|(n, r)| (n, r.x0)).collect(); + let boards: Vec<_> = super::artboards(data.as_bytes()).0.into_iter().map(|(n, r)| (n, r.x0)).collect(); assert_eq!(boards, [("one".to_string(), 0.0), ("two".to_string(), 200.0)]); } @@ -3375,6 +5049,35 @@ fn a_style_name_outside_ascii_links_its_objects() { assert_eq!(art(&r.doc)[0].extras().graphic_style, Some(1)); } +#[test] +fn an_object_in_a_symbols_art_with_a_listed_style_is_linked() { + let defs = styles_and_list(&[fill_style("Blue", "0 0 0 0 0 0 1 Xa\n")], &["Blue"]); + let body = + format!("{defs}{}{}", symbols(&symbol("Tile", &styled_square("Blue"), 5)), layer(&instance("Tile", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let r = read_ok(&body); + assert_eq!(style_names(&r.doc), [("Blue".to_string(), 1)]); + let tile = &r.doc.symbols[0].art; + assert!(matches!(tile.kind, NodeKind::Path { .. }), "{tile:#?}"); + assert_eq!(fill(tile).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(tile.extras().graphic_style, Some(1), "{tile:#?}"); + // A symbol's art written as a group holding one object stays that group when the group is + // linked to the style. + let empty = "/KnownStyle :\n(Empty) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n"; + let defs = styles_and_list(&[empty.to_string()], &["Empty"]); + let square = rect_path(0.0, 0.0, 10.0, 10.0); + let hidden = square.replace('\n', "\n%_"); + // The styled group is the definition's own group, without one around it. + let group = format!( + "%AI14_BeginSymbol\n(Group)\n0 A\n0 Xw\n0 Ae\nu\n{RED}{square}f\nU\n%_u\n%_{hidden}f\n%_U\n1 (Empty) XW\n\ + %_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n%AI10_EndSymbol\n" + ); + let body = format!("{defs}{}{}", symbols(&group), layer(&instance("Group", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]))); + let art = &read_ok(&body).doc.symbols[0].art; + assert!(matches!(art.kind, NodeKind::Group { .. }), "{art:#?}"); + assert_eq!(art.extras().graphic_style, Some(1), "{art:#?}"); +} + #[test] fn without_a_style_list_the_default_graphic_styles_stay() { let defaults = style_names(&Document::new(1.0, 1.0)); @@ -3561,6 +5264,206 @@ fn an_object_with_path_effects_comes_in_as_itself_with_them_live() { assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +/// The paint of a blue fill in a style. +const BLUE_FILL: Option<&str> = Some("0 0 0 0 0 0 1 Xa\n"); + +/// An art style section with style `Bent`: effect `name` with dictionary `keys` on the whole +/// object, over a fill painting with `paint`, or over a fill and stroke that paint nothing. +fn distort_styles(name: &str, keys: &str, paint: Option<&str>) -> String { + let (paints, color) = match paint { + Some(p) => ("0 1", p), + None => ("0 0", ""), + }; + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Bent) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{color}{paints} Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// Free Distort's 16 entries for a 40 × 30 pt object whose source frame is its own box, with its +/// destination corners `dst` (top left, top right, bottom left, bottom right, art space). +fn free_distort_keys(dst: [[f64; 2]; 4]) -> String { + let src = [[20.0, 50.0], [60.0, 50.0], [20.0, 20.0], [60.0, 20.0]]; + let mut out = String::new(); + for (which, c) in [("src", src), ("dst", dst)] { + for (i, [h, v]) in c.into_iter().enumerate() { + out += &format!("{h} /Real ({which}{i}h) ,\n{v} /Real ({which}{i}v) ,\n"); + } + } + out +} + +#[test] +fn an_object_with_a_distort_effect_that_draws_alike_comes_in_as_itself_with_it_live() { + // GUARDS: only type took Distort & Transform effects; a path with Transform, Twist, a still Tweak, + // Pucker & Bloat at 0 or an affine Free Distort came in as its drawn look. + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + // A slanted box: its corners make a parallelogram. + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + for (name, keys, id) in [ + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n0.5 /Real (rotate_Radians) ,\n0 /Bool (transformPatterns) ,\n", "distort.transform"), + ("Adobe Twirl", "45 /Real (angle) ,\n", "distort.twist"), + ("Adobe Scribble and Tweak", "30 /Real (horz) ,\n0 /Bool (anch) ,\n0 /Bool (in) ,\n0 /Bool (out) ,\n", "distort.tweak"), + ("Adobe Punk and Bloat", "0 /Real (d_factor) ,\n", "distort.puckerBloat"), + ("Adobe Free Distort", slanted.as_str(), "distort.freeDistort"), + ("Adobe Free Distort", "", "distort.freeDistort"), + ] { + let r = read_ok(&format!("{}{}", distort_styles(name, keys, BLUE_FILL), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{name}: the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (40.0, 30.0), "{name}: the object keeps its own path"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0)), "{name}"); + let ids: Vec<_> = a[0].appearance.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, [id], "{name}"); + } +} + +#[test] +fn an_object_with_a_distort_effect_drawn_another_way_keeps_its_drawn_look() { + // Pucker & Bloat and Zig Zag draw other outlines than the file's, a Free Distort whose corners + // aren't a parallelogram bends the curves differently, and Transform's copies paint as one path. + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0)); + let bent = free_distort_keys([[25.0, 50.0], [65.0, 52.0], [20.0, 20.0], [60.0, 20.0]]); + for (name, keys) in [ + ("Adobe Punk and Bloat", "-50 /Real (d_factor) ,\n"), + ("Adobe Zigzag", "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n"), + ("Adobe Free Distort", bent.as_str()), + ("Adobe Scribble and Tweak", "30 /Real (horz) ,\n"), + ("Adobe Transform", "1 /Bool (randomize) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n2 /Int (numCopies) ,\n0 /Bool (transformPatterns) ,\n"), + ] { + let r = read_ok(&format!("{}{}", distort_styles(name, keys, BLUE_FILL), layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{name}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + } +} + +/// The gradient `G`, white to black, defined for a document. +const GRADIENT_G: &str = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; + +#[test] +fn an_object_whose_outline_moves_away_from_its_gradient_keeps_its_drawn_look() { + // GUARDS: a gradient stays where it is placed while Transform, Twist or Free Distort moves the + // outline, so the live object lost the gradient its drawn look shows. + let gradient = Some("Bb\n0 0 0 0 Bh\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n"); + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let object = format!( + "0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_1 (G) 20 35 0 40 1 0 0 1 0 0 Bg\n%_{hidden_rect}f\n%_0 BB\n1 (Bent) XW\n", + rect_path(16.0, 16.0, 64.0, 54.0) + ); + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + let shaded = format!("Bb\n1 (G) 5 5 0 10 1 0 0 1 0 0 Bg\n{}f\n0 BB\n", rect_path(5.0, 0.0, 15.0, 10.0)).replace('\n', "\n%_"); + let group = format!("0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{shaded}U\n1 (Bent) XW\n", rect_path(0.0, 0.0, 15.0, 10.0), hidden(RED, 0.0)); + let slanted = free_distort_keys([[25.0, 50.0], [65.0, 50.0], [20.0, 20.0], [60.0, 20.0]]); + let moves = [ + ("Adobe Transform", "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n"), + ("Adobe Twirl", "45 /Real (angle) ,\n"), + ("Adobe Free Distort", slanted.as_str()), + ]; + for (name, keys) in moves { + // A gradient in the style, and one on a member of a group. + for (paint, art_) in [(gradient, &object), (None, &group)] { + let r = read_ok(&format!("{GRADIENT_G}{}{}", distort_styles(name, keys, paint), layer(art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{name}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{name}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{name}: {:?}", r.warnings); + } + } + // An effect that leaves the outline where it is keeps the gradient under it. + let r = read_ok(&format!("{GRADIENT_G}{}{}", distort_styles("Adobe Punk and Bloat", "", gradient), layer(&object))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "{a:#?}"); + assert!(matches!(fill(&a[0]), Paint::Gradient(_)), "{:?}", fill(&a[0])); +} + +/// A group with style `Bent`, its drawn look one path, holding a red and a blue square. +fn distort_group() -> String { + let hidden = |color: &str, x: f64| format!("{color}{}f\n", rect_path(x, 0.0, x + 10.0, 10.0)).replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (Bent) XW\n", + rect_path(0.0, 0.0, 15.0, 10.0), + hidden(RED, 0.0), + hidden("0 0 1 0 0 0 1 Xa\n", 5.0) + ) +} + +#[test] +fn a_group_with_a_transform_keeps_its_members_and_the_effect() { + // GUARDS: the group came in as its drawn look, one path with no effect. + let keys = "5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n"; + let r = read_ok(&format!("{}{}", distort_styles("Adobe Transform", keys, None), layer(&distort_group()))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let members = a[0].children().cloned().unwrap_or_default(); + assert_eq!(members.len(), 2, "the squares, not the look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.params["moveH"].as_f64()), ("distort.transform", Some(5.0))); + assert!(a[0].appearance.items.is_empty(), "{:?}", a[0].appearance); +} + +/// `styles` (from [`distort_styles`]) with a red stroke 2 pt wide in place of the stroke that +/// paints nothing. +fn with_red_stroke(styles: &str) -> String { + styles.replace("/StrokeStyle : 0 1 0 0 0 Xy\n0 0 Xd", "/StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd") +} + +#[test] +fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { + // GUARDS: Twist was read on curves, strokes and groups, and Transform scaling a stroked object, + // where the outline VectorCraft draws hasn't been checked. + let object = |hidden: &str| { + format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) + }; + let square = object(&rect_path(20.0, 20.0, 60.0, 50.0)); + let curved = object("20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"); + let twist = distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", BLUE_FILL); + let scale = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"; + let corner = distort_styles("Adobe Transform", &format!("0 /Int (pinPoint) ,\n{scale}"), BLUE_FILL); + let center = distort_styles("Adobe Transform", scale, BLUE_FILL); + let moved = distort_styles("Adobe Transform", "0 /Int (pinPoint) ,\n5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n", BLUE_FILL); + let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); + for (what, r) in [ + ("a twisted curve", read(&twist, &curved)), + ("a twisted stroke", read(&with_red_stroke(&twist), &square)), + ("a twisted group", read(&distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", None), &distort_group())), + ("a stroke scaled from a corner", read(&with_red_stroke(&corner), &square)), + ("a stroke scaled from the center", read(&with_red_stroke(¢er), &square)), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } + for (what, r) in [ + ("a twisted square", read(&twist, &square)), + ("a stroke moved from a corner", read(&with_red_stroke(&moved), &square)), + ("a fill scaled from a corner", read(&corner, &square)), + ("a fill scaled from the center", read(¢er, &square)), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }) && a[0].appearance.effects.len() == 1, "{what}: {a:#?}"); + } + let r = read(&twist, &square); + let a = art(&r.doc); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance) }; + assert_eq!((e.id.as_str(), e.params["angle"].as_f64()), ("distort.twist", Some(45.0))); +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. @@ -3712,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) } @@ -3744,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)); @@ -3754,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)]; @@ -3788,7 +5691,7 @@ fn live_envelope(n: &Node) -> (&[Arc], &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" ) @@ -4426,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) } @@ -4458,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]) } @@ -4512,6 +6415,15 @@ fn a_blend_comes_in_as_a_live_blend() { assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); } +/// The tags after a blend's drawn steps are the live blend's. +#[test] +fn a_live_blend_keeps_the_tags_of_its_drawn_steps() { + let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])); + let (blend, warnings) = read_blend(&body.replace("\nU\n9 () XW\n0 Ae\n", "\nU\n/sku (B-1) XT\n9 () XW\n0 Ae\n")); + assert!(matches!(blend.kind, NodeKind::Blend { .. }), "a live blend: {:?} {warnings:?}", blend.kind); + assert_eq!(tags(&blend).1, [tag("sku", "B-1")]); +} + /// A spine written from the right key to the left one keeps the keys in their order on it (the /// red key first), sitting on its last and first anchors. #[test] @@ -5212,6 +7124,41 @@ fn a_brushs_art_takes_the_patterns_defined_before_it() { assert!(matches!(fill(&s.art), Paint::Pattern { ref pattern, .. } if pattern == "Dots"), "{:?}", r.warnings); } +/// A brush's art filled with a pattern defined in the version 7 form places the tiles with the +/// fill's offset, scale, rotation, reflection and shear operands, and a brush whose art has such a +/// fill without all nine of them isn't read. +#[test] +fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() { + let def = pattern7("Grid", "(0 g) @ _ &\n"); + let read_with = |ops: &str| { + let section = format!("%AI8_BeginBrushPattern\n(Dot art)\n0 A\n(Grid) {ops} p\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 4.0, 4.0)); + read_ok(&format!("{def}{section}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))) + }; + let placed = |ops: &str| { + let r = read_with(ops); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + match fill(&s.art) { + Paint::Pattern { xf, .. } => xf, + p => panic!("{ops}: {p:?} {:?}", r.warnings), + } + }; + let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); + // The operands and the move they make from the plain placement (a b c d e f): those of + // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the + // art's space has it. + let cases = [ + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]), + ]; + for (ops, want) in cases { + let got = (placed(ops) * plain.inverse()).as_coeffs(); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{ops}: {got:?}"); + } + let r = read_with("0 0 1 1 0 0 0 0 [1 0 0 1 0 0]"); + assert!(!vectorcraft_brush::library(&r.doc).iter().any(|b| b.name == "Spray"), "{:?}", r.warnings); +} + /// A file without brush objects keeps the default brushes. #[test] fn a_file_without_brushes_keeps_the_default_ones() { @@ -5274,6 +7221,107 @@ fn a_gradients_br_is_not_a_brush() { assert_eq!(g.gradient.stops.len(), 2); } +/// The Brush Options codes for how a Calligraphic brush's values vary: Tilt, Bearing and Rotation +/// are the pen's other channels (#372: a 6D Art Pen brush varies its diameter with the pressure, +/// its roundness with the bearing and its angle with the barrel's rotation). The stylus wheel isn't +/// read: it varies at random, as an unknown code does. +#[test] +fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { + use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, Tilt}; + let modes = |params: &str| { + let d = brush::parse_tool_object(brush::Tool::Calligraphic, "Pen", params).unwrap(); + let brush::DraftKind::Calligraphic(c) = d.kind else { panic!("{d:?}") }; + c.modes.unwrap() + }; + assert_eq!(modes("1 51 69 13 57 -346 14 2 5 6 0"), [Rotation, Bearing, Pressure]); + assert_eq!(modes("1 2 6 40 60 -30 10 4 4 4 0"), [Tilt, Tilt, Tilt]); + assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [Random, Random, Random], "the stylus wheel"); + assert_eq!(modes("1 4 4 50 50 10 10 3 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); +} + +/// A 6D Art Pen brush: diameter 4 to 8 with the pressure, roundness 30 to 50 with the bearing and +/// angle -150 to 210 with the barrel's rotation. +const SIX_D: &str = "1 4 8 30 50 -150 210 2 5 6 0"; + +/// The style `Inked`: a stroke in red of weight `weight` with the Calligraphic brush `brush` at +/// diameter, roundness and angle `settings` (each its value and variation either side), varying by +/// the codes `codes`, its angle relative to `relative` (0 the page). +fn brushed_style(brush: &str, weight: f64, settings: [(f64, f64); 3], codes: [u8; 3], relative: u8) -> String { + let [(d, dv), (r, rv), (a, av)] = settings; + let [dm, rm, am] = codes; + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Inked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({CALLIGRAPHIC}) 1 0 /Filter ,\n1 /Visible ,\n(Calligraphic Brush) /Title ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 1 1 0 1 0 0 XA\n0 1 0 0 0 Xy\n0 J 0 j {weight} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + {d} /Real (Diameter) ,\n{dv} /Real (DiameterVariation) ,\n{dm} /Int (DiameterDependsOn) ,\n\ + {r} /Real (Roundness) ,\n{rv} /Real (RoundnessVariation) ,\n{rm} /Int (RoundnessDependsOn) ,\n\ + {a} /Real (Angle) ,\n{av} /Real (AngleVariation) ,\n{am} /Int (AngleDependsOn) ,\n{relative} /Int (AngleRelativeTo) ,\n\ + ({brush}) /UnicodeString (DisplayString) ,\n/GObjRef : ({brush}) ({CALLIGRAPHIC}) /PluginObject ; (Brush) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /FillStyle : 0 O\n0 0 0 0 k\n0 0 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + ) +} + +/// The settings [`SIX_D`] has, as an art style writes them. +const SIX_D_SETTINGS: [(f64, f64); 3] = [(6.0, 2.0), (40.0, 10.0), (30.0, 180.0)]; + +/// A brushed path as the file writes it: its drawn look (a filled outline) in a group, then the +/// path itself on `%_` lines, unpainted, with the style `Inked`. +fn brushed_path() -> String { + let line = "20 20 m\n100 60 L\n"; + format!("0 Ae\nu\n{RED}{}f\nU\n0 0 Xd\n6 () XW\n%_{}n\n1 (Inked) XW\n", rect_path(20.0, 18.0, 100.0, 62.0), line.replace('\n', "\n%_")) +} + +/// A path drawn with a Calligraphic brush comes in as the path, its stroke in that brush at its +/// weight (the weight scales the brush), not as its drawn look: here a 6D Art Pen brush, whose +/// channels the brush keeps (#372). +#[test] +fn a_path_with_a_calligraphic_brush_comes_in_brushed() { + let def = plugin_object(CALLIGRAPHIC, "Six D", SIX_D); + let style = brushed_style("Six D", 0.5, SIX_D_SETTINGS, [2, 5, 6], 0); + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, not its look: {a:#?}"); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let st = a[0].appearance.stroke().unwrap(); + assert_eq!((st.brush.as_deref(), st.width, st.paint.color()), (Some("Six D"), 0.5, Some(Color::rgb(1.0, 0.0, 0.0)))); + assert!(a[0].appearance.fill().is_none_or(|f| f.paint.is_none()), "{:?}", a[0].appearance); + use vectorcraft_brush::{BrushKind, Variation}; + let lib = vectorcraft_brush::library(&r.doc); + let BrushKind::Calligraphic(c) = brush_named(&lib, "Six D") else { panic!("calligraphic") }; + assert_eq!(c.modes, Some([Variation::Rotation, Variation::Bearing, Variation::Pressure])); + // With no pen recorded on the path, the nib is the brush's own at the stroke's weight. + let pieces = vectorcraft_brush::stroke_pieces(&r.doc, &lib[0], &a[0].path_data().unwrap().to_bezpath(), st); + let height = pieces.iter().filter_map(|n| n.geometric_bounds()).map(|b| b.height()).fold(0.0, f64::max); + assert!(height > 40.0 && height < 46.0, "the line's rise and about half the nib's 3 pt: {height}"); +} + +/// A brushed path keeps its drawn look when its stroke can't be read as the brush: the object's +/// own settings differ from the brush's (Options of Selected Object), its angle follows the path, +/// or the file defines no brush of its name. +#[test] +fn a_brushed_path_the_brush_cant_draw_keeps_its_drawn_look() { + let def = plugin_object(CALLIGRAPHIC, "Six D", SIX_D); + let mut own = SIX_D_SETTINGS; + own[0] = (9.0, 2.0); + let cases = [ + ("its own settings", def.clone(), brushed_style("Six D", 1.0, own, [2, 5, 6], 0)), + ("its own modes", def.clone(), brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 4], 0)), + ("an angle on the path", def.clone(), brushed_style("Six D", 1.0, SIX_D_SETTINGS, [2, 5, 6], 1)), + ("no such brush", def, brushed_style("Other", 1.0, SIX_D_SETTINGS, [2, 5, 6], 0)), + ]; + for (why, def, style) in cases { + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{why}: the drawn look, {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; /// Editing data in the legacy format (version 7 specification, chapter 2): `%AI5_FileFormat 2.0`, diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index cb4c2594b5..ac5f38d6b8 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -396,6 +396,9 @@ pub(super) struct Texts { /// The document's character styles (`[Normal Character Style]` first), each a name, the /// character style it is based on (key 5, an index into these) and its attributes (key 6). char_sheets: Vec, + /// The document's paragraph styles (`[Normal Paragraph Style]` first), each a name, its + /// attributes (key 5) and the paragraph style it is based on (key 6, an index into these). + para_sheets: Vec, frames: Vec, } @@ -434,21 +437,17 @@ impl Texts { .map(|f| f.get("0").and_then(|f| f.get("0")).and_then(|f| f.get("0")).and_then(Val::str).unwrap_or_default().to_string()) .collect(); let main = doc.get("1")?; + let sheets = |key: &str| -> Vec { + let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); + list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() + }; Some(Texts { stories: main.get("1")?.list().to_vec(), fonts, defaults: main.get("2")?.clone(), para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), - char_sheets: doc - .get("0")? - .get("5") - .and_then(|s| s.get("0")) - .map(Val::list) - .unwrap_or_default() - .iter() - .take(MAX_SHEETS) - .map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))) - .collect(), + char_sheets: sheets("5"), + para_sheets: sheets("6"), frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), }) } @@ -541,8 +540,10 @@ impl Texts { let mut paras = vec![]; for run in s.get("0")?.get("5").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { let n = run.get("1").and_then(Val::num)? as usize; - let props = run.get("0").and_then(|r| r.get("0")).and_then(|r| r.get("5")); - paras.push((n, self.para(props))); + paras.push((n, self.para(run.get("0").and_then(|r| r.get("0"))))); + } + if paras.is_empty() { + paras.push((text.chars().count(), self.para(None))); } let mut runs = vec![]; for run in s.get("0")?.get("6").map(|p| p.get("0").map(Val::list).unwrap_or_default()).unwrap_or_default() { @@ -555,9 +556,19 @@ impl Texts { Some(Story { text, anchor, lines, frames, paras, runs, path_spacing, vertical }) } - /// A paragraph's attributes: its own keys, else the document's. - fn para(&self, p: Option<&Val>) -> Para { - let pick = |k: &str| p.and_then(|p| p.get(k)).or_else(|| self.para_defaults.get(k)); + /// A paragraph's attributes (`run`: its attributes, key 5, and the paragraph style it is based + /// on, key 6): its own keys, else those of its paragraph style and the ones that is based on, + /// else those of `[Normal Paragraph Style]`, else the document's. + fn para(&self, run: Option<&Val>) -> Para { + let mut chain = vec![]; + let mut at = run; + for _ in 0..=MAX_SHEETS_BASED_ON { + let Some(style) = at else { break }; + chain.extend(style.get("5")); + at = style.get("6").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.para_sheets.get(i as usize)); + } + chain.extend(self.para_sheets.first().and_then(|s| s.get("5"))); + let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.para_defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num).filter(|v| v.abs() < 1e5).unwrap_or(0.0); Para { justify: pick("0").and_then(Val::num).map_or(0, |v| v.clamp(0.0, 6.0) as u8), @@ -573,7 +584,7 @@ impl Texts { /// A run's character style (`run`: its attributes, key 6, and the character style it is based /// on, key 5): its own keys, else those of its character style and the ones that is based on, - /// else the document's. + /// else those of `[Normal Character Style]`, else the document's. fn style(&self, run: Option<&Val>) -> Style { // The run's attributes, then its character style's, then the styles each is based on. let mut chain = vec![]; @@ -583,6 +594,7 @@ impl Texts { chain.extend(style.get("6")); at = style.get("5").and_then(Val::num).filter(|i| i.is_finite() && *i >= 0.0).and_then(|i| self.char_sheets.get(i as usize)); } + chain.extend(self.char_sheets.first().and_then(|s| s.get("6"))); let pick = |k: &str| chain.iter().find_map(|s| s.get(k)).or_else(|| self.defaults.get(k)); let num = |k: &str| pick(k).and_then(Val::num); let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false))); @@ -1074,9 +1086,10 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), char_sheets: vec![], + para_sheets: vec![], frames: vec![], }; - let justify = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).justify; + let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify; // Right to left from the document's defaults, or the paragraph's own. assert_eq!(justify(b"/0 0"), Justify::Right); assert_eq!(justify(b"/0 1 /33 1"), Justify::Left); @@ -1096,6 +1109,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: vec![], } .para(None); @@ -1142,6 +1156,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: cases.iter().map(|c| frame(c)).collect(), }; let vertical: Vec = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect(); @@ -1157,13 +1172,14 @@ mod tests { fonts: vec![], defaults: read(b"/35 1").unwrap(), para_defaults: Val::Dict(BTreeMap::new()), - char_sheets: vec![read(b"/0 (Block) /6 << /35 3 >>").unwrap()], + char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()], + para_sheets: vec![], frames: vec![], }; let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko; assert!(tcy(b"/6 << /35 3 >>"), "the run's own"); - assert!(tcy(b"/5 0 /6 << >>"), "its character style's"); - assert!(!tcy(b"/5 0 /6 << /35 1 >>"), "the run's own wins"); + assert!(tcy(b"/5 1 /6 << >>"), "its character style's"); + assert!(!tcy(b"/5 1 /6 << /35 1 >>"), "the run's own wins"); for other in [&b"/6 << >>"[..], b"/6 << /35 2 >>", b"/6 << /35 3.5 >>", b"/6 << /35 (3) >>", b"/6 << /35 -3 >>", b"/6 << /35 1e308 >>"] { assert!(!tcy(other), "{}", String::from_utf8_lossy(other)); } @@ -1180,9 +1196,10 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: read(b"/33 1").unwrap(), char_sheets: vec![], + para_sheets: vec![], frames: vec![], }; - let direction = |own: &[u8]| para_style(&texts.para(Some(&read(own).unwrap())), 1.0).direction; + let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction; assert_eq!(direction(b"/0 2"), Some(ParaDirection::RightToLeft), "from the document's defaults"); assert_eq!(direction(b"/0 2 /33 0"), None, "the paragraph's own"); let plain = Texts { para_defaults: Val::Dict(BTreeMap::new()), ..texts }; @@ -1221,6 +1238,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], }; texts.frame(0) @@ -1520,6 +1538,7 @@ mod tests { defaults: Val::Dict(BTreeMap::new()), para_defaults: Val::Dict(BTreeMap::new()), char_sheets: vec![], + para_sheets: vec![], frames: vec![read(doc.as_bytes()).unwrap()], }; texts.frame(0).unwrap() diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index f4c210b9cd..75f7c7d13f 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -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))?, diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1498c730a0..698201be55 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -94,7 +94,7 @@ pub(super) type Built = Result<(Document, Vec), String>; /// `structure` (the editing copy `data` read) with nothing compared with the pages, when the file's /// text document makes the type of every text object (at least one shows, and none is type that a /// look draws), no object is unread or has another placement or drawn art that the page would -/// choose, and its artboards are the pages, one for one and of their size, in points or in the pages' +/// choose, no linked image shows a placeholder, and its artboards are the pages, one for one and of their size, in points or in the pages' /// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for /// [`build_from`] with the page. pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { @@ -116,9 +116,11 @@ pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f6 /// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its /// place), no placed file with another placement, no live envelope with the drawn art it replaced -/// (the comparison with the page chooses between them)? +/// (the comparison with the page chooses between them), no linked image showing a placeholder +/// where the page has its pixels? fn nothing_waits_on_page(structure: &Structure) -> bool { - structure.unread.is_empty() + structure.placeholders.is_empty() + && structure.unread.is_empty() && structure.unread_elsewhere.is_empty() && structure.placed_elsewhere.is_empty() && structure.envelopes_drawn.is_empty() @@ -168,6 +170,16 @@ fn page_scale_alone(structure: &Structure, pages: &[(f64, f64)], unit: f64) -> O [1.0, unit].into_iter().find(|&k| k.is_finite() && k >= 1.0 && fits(k)) } +/// The areas left out of the comparisons with `page`: the `restyled` looks', and on a PostScript +/// page, which draws nothing for them, the linked images' `placeholders`. A PDF part draws those +/// images' pixels, which the placeholders don't match. +fn left_out_of_comparisons(page: Page, mut restyled: Vec, placeholders: Vec) -> Vec { + if matches!(page, Page::Art) { + restyled.extend(placeholders); + } + restyled +} + /// [`build`] from `structure`, the editing copy `data` already read. pub(super) fn build_from( structure: Structure, @@ -189,6 +201,7 @@ pub(super) fn build_from( unread_elsewhere, slot_names, restyled, + placeholders, placed_elsewhere, envelopes_drawn, styles_read, @@ -198,6 +211,7 @@ pub(super) fn build_from( bindings_skipped, warnings, } = structure; + let restyled = left_out_of_comparisons(page, restyled, placeholders); // Editing data in the units of the page's user space ([`in_units`]), or at its declared large // canvas scale ([`page_scale`]), is compared with the page scaled down to those units, and the // document read from it is scaled up by `unit`. @@ -317,6 +331,7 @@ pub(super) fn build_from( // Its page is the file's own (its bounding box), as when it comes in as its page: art // reaching past the editing data's artboard stays on it (#1102). doc.artboards.truncate(1); + doc.opened_artboard = None; if let Some(a) = doc.artboards.first_mut() { a.rect = rect; } @@ -1600,6 +1615,19 @@ mod candidate_tests { assert_eq!(more_pages(Some(&tiny_boards), &tiny, 1).len() + 1, MAX_PAGES_COMPARED); } + /// A linked image showing a placeholder (`XF`) waits on the page, whose PDF part draws its + /// pixels: the layers aren't used without it. + #[test] + fn a_linked_image_placeholder_waits_on_the_page() { + let raster = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[ 1 0 0 1 0 4 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n%AI5_EndRaster\n"; + let data = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{raster}LB\n%AI5_EndLayer--\n%%Trailer\n" + ); + let structure = ai::read(data.as_bytes(), false).unwrap(); + assert_eq!(structure.placeholders.len(), 1); + assert!(!nothing_waits_on_page(&structure)); + } + /// The pages a box touches with a margin round it include those it only comes near. #[test] fn the_pages_within_reach_of_a_box_count_as_touched() { diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 26cca96c0f..22c3cf7c7b 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -7,8 +7,8 @@ use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect /// hidden ones too), groups, compound paths, clipping groups and artboards, with the text and the /// strokes around it of the page. When the file has no editing copy, `visible` as it was; when it /// has one that can't be used, `visible` with a warning that says why, with the swatches of the -/// editing copy's palette ([`use_palette`]) and its variable library ([`use_variables`]) when it -/// could be read, and with its layer tree, empty, +/// editing copy's palette ([`use_palette`]), its graphic styles ([`use_styles`]) and its variable +/// library ([`use_variables`]) when it could be read, and with its layer tree, empty, /// below the page's layer when that could be read (#2033). A program in the legacy format without /// layers (`illustrator`, see [`program_alone`]) is read with its art on one layer; when that /// can't be used, the file is `visible` as it was. @@ -40,6 +40,7 @@ pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool, illus let have = v.document.patterns.len(); use_palette(data, &mut v.document); use_brushes(data, &mut v.document, have, &mut v.warnings); + use_styles(data, &mut v.document, true, 1.0, None); use_variables(data, &mut v.document, &mut v.warnings); } if tree.is_empty() { @@ -99,11 +100,12 @@ fn layer_tree(nodes: &[Arc]) -> Vec> { /// notes, or a note saying why the layers weren't read when the editing data can't be decompressed /// or its layers can't be read. The flag returned is `true` when the document is the one read from /// the layers; else the document is `visible`, its pages moved by `place_pages` when the editing -/// data was decompressed but its layers can't be read, and its swatches, brushes and variables those -/// of the editing data's palette ([`use_palette`]), brushes ([`use_brushes`]) and variable library -/// ([`use_variables`]) when it was -/// decompressed. `outlined`: the PDF part's type was read as -/// outlines (a file whose type shows then comes in as its PDF part). +/// 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, 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`, /// by which its art came in scaled. Editing data whose artboard matches the page only in those @@ -133,19 +135,26 @@ 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, Some(&boards)); use_variables(&data, &mut visible, &mut warnings); return (visible, warnings, false); } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { - place_pages(&ai::artboards(&data), &mut visible, unit); + let (boards, active) = ai::artboards(&data); + place_pages(&boards, active, &mut visible, unit); 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, Some(&boards)); let mut all = unread(warnings, why); use_variables(&data, &mut visible, &mut all); (visible, all, false) @@ -275,32 +284,75 @@ fn use_brushes(data: &[u8], doc: &mut Document, have: usize, warnings: &mut Vec< warnings.extend(note.filter(|n| !warnings.contains(n))); } -/// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as -/// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on -/// each, to where they are, so the artboards keep their names and layout when the layers can't be -/// read (#1068). Left as they are unless there are as many artboards as pages, each the size of its -/// page in points, or, when `unit` is above 1, each the size of its page in units of `unit` points: -/// then the layout is drawn `unit` times as large. -fn place_pages(boards: &[(String, Rect)], doc: &mut Document, unit: f64) { - if boards.is_empty() || boards.len() != doc.artboards.len() { +/// `doc` (a file read as its page or PDF part, in place of its layers) with the graphic styles of +/// its editing data `data` in place of the default ones, as [`build`] gives a document read from +/// the layers ([`ai::graphic_styles`], `large_canvas` as it takes it). Unless `large_canvas` is set, +/// their strokes and effects are drawn `unit` times as large when the editing data's artboards are +/// the size of `doc`'s pages in units of `unit` points, else as many times as large as the data's +/// declared large canvas scale when they are the pages' size at that scale ([`board_scale`]). +/// `boards`: the editing data's artboards when they were already read. Left as it is when the +/// editing data has no style this reads. +fn use_styles(data: &[u8], doc: &mut Document, large_canvas: bool, unit: f64, boards: Option<&[(String, Rect)]>) { + let (mut styles, canvas) = ai::graphic_styles(data, large_canvas); + if styles.is_empty() { return; } + if !large_canvas && (unit != 1.0 || canvas != 1.0) { + let read; + let boards = match boards { + Some(b) => b, + None => { + read = ai::artboards(data).0; + &read + } + }; + let k = board_scale(boards, doc, unit).or_else(|| board_scale(boards, doc, canvas)); + if let Some(k) = k.filter(|k| *k != 1.0) { + for g in &mut styles { + g.appearance.scale_strokes(k); + g.appearance.scale_effects(k, vectorcraft_effects::scale_effect); + } + } + } + doc.graphic_styles = styles.into(); +} + +/// How many points a unit of `boards` (the artboards of a file's editing data, in art space) is in +/// `doc` (the file read as its PDF part: a page per artboard): 1 when there are as many artboards as +/// pages, each the size of its page in points, or `unit` when `unit` is above 1 and each is the size +/// of its page in units of `unit` points. `None` otherwise. +fn board_scale(boards: &[(String, Rect)], doc: &Document, unit: f64) -> Option { + if boards.is_empty() || boards.len() != doc.artboards.len() { + return None; + } let differ = |k: f64| { boards .iter() .zip(&doc.artboards) .any(|((_, b), a)| (b.width() - a.rect.width() / k).abs() > 0.5 || (b.height() - a.rect.height() / k).abs() > 0.5) }; - let k = if !differ(1.0) { - 1.0 + if !differ(1.0) { + Some(1.0) } else if unit.is_finite() && unit > 1.0 && !differ(unit) { - unit + Some(unit) } else { - return; - }; + None + } +} + +/// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as +/// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on +/// each, to where they are, so the artboards keep their names and layout when the layers can't be +/// read (#1068); the page of the artboard at `active` (the active one) is the active artboard. Left +/// as they are unless there are as many artboards as pages, each the size of its page in points, +/// or, when `unit` is above 1, each the size of its page in units of `unit` points: then the layout +/// is drawn `unit` times as large. +fn place_pages(boards: &[(String, Rect)], active: Option, doc: &mut Document, unit: f64) { + let Some(k) = board_scale(boards, doc, unit) else { return }; for ((name, _), a) in boards.iter().zip(&mut doc.artboards) { a.name.clone_from(name); } + 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. @@ -315,6 +367,13 @@ fn place_pages(boards: &[(String, Rect)], doc: &mut Document, unit: f64) { } } +/// 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, doc: &Document) -> Option { + 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 }; diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 8f9cb55810..86fa8e35dd 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -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); +} diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index d4ae4db83e..b896063aac 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -209,14 +209,14 @@ fn a_postscript_ai_with_a_multi_layer_mask_opens_with_its_layers() { } /// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation and -/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`XB` (a tab definition) and `Th` -/// (hyphen control). These keep no geometry, so the reader drops them rather than failing the -/// file the way it did before — the symptom seen on Illustrator 6/8 EPS files whose -/// `Adobe_level2_AI5` program can't be run. +/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition) and `Th` +/// (hyphen control). The reader drops `XL` and keeps the tab definition as the paragraph's tab +/// stops rather than failing the file the way it did before (the symptom seen on Illustrator 6/8 +/// EPS files whose `Adobe_level2_AI5` program can't be run). #[test] fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\ - %_ 0 XL\n36 0 Xb\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n"; + %_ 0 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n"; // The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped // on a hidden one), beside the square so the layer is never empty. let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer")); @@ -234,6 +234,8 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { let [p] = texts.as_slice() else { panic!("{texts:?}") }; assert!(!p.hyphenate); assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25)); + let tabs: Vec<_> = p.tabs.iter().map(|t| (t.position, t.align)).collect(); + assert_eq!(tabs, [(72.0, vectorcraft_doc::TabAlign::Right)]); } /// An Illustrator 3 file of paths alone, as image editors export their paths (storytold/photocraft#6036): @@ -350,6 +352,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings); } +/// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then +/// `XF` with no samples) comes in through its layers, the image as a linked image of that file +/// showing a placeholder where the matrix puts the image. +#[test] +fn a_legacy_file_with_a_linked_image_comes_in_through_its_layers() { + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ + /XG {pop pop} def /XF {13 {pop} repeat} def"; + let raster = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[2 0 0 3 20 80] 0 0 10 20 10 20 8 3 0 0 0 0 XF\n%AI5_EndRaster\n"; + let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{}\n{raster}LB\n%AI5_EndLayer--\n", tri(10)); + let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog")); + let r = import(file.as_bytes()).unwrap(); + assert!(!r.preview); + let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Back"], "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert_eq!(art.len(), 2, "{:?}", r.warnings); + let NodeKind::Image(im) = &art[1].kind else { panic!("{:?}", art[1].kind) }; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some("photo.tif")); + // The image's 10 × 20 pixels from (20, 80) in art space, 2 and 3 points each: 20 20 40 80 on + // the page, y down. + assert_eq!((im.width, im.height), (10, 20)); + let (top_left, bottom_right) = (im.xf * Point::ZERO, im.xf * Point::new(10.0, 20.0)); + assert!( + (top_left - Point::new(20.0, 20.0)).hypot() < 0.01 && (bottom_right - Point::new(40.0, 80.0)).hypot() < 0.01, + "{top_left:?} {bottom_right:?}" + ); + assert!(r.warnings.iter().any(|w| w.contains("show a placeholder")), "{:?}", r.warnings); +} + /// A file in the legacy format without layers (Illustrator 3) whose prolog is included: its prolog, /// a setup, and `art`. fn layerless(art: &str) -> Vec { @@ -417,6 +448,47 @@ fn a_version_7_palette_keeps_its_swatches_without_names() { assert_eq!(d.swatch("Gray K=0").unwrap().paint.color(), Some(Color::gray(0.0)), "1 g is white"); } +/// A gradient's name in the file is shown up to its newline (the AI7 spec's §4): two gradients +/// named `Sky` apart from what follows the newline come in as swatches "Sky" and "Sky 2", and each +/// object keeps its own gradient, linked to its own swatch. A palette swatch that has the name +/// "Sky" of its own keeps it, and the gradients take the next free names. +#[test] +fn gradient_names_are_shown_up_to_their_newline() { + let gradient = |name: &str, gray: f64| { + format!("%AI5_BeginGradient: ({name})\n({name}) 0 2 Bd\n[\n%_{gray} 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n") + }; + let cell = |name: &str| format!("Bb\n2 ({name}) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\nPc\n"); + let fill = |name: &str, x: u32| format!("Bb\n1 ({name}) 0 0 0 100 1 0 0 1 0 0 Bg\n{}\n0 BB\n", tri(x)); + let body = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 1 -1 79 128 255 0 50 0 Lb\n(Art) Ln\n0 A\n0 Xw\n{}{}LB\n%AI5_EndLayer--\n", + fill("Sky\\n2", 10), + fill("Sky\\n1", 30) + ); + let first_stop = |p: &Paint| match p { + Paint::Gradient(g) => (g.swatch.clone(), g.gradient.stops.first().map(|s| s.color)), + _ => panic!("{p:?}"), + }; + for (own, first, second) in [("", "Sky", "Sky 2"), ("0 1 1 0 (Sky) 0 x\nPc\n", "Sky 2", "Sky 3")] { + let setup = format!( + "{}{}%AI5_BeginPalette\n0 0 Pb\nPn\nPc\n{own}{}{}PB\n%AI5_EndPalette\n", + gradient("Sky\\n1", 1.0), + gradient("Sky\\n2", 0.5), + cell("Sky\\n1"), + cell("Sky\\n2") + ); + let r = import(&stream7(&setup, &body)).unwrap(); + let d = &r.document; + let names: Vec<&str> = d.swatches.iter().map(|s| s.name.as_str()).collect(); + let expected: Vec<&str> = ["[None]"].into_iter().chain((!own.is_empty()).then_some("Sky")).chain([first, second]).collect(); + assert_eq!(names, expected, "{:?}", r.warnings); + assert_eq!(first_stop(&d.swatch(first).unwrap().paint), (Some(first.into()), Some(Color::gray(0.0)))); + assert_eq!(first_stop(&d.swatch(second).unwrap().paint), (Some(second.into()), Some(Color::gray(0.5)))); + let art = d.layers[0].children().unwrap(); + let fills: Vec<_> = art.iter().map(|n| first_stop(&n.appearance.fill().unwrap().paint)).collect(); + assert_eq!(fills, [(Some(second.into()), Some(Color::gray(0.5))), (Some(first.into()), Some(Color::gray(0.0)))]); + } +} + /// A version 8 file's paths keep their notes and Show Center. #[test] fn a_legacy_files_paths_keep_their_notes_and_show_center() { @@ -433,6 +505,26 @@ fn a_legacy_files_paths_keep_their_notes_and_show_center() { assert!(kids[0].shows_center() && !kids[1].shows_center()); } +/// A version 8 file's object tags open as each object's URL and data. +#[test] +fn a_legacy_files_object_tags_open_as_urls_and_data() { + let body = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Tags) Ln\n0 A\n0 0 0 1 k\n{}\n/AdobeURL (https://example.com) XT\n/sku (B-7) XT\n\ + u\n{}\nU\n/part () XT\nLB\n%AI5_EndLayer--\n", + tri(10), + tri(40) + ); + let r = import(&ai(AI8, "", &body)).unwrap(); + let kids = r.document.layers[0].children().unwrap(); + let attrs: Vec<_> = kids.iter().map(|n| n.extras().attrs.as_deref().map(|a| (a.url.clone(), a.data.clone()))).collect(); + assert_eq!( + attrs, + [Some(("https://example.com".into(), vec![("sku".into(), "B-7".into())])), Some((String::new(), vec![("part".into(), String::new())]))], + "{:?}", + r.warnings + ); +} + #[test] fn unbalanced_and_runaway_groups_are_read_safely() { // Ends without a beginning end nothing; groups left open hold the rest. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index a571774262..c32ab0c592 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -419,6 +419,18 @@ fn group_with_only_placed_file_without_preview_uses_page_art() { assert!(notes.iter().any(|n| n.contains("placed files (1)")), "{notes:?}"); } +/// A linked image whose pixels the editing data doesn't keep (`XF`) shows a placeholder where the +/// PDF part draws the image: the layers are compared with the PDF part there, and the file comes in +/// as its PDF part when they differ. +#[test] +fn a_linked_image_without_pixels_is_compared_with_the_pdf_part() { + let linked = "%AI5_File:\n%AI5_BeginRaster\n(photo.tif) 0 XG\n[ 10 0 0 10 50 54 ] 0 0 4 4 4 4 8 3 0 0 0 0 XF\n%AI5_EndRaster"; + let art = native(&(layer("Live", true, &square(10, 10)) + &layer("Linked", true, linked))); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_two_squares(), vec![], false, false, 1.0); + assert!(!read, "{notes:?}"); + assert_eq!(names(&doc), ["Layer 1"]); +} + #[test] fn top_level_pattern_uses_page_art_beside_live_path() { let body = format!("(Absent) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}\n{}", square_path(50, 10), square(70, 10)); @@ -1366,6 +1378,114 @@ fn an_ai_brush_library_without_layers_keeps_its_brushes() { assert!(d.pattern("Dots").is_some_and(|p| !p.art.is_empty()), "the pattern the brush's art paints with"); } +/// An art style that strokes with black at `width` units, after the effects `effects` (filters as +/// the format writes them), as the format writes it. +fn stroke_art_style(name: &str, width: f64, effects: &str) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{effects}\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n" + ) +} + +/// The art styles and the style list of a graphic style library: Thin, Medium and Thick, listed in +/// that order, 1, 2 and 3 units wide, Medium after an Offset Path of 4 units, and Unlisted, which +/// the list leaves out, with Thin listed twice. +fn style_list() -> String { + let offset = "/BasicFilter :\n(Adobe Offset Path) 1 0 /Filter ,\n1 /Visible ,\n(OffsetPath.aip) /PluginFileName ,\n(Offset Path) /Title ,\n\ + /Dictionary : /NotRecorded ,\n4 /Real (ofst) ,\n6 /Real (mlim) ,\n1 /Int (jntp) ,\n; /Dict ;\n /Part ,\n"; + format!( + "%AI9_BeginArtStyles\n{}{}{}{}%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(Thin)\n(Medium)\n(Thick)\n(Thin)\n%AI9_EndArtStyleList\n", + stroke_art_style("Thick", 3.0, ""), + stroke_art_style("Unlisted", 4.0, ""), + stroke_art_style("Thin", 1.0, ""), + stroke_art_style("Medium", 2.0, offset) + ) +} + +/// The offset of each Offset Path in the graphic styles of `d`. +fn style_offsets(d: &Document) -> Vec { + let effects = d.graphic_styles.iter().flat_map(|g| &g.appearance.effects); + effects.filter(|e| e.id == "path.offsetPath").filter_map(|e| e.params["offset"].as_f64()).collect() +} + +/// A graphic style library (the art styles and list of [`style_list`], and no layers) with the +/// editing data's setup `setup` before them. +fn style_library(setup: &str) -> String { + let styles = style_list(); + format!("%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%BeginSetup\n{setup}{styles}%%EndSetup\n%%PageTrailer\n%%Trailer\n") +} + +/// A graphic style library (art styles and their list, no layers) comes in as its PDF part with the +/// library's graphic styles in place of the default ones, in the list's order: Other Library lists them. +#[test] +fn an_ai_graphic_style_library_without_layers_keeps_its_styles() { + let (d, warnings, read) = crate::layered_ai(&private(&style_library("")), pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(!read, "{warnings:?}"); + let styles: Vec<(&str, u32, f64)> = d.graphic_styles.iter().map(|g| (g.name.as_str(), g.id, g.appearance.stroke_width())).collect(); + assert_eq!(styles, [("Thin", 1, 1.0), ("Medium", 2, 2.0), ("Thick", 3, 3.0)], "{warnings:?}"); + assert_eq!(style_offsets(&d), [4.0]); + assert!(warnings.is_empty(), "{warnings:?}"); + // Without a style list, the default styles stay. + let (d, warnings, _) = crate::layered_ai(&private(&native("")), pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert_eq!(d.graphic_styles, Document::new(1.0, 1.0).graphic_styles, "{warnings:?}"); +} + +/// A graphic style library whose artboard is its page in the units of a `UserUnit` of 10 comes in +/// with its styles' stroke weights and effects ten times as large, as the page's art is; one whose +/// artboard is the page in points keeps them. Without a `UserUnit`, a Large Canvas library whose +/// artboard is the page at its declared scale of 10 comes in with them ten times as large too. +#[test] +fn an_ai_graphic_style_library_in_the_units_of_a_user_unit_page_comes_in_at_the_pages_size() { + let board = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let widths = |d: &Document| d.graphic_styles.iter().map(|g| g.appearance.stroke_width()).collect::>(); + let page = in_points(pdf_part(10.0, 86.0), 10.0); + let (d, warnings, read) = crate::layered_ai(&private(&style_library(board)), page, vec![], false, true, 10.0); + assert!(!read, "{warnings:?}"); + assert_eq!(widths(&d), [10.0, 20.0, 30.0], "{warnings:?}"); + assert_eq!(style_offsets(&d), [40.0]); + let points = board.replace("0 100 /Real", "0 1000 /Real").replace("100 0 /Real", "1000 0 /Real"); + let page = in_points(pdf_part(10.0, 86.0), 10.0); + let (d, warnings, _) = crate::layered_ai(&private(&style_library(&points)), page, vec![], false, true, 10.0); + assert_eq!(widths(&d), [1.0, 2.0, 3.0], "{warnings:?}"); + assert_eq!(style_offsets(&d), [4.0]); + let large = format!("%AI24_LargeCanvasScale: 10\n{board}"); + let page = in_points(pdf_part(10.0, 86.0), 10.0); + let (d, warnings, _) = crate::layered_ai(&private(&style_library(&large)), page, vec![], false, true, 1.0); + assert_eq!(widths(&d), [10.0, 20.0, 30.0], "{warnings:?}"); + assert_eq!(style_offsets(&d), [40.0]); +} + +/// An EPS whose editing copy has graphic styles and no layers comes in as its page with those +/// styles, at the page's size when the copy is a Large Canvas one. +#[test] +fn an_eps_without_layers_keeps_its_graphic_styles() { + let r = import(&eps(&page_square(50, 50), &style_library(""))).unwrap(); + let names: Vec<&str> = r.document.graphic_styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Thin", "Medium", "Thick"], "{:?}", r.warnings); + let r = import(&eps(&page_square(50, 50), &style_library("%AI24_LargeCanvasScale: 10\n"))).unwrap(); + let widths: Vec = r.document.graphic_styles.iter().map(|g| g.appearance.stroke_width()).collect(); + assert_eq!(widths, [10.0, 20.0, 30.0], "{:?}", r.warnings); + assert_eq!(style_offsets(&r.document), [40.0]); +} + +/// A `.ai` that comes in as its PDF part, and an EPS that comes in as its page, because their +/// layers can't be used (their editing data is for another page) get the graphic styles of their +/// editing data's style list in place of the default ones. +#[test] +fn a_file_whose_layers_cant_be_used_keeps_its_graphic_styles() { + let art = native(&format!("{}{}", style_list(), layer("Art", true, &square(10, 10)))).replace(" 0 0 100 100", " 0 0 600 400"); + let names = |d: &Document| d.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let (d, warnings, read) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, false, 1.0); + assert!(!read && warnings.iter().any(|w| w.contains("600 × 400")), "{warnings:?}"); + assert_eq!(names(&d), ["Thin", "Medium", "Thick"], "{warnings:?}"); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("600 × 400")), "{:?}", r.warnings); + assert_eq!(names(&r.document), ["Thin", "Medium", "Thick"], "{:?}", r.warnings); +} + /// A PDF part whose tiling has the name of a pattern its editing data defines (the PDF part names /// its tilings `Pattern 1`, `Pattern 2` and so on): the editing data's pattern comes in under a free /// variant of the name, and the palette's swatch and the brush's art paint with it, not with the @@ -2165,6 +2285,99 @@ fn an_ai_file_read_as_its_pdf_part_keeps_its_artboard_layout() { assert!((moved[1] - vectorcraft_geom::Point::new(100.0, 1600.0)).hypot() < 1e-6, "the second's art goes with its page: {moved:?}"); } +/// A `.ai` read as its PDF part opens on the page of the artboard its editing data names as the +/// active one (`CropAreaActive`), also when the reading stops before the artboards. +#[test] +fn an_ai_file_read_as_its_pdf_part_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 + ) + }; + // `before` in the document's data, before the artboards; an operator this doesn't know, so the + // layers aren't read. + let unread = |before: &str, active: &str| { + let boards = format!( + "%_/Document :\n%_/Dictionary :\n{before}%_/Array :\n{}{}%_; (ArtboardArray) ,\n{active}%_; /NotRecorded ,\n%_;\n", + board(0), + board(120) + ); + native(&(boards + &layer("Art", true, &(square(10, 10) + "\n1 Zz")))) + }; + 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); + let opened = |before: &str, active: &str| { + let (d, w, read) = crate::layered_ai(&private(&unread(before, active)), pdf.clone(), vec![], false, false, 1.0); + assert!(!read && w.iter().any(|w| w.contains("layers weren't read")), "{w:?}"); + d.opened_artboard + }; + let stops = "%_/Array :\n%_/Dictionary :\nLB\n"; + // Another entry, a dictionary of its own, between the array and the entry. + let between = "%_/Dictionary :\n%_1 /Int (Other) ,\n%_; (Inner) ,\n%_1 /Int (CropAreaActive) ,\n"; + for before in ["", stops] { + assert_eq!(opened(before, "%_1 /Int (CropAreaActive) ,\n"), Some(2), "{before}"); + assert_eq!(opened(before, between), Some(2), "{before}"); + assert_eq!(opened(before, "%_0 /Int (CropAreaActive) ,\n"), None, "{before}"); + assert_eq!(opened(before, ""), None, "{before}"); + // A `CropAreaActive` of a dictionary inside the holder is not the holder's. + assert_eq!(opened(before, "%_/Dictionary :\n%_1 /Int (CropAreaActive) ,\n%_; (Inner) ,\n"), None, "{before}"); + } + // The entry before the array, after what stops the reading. + assert_eq!(opened(&format!("{stops}%_; ,\n%_; (Art) ,\n%_1 /Int (CropAreaActive) ,\n"), ""), Some(2)); + // What stops the reading between the array and the entry. + assert_eq!(opened("", "%_/Dictionary :\nLB\n%_; (Inner) ,\n%_1 /Int (CropAreaActive) ,\n"), Some(2)); + // Lines ended by carriage returns. + let (d, ..) = + crate::layered_ai(&private(&unread(stops, "%_1 /Int (CropAreaActive) ,\n").replace('\n', "\r")), pdf.clone(), vec![], false, false, 1.0); + 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::>(), pdf.artboards.iter().map(|a| a.rect).collect::>()); + 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 @@ -2358,6 +2571,53 @@ fn type_from_the_text_document_takes_its_character_styles_attributes() { assert_eq!(style(2), (solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Some(18.0)), "the run's own colour"); } +/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character +/// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large +/// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point +/// indent) and the base attributes at the page's, so the type comes in at 12 points with a 6-point +/// indent. +#[test] +fn a_story_without_runs_takes_the_normal_styles() { + let own_style = "/5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >>"; + let doc = text_document(&[("Plain\r", 0, (8191.5, 8191.5), (0.0, 0.0), 0.0), ("Runs\r", 0, (8191.5, 8190.5), (0.0, -1.0), 0.0)]) + // The first story has no runs. + .replacen(&format!("/6 << /0 [ << /0 << /0 << /0 () {own_style} >> >> /1 6 >> ] >> "), "", 1) + .replacen("/5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 6 >> ] >> ", "", 1) + // The second story's runs name no style. + .replacen(own_style, "/6 << /0 0 >>", 1) + .replacen("/5 << /0 0 >> /6 0", "/5 << /0 0 >>", 1) + // The document's base attributes: 12 points, white, a 60-point indent, hyphenated. + .replacen("/2 << /1 12.0 >>", "/2 << /1 12.0 /53 << /99 /SimplePaint /0 << /0 0 /1 [ 1.0 1.0 ] >> >> >> /3 << /1 60.0 /9 true >>", 1) + // The normal styles: 1.2 art units, blue; a 0.6 art unit indent, not hyphenated. + .replacen( + "/0 << /1 <<", + "/0 << /5 << /0 [ << /0 << /0 ([Normal Character Style]) /6 << /0 0 /1 1.2 \ + /53 << /99 /SimplePaint /0 << /0 1 /1 [ 1.0 0.0 0.0 1.0 ] >> >> >> >> >> ] >> \ + /6 << /0 [ << /0 << /0 ([Normal Paragraph Style]) /5 << /1 0.6 /9 false >> >> >> ] >> /1 <<", + 1, + ); + assert!(!doc.contains("/1 14.0") && !doc.contains("/6 0 "), "{doc}"); + // A 10 × 10 unit copy of the page's 100 × 100 points, its template box centered at (5, 5). + let art = native_with_text( + &(layer("Back", true, "0 0 1 0 k\n5 5 m\n5.4 5 L\n5.4 5.4 L\n5 5.4 L\nf") + &layer("Spare", false, &(text_object(0) + &text_object(1)))), + &doc, + ) + .replace("0 0 100 100", "0 0 10 10") + .replace("%AI3_TemplateBox: 50 50 50 50\n", "%AI3_TemplateBox: 5 5 5 5\n%AI24_LargeCanvasScale: 10\n"); + let r = import(&eps(&page_square(50, 50), &art)).unwrap(); + assert_eq!(names(&r.document), ["Back", "Spare"], "{:?}", r.warnings); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.iter().map(|t| t.plain_text()).collect::>(), ["Plain", "Runs"], "{:?}", r.warnings); + let [.., e, f] = texts[0].xf.as_coeffs(); + assert!((e - 50.0).abs() < 1e-6 && (f - 50.0).abs() < 1e-6, "{:?}", texts[0].xf); + for t in texts { + let style = &t.runs[0].style; + assert!((style.size - 12.0).abs() < 1e-9, "{}: {}", t.plain_text(), style.size); + assert_eq!(style.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "{}", t.plain_text()); + assert!((t.para.first_line_indent - 6.0).abs() < 1e-9 && !t.para.hyphenate, "{}: {:?}", t.plain_text(), t.para); + } +} + #[test] fn type_from_the_text_document_keeps_its_case_setting() { // Key 12 of a character style is its case: 1 Small Caps, 2 All Caps. The characters stay as diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 290fe3c414..4129618027 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -150,6 +150,27 @@ pub struct LegacyAiOutput { pub warnings: Vec, } +/// 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 diff --git a/crates/eps/src/legacy_ai/prolog.rs b/crates/eps/src/legacy_ai/prolog.rs index 554447cecb..b0d606bba9 100644 --- a/crates/eps/src/legacy_ai/prolog.rs +++ b/crates/eps/src/legacy_ai/prolog.rs @@ -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 diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 617aa54552..851228ea6d 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -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, 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 = "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 = 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); diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 1fe58d6595..ae8fddc70b 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -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 = 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"); } diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 51d2447523..c5ee02e72e 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -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; diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 64c5da6d4d..1c3143f3f6 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -751,7 +751,8 @@ impl<'a> Scene<'a> { /// The stops of a gradient with a spot ink as tints of its inks: a Separation space when every /// stop is a tint of one spot ink or paper white, else (at Level 3) a DeviceN space of the /// process inks the stops use, in CMYK order, and the spot inks, in the order the stops name - /// them. Paper white adds no ink and a gray stop is black ink. An off-center midpoint is a stop + /// them. Paper white adds no ink, a gray stop is black ink, and a spot stop's process plates + /// print with its ink. An off-center midpoint is a stop /// with the inks halfway between its two stops. `None` for a gradient without a spot ink, and, /// with a warning, for one whose inks can't be kept or that is mixed by the Perceptual method; /// it is then written in process colors. @@ -799,6 +800,10 @@ impl<'a> Scene<'a> { if let Some(i) = names.iter().position(|m| *m == n) { v[4 + i] = unit(s.tint); } + // Process plates printed with the spot ink (a DeviceN mix from a file). + if let Some(p) = s.plates { + v[..4].copy_from_slice(&p.map(unit)); + } } None if paper(&s.color) => {} None => match self.process(&s.color) { diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 2067a7d9c2..2a59f99df2 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -352,6 +352,16 @@ fn gradients_mixing_spot_inks_with_other_inks_are_device_n_shadings() { assert!(page.contains("/C0 [0 0 1] /C1 [0.6 0 0]") && page.contains("/C0 [0.6 0 0] /C1 [0 0.4 0]"), "{page}"); assert!(!out.warnings.iter().any(|w| w.contains("spot")), "{:?}", out.warnings); + // Gold Ink 0% to 100% over a constant 30% cyan plate (a DeviceN gradient read from a PDF, + // #3235): Cyan and Gold Ink. + let mut over = spot_stop(1.0, "Gold Ink", GOLD, 1.0); + over.plates = Some([0.3, 0.0, 0.0, 0.0]); + let plated = spot_gradient_doc(vec![GradientStop::new(0.0, Color::cmyk(0.3, 0.0, 0.0, 0.0)), over]); + let out = export(&plated, &opts(&plated), None, None).unwrap(); + let ps = text(&out); + assert!(ps.contains("/VCdn0 [/DeviceN [/Cyan (Gold Ink) cvn ] /DeviceCMYK {2 array astore"), "{ps}"); + assert!(checked_page(&ps).contains("/C0 [0.3 0] /C1 [0.3 1]"), "{ps}"); + // Read back as bands, the tint transforms give each ink's CMYK equivalent. for (d, end) in [(&two, [0.5, 0.0, 0.5, 0.0]), (&mixed, [0.0, 0.0, 0.0, 0.4])] { let out = export(d, &EpsOptions { compatible_gradients: true, ..opts(d) }, None, None).unwrap(); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 65c10ba802..f82cd4eb1b 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -251,8 +251,11 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { if version < 3 { d.store_legacy_color_profiles(); } - // Apps that read only older file versions predate 0.21.0 and turn Twist the other way. + // Apps before this one's version take Color Halftone's Max Radius in points (#3260), and + // predate 0.21.0, turning Twist the other way. The radii first: their conversion runs only on + // a document of version 3 or later, and the Twist one then marks it version 1. if version < VERSION { + d.halftone_radii_to_points(); d.store_legacy_twist_angles(); } let v1 = if version == 1 { @@ -547,6 +550,8 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result doc.migrate_overprint_black(); // Saved before v3: the assigned profiles move out of `unknown`. doc.migrate_color_profiles(); + // A document before version 3: Color Halftone's Max Radius in points becomes pixels (#3260). + doc.migrate_halftone_radii(); doc.fix_next_id(); // Untrusted: the bleed and type proportions, within the ranges Document Setup takes. doc.setup.keep_in_range(); @@ -839,6 +844,49 @@ mod tests { use vectorcraft_doc::{Appearance, ImageObject, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect, shapes}; + /// Color Halftone's Max Radius is in pixels of the raster effects resolution since document + /// version 3 (#3260): a file from before (version 1, or version 2 from 0.21.0 on) opens with + /// its radius in points converted, one saved since opens as it was. At 72 ppi a point is a + /// pixel, so the number stays. + #[test] + fn halftone_radii_of_older_documents_open_in_pixels() { + for ppi in [72.0, 300.0] { + let mut d = Document::new(100.0, 100.0); + d.raster_effects_ppi = ppi; + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut look = Appearance::default_art(); + look.effects.push(vectorcraft_doc::Effect { + id: "pixelate.colorHalftone".into(), + params: serde_json::json!({"maxRadius": 8.0}), + visible: true, + }); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), look)).unwrap(); + let radius = |d: &Document| d.node(id).unwrap().appearance.effects[0].params["maxRadius"].as_f64().unwrap(); + assert_eq!(radius(&load(&save(&d, false)).unwrap()), 8.0, "{ppi} ppi: saved in pixels, opened in pixels"); + // Version 2 (0.21.0's Twist) still held the radius in points. + d.version = 2; + let v2 = load(&save(&d, false)).unwrap(); + assert!((radius(&v2) - 8.0 * ppi / 72.0).abs() < 1e-9, "version 2, 8 pt at {ppi} ppi: {}", radius(&v2)); + d.version = 1; + let old = load(&save(&d, false)).unwrap(); + assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION); + assert!((radius(&old) - 8.0 * ppi / 72.0).abs() < 1e-9, "8 pt at {ppi} ppi: {}", radius(&old)); + // Saved for an older app, in every older version: the radius in points, which opens + // here in pixels again. + let px = radius(&old); + for version in MIN_VERSION..VERSION { + let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); + let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap(); + let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len(); + let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap(); + assert!((saved - 8.0).abs() < 1e-9, "{ppi} ppi, version {version} holds 8 pt: {saved}"); + let back = load(&bytes).unwrap(); + assert!((radius(&back) - px).abs() < 1e-9, "{ppi} ppi, version {version}: {}", radius(&back)); + } + assert_eq!(radius(&old), px, "{ppi} ppi: saving leaves the open document as it is"); + } + } + #[test] fn roundtrip() { let mut d = Document::new(100.0, 100.0); @@ -909,8 +957,8 @@ mod tests { /// A version 1 document written before VectorCraft 0.21.0 (or by an app the file does not /// name) has its Twist angles negated when it opens; one written by 0.21.0 or later, and a - /// version 2 document, keep them. Each opens as version 2. A save for an older file version - /// negates them back. + /// later document, keep them. Each opens as the current version. A save for an older file + /// version negates them back. #[test] fn twist_angles_follow_the_document_version_and_generator() { use vectorcraft_doc::Effect; @@ -921,9 +969,14 @@ mod tests { a.effects.push(Effect { id: "distort.twist".into(), params: serde_json::json!({"angle": 30.0}), visible: true }); d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), a)).unwrap(); let angle = |d: &Document| d.node(id).and_then(|n| n.appearance.effects[0].params["angle"].as_f64()); + let now = vectorcraft_doc::FORMAT_VERSION; let current = save(&d, false); let back = load(¤t).unwrap(); - assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "a version 2 document is read as saved"); + assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "a current document is read as saved"); + let mut v2: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + v2["document"]["version"] = 2.into(); + let back = load(&serde_json::to_vec(&v2).unwrap()).unwrap(); + assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "a version 2 document keeps its angles"); let opened = |generator: Option<&str>| { let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); v["document"]["version"] = 1.into(); @@ -937,10 +990,10 @@ mod tests { (d.version, angle(&d)) }; for g in [Some("VectorCraft 0.20.0"), Some("VectorCraft 0.9.12"), Some("DrawCraft 0.1.0"), Some("VectorCraft"), None] { - assert_eq!(opened(g), (2, Some(-30.0)), "{g:?}"); + assert_eq!(opened(g), (now, Some(-30.0)), "{g:?}"); } for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.3", "VectorCraft 1.0.0"] { - assert_eq!(opened(Some(g)), (2, Some(30.0)), "{g}"); + assert_eq!(opened(Some(g)), (now, Some(30.0)), "{g}"); } // A file may repeat `generator`: the first one names the app. let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); @@ -954,7 +1007,7 @@ mod tests { v["generator"] = "VectorCraft 0.20.0".into(); let old = load(&serde_json::to_vec(&v).unwrap()).unwrap(); let again = load(&save(&old, false)).unwrap(); - assert_eq!((again.version, angle(&again)), (2, Some(-30.0)), "saved again, it is version 2"); + assert_eq!((again.version, angle(&again)), (now, Some(-30.0)), "saved again, it is the current version"); // Saved for an older file version (apps before 0.21.0): version 1 with the angle negated // back, whatever the generator, and it reopens as it was. for version in MIN_VERSION..VERSION { @@ -963,7 +1016,7 @@ mod tests { assert_eq!(v["document"]["version"], 1, "file version {version}"); assert!(String::from_utf8_lossy(&bytes).contains(r#""angle":-30.0"#), "file version {version}"); let back = load(&bytes).unwrap(); - assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "file version {version}"); + assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "file version {version}"); } } diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index b1847d9ce3..59a8f30660 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -547,17 +547,38 @@ impl PathData { /// Tight geometric bounds (curve extrema, not control points), measured by [`curve_bounds`]: a /// segment with a control point that is not finite or past `f64::MAX / 16` in x or y is measured /// by its control points. + /// + /// Walks the segments in place, without building the path: the same segments in the same order, + /// so the result is bit for bit `curve_bounds(&self.to_bezpath())` (a path of lone anchors, with + /// no segment, is `Rect::ZERO`, as there). pub fn bounds(&self) -> Option { if self.is_empty() { return None; } - let bp = self.to_bezpath(); if self.anchor_count() == 1 && let Some(a) = self.subpaths.iter().find_map(|s| s.anchors.first()) { return Some(Rect::from_points(a.p, a.p)); } - Some(curve_bounds(&bp)) + let mut bbox: Option = None; + for sp in &self.subpaths { + for i in 0..sp.segment_count() { + let c = sp.segment(i); + // `to_bezpath_into` writes a line where neither handle is out, else a cubic. + let seg = segment_bounds(if sp.segment_is_line(i) { PathSeg::Line(kurbo::Line::new(c.p0, c.p3)) } else { PathSeg::Cubic(c) }); + bbox = Some(bbox.map_or(seg, |bb| bb.union(seg))); + } + // A closed subpath's last segment ends on its first anchor, so its `ClosePath` adds no + // line, unless that anchor is NaN: it then differs from itself, and kurbo closes with one. + if sp.closed + && let Some(a) = sp.anchors.first() + && (a.p.x.is_nan() || a.p.y.is_nan()) + { + let seg = segment_bounds(PathSeg::Line(kurbo::Line::new(a.p, a.p))); + bbox = Some(bbox.map_or(seg, |bb| bb.union(seg))); + } + } + Some(bbox.unwrap_or_default()) } /// Bounds including control handles (used for quick culling). pub fn control_bounds(&self) -> Option { @@ -720,6 +741,48 @@ fn push_curve(cur: &mut Option, last: Point, c1: Point, c2: Point, p: P mod tests { use super::*; + /// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives, + /// for lines, curves, open and closed subpaths, lone anchors and empty subpaths. + #[test] + fn bounds_match_the_bezpath_bit_for_bit() { + use proptest::prelude::*; + fn reference(pd: &PathData) -> Option { + if pd.is_empty() { + return None; + } + if pd.anchor_count() == 1 { + let a = pd.subpaths.iter().find_map(|s| s.anchors.first())?; + return Some(Rect::from_points(a.p, a.p)); + } + Some(curve_bounds(&pd.to_bezpath())) + } + let bits = |r: Option| r.map(|r| [r.x0, r.y0, r.x1, r.y1].map(f64::to_bits)); + let coord = || prop_oneof![(-1e3f64..1e3), Just(0.0), Just(1e-300), Just(-7.25)]; + let pt = move || (coord(), coord()).prop_map(|(x, y)| Point::new(x, y)); + // Handles retracted (equal to the anchor) a third of the time: lines and curves mix. + let handle = move || prop_oneof![Just(None), pt().prop_map(Some)]; + let anchor = + (pt(), handle(), handle()).prop_map(|(p, i, o)| Anchor { p, h_in: i.unwrap_or(p), h_out: o.unwrap_or(p), kind: AnchorKind::Corner }); + let sub = (proptest::collection::vec(anchor, 0..6), any::()).prop_map(|(a, c)| SubPath::new(a, c)); + let path = proptest::collection::vec(sub, 0..4).prop_map(PathData::new); + proptest!(ProptestConfig::with_cases(2000), |(pd in path)| { + prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + }); + // Two lone anchors: no segment, as the path has none. + let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]); + assert_eq!(lone.bounds(), Some(Rect::ZERO)); + assert_eq!(bits(lone.bounds()), bits(reference(&lone))); + // A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own. + let nan = Point::new(f64::NAN, 1.0); + let closed = |pts: &[Point]| SubPath::polyline(pts, true); + for pd in [ + PathData::new(vec![closed(&[nan]), closed(&[Point::new(5.0, 5.0)])]), + PathData::new(vec![closed(&[nan, Point::new(3.0, 4.0), Point::new(6.0, 1.0)])]), + ] { + assert_eq!(bits(pd.bounds()), bits(reference(&pd))); + } + } + fn square() -> PathData { PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true)) } diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 2747fdf45a..d66ab38606 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -103,15 +103,44 @@ pub fn ellipse(r: Rect) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// How an ellipse or shape arc is closed or left open when cut between start and end angles. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EllipseMode { + /// Closed sector through the centre (pie slice). + #[default] + Slice, + /// Open arc curve without closing segments. + Arc, + /// Closed arc with a straight chord connecting the end back to the start. + Chord, + /// Whole closed shape (ignores start/end cut). + Whole, +} + /// The ellipse inscribed in `r` cut as a pie: from `start` to `end` degrees, measured /// counterclockwise on screen from 3 o'clock (as Illustrator's Pie Start and End Angle are), then /// back through the centre. A pie spanning the whole turn (or nothing) is the whole [`ellipse`]. /// The arc is one cubic per quarter turn at most: the centre, then the arc's anchors. pub fn ellipse_pie(r: Rect, start: f64, end: f64) -> PathData { - let span = (end - start).rem_euclid(360.0); - if !(start.is_finite() && end.is_finite()) || span < 1e-9 || 360.0 - span < 1e-9 { + ellipse_arc(r, start, end, EllipseMode::Slice) +} + +/// The ellipse inscribed in `r` cut from `start` to `end` degrees according to `mode`: +/// - [`EllipseMode::Slice`]: closed through the centre (pie chart). +/// - [`EllipseMode::Chord`]: closed with a straight chord between the endpoints. +/// - [`EllipseMode::Arc`]: open elliptical arc (no centre lines, `closed = false`). +/// - [`EllipseMode::Whole`]: full closed [`ellipse`]. +pub fn ellipse_arc(r: Rect, start: f64, end: f64, mode: EllipseMode) -> PathData { + if mode == EllipseMode::Whole || !(start.is_finite() && end.is_finite()) { return ellipse(r); } + let raw_span = (end - start).rem_euclid(360.0); + let full = raw_span < 1e-9 || 360.0 - raw_span < 1e-9; + if full && mode != EllipseMode::Arc { + return ellipse(r); + } + let span = if full { 360.0 } else { raw_span }; let r = r.abs(); let c = r.center(); let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); @@ -135,7 +164,10 @@ pub fn ellipse_pie(r: Rect, start: f64, end: f64) -> PathData { }; let step = span / f64::from(pieces); let k = 4.0 / 3.0 * (step.to_radians() / 4.0).tan(); - let mut anchors = vec![Anchor::corner(c)]; + let mut anchors = Vec::with_capacity(pieces as usize + 2); + if mode == EllipseMode::Slice { + anchors.push(Anchor::corner(c)); + } for i in 0..=pieces { let a = start + step * f64::from(i); let (p, d) = (at(a), tangent(a) * k); @@ -144,6 +176,123 @@ pub fn ellipse_pie(r: Rect, start: f64, end: f64) -> PathData { let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth }; anchors.push(Anchor { p, h_in, h_out, kind }); } + let closed = mode != EllipseMode::Arc; + PathData::single(SubPath::new(anchors, closed)) +} + +/// Cut or open any closed single-subpath `path` around `center` from `start_deg` to `end_deg` +/// according to `mode` ([`EllipseMode::Slice`], [`EllipseMode::Arc`], [`EllipseMode::Chord`], +/// [`EllipseMode::Whole`]). +pub fn apply_shape_arc(path: PathData, center: Point, start_deg: f64, end_deg: f64, mode: EllipseMode) -> PathData { + use kurbo::{BezPath, ParamCurve}; + if mode == EllipseMode::Whole || !(start_deg.is_finite() && end_deg.is_finite()) { + return path; + } + let Some(sp) = path.subpaths.first() else { + return path; + }; + let n = sp.segment_count(); + if !sp.closed || n == 0 { + return path; + } + let raw_span = (end_deg - start_deg).rem_euclid(360.0); + let full = raw_span < 1e-9 || 360.0 - raw_span < 1e-9; + if full { + if mode == EllipseMode::Arc { + let mut open_sp = sp.clone(); + open_sp.closed = false; + return PathData::single(open_sp); + } + return path; + } + let u0 = start_deg.rem_euclid(360.0) / 360.0; + let du = (raw_span / 360.0).clamp(1e-6, 1.0 - 1e-6); + let s0 = u0 * (n as f64); + let s1 = (u0 + du) * (n as f64); + let k0 = (s0.floor() as usize).min(n.saturating_sub(1)); + let t0 = (s0 - k0 as f64).clamp(0.0, 1.0); + let k1 = s1.floor() as usize; + let t1 = (s1 - k1 as f64).clamp(0.0, 1.0); + let mut cubics = Vec::new(); + if k0 == k1 { + if t1 > t0 + 1e-9 { + cubics.push(sp.segment(k0 % n).subsegment(t0..t1)); + } + } else { + if t0 < 1.0 - 1e-9 { + cubics.push(sp.segment(k0 % n).subsegment(t0..1.0)); + } + for k in (k0 + 1)..k1 { + cubics.push(sp.segment(k % n)); + } + if t1 > 1e-9 { + cubics.push(sp.segment(k1 % n).subsegment(0.0..t1)); + } + } + let Some(first) = cubics.first() else { + return path; + }; + let mut bp = BezPath::new(); + if mode == EllipseMode::Slice { + bp.move_to(center); + bp.line_to(first.p0); + } else { + bp.move_to(first.p0); + } + for c in &cubics { + if c.p0.distance(c.p1) <= 1e-9 && c.p3.distance(c.p2) <= 1e-9 { + bp.line_to(c.p3); + } else { + bp.curve_to(c.p1, c.p2, c.p3); + } + } + if mode != EllipseMode::Arc { + bp.close_path(); + } + PathData::from_bezpath(&bp) +} + +/// Deterministic vertex jitter for `randomized` polygons and stars (`(dr, da)` in `[-1, 1]`). +fn vertex_jitter(index: u32, total: u32) -> (f64, f64) { + let mut s = 0x9e37_79b9_7f4a_7c15_u64 + .wrapping_add((u64::from(index) + 1).wrapping_mul(0xbf58_476d_1ce4_e5b9)) + .wrapping_add(u64::from(total).wrapping_mul(0x94d0_49bb_1331_11eb)); + let mut next = || { + s ^= s >> 12; + s ^= s << 25; + s ^= s >> 27; + let v = s.wrapping_mul(0x2545_f491_4f6c_dd1d); + ((v >> 11) as f64 / ((1u64 << 53) as f64)) * 2.0 - 1.0 + }; + (next(), next()) +} + +/// Build a closed subpath from polygon/star vertices with optional smooth bezier `rounded` +/// tangents (`-10..=10`). +fn contour_with_rounding(pts: &[Point], rounded: f64) -> PathData { + let n = pts.len(); + if n == 0 || !rounded.is_finite() || rounded.abs() < 1e-9 { + return PathData::single(SubPath::polyline(pts, true)); + } + let r_factor = rounded.clamp(-10.0, 10.0) * 0.4; + let mut anchors = Vec::with_capacity(n); + for i in 0..n { + let p_prev = pts[(i + n - 1) % n]; + let p = pts[i]; + let p_next = pts[(i + 1) % n]; + let v_in = p - p_prev; + let v_out = p_next - p; + let len_in = v_in.hypot(); + let len_out = v_out.hypot(); + let u_in = if len_in > 1e-9 { v_in / len_in } else { Vec2::ZERO }; + let u_out = if len_out > 1e-9 { v_out / len_out } else { Vec2::ZERO }; + let sum = u_in + u_out; + let sum_len = sum.hypot(); + let tangent = if sum_len > 1e-9 { sum / sum_len } else { Vec2::new(-u_in.y, u_in.x) }; + let h_in = p - tangent * (len_in * r_factor); + let h_out = p + tangent * (len_out * r_factor); + anchors.push(Anchor { p, h_in, h_out, kind: AnchorKind::Smooth }); + } PathData::single(SubPath::new(anchors, true)) } @@ -160,6 +309,26 @@ pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> Pat PathData::single(SubPath::polyline(&pts, true)) } +/// Regular polygon with `sides` (≥ 3), bezier tangent `rounded` factor and deterministic +/// `randomized` vertex jitter. +pub fn polygon_configured(center: Point, radius: f64, sides: u32, rotation_deg: f64, rounded: f64, randomized: f64) -> PathData { + if (!rounded.is_finite() || rounded.abs() < 1e-9) && (!randomized.is_finite() || randomized.abs() < 1e-9) { + return polygon(center, radius, sides.clamp(3, 1000), rotation_deg); + } + let n = sides.clamp(3, 1000); + let rot = if rotation_deg.is_finite() { rotation_deg.to_radians() } else { 0.0 }; + let rand_amt = if randomized.is_finite() { randomized.clamp(0.0, 10.0) } else { 0.0 }; + let pts: Vec = (0..n) + .map(|i| { + let (dr, da) = if rand_amt > 1e-9 { vertex_jitter(i, n) } else { (0.0, 0.0) }; + let r = (radius * (1.0 + rand_amt * 0.45 * dr)).max(0.01); + let a = -PI / 2.0 + rot + TAU * (i as f64 / n as f64) + rand_amt * (PI / n as f64) * da; + Point::new(center.x + r * a.cos(), center.y + r * a.sin()) + }) + .collect(); + contour_with_rounding(&pts, rounded) +} + /// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, first tip up. pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData { let n = points.max(2) * 2; @@ -174,6 +343,27 @@ pub fn star(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64) -> PathData::single(SubPath::polyline(&pts, true)) } +/// Star with `points` tips (≥ 2), outer radius `r1`, inner radius `r2`, bezier tangent `rounded` +/// factor and deterministic `randomized` vertex jitter. +pub fn star_configured(center: Point, r1: f64, r2: f64, points: u32, rotation_deg: f64, rounded: f64, randomized: f64) -> PathData { + if (!rounded.is_finite() || rounded.abs() < 1e-9) && (!randomized.is_finite() || randomized.abs() < 1e-9) { + return star(center, r1, r2, points.clamp(2, 1000), rotation_deg); + } + let n = points.clamp(2, 1000) * 2; + let rot = if rotation_deg.is_finite() { rotation_deg.to_radians() } else { 0.0 }; + let rand_amt = if randomized.is_finite() { randomized.clamp(0.0, 10.0) } else { 0.0 }; + let pts: Vec = (0..n) + .map(|i| { + let base_r = if i % 2 == 0 { r1 } else { r2 }; + let (dr, da) = if rand_amt > 1e-9 { vertex_jitter(i, n) } else { (0.0, 0.0) }; + let r = (base_r * (1.0 + rand_amt * 0.45 * dr)).max(0.01); + let a = -PI / 2.0 + rot + TAU * (i as f64 / n as f64) + rand_amt * (PI / n as f64) * da; + Point::new(center.x + r * a.cos(), center.y + r * a.sin()) + }) + .collect(); + contour_with_rounding(&pts, rounded) +} + /// Inner radius of a "straight-armed" star (Illustrator's Alt-drag behaviour): shoulders aligned. pub fn straight_star_inner_radius(r1: f64, points: u32) -> f64 { let n = points.max(3) as f64; @@ -249,6 +439,137 @@ pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clo PathData::single(sp) } +/// Configurable spiral with `turns` revolutions (`0.25..=50.0`), `divergence` radial growth power +/// (`0.05..=20.0`, `1.0` = uniform Archimedean spacing) and `inner_radius` fraction (`0.0..=0.99`). +pub fn spiral_configured(center: Point, radius: f64, turns: f64, divergence: f64, inner_radius: f64, clockwise: bool) -> PathData { + let turns = if turns.is_finite() { turns.clamp(0.25, 50.0) } else { 3.0 }; + let div = if divergence.is_finite() { divergence.clamp(0.05, 20.0) } else { 1.0 }; + let inner_frac = if inner_radius.is_finite() { inner_radius.clamp(0.0, 0.99) } else { 0.0 }; + let r_outer = if radius.is_finite() { radius.abs().max(0.01) } else { 50.0 }; + let r_inner = r_outer * inner_frac; + let steps = (turns * 4.0).round().clamp(1.0, 200.0) as usize; + let dir = if clockwise { 1.0 } else { -1.0 }; + let total_angle = dir * turns * TAU; + let dtheta = (turns * TAU) / (steps as f64); + let k = if dtheta > 1e-6 { KAPPA / dtheta } else { KAPPA }; + let mut anchors = Vec::with_capacity(steps + 1); + for i in 0..=steps { + let u = (i as f64) / (steps as f64); + let theta = u * total_angle; + let f = if u <= 0.0 { 0.0 } else { u.powf(div) }; + let r = r_inner + (r_outer - r_inner) * f; + let p = Point::new(center.x + r * theta.cos(), center.y + r * theta.sin()); + let dr_du = if u > 1e-9 { + (r_outer - r_inner) * div * u.powf(div - 1.0) + } else if (div - 1.0).abs() < 1e-9 { + r_outer - r_inner + } else { + 0.0 + }; + let dx_du = dr_du * theta.cos() - r * theta.sin() * total_angle; + let dy_du = dr_du * theta.sin() + r * theta.cos() * total_angle; + let d = Vec2::new(dx_du, dy_du) * (k / (steps as f64)); + let h_in = if i == 0 { p } else { p - d }; + let h_out = if i == steps { p } else { p + d }; + anchors.push(Anchor { p, h_in, h_out, kind: AnchorKind::Smooth }); + } + PathData::single(SubPath::new(anchors, false)) +} + +/// Rotatable 3D box inscribed in `r`, rotated by `(angle_x, angle_y, angle_z)` degrees and using +/// orthographic parallel projection per axis when `parallel_*` is true or perspective foreshortening +/// when false. Emits the visible front-facing quad faces with clockwise winding. +pub fn box3d(r: Rect, angle_x: f64, angle_y: f64, angle_z: f64, parallel_x: bool, parallel_y: bool, parallel_z: bool) -> PathData { + let r = r.abs(); + if r.width() <= 1e-9 || r.height() <= 1e-9 { + return rectangle(r); + } + let rx = if angle_x.is_finite() { angle_x.to_radians() } else { 30.0_f64.to_radians() }; + let ry = if angle_y.is_finite() { angle_y.to_radians() } else { 35.0_f64.to_radians() }; + let rz = if angle_z.is_finite() { angle_z.to_radians() } else { 0.0 }; + let (sx, cx) = rx.sin_cos(); + let (sy, cy) = ry.sin_cos(); + let (sz, cz) = rz.sin_cos(); + + let transform_pt = |mut x: f64, mut y: f64, mut z: f64| -> (f64, f64, f64) { + if !parallel_x { + let k = 1.0 - 0.22 * x; + y *= k; + z *= k; + } + if !parallel_y { + let k = 1.0 - 0.22 * y; + x *= k; + z *= k; + } + // Rotate around X + let (y1, z1) = (y * cx - z * sx, y * sx + z * cx); + // Rotate around Y + let (x2, z2) = (x * cy + z1 * sy, -x * sy + z1 * cy); + // Rotate around Z + let (x3, y3) = (x2 * cz - y1 * sz, x2 * sz + y1 * cz); + let persp = if parallel_z { 1.0 } else { 1.0 / (1.0 - 0.25 * z2).max(0.2) }; + (x3 * persp, y3 * persp, z2) + }; + + let raw_verts: [(f64, f64, f64); 8] = [ + transform_pt(-1.0, -1.0, -1.0), + transform_pt(1.0, -1.0, -1.0), + transform_pt(1.0, 1.0, -1.0), + transform_pt(-1.0, 1.0, -1.0), + transform_pt(-1.0, -1.0, 1.0), + transform_pt(1.0, -1.0, 1.0), + transform_pt(1.0, 1.0, 1.0), + transform_pt(-1.0, 1.0, 1.0), + ]; + + let mut min_x = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut min_y = f64::INFINITY; + let mut max_y = f64::NEG_INFINITY; + for &(vx, vy, _) in &raw_verts { + min_x = min_x.min(vx); + max_x = max_x.max(vx); + min_y = min_y.min(vy); + max_y = max_y.max(vy); + } + let span_x = (max_x - min_x).max(1e-6); + let span_y = (max_y - min_y).max(1e-6); + let proj = |i: usize| -> Point { + let (vx, vy, _) = raw_verts[i]; + Point::new(r.x0 + (vx - min_x) / span_x * r.width(), r.y0 + (vy - min_y) / span_y * r.height()) + }; + + // 6 cube faces with outward-pointing vertex order in 3D. + const FACES: [[usize; 4]; 6] = [ + [4, 5, 6, 7], // +Z front + [1, 0, 3, 2], // -Z back + [0, 4, 7, 3], // -X left + [5, 1, 2, 6], // +X right + [0, 1, 5, 4], // -Y top + [7, 6, 2, 3], // +Y bottom + ]; + + let mut faces_with_depth: Vec<(f64, SubPath)> = Vec::new(); + for idx in FACES { + let z_avg = (raw_verts[idx[0]].2 + raw_verts[idx[1]].2 + raw_verts[idx[2]].2 + raw_verts[idx[3]].2) * 0.25; + let mut pts = [proj(idx[0]), proj(idx[1]), proj(idx[2]), proj(idx[3])]; + let mut sp = SubPath::polyline(&pts, true); + let area = sp.signed_area(); + // Outward face in camera space has positive signed area (clockwise on screen, y down). + if area > 1e-4 { + faces_with_depth.push((z_avg, sp)); + } else if faces_with_depth.is_empty() && area.abs() > 1e-4 { + pts.reverse(); + sp = SubPath::polyline(&pts, true); + faces_with_depth.push((z_avg, sp)); + } + } + faces_with_depth.sort_by(|a, b| a.0.total_cmp(&b.0)); + let subpaths: Vec = faces_with_depth.into_iter().map(|(_, sp)| sp).collect(); + if subpaths.is_empty() { rectangle(r) } else { PathData::new(subpaths) } +} + /// The largest grid divider skew, in percent either way. pub const GRID_SKEW_MAX: f64 = 500.0; @@ -628,4 +949,41 @@ mod tests { let seg = arc_segment(Point::ZERO, 0, 100.0, 50.0, true, 50.0, false); assert_eq!(seg.anchor_count(), 2); } + + #[test] + fn ellipse_arc_modes_and_configured_shapes() { + let r = Rect::new(0.0, 0.0, 100.0, 100.0); + let slice = ellipse_arc(r, 0.0, 90.0, EllipseMode::Slice); + assert!(slice.is_closed() && slice.anchor_count() == 3); + assert_eq!(slice, ellipse_pie(r, 0.0, 90.0), "ellipse_pie matches Slice mode"); + let chord = ellipse_arc(r, 0.0, 90.0, EllipseMode::Chord); + assert!(chord.is_closed() && chord.anchor_count() == 2); + let open_arc = ellipse_arc(r, 0.0, 90.0, EllipseMode::Arc); + assert!(!open_arc.is_closed() && open_arc.anchor_count() == 2); + let whole = ellipse_arc(r, 0.0, 90.0, EllipseMode::Whole); + assert_eq!(whole, ellipse(r)); + + // Rectangle opened/cut with apply_shape_arc + let rect_open = apply_shape_arc(rectangle(r), r.center(), 30.0, 300.0, EllipseMode::Arc); + assert!(!rect_open.is_closed()); + let rect_slice = apply_shape_arc(rectangle(r), r.center(), 30.0, 300.0, EllipseMode::Slice); + assert!(rect_slice.is_closed() && rect_slice.subpaths[0].anchors[0].p == r.center()); + + // Polygon and Star with rounded and randomized, and unconfigured parity + assert_eq!(polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.0, 0.0), polygon(Point::ZERO, 50.0, 6, 0.0)); + assert_eq!(star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.0, 0.0), star(Point::ZERO, 50.0, 25.0, 5, 0.0)); + let poly_round = polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.5, 0.1); + assert_eq!(poly_round.anchor_count(), 6); + assert!(poly_round.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out())); + let star_round = star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.5, 0.1); + assert_eq!(star_round.anchor_count(), 10); + + // Spiral configured + let sp = spiral_configured(Point::ZERO, 100.0, 3.0, 1.5, 0.25, true); + assert!(!sp.is_closed() && sp.anchor_count() == 13); + + // 3D Box + let b3d = box3d(r, 30.0, 35.0, 0.0, true, true, true); + assert!(!b3d.subpaths.is_empty() && b3d.subpaths.iter().all(|s| s.closed && s.anchors.len() == 4)); + } } diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 64a7f0ea1f..0a81bb127f 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -181,9 +181,11 @@ impl Headless { fn pointer(&mut self, p: &Value) -> Result { let events = p.get("events").and_then(Value::as_array).ok_or("missing `events`")?; let base: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); + let default = PointerEvent::json_backquote(p, false)?; + let held = events.iter().map(|e| PointerEvent::json_backquote(e, default)).collect::, _>>()?; self.ensure_document(); let mut requests = vec![]; - for e in events { + for (e, backquote) in events.iter().zip(held) { let kind = s(e, "kind").unwrap_or(""); let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; if s(e, "space") == Some("screen") { @@ -192,8 +194,6 @@ impl Headless { let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?; let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?; let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base); - let backquote = - e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); let ev = PointerEvent { kind, pos: Point::new(x, y), diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2e153b62b7..90df3349ec 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1431,6 +1431,34 @@ fn pointer_gesture_forwards_backquote_on_each_event() { assert_eq!(rect["bounds"]["x"], 100.0, "{doc}"); } +/// A `backquote` that is not a boolean is an error, and none of the gesture's events runs. +#[test] +fn pointer_gesture_rejects_a_backquote_that_is_not_a_boolean() { + let mut s = server(); + let made = call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 50, "height": 50, "fill": "#ff0000"})); + let id = serde_json::from_str::(&text_of(&made)).unwrap()["id"].as_u64().unwrap(); + let drag = |top: Option, first: Option| { + let mut down = json!({"kind": "down", "x": 300, "y": 300}); + if let Some(b) = first { + down["backquote"] = b; + } + let mut a = json!({"tool": "rectangle", "events": [down, {"kind": "drag", "x": 350, "y": 350}, {"kind": "up", "x": 350, "y": 350}]}); + if let Some(b) = top { + a["backquote"] = b; + } + a + }; + for (n, args) in [drag(Some(json!("true")), None), drag(None, Some(json!(1)))].into_iter().enumerate() { + let r = call(&mut s, 2 + n as u64, "pointer_gesture", args); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("`backquote` must be a boolean"), "{r}"); + } + let inspected = call(&mut s, 4, "inspect_document", json!({})); + let doc = serde_json::from_str::(&text_of(&inspected)).unwrap(); + let children = doc["layers"][0]["children"].as_array().unwrap(); + assert_eq!(children.iter().map(|n| n["id"].as_u64()).collect::>(), vec![Some(id)], "{doc}"); +} + /// A Shift-drag marquee reaches agents (#483): `pointer_gesture` with `mods.shift` toggles the /// objects it reaches, so a selected one leaves the selection and an unselected one joins it. #[test] diff --git a/crates/mcp/src/tests/exportas.rs b/crates/mcp/src/tests/exportas.rs index 679a3f554e..0d9dc5c49d 100644 --- a/crates/mcp/src/tests/exportas.rs +++ b/crates/mcp/src/tests/exportas.rs @@ -16,6 +16,24 @@ fn three_boards() -> Headless { h } +#[test] +fn raster_export_uses_document_resolution_unless_overridden() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 72, "height": 36, "rasterEffectsPpi": 300}})).unwrap(); + for (args, size) in [ + (json!({}), (300, 150)), + (json!({"scale": 1}), (72, 36)), + (json!({"options": {"scale": 2}}), (144, 72)), + (json!({"scale": 2, "options": {"ppi": 150}}), (150, 75)), + ] { + let mut params = args.clone(); + params["format"] = json!("png"); + let r = text(&call_tool(&mut h, "export", ¶ms)); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + assert_eq!(image::load_from_memory(&bytes).unwrap().to_rgba8().dimensions(), size, "{args}"); + } +} + #[test] fn export_with_a_range_writes_one_file_per_artboard() { let mut h = three_boards(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index c889c2237a..105dca3467 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -391,7 +391,7 @@ pub fn tool_definitions() -> Vec { json!({ "format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::>(), "description": "Default: from the path's extension"}, "path": string("Destination file (omit to get dataBase64)"), - "scale": num("Raster pixels per point (default 1)"), + "scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"), "artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"}, "range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF and WMF: one, or one file each with options.useArtboards: true)"), "selection": {"type": "boolean", "description": "Export only the selection, cropped to it"}, diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 9e3af3dbaa..f9d768eaa5 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -125,6 +125,12 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result PathData; // delta < 0 insets +pub fn try_offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> Result; pub fn outline_stroke(path: &PathData, width: f64, cap: Cap, join: Join, miter_limit: f64) -> PathData; ``` diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index f61ac5e488..163fe7e7ca 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -296,11 +296,15 @@ impl Tidy { } impl Arrangement { - pub(crate) fn new(mut paths: Vec<(BezPath, FillRule)>) -> Result { + pub(crate) fn new(paths: Vec<(BezPath, FillRule)>) -> Result { + Self::new_budgeted(paths, crate::budget::MAX_SEGMENT_PAIRS) + } + + pub(crate) fn new_budgeted(mut paths: Vec<(BezPath, FillRule)>, cap: usize) -> Result { let eps = eps_for(paths.iter().map(|p| &p.0))?; snap_horizontals(&mut paths.iter_mut().map(|p| &mut p.0).collect::>(), eps); // Counted on the snapped geometry, which is what the sweep sees: snapping can bring boxes into contact. - if !crate::budget::sweep_fits(paths.iter().map(|p| &p.0)) { + if !crate::budget::sweep_fits_within(paths.iter().map(|p| &p.0), cap) { return Err(PathOpsError::TooComplex); } // The sweep can panic on rare near-degenerate input; that must never take the app down, @@ -835,6 +839,23 @@ mod tests { assert_eq!(tidy.repair(&lens), lens); } + #[test] + fn arrangement_new_budgeted_fails_on_complexity_and_open_paths() { + let mut bp = BezPath::new(); + for i in 0..100 { + let r = kurbo::Rect::new(0.0, 0.0, 10.0 + i as f64, 10.0 + i as f64); + bp.extend(r.to_path(0.1).iter()); + } + let too_complex = Arrangement::new_budgeted(vec![(bp, FillRule::NonZero)], 5); + assert_eq!(too_complex.err(), Some(PathOpsError::TooComplex)); + + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((10.0, 10.0)); + let failed_arr = Arrangement::new_budgeted(vec![(open, FillRule::NonZero)], 1000); + assert_eq!(failed_arr.err(), Some(PathOpsError::OpenPath)); + } + fn square(x: f64, y: f64, size: f64) -> PathData { PathData::single(vectorcraft_geom::SubPath::new( [(x, y), (x + size, y), (x + size, y + size), (x, y + size)] diff --git a/crates/pathops/src/budget.rs b/crates/pathops/src/budget.rs index 01559ce8a8..824af9fc2f 100644 --- a/crates/pathops/src/budget.rs +++ b/crates/pathops/src/budget.rs @@ -82,10 +82,15 @@ pub(crate) fn overlaps_within(boxes: &[Rect], cap: usize) -> bool { true } +/// Can a planar map be built of `paths` within `cap` segment pairs? +pub(crate) fn sweep_fits_within<'a>(paths: impl IntoIterator, cap: usize) -> bool { + let boxes: Vec = paths.into_iter().flat_map(|p| p.segments().map(|s| s.bounding_box())).collect(); + overlaps_within(&boxes, cap) +} + /// Can a planar map be built of `paths` within [`MAX_SEGMENT_PAIRS`]? pub(crate) fn sweep_fits<'a>(paths: impl IntoIterator) -> bool { - let boxes: Vec = paths.into_iter().flat_map(|p| p.segments().map(|s| s.bounding_box())).collect(); - overlaps_within(&boxes, MAX_SEGMENT_PAIRS) + sweep_fits_within(paths, MAX_SEGMENT_PAIRS) } #[cfg(test)] diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 980509a871..3d1b17fef9 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -25,7 +25,7 @@ pub use edit::{ remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, smooth_options, split_into_grid, }; -pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region}; +pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions}; pub use planar::{ BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point, diff --git a/crates/pathops/src/offset.rs b/crates/pathops/src/offset.rs index ec6b517f7a..f028c0704f 100644 --- a/crates/pathops/src/offset.rs +++ b/crates/pathops/src/offset.rs @@ -7,12 +7,26 @@ pub use kurbo::{Cap, Join}; use linesweeper::topology::{ContourIdx, Contours}; +use crate::PathOpsError; use crate::boolean::{Arrangement, DEFAULT_PRECISION, Tidy, all_contours_to_path, contours_to_path, fill_bezpath, normalize_bez}; use crate::edit::remove_redundant_points; /// Flattening/fit tolerance handed to kurbo's stroker. const STROKE_TOL: f64 = 1e-3; +/// Most overlapping segment pairs allowed for planar arrangement in offset path: 524,288 (1 << 19). +/// +/// Rationale: +/// - The global boolean sweep cap is `MAX_SEGMENT_PAIRS = 1 << 22` (4,194,304 pairs). +/// - An offset operation decomposes paths into outer rings, inner/fill boundaries, and open +/// subpath strokes. When applied to multi-copy transformations (e.g. 25–50 copies in #4145), +/// these parallel strokes create dense self- and cross-intersections where pairwise bounding-box +/// overlaps scale quadratically with the number of segments. +/// - At 1 << 19 (524,288 segment pairs), the planar sweep memory usage is bounded to tens of MBs +/// and completes within ~100 ms on typical CPUs, preventing exponential allocation spikes and +/// application hangs while still generously accommodating legitimate complex artwork. +pub const MAX_OFFSET_SEGMENT_PAIRS: usize = 1 << 19; + /// Drop collinear and coincident spine vertices before stroking (#3446). Uses `tol` only for /// redundancy; does not simplify or refit the spine. fn compact_stroke_spine(bp: &BezPath, tol: f64) -> BezPath { @@ -92,13 +106,23 @@ pub fn stroke_region(outlines: &[BezPath]) -> PathData { normalize_bez(&all, FillRule::NonZero).map(|c| all_contours_to_path(&c, &tidy)).unwrap_or_default() } -/// Object → Path → Offset Path. Positive `delta` grows the filled area, negative insets it. -/// Closed subpaths are treated as a non-zero filled region; open subpaths are outlined with a -/// stroke of width `2|delta|` (butt caps). An open subpath whose last anchor sits on its first is -/// offset as a closed one. -pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> PathData { - if !delta.is_finite() || path.is_empty() { - return PathData::default(); +/// Validate that all anchor coordinates and control handles of `path` are finite. +fn path_is_finite(path: &PathData) -> bool { + path.subpaths.iter().all(|sp| { + sp.anchors.iter().all(|a| { + a.p.x.is_finite() && a.p.y.is_finite() && a.h_in.x.is_finite() && a.h_in.y.is_finite() && a.h_out.x.is_finite() && a.h_out.y.is_finite() + }) + }) +} + +/// Fallible [`offset_path`] that returns an error when the input is non-finite or exceeds +/// the complexity bound ([`MAX_OFFSET_SEGMENT_PAIRS`]), or when planar arrangement fails. +pub fn try_offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> Result { + if !delta.is_finite() || !path_is_finite(path) { + return Err(PathOpsError::NonFinite); + } + if path.is_empty() { + return Ok(PathData::default()); } let subpaths: Vec = path.subpaths.iter().map(close_if_ends_meet).collect(); let closed = PathData::new(subpaths.iter().filter(|s| s.closed && s.anchors.len() > 1).cloned().collect()); @@ -111,9 +135,10 @@ pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> } else { BezPath::new() }; - let Ok(arr) = Arrangement::new(vec![(fill, FillRule::NonZero), (ring, FillRule::NonZero), (open_bp, FillRule::NonZero)]) else { - return PathData::default(); - }; + let arr = Arrangement::new_budgeted( + vec![(fill, FillRule::NonZero), (ring, FillRule::NonZero), (open_bp, FillRule::NonZero)], + MAX_OFFSET_SEGMENT_PAIRS, + )?; let c = if delta >= 0.0 { arr.contours(|m| m[0] || m[1] || m[2]) } else { arr.contours(|m| m[0] && !m[1]) }; // When `d` exceeds a curvature radius the stroker's inner offset inverts and its loops cancel // winding, leaving faces uncovered that are really within `d` of the path. Every face of the @@ -124,10 +149,25 @@ pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> let spurious: Vec = c.contours().map(|k| k.outer == drop_outer && deep_point(&k.path).is_some_and(|p| any_within(&src, p, d * (1.0 - 1e-4) - 1e-6))).collect(); if !spurious.contains(&true) { - return all_contours_to_path(&c, &Tidy::free(DEFAULT_PRECISION)); + return Ok(all_contours_to_path(&c, &Tidy::free(DEFAULT_PRECISION))); } let keep = (0..spurious.len()).filter(|&i| !has_marked_ancestor(&c, i, &spurious)).map(ContourIdx); - contours_to_path(&c, keep, &Tidy::free(DEFAULT_PRECISION)) + Ok(contours_to_path(&c, keep, &Tidy::free(DEFAULT_PRECISION))) +} + +/// Object → Path → Offset Path. Positive `delta` grows the filled area, negative insets it. +/// Closed subpaths are treated as a non-zero filled region; open subpaths are outlined with a +/// stroke of width `2|delta|` (butt caps). An open subpath whose last anchor sits on its first is +/// offset as a closed one. +/// +/// If planar arrangement exceeds complexity or encounters a degenerate arrangement error, +/// gracefully preserves `path` unchanged to prevent rendering crashes or disappearing artwork (#4145). +/// Non-finite input returns an empty path. +pub fn offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> PathData { + try_offset_path(path, delta, join, miter_limit).unwrap_or_else(|e| match e { + PathOpsError::NonFinite => PathData::default(), + _ => path.clone(), + }) } /// An open subpath of three or more anchors whose last anchor lies within 1e-6 of its first (the @@ -442,4 +482,45 @@ mod tests { let arc_raw = stroke_bez_without_spine_compact(&arc_bez, width, cap, join, miter); assert!(outline_max_deviation(&arc_compact, &arc_raw) <= 1e-3, "curved spine compaction must not refit the stroke outline"); } + + #[test] + fn offset_path_recovers_gracefully_when_complexity_exceeds_budget() { + // Issue #4145: dense overlapping geometry must not hang or panic; if complexity passes + // the offset cap, try_offset_path reports PathOpsError::TooComplex and offset_path + // preserves the input path unchanged. + let mut bp = BezPath::new(); + for i in 0..300 { + let offset = i as f64 * 0.1; + let rect = kurbo::Rect::new(offset, offset, offset + 100.0, offset + 100.0); + bp.extend(rect.to_path(0.1).iter()); + } + let path = PathData::from_bezpath(&bp); + assert_eq!(try_offset_path(&path, 5.0, Join::Round, 4.0), Err(PathOpsError::TooComplex)); + let res = offset_path(&path, 5.0, Join::Round, 4.0); + assert_eq!(res, path); + } + + #[test] + fn offset_path_returns_empty_on_non_finite() { + let rect = kurbo::Rect::new(0.0, 0.0, 100.0, 100.0); + let path = PathData::from_bezpath(&rect.to_path(0.1)); + assert_eq!(try_offset_path(&path, f64::NAN, Join::Round, 4.0), Err(PathOpsError::NonFinite)); + assert_eq!(try_offset_path(&path, f64::INFINITY, Join::Round, 4.0), Err(PathOpsError::NonFinite)); + assert!(offset_path(&path, f64::NAN, Join::Round, 4.0).is_empty()); + assert!(offset_path(&path, f64::INFINITY, Join::Round, 4.0).is_empty()); + + // Even with dense overlapping geometry, non-finite points return NonFinite error and empty rather than fallback. + let mut bp = BezPath::new(); + for i in 0..300 { + let offset = i as f64 * 0.1; + let rect = kurbo::Rect::new(offset, offset, offset + 100.0, offset + 100.0); + bp.extend(rect.to_path(0.1).iter()); + } + let mut dense_non_finite = PathData::from_bezpath(&bp); + dense_non_finite + .subpaths + .push(SubPath::polyline(&[vectorcraft_geom::Point::new(f64::NAN, 0.0), vectorcraft_geom::Point::new(10.0, 10.0)], true)); + assert_eq!(try_offset_path(&dense_non_finite, 5.0, Join::Round, 4.0), Err(PathOpsError::NonFinite)); + assert!(offset_path(&dense_non_finite, 5.0, Join::Round, 4.0).is_empty()); + } } diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 5e6f55135a..f0c5ab505b 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -155,7 +155,19 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve .collect(), // topmost(m) == Some(i) PathfinderOp::Trim => { - (0..n).flat_map(|i| one(all_contours_to_path(&arr.contours_where(|w| arr.covered(w).next_back() == Some(i)), p), shapes[i].key)).collect() + let mut subpaths = vec![Vec::new(); n]; + each_classified_face( + &arr, + n, + |w| arr.covered(w).next_back(), + |i, c, group| { + if let Some(sp) = subpaths.get_mut(i) { + let p = contours_to_path(c, group.iter().copied(), &arr.tidy); + sp.extend(p.subpaths); + } + }, + ); + subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } PathfinderOp::Merge => { let mut keys: Vec = Vec::new(); @@ -178,16 +190,22 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve if n < 2 { return Vec::new(); } - (0..n - 1) - .flat_map(|i| { - // m[n - 1] && topmost(&m[..n - 1]) == Some(i): the front shape, then i below it - let c = arr.contours_where(|w| { - let mut c = arr.covered(w).rev(); - c.next() == Some(n - 1) && c.next() == Some(i) - }); - one(all_contours_to_path(&c, p), shapes[i].key) - }) - .collect() + let mut subpaths = vec![Vec::new(); n - 1]; + each_classified_face( + &arr, + n - 1, + |w| { + let mut c = arr.covered(w).rev(); + if c.next() == Some(n - 1) { c.next() } else { None } + }, + |i, c, group| { + if let Some(sp) = subpaths.get_mut(i) { + let p = contours_to_path(c, group.iter().copied(), &arr.tidy); + sp.extend(p.subpaths); + } + }, + ); + subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } PathfinderOp::Outline => outline_edges(&arr, shapes), PathfinderOp::HardMix | PathfinderOp::SoftMix => regions_of(&arr) @@ -219,29 +237,29 @@ fn regions_of(arr: &Arrangement) -> Vec { out } -/// Calls `f` with each face of `arr` whose coverage is one of `masks` (distinct): the index of -/// its mask in `masks`, the contour pass it is in, and its contours, an outer contour and the -/// holes of its mask directly inside it ([`face_groups`]). Each mask's faces come in the order -/// of that mask's own contour pass. +/// Calls `f` with each face of `arr` classified by `classify: impl Fn(&Multi) -> Option` +/// into `0..num_classes`: the index of its class, the contour pass it is in, and its contours, +/// an outer contour and the holes of its class directly inside it ([`face_groups`]). /// -/// A contour pass walks the whole arrangement, so one pass per mask would cost masks × edges -/// (two blends crossing make thousands of each). Instead the masks go into batches whose faces -/// share no vertex (so no edge either): one pass per batch walks each face's contours exactly as -/// its own mask's pass would, and the mask a contour bounds is the one of its batch at its first -/// point. -fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Contours, &[ContourIdx])) { - if masks.is_empty() { +/// A contour pass walks the whole arrangement, so one pass per class would cost classes × edges. +/// Instead the classes go into batches whose faces share no vertex (so no edge either): one pass +/// per batch walks each face's contours exactly as its own class's pass would, and the class a +/// contour bounds is the one of its batch at its first point. +fn each_classified_face( + arr: &Arrangement, + num_classes: usize, + classify: impl Fn(&Multi) -> Option, + mut f: impl FnMut(usize, &Contours, &[ContourIdx]), +) { + if num_classes == 0 { return; } - // Each mask is found by the inputs it covers. - let ids = CoverIds::new(masks.iter().map(|m| m.iter().enumerate().filter(|(_, b)| **b).map(|(k, _)| k).collect()).collect()); - let id = |w: &Multi| ids.of(arr, w); let top = &arr.top; - // The masks of the faces around each vertex. + // The classes of the faces around each vertex. let mut around: HashMap<(u64, u64), Vec> = HashMap::new(); for s in top.segment_indices() { let h = s.first_half(); - let sides = [id(top.winding_clockwise(h)), id(top.winding_counter_clockwise(h))]; + let sides = [classify(top.winding_clockwise(h)), classify(top.winding_counter_clockwise(h))]; for end in [h, s.second_half()] { let at = around.entry(vertex_key(top.point(end).to_kurbo())).or_default(); for m in sides.into_iter().flatten() { @@ -251,16 +269,16 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con } } } - let mut near = vec![Vec::new(); masks.len()]; + let mut near = vec![Vec::new(); num_classes]; for at in around.values() { for &a in at { near[a].extend(at.iter().copied().filter(|&b| b != a)); } } - // Greedy colouring: each mask takes the first batch none of its neighbours is in. - let mut batch = vec![usize::MAX; masks.len()]; + // Greedy colouring: each class takes the first batch none of its neighbours is in. + let mut batch = vec![usize::MAX; num_classes]; let mut batches = 0; - for m in 0..masks.len() { + for m in 0..num_classes { let mut taken = vec![false; batches]; for &n in &near[m] { if let Some(t) = taken.get_mut(batch[n]) { @@ -271,7 +289,7 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con batches = batches.max(batch[m] + 1); } for b in 0..batches { - let c = arr.contours_where(|w| id(w).is_some_and(|m| batch[m] == b)); + let c = arr.contours_where(|w| classify(w).is_some_and(|m| batch[m] == b)); let owner: Option> = c .contours() .map(|ct| { @@ -281,9 +299,9 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con .collect(); let Some(owner) = owner else { // Not expected: every contour starts at a vertex of the arrangement. Fall back to a - // pass per mask for this batch. - for (m, mask) in masks.iter().enumerate().filter(|(m, _)| batch[*m] == b) { - let c = arr.contours(|k| k == *mask); + // pass per class for this batch. + for m in (0..num_classes).filter(|m| batch[*m] == b) { + let c = arr.contours_where(|w| classify(w) == Some(m)); let owner = vec![m; c.contours().count()]; for (_, group) in face_groups(&c, &owner) { f(m, &c, &group); @@ -297,6 +315,25 @@ fn each_face(arr: &Arrangement, masks: &[&[bool]], mut f: impl FnMut(usize, &Con } } +/// Calls `f` with each face of `arr` whose coverage is one of `masks` (distinct): the index of +/// its mask in `masks`, the contour pass it is in, and its contours, an outer contour and the +/// holes of its mask directly inside it ([`face_groups`]). Each mask's faces come in the order +/// of that mask's own contour pass. +/// +/// A contour pass walks the whole arrangement, so one pass per mask would cost masks × edges +/// (two blends crossing make thousands of each). Instead the masks go into batches whose faces +/// share no vertex (so no edge either): one pass per batch walks each face's contours exactly as +/// its own mask's pass would, and the mask a contour bounds is the one of its batch at its first +/// point. +fn each_face(arr: &Arrangement, masks: &[&[bool]], f: impl FnMut(usize, &Contours, &[ContourIdx])) { + if masks.is_empty() { + return; + } + // Each mask is found by the inputs it covers. + let ids = CoverIds::new(masks.iter().map(|m| m.iter().enumerate().filter(|(_, b)| **b).map(|(k, _)| k).collect()).collect()); + each_classified_face(arr, masks.len(), |w| ids.of(arr, w), f); +} + /// Lists of inputs, each ascending as [`Arrangement::covered`] gives them, found by the inputs /// that cover a winding. struct CoverIds { @@ -1355,4 +1392,68 @@ mod tests { assert_eq!(faces[0].key, 7); assert!((crate::area(&faces[0].path, faces[0].rule) - 10000.0).abs() < 1e-6); } + + fn old_trim(shapes: &[Shape], precision: f64) -> Vec { + let n = shapes.len(); + let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; + (0..n) + .flat_map(|i| { + let c = arr.contours_where(|w| arr.covered(w).next_back() == Some(i)); + one(all_contours_to_path(&c, &arr.tidy), shapes[i].key) + }) + .collect() + } + + fn old_crop(shapes: &[Shape], precision: f64) -> Vec { + let n = shapes.len(); + if n < 2 { + return Vec::new(); + } + let Some(arr) = arrangement(shapes, precision) else { return Vec::new() }; + (0..n - 1) + .flat_map(|i| { + let c = arr.contours_where(|w| { + let mut c = arr.covered(w).rev(); + c.next() == Some(n - 1) && c.next() == Some(i) + }); + one(all_contours_to_path(&c, &arr.tidy), shapes[i].key) + }) + .collect() + } + + #[test] + fn trim_and_crop_differential_matches_reference_on_overlapping_shapes() { + let shapes = vec![ + Shape::new(rect(0.0, 0.0, 60.0, 60.0), FillRule::NonZero, 1), + Shape::new(rect(30.0, 0.0, 90.0, 60.0), FillRule::NonZero, 2), + Shape::new(rect(15.0, 15.0, 75.0, 75.0), FillRule::NonZero, 3), + Shape::new(rect(40.0, 40.0, 100.0, 100.0), FillRule::NonZero, 4), + ]; + + let trim_actual = pathfinder_with(PathfinderOp::Trim, &shapes, DEFAULT_PRECISION); + let trim_expected = old_trim(&shapes, DEFAULT_PRECISION); + assert_eq!(trim_actual.len(), trim_expected.len(), "trim shape count must match"); + for (actual, expected) in trim_actual.iter().zip(&trim_expected) { + assert_eq!(actual.key, expected.key); + assert_eq!(actual.path, expected.path, "subpath order and contours must match reference trim"); + } + + let crop_actual = pathfinder_with(PathfinderOp::Crop, &shapes, DEFAULT_PRECISION); + let crop_expected = old_crop(&shapes, DEFAULT_PRECISION); + assert_eq!(crop_actual.len(), crop_expected.len(), "crop shape count must match"); + for (actual, expected) in crop_actual.iter().zip(&crop_expected) { + assert_eq!(actual.key, expected.key); + assert_eq!(actual.path, expected.path, "subpath order and contours must match reference crop"); + } + + // Test with shape that has no face left (completely covered by front shape) + let covered = vec![ + Shape::new(rect(10.0, 10.0, 20.0, 20.0), FillRule::NonZero, 10), // inside shape 20 + Shape::new(rect(0.0, 0.0, 50.0, 50.0), FillRule::NonZero, 20), + ]; + let trim_cov_actual = pathfinder_with(PathfinderOp::Trim, &covered, DEFAULT_PRECISION); + let trim_cov_expected = old_trim(&covered, DEFAULT_PRECISION); + assert_eq!(trim_cov_actual.len(), 1); + assert_eq!(trim_cov_actual, trim_cov_expected); + } } diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index 3abf7cfeaa..aa853b2469 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -423,8 +423,8 @@ impl Map { } /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) -/// that lie under the outline of a closed path in front of them, whose edges are that closed -/// path's. +/// that lie under another path in front of them, whose edges are that path's: under a closed +/// path's outline, or along an open path in front. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { let m = map_with(shapes, false, precision)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; @@ -461,61 +461,65 @@ pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Ve }) .collect() }; - let edge_shapes = to_shapes(chains_by(edges, around, |e| Some(e.source))); let is_line = |i: usize| shapes.get(i).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed)); - let under = to_shapes(chains_by(edges, around, |e| if is_line(e.source) { None } else { e.sources.iter().rev().copied().find(|&i| is_line(i)) })); + // An edge is the front-most input's. Every other open path along it has a piece there too. + let edge_shapes = to_shapes(chains_by(edges, around, |e| vec![e.source])); + let under = to_shapes(chains_by(edges, around, |e| e.sources.iter().rev().copied().filter(|&i| i != e.source && is_line(i)).collect())); Some((regions, edge_shapes, under)) } -/// The edges that `key` gives an input, joined into chains through the vertices where only two -/// edges of the same input meet, each with that input. A chain is closed when it comes back round -/// to where it started. -fn chains_by(edges: &[Edge], around: &[Vec], key: impl Fn(&Edge) -> Option) -> Vec<(Vec, bool, usize)> { - let keys: Vec> = edges.iter().map(&key).collect(); - let key_of = |h: usize| keys.get(h / 2).copied().flatten(); - let passes = |v: usize| -> Option<(usize, usize)> { +/// The edges that `keys` gives each input, joined into chains through the vertices where only two +/// edges of the same input meet, each with that input. An edge that several inputs share is in a +/// chain for each of them. A chain is closed when it comes back round to where it started. +fn chains_by(edges: &[Edge], around: &[Vec], keys: impl Fn(&Edge) -> Vec) -> Vec<(Vec, bool, usize)> { + let keys: Vec> = edges.iter().map(&keys).collect(); + // Where input `k` is among the inputs half-edge `h` gives. + let slot = |h: usize, k: usize| keys.get(h / 2).and_then(|ks| ks.iter().position(|&x| x == k)); + let passes = |v: usize, k: usize| -> Option<(usize, usize)> { let list = around.get(v)?; let (&a, &b) = (list.first()?, list.get(1)?); - (list.len() == 2 && key_of(a).is_some() && key_of(a) == key_of(b)).then_some((a, b)) + (list.len() == 2 && slot(a, k).is_some() && slot(b, k).is_some()).then_some((a, b)) }; - // Edges with no input to give are never walked. - let mut used: Vec = keys.iter().map(Option::is_none).collect(); + // Each edge's inputs, and whether its chain for each has been walked. + let mut used: Vec> = keys.iter().map(|ks| vec![false; ks.len()]).collect(); let mut chains: Vec<(Vec, bool, usize)> = Vec::new(); - // A chain from half-edge `h0` up to the next vertex where it doesn't pass straight through. - let walk = |h0: usize, used: &mut Vec| -> Option<(Vec, bool, usize)> { - let source = key_of(h0)?; + // A chain of input `k` from half-edge `h0` up to the next vertex where it doesn't pass straight through. + let walk = |h0: usize, k: usize, used: &mut Vec>| -> Option<(Vec, bool, usize)> { let mut segs = Vec::new(); let mut h = h0; loop { - let u = used.get_mut(h / 2)?; + let u = used.get_mut(h / 2)?.get_mut(slot(h, k)?)?; if *u { - return Some((segs, true, source)); + return Some((segs, true, k)); } *u = true; segs.extend(half_segs(edges, h)); let v = origin(edges, twin(h))?; - let Some((a, b)) = passes(v) else { return Some((segs, origin(edges, h0) == Some(v), source)) }; + let Some((a, b)) = passes(v, k) else { return Some((segs, origin(edges, h0) == Some(v), k)) }; h = if a == twin(h) { b } else { a }; } }; + let unwalked = |used: &[Vec], h: usize, k: usize| slot(h, k).is_some_and(|s| used.get(h / 2).and_then(|u| u.get(s)) == Some(&false)); for v in 0..around.len() { - if passes(v).is_some() { - continue; - } for &h in around.get(v).map(Vec::as_slice).unwrap_or_default() { - if !used.get(h / 2).copied().unwrap_or(true) - && let Some(c) = walk(h, &mut used) - { - chains.push(c); + for &k in keys.get(h / 2).map(Vec::as_slice).unwrap_or_default() { + if passes(v, k).is_none() + && unwalked(&used, h, k) + && let Some(c) = walk(h, k, &mut used) + { + chains.push(c); + } } } } // What's left are closed loops with no junction on them. for e in 0..edges.len() { - if !used.get(e).copied().unwrap_or(true) - && let Some(c) = walk(2 * e, &mut used) - { - chains.push(c); + for &k in keys.get(e).map(Vec::as_slice).unwrap_or_default() { + if unwalked(&used, 2 * e, k) + && let Some(c) = walk(2 * e, k, &mut used) + { + chains.push(c); + } } } chains diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 290bc270d4..fde156f9b3 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -19,8 +19,9 @@ pub struct BuilderArrangement { /// share one); only when asked for. pub edges: Vec, /// The pieces of the paths with no closed subpath that lie under the outline of a closed path - /// in front of them, keyed by input index. No piece of `lines` covers them; there the edge is - /// the closed path's (in `edges`, when asked for). + /// in front of them, or along another such path in front of them, keyed by input index. No + /// piece of theirs is in `lines`; there the edge is the path's in front (in `edges` when it is + /// a closed path's and they were asked for, else in `lines`). pub lines_under: Vec, } diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index 654d7d5cb7..3cee370df8 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -444,6 +444,31 @@ fn shape_builder_keeps_the_pieces_of_a_line_under_an_outline_in_front() { assert!(shape_builder(&s, true).lines_under.is_empty()); } +#[test] +fn shape_builder_gives_each_coincident_line_its_pieces() { + // Two lines along the same stretch, whose left half lies under the bottom edge of a rectangle + // in front of them: each has its own pieces, under the edge and beyond it. Beyond the edge the + // front line's piece is the edge, and the back line's lies under it. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), rect(0.0, 0.0, 100.0, 50.0, 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + let spans = |pieces: &[Shape], key: u64| { + let mut v: Vec<_> = pieces.iter().filter(|l| l.key == key).filter_map(|l| l.path.bounds().map(|b| (b.x0, b.x1))).collect(); + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + v + }; + assert_eq!(spans(&lines, 1), [(100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 1), [(0.0, 100.0)], "{lines_under:?}"); + assert_eq!(spans(&lines, 0), [], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Without the rectangle, both lines are cut where the line across them crosses. + let s = [line((0.0, 50.0), (200.0, 50.0), 0), line((0.0, 50.0), (200.0, 50.0), 1), line((100.0, 0.0), (100.0, 100.0), 2)]; + let BuilderArrangement { lines, lines_under, .. } = shape_builder(&s, false); + assert_eq!(spans(&lines, 1), [(0.0, 100.0), (100.0, 200.0)], "{lines:?}"); + assert_eq!(spans(&lines_under, 0), [(0.0, 100.0), (100.0, 200.0)], "{lines_under:?}"); + // Live Paint's edges stay one per stretch, the front line's. + assert_eq!(live_paint(&s).1.iter().filter(|e| e.key == 0).count(), 0); +} + #[test] fn shape_builder_merges_adjacent_gap_closed_faces_without_keeping_bridges() { let outline = Shape::new( diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 71c9ab25de..cfb3d93441 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -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; diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 6a4294c699..92607d5c51 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -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))?; } diff --git a/crates/pdf/src/export/links.rs b/crates/pdf/src/export/links.rs new file mode 100644 index 0000000000..5eec2fd837 --- /dev/null +++ b/crates/pdf/src/export/links.rs @@ -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, 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, 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 { + 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"); + } +} diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 80a95ad167..389552948e 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -196,7 +196,7 @@ impl Exporter<'_> { } NodeKind::Text(t) => self.text(s, n, t, page), NodeKind::Image(im) => match n.extras().colorize.as_deref() { - Some(p @ Paint::Solid { .. }) => { + Some(p @ Paint::Solid { .. }) if self.doc.image_blob(im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { if writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) { if let Some(colorized) = self.colorized_image(im, p, !n.extras().pixelated) { self.image(s, im, Some(colorized), n.extras().pixelated); diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 379ebbd506..3138484ebd 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -92,7 +92,8 @@ impl Exporter<'_> { .stops .iter() .map(|s| match s.swatch.as_deref() { - Some(n) if n == ink => Some(s.tint), + // A stop that also prints process plates needs a DeviceN space. + Some(n) if n == ink && s.plates.is_none() => Some(s.tint), _ if self.paper_stop(s) => Some(0.0), _ => None, }) @@ -119,7 +120,8 @@ impl Exporter<'_> { /// a DeviceN space of the process inks the stops use (in CMYK order) and the spot inks (in /// the order the stops name them), with midpoints as explicit stops (the tints and opacity /// there are halfway), or for a Perceptual gradient the stops on its curve - /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink. `None`, with a + /// ([`vectorcraft_color::Gradient::ink_mixes`]). Paper white adds no ink; a spot stop with + /// process plates ([`vectorcraft_color::GradientStop::plates`]) prints them too. `None`, with a /// warning, when a stop is written in RGB or Lab or the spot inks can't share a DeviceN space; /// the gradient is then written in the colors of its stops. fn device_n_stops(&mut self, g: &vectorcraft_color::Gradient) -> Option> { @@ -145,6 +147,9 @@ impl Exporter<'_> { Some(n) => { let i = spots.iter().position(|(m, _)| *m == n)?; v[4 + i] = s.tint; + if let Some(p) = s.plates { + v[..4].copy_from_slice(&p.map(|t| t.clamp(0.0, 1.0))); + } } None if self.paper_stop(s) => {} None => match self.page_color(&s.color) { @@ -379,7 +384,7 @@ impl Exporter<'_> { fn one_spot_ink<'g>(&self, g: &'g vectorcraft_color::Gradient) -> Option<&'g str> { let spot = |s: &'g vectorcraft_color::GradientStop| s.swatch.as_deref().filter(|n| self.doc.swatch(n).is_some_and(|w| w.spot)); let ink = g.stops.iter().find_map(spot)?; - g.stops.iter().all(|s| spot(s) == Some(ink) || self.paper_stop(s)).then_some(ink) + g.stops.iter().all(|s| (spot(s) == Some(ink) && s.plates.is_none()) || self.paper_stop(s)).then_some(ink) } /// Can every stop of `g` be inks of a DeviceN space ([`Self::device_n_stops`]): is a stop diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index 5e7c7e77ab..7f9b939f92 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -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(()) } diff --git a/crates/pdf/src/import_color.rs b/crates/pdf/src/import_color.rs index 2362634edb..b7e033b6ce 100644 --- a/crates/pdf/src/import_color.rs +++ b/crates/pdf/src/import_color.rs @@ -323,6 +323,41 @@ impl<'p> Colors<'p> { } } + /// A gradient stop's colour that paints one spot ink together with process plates (a + /// DeviceN colour of an ink and process colorants): the ink's swatch (marked used), its tint + /// and the process plates (C, M, Y, K). `None` for any other colour ([`Colors::native`] takes + /// it). + pub fn ink_with_plates(&mut self, space: Space, comps: &[f32]) -> Option<(String, f32, [f32; 4])> { + let Space::Inks(i) = space else { return None }; + let colorants = &self.spaces.get(i)?.colorants; + let mut cmyk = [0.0f32; 4]; + let mut ink = None; + for (c, t) in colorants.iter().zip(comps) { + let t = round3(t.clamp(0.0, 1.0)); + match *c { + Colorant::Unknown => return None, + Colorant::None => {} + Colorant::Process(ch) => { + if let Some(v) = cmyk.get_mut(ch) { + *v = v.max(t); + } + } + // A second ink (or every plate) painting too can't be one stop. + Colorant::Ink(_) | Colorant::All if t > 0.0 && ink.is_some() => return None, + Colorant::All if t > 0.0 => return None, + Colorant::Ink(k) if t > 0.0 => ink = Some((k, t)), + Colorant::Ink(_) | Colorant::All => {} + } + } + let (k, t) = ink?; + if cmyk.iter().all(|v| *v <= 0.0) { + return None; + } + let ink = self.inks.get_mut(k)?; + ink.used = true; + Some((ink.name.clone(), t, cmyk)) + } + /// Mark each ink that components `comps` of `space` paint with (a tint above 0) as used, so it /// becomes a spot swatch; nothing for a space with a colorant that can't be read. pub fn mark_inks(&mut self, space: Space, comps: &[f32]) { diff --git a/crates/pdf/src/import_shading.rs b/crates/pdf/src/import_shading.rs index a8a8b25eaa..c80b2a29b4 100644 --- a/crates/pdf/src/import_shading.rs +++ b/crates/pdf/src/import_shading.rs @@ -17,7 +17,7 @@ use vectorcraft_doc::{AppearanceItem, Node, NodeKind, OpacityMask}; use vectorcraft_geom::PathData; use crate::import::{closed_subpaths, round3}; -use crate::import_color::{Colors, Native}; +use crate::import_color::{Colors, Native, Space}; use crate::import_mask::{contains, is_rectangle, luminance}; /// The most mesh patches (or triangles) imported per shading: past it, the shading is a flat @@ -51,14 +51,8 @@ pub(crate) fn shading_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, ink } } let ts: Vec = linear_keep(&pts).iter().filter_map(|&k| pts.get(k)).map(|p| p.0).collect(); - let mut stop_at = |t: f32, offset: f32| -> GradientStop { - let rgb = sample(t).unwrap_or(Color::BLACK); - match at(t).and_then(|v| colors.native(space, &v)) { - Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, - Some(Native { color, link: None }) => GradientStop::new(offset, color), - None => GradientStop::new(offset, rgb), - } - }; + let mut stop_at = + |t: f32, offset: f32| -> GradientStop { shading_stop(colors, space, at(t).as_deref(), offset, sample(t).unwrap_or(Color::BLACK)) }; let c = |x: f32, y: f32| m * Point::new(x as f64, y as f64); let (kind, geom, stops) = if *axial { let geom = GradientGeom { start: c(coords[0], coords[1]), end: c(coords[2], coords[3]), aspect: 1.0, focal: None }; @@ -81,6 +75,21 @@ pub(crate) fn shading_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, ink Some((g, *extend)) } +/// A shading's stop at `offset` of components `comps` of `space` in their own model, linked to +/// its spot swatch at its tint (with the process plates it prints with, looking like `rgb`, the +/// colour the file gives it); `rgb` when the components can't be read or kept. +fn shading_stop(colors: &mut Colors<'_>, space: Space, comps: Option<&[f32]>, offset: f32, rgb: Color) -> GradientStop { + let Some(v) = comps else { return GradientStop::new(offset, rgb) }; + if let Some((name, tint, plates)) = colors.ink_with_plates(space, v) { + return GradientStop { swatch: Some(name), tint, plates: Some(plates), ..GradientStop::new(offset, rgb) }; + } + match colors.native(space, v) { + Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, + Some(Native { color, link: None }) => GradientStop::new(offset, color), + None => GradientStop::new(offset, rgb), + } +} + /// The samples of `pts` (offset, RGB; at least one) a gradient keeps as stops: the first, the /// last, and each one that linear interpolation between its neighbouring stops doesn't reproduce. fn linear_keep(pts: &[(f32, [f32; 3])]) -> Vec { @@ -299,11 +308,7 @@ fn function_gradient(sp: &ShadingPattern, colors: &mut Colors<'_>, inks: Option< for k in linear_keep(&pts) { let Some(&(offset, read, c)) = piece.get(k) else { continue }; let rgb = Color::rgb(round3(c[0]), round3(c[1]), round3(c[2])); - out.push(match value(read).and_then(|v| colors.native(space, &v)) { - Some(Native { color, link: Some((name, tint)) }) => GradientStop { swatch: Some(name), tint, ..GradientStop::new(offset, color) }, - Some(Native { color, link: None }) => GradientStop::new(offset, color), - None => GradientStop::new(offset, rgb), - }); + out.push(shading_stop(colors, space, value(read).as_deref(), offset, rgb)); } } if out.len() > MAX_FUNCTION_STOPS { diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index a8e54b3248..559fc61475 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -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, } } } diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 7c84996427..a46d1137a7 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -9,7 +9,7 @@ use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_doc::inks::{Link, inks, plates, visit_node_colors}; use vectorcraft_doc::overprint::darken_overprints; -use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; +use vectorcraft_doc::{ColorMode, Document, ImageBlob, Node, NodeKind}; use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings}; @@ -120,7 +120,7 @@ impl<'a> Separator<'a> { for n in nodes { darken_overprints(n, discard_white); self.node(plate, Arc::make_mut(n)); - keep_colorized_pixels(n, &mut colorized); + keep_colorized_pixels(n, &d.images, &mut colorized); } // A colorized image's pixels say where its color prints, on every plate: they are kept // under their own key, and only the color is separated. @@ -153,13 +153,20 @@ fn colorized_key(key: &str) -> String { } /// Point the colorized images in `n`'s subtree at [`colorized_key`], collecting their keys in -/// `keys`. -fn keep_colorized_pixels(n: &mut Arc, keys: &mut BTreeSet) { +/// `keys`. An image whose pixels in `images` don't take its colorize paint +/// ([`ImageBlob::takes_colorize`]) loses the paint instead, and is separated as the image it shows. +fn keep_colorized_pixels(n: &mut Arc, images: &BTreeMap, keys: &mut BTreeSet) { let colorized = |n: &Node| matches!(n.kind, NodeKind::Image(ref im) if im.pixels.is_none()) && n.extras().colorize.is_some(); if !colorized(n) && n.children().is_none_or(|ch| ch.is_empty()) { return; } let node = Arc::make_mut(n); + if colorized(node) + && let NodeKind::Image(im) = &node.kind + && images.get(&im.key).is_some_and(|b| !b.takes_colorize()) + { + node.extras_mut().colorize = None; + } if colorized(node) && let NodeKind::Image(im) = &mut node.kind { @@ -168,7 +175,7 @@ fn keep_colorized_pixels(n: &mut Arc, keys: &mut BTreeSet) { } if let Some(ch) = node.children_mut() { for c in ch.iter_mut() { - keep_colorized_pixels(c, keys); + keep_colorized_pixels(c, images, keys); } } } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 132b338e76..f8df385009 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -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; diff --git a/crates/pdf/src/tests/colorize.rs b/crates/pdf/src/tests/colorize.rs index 406ae08b81..5ec2e813ab 100644 --- a/crates/pdf/src/tests/colorize.rs +++ b/crates/pdf/src/tests/colorize.rs @@ -166,6 +166,34 @@ fn separations_print_the_image_on_its_ink_plate() { } } +/// A linked image showing the missing-link placeholder is written in the placeholder's own colors +/// though it keeps a colorize paint for its file, and printed separations separate it as an +/// uncolorized image. +#[test] +fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() { + let placeholder = || { + let mut d = doc(ColorMode::Cmyk, None); + let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap()); + d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }); + d + }; + let plain = placeholder(); + let mut d = placeholder(); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))); + let (colorized, uncolorized) = (images(&pdf(&d)), images(&pdf(&plain))); + assert!(!colorized.is_empty()); + assert_eq!(colorized, uncolorized, "the placeholder as it is, without a soft mask from its coverage"); + let settings: PrintSettings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap(); + assert!(!job.plates.is_empty()); + for p in &job.plates { + let n = &p.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("the image") }; + assert_eq!((im.key.as_str(), n.extras().colorize.is_none()), ("pic", true), "separated as the image it shows"); + } +} + /// A pixelated colorized image (an envelope's with Anti-Alias off) is written without /// /Interpolate, as an uncolorized one is. #[test] diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index e26697858f..011f298eea 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -178,12 +178,65 @@ fn a_spot_ink_mixed_with_a_process_plate_keeps_its_swatch() { for (what, page) in [("fill", fill), ("shading", sh)] { let r = import_with_report(&pdf_with(&[page], &[func], None), &ImportOptions::default()).unwrap(); let d = &r.document; - assert!(r.warnings.iter().any(|w| w.contains("several inks")), "{what}: {:?}", r.warnings); - assert!(links(d).iter().all(Option::is_none), "{what}: the art stays RGB"); let gold = d.swatch("Gold").unwrap_or_else(|| panic!("{what}: no Gold swatch")); assert!(gold.spot && gold.global, "{what}: Gold is a spot swatch"); assert!(near(gold.paint.color().unwrap(), Color::cmyk(0.0, 0.0, 1.0, 0.0)), "{what}: {gold:?}"); assert_eq!(d.swatches.iter().filter(|s| s.spot).count(), 1, "{what}: Cyan is a process plate"); + if what == "fill" { + // A solid paint can't link to an ink and process plates together. + assert!(r.warnings.iter().any(|w| w.contains("several inks")), "{what}: {:?}", r.warnings); + assert!(links(d).iter().all(Option::is_none), "{what}: the art stays RGB"); + } + } +} + +/// A gradient stop of `d`'s only gradient, in paint order. +fn gradient_stops(d: &Document) -> Vec { + let mut out = vec![]; + d.walk(|n: &Node| { + for i in &n.appearance.items { + if let Paint::Gradient(g) = i.paint() { + out.extend(g.gradient.stops.iter().cloned()); + } + } + }); + out +} + +#[test] +fn a_device_n_gradient_of_a_spot_ink_over_a_process_plate_keeps_both_inks() { + // #3235: an axial shading in [/DeviceN [/Gold /Cyan] /DeviceCMYK …], Gold 0 to 1 over Cyan + // at 0.3 (ISO 32000-1:2008, 8.6.6.5 and 8.7.4.5.3). Its stops link to Gold, with the cyan + // plate kept, and PDF export (PDF/X-4 too) writes it again as a DeviceN shading of both inks. + let space = format!("[/DeviceN [/Gold /Cyan] /DeviceCMYK {} 0 R]", first_extra(1)); + let func = "<< /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1 0 1] /Length 17 >>\nstream\n{ exch 0 exch 0 }\nendstream"; + let shading = format!( + "<< /ShadingType 2 /ColorSpace {space} /Coords [0 0 50 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0 0.3] /C1 [1 0.3] /N 1 >> /Extend [true true] >>" + ); + let page = PdfPage { resources: format!("/Shading << /Sh0 {shading} >>"), ..PdfPage::new(100.0, 50.0, "q 0 0 50 50 re W n /Sh0 sh Q") }; + let r = import_with_report(&pdf_with(&[page], &[func], None), &ImportOptions::default()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("several inks")), "{:?}", r.warnings); + let d = &r.document; + let stops = gradient_stops(d); + let (Some(first), Some(last)) = (stops.first(), stops.last()) else { panic!("no gradient: {stops:?}") }; + // Gold at 0 % is cyan alone; Gold at 100 % keeps the cyan plate. + assert_eq!((first.swatch.as_deref(), first.plates), (None, None), "{first:?}"); + assert!(near(first.color, Color::cmyk(0.3, 0.0, 0.0, 0.0)), "{first:?}"); + assert_eq!(last.swatch.as_deref(), Some("Gold"), "{last:?}"); + assert!((last.tint - 1.0).abs() < 1e-3, "{last:?}"); + let plates = last.plates.unwrap_or_else(|| panic!("no plates: {last:?}")); + assert!((plates[0] - 0.3).abs() < 1e-3 && plates[1..].iter().all(|p| *p == 0.0), "{plates:?}"); + // The stop looks as the file draws it: cyan and yellow, a green. + let [r_, g_, b_] = last.color.to_rgb(); + assert!(g_ > r_ && g_ > b_, "{:?}", last.color); + for standard in [Standard::None, Standard::PdfX4] { + let mut o = PdfOptions::uncompressed(); + (o.settings.standard, o.settings.compatibility) = (standard, standard.version()); + let text = String::from_utf8_lossy(&export(d, &o).unwrap()).into_owned(); + assert!(text.contains("/DeviceN [/Cyan /Gold]") || text.contains("/DeviceN[/Cyan/Gold]"), "{standard:?}: no DeviceN space of Cyan and Gold"); + assert!(text.contains("/Separation /Gold") || text.contains("/Separation/Gold"), "{standard:?}: Gold has no Separation colorant"); + assert!(text.contains("/C0 [0.3 0]") || text.contains("/C0[0.3 0]"), "{standard:?}: the first stop is cyan alone"); + assert!(text.contains("/C1 [0.3 1]") || text.contains("/C1[0.3 1]"), "{standard:?}: the last stop is cyan and Gold"); } } diff --git a/crates/pdf/src/tests/links.rs b/crates/pdf/src/tests/links.rs new file mode 100644 index 0000000000..c23854439f --- /dev/null +++ b/crates/pdf/src/tests/links.rs @@ -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> { + let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap(); + file.pages() + .iter() + .map(|page| { + let Some(annots) = page.raw().get::>(b"Annots") else { return vec![] }; + annots + .iter::>() + .filter(|a| a.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Link")) + .map(|a| { + let action = a.get::>(b"A").unwrap(); + assert_eq!(action.get::>(b"S").unwrap().as_ref(), b"URI"); + let uri = action.get::>(b"URI").unwrap().as_bytes().to_vec(); + let r: Vec = a.get::>(b"Rect").unwrap().iter::().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"))); +} diff --git a/crates/render/src/blobs.rs b/crates/render/src/blobs.rs index 88d7216380..ab5d831a0b 100644 --- a/crates/render/src/blobs.rs +++ b/crates/render/src/blobs.rs @@ -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) } @@ -77,18 +78,18 @@ pub(crate) fn mip_level(m: Affine, w: u16, h: u16) -> u8 { } /// Image pixels `pm` (stored as `key`) to draw through `m` (unit square → device pixels), shrunk -/// by halves while still at least as fine as the device pixels ([`images::mip_level`]); the -/// pixels drawn are marked used in the store. -pub(crate) fn image_mip(key: &images::ImageKey, pm: Arc, m: Affine) -> Arc { +/// by halves while still at least as fine as the device pixels ([`images::mip_level`]), and their +/// key; the pixels drawn are marked used in the store. +pub(crate) fn image_mip(key: images::ImageKey, pm: Arc, m: Affine) -> (images::ImageKey, Arc) { let level = mip_level(m, pm.width(), pm.height()); let mut s = images::store(); if level == 0 { - let _ = s.get(key); // Marks the full pixels used (they were only looked at). - return pm; + let _ = s.get(&key); // Marks the full pixels used (they were only looked at). + return (key, pm); } let at = |l: u8| images::ImageKey { mip: l, ..key.clone() }; if let Some(p) = s.get(&at(level)) { - return p; + return (at(level), p); } // From the finest level kept below it. let (mut l, mut cur) = (1..level).rev().find_map(|l| s.peek(&at(l)).map(|p| (l, p))).unwrap_or((0, pm)); @@ -98,7 +99,7 @@ pub(crate) fn image_mip(key: &images::ImageKey, pm: Arc, m: Affine) -> A let half = Arc::new(images::half(&cur)); cur = images::store().insert(at(l), half); } - cur + (at(level), cur) } /// Can image node `n` (`im`) clipped by `region` be painted straight into the region: visible, diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 81b7198937..df71c6da97 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -1,6 +1,6 @@ use super::options::{AntiAlias, RenderOptions}; use super::threads::single_threaded_context; -use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, live}; +use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, kurbo, live}; /// Hasher for pointer-keyed caches: a multiply-xorshift (SipHash showed up in frame profiles). #[derive(Default, Clone, Copy)] @@ -30,23 +30,46 @@ pub(crate) type PtrMap = HashMap, pub(crate) outline: Arc, pub(crate) stamp: u64, pub(crate) crop: Option, + pub(crate) own: bool, } /// The slices of a stroke whose gradient runs along or across it, each with its paint and bounds. pub(crate) type Slices = Arc>; -/// [`Slices`] cached for a stroke: (owning node, slices, last frame used). +/// The key of cached [`Slices`]: ([`Renderer::stroke_owner`] of the stroke's object, stroke layer +/// address, tolerance level). +pub(crate) type SliceKey = (usize, usize, i32); + +/// What the [`SliceKey`] of the latest slices of an object's stroke is found under once the object +/// has changed: (the object's id, the stroke's place in its appearance items, tolerance level). +pub(crate) type MovedSliceKey = (u64, usize, i32); + +/// [`Slices`] cached for a stroke: (owning node, the node whose path and stroke the slices were +/// made from, either the owning node or an earlier copy of it that the owning node is moved from, +/// the slices, the offset they are drawn moved by, the fill rule they were made with, whether they +/// were made along the path [`Node::stroke_path`] makes from that node, last frame used). pub(crate) struct SliceEntry { pub(crate) node: Arc, + pub(crate) made: Arc, pub(crate) slices: Slices, + pub(crate) by: kurbo::Vec2, + pub(crate) rule: FillRule, + pub(crate) own: bool, pub(crate) stamp: u64, } diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index a49817cd06..3f13d1b3e3 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -70,7 +70,11 @@ impl Renderer { } let fits = full.area() <= PIXEL_BUDGET; // Device pixels from a pixel to the content deciding it (`None`: anywhere). - let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx).map(|d| m + d / f.px)); + // De-Interlace's field lines and Color Halftone's pixels: the rows of the document's + // raster grid (1 to 2400 ppi). + let ppi = doc_raster_ppi(f.doc); + let line = 72.0 / ppi; + let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx, line).map(|d| m + d / f.px)); let linear = linear_key(f.view); let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink)); // Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a @@ -104,13 +108,14 @@ impl Renderer { Ink::Display | Ink::RichBlack if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk, _ => effects::pixel::Channels::Rgb, }; - // De-Interlace's field lines: the rows of the document's raster grid (1 to 2400 ppi). - let ppi = doc_raster_ppi(f.doc); // What the content reads (as the raster kept for it found it, else found now), with the - // channels the effects run on and, under De-Interlace or Rasterize, the resolution. + // channels the effects run on and, under De-Interlace, Color Halftone (its dots are sized + // in the grid's pixels) or Rasterize, the resolution. let inputs = key.map(|key| { let reads = self.pixel_fx.get(&key).filter(|e| e.node.is(content.node)).map_or_else(|| Reads::of(content.node), |e| e.inputs.reads); - let interlaced = chain.iter().any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. }) | RasterFx::Rasterize(_))); + let interlaced = chain + .iter() + .any(|fx| matches!(fx, RasterFx::Pixel(PixelFx::DeInterlace { .. } | PixelFx::ColorHalftone { .. }) | RasterFx::Rasterize(_))); self.raster_inputs(f, content.node, reads).with((std::mem::discriminant(&channels), interlaced.then_some(ppi.to_bits()))) }); let interacting = f.opts.interacting; @@ -156,7 +161,6 @@ impl Renderer { let to_doc = view.inverse(); let px = f.px / k; let frame = Frame { mt: false, view, visible: to_doc.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)), px, ..*f }; - let line = 72.0 / ppi; let (before, decoded) = (self.stats.moved, crate::paint::decode_failures()); let outer_image_left_out = self.image_left_out.replace(false); let pattern_images_left_out = crate::pattern::images_left_out(); @@ -232,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 { @@ -644,7 +651,7 @@ impl Renderer { AppearanceItem::Stroke(st) => { let st = &*f.stroke(st); let w = effects::stroke::aligned_width(st, effects::stroke::is_closed(ig)); - effects::stroke::line_outline(&effects::stroke::stroke_pieces(ig, st).line, st, w, f.px * 0.25) + crate::stroke::outline(&effects::stroke::stroke_pieces(ig, st).line, st, w, f.px * 0.25) } }; let outset = n.appearance.outset(); diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index 70bbafec52..5fa9b107ed 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -70,12 +70,12 @@ pub(super) fn hard_edged(chain: &[&RasterFx], px: f64) -> bool { matches!(chain.first(), Some(RasterFx::Rasterize(r)) if !r.anti_alias && r.cell(72.0) >= px) } -/// How far (document units) from a pixel the content deciding it after `fx` lies; `None` when -/// anywhere in the object. -pub(super) fn looks_around(fx: &RasterFx) -> Option { +/// How far (document units) from a pixel the content deciding it after `fx` lies, with the +/// document's raster grid lines `line` apart; `None` when anywhere in the object. +pub(super) fn looks_around(fx: &RasterFx, line: f64) -> Option { match fx { - RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius } => Some(1.5 * radius), - RasterFx::Pixel(p) => p.reach(), + 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), } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 987499710f..fd8d68a98d 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -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. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 031c5afa94..74ff632d67 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -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 = (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"); + } +} diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index a187be25e7..dbdbf00669 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -15,6 +15,7 @@ use std::collections::HashMap; use std::sync::{Arc, LazyLock, Mutex, MutexGuard, Weak}; use vectorcraft_doc::ImageBlob; +use vectorcraft_doc::cmyk::Inks; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -107,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 @@ -375,21 +378,71 @@ pub fn newly_undecodable<'a>(blobs: impl IntoIterator) -> /// `pm` at half the size (rounded up), each pixel the mean of the 2×2 it covers (the last row and /// column repeat on odd sizes). pub(crate) fn half(pm: &Pixmap) -> Pixmap { - let (w, h) = (pm.width() as usize, pm.height() as usize); + let (data, ow, oh) = half_with(pm.data(), pm.width().into(), pm.height().into(), PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }, |q| PremulRgba8 { + r: mean(q.map(|p| p.r)), + g: mean(q.map(|p| p.g)), + b: mean(q.map(|p| p.b)), + a: mean(q.map(|p| p.a)), + }); + Pixmap::from_parts(data, ow as u16, oh as u16) +} + +/// CMYK image ink amounts `inks` at half the size, as [`half`] halves pixels: each ink the mean +/// of the 2×2 it covers. `None` only if the halved size were no CMYK image's, which a halved +/// image's never is. +pub(crate) fn half_inks(inks: &Inks) -> Option { + let (w, h) = (usize::try_from(inks.width).ok()?, usize::try_from(inks.height).ok()?); + let (data, ow, oh) = + half_with(inks.data.as_chunks::<4>().0, w, h, [0; 4], |q| std::array::from_fn(|c| mean(q.map(|p| p.get(c).copied().unwrap_or(0))))); + Inks::new(u32::try_from(ow).ok()?, u32::try_from(oh).ok()?, data.into_flattened()) +} + +/// `w`×`h` texels `src` at half the size (rounded up, at least 1×1), each the `mean` of the 2×2 +/// it covers (the last row and column repeat on odd sizes; `blank` stands in for texels `src` +/// is short of), and that size. +fn half_with(src: &[T], w: usize, h: usize, blank: T, mean: impl Fn([T; 4]) -> T) -> (Vec, usize, usize) { let (ow, oh) = (w.div_ceil(2).max(1), h.div_ceil(2).max(1)); - let src = pm.data(); - let at = |x: usize, y: usize| { - src.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or(PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }) - }; - let mut data = Vec::with_capacity(ow * oh); - for y in 0..oh { - for x in 0..ow { - let q = [at(2 * x, 2 * y), at(2 * x + 1, 2 * y), at(2 * x, 2 * y + 1), at(2 * x + 1, 2 * y + 1)]; - let mean = |c: fn(&PremulRgba8) -> u8| ((q.iter().map(|p| u32::from(c(p))).sum::() + 2) / 4) as u8; - data.push(PremulRgba8 { r: mean(|p| p.r), g: mean(|p| p.g), b: mean(|p| p.b), a: mean(|p| p.a) }); + let at = |x: usize, y: usize| src.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or(blank); + let data = (0..oh) + .flat_map(|y| (0..ow).map(move |x| (x, y))) + .map(|(x, y)| mean([at(2 * x, 2 * y), at(2 * x + 1, 2 * y), at(2 * x, 2 * y + 1), at(2 * x + 1, 2 * y + 1)])) + .collect(); + (data, ow, oh) +} + +/// The mean of four channel values, rounded to nearest. +fn mean(v: [u8; 4]) -> u8 { + ((v.iter().map(|&c| u32::from(c)).sum::() + 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 { + 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 = 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); } } - Pixmap::from_parts(data, ow as u16, oh as u16) } /// Pixels `pm` colorized with `rgb`: each pixel takes the color, as opaque as the pixel is dark @@ -427,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] diff --git a/crates/render/src/ink.rs b/crates/render/src/ink.rs index d4a5629e56..dee93e9030 100644 --- a/crates/render/src/ink.rs +++ b/crates/render/src/ink.rs @@ -395,6 +395,22 @@ pub(crate) fn cmyk_pixmap(blob: &ImageBlob, lut: &InkLut) -> Option { 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 { + if !shows_own_inks(key) { + return None; + } + (0..key.mip).try_fold(blob?.cmyk()?, |inks, _| images::half_inks(&inks)) +} + /// The separation tables of placed images ([`Ink::Cmy`], [`Ink::K`]) and their generation. fn separation() -> (Arc<[ProofLut; 2]>, u64) { cached(&SEPARATE, |cms| { @@ -432,10 +448,7 @@ fn darkened_image(key: &ImageKey, pm: &Arc, ink: Ink, amount: f32, blob: } let base = ink.base(); let display = matches!(base, Ink::Display | Ink::RichBlack); - let raw_cmyk = (key.luts.0 != 0 && key.adjust.is_none() && !key.grey) - .then(|| blob.and_then(ImageBlob::cmyk)) - .flatten() - .filter(|i| (i.width, i.height) == (u32::from(pm.width()), u32::from(pm.height()))); + let raw_cmyk = key_inks(key, blob).filter(|i| (i.width, i.height) == (u32::from(pm.width()), u32::from(pm.height()))); let sep = (!display).then(separation); let shown = (display && raw_cmyk.is_some()).then(display_lut); let mut out = Pixmap::new(pm.width(), pm.height()); @@ -487,8 +500,7 @@ pub(crate) fn ink_image(key: &ImageKey, pm: &Arc, ink: Ink, blob: Option } // CMYK images (shown through the display table) paint their own inks; the others are separated. let size = (pm.width() as u32, pm.height() as u32); - let cmyk = key.luts.0 != 0 && key.adjust.is_none() && !key.grey; - let inks = blob.filter(|_| cmyk).and_then(ImageBlob::cmyk).filter(|i| (i.width, i.height) == size); + let inks = key_inks(key, blob).filter(|i| (i.width, i.height) == size); let planes = [Ink::Cmy, Ink::K].map(|plane| { let mut out = Pixmap::new(pm.width(), pm.height()); if let Some(inks) = &inks { @@ -532,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)); diff --git a/crates/render/src/kept_paths.rs b/crates/render/src/kept_paths.rs index 4525a0f1c3..293e824664 100644 --- a/crates/render/src/kept_paths.rs +++ b/crates/render/src/kept_paths.rs @@ -1,25 +1,39 @@ //! The paths of long paths and compound paths kept by object id, with the boxes of their segments //! and of their miter tips by runs of segments. When an object's anchors move, the renderer changes -//! only the path elements, boxes and tips of the segments that start or end at a moved anchor, -//! instead of making its path again and measuring it whole. +//! only the path elements, boxes and tips of the segments that start or end at a moved anchor. +//! When anchors are added or deleted, or a subpath is closed or opened, it replaces only the path +//! elements of the segments between the first and the last anchor that changed, and measures again +//! only the runs that hold them. When a compound path gains or loses members, or a member gains or +//! loses subpaths, it makes the path of those members again. In each case it does not make the +//! object's path again or measure it whole. use std::sync::Arc; use vectorcraft_doc::{LineJoin, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::bez::has_length; use vectorcraft_geom::path::segment_bounds; -use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Rect, SubPath}; +use vectorcraft_geom::{Anchor, BezPath, PathData, PathEl, PathSeg, Point, Rect, SubPath}; /// Paths and compound paths with at least this many anchors are kept ([`KeptPath`]). pub(crate) const KEPT_ANCHORS: usize = 1024; -/// Segments measured together into one box. -const RUN: usize = 128; +/// Segments measured together into one box in a subpath measured whole. A run that anchors were +/// added to or deleted from holds more or fewer, and one that grows past twice this is split. +pub(crate) const RUN: usize = 128; + +/// The most subpaths one edit may add anchors to, delete anchors from, close or open: past this, +/// the kept path is made again whole. +const SPLICES: usize = 16; /// The boxes and the miter tips' boxes of a subpath's runs ([`KeptPath::runs`]). #[cfg(test)] pub(crate) type RunBoxes = (Vec>, Vec>); +/// A subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each of its +/// runs ([`KeptPath::layout`]). +#[cfg(test)] +pub(crate) type Layout = ((usize, usize, usize, bool), Vec); + /// A subpath of a kept path. struct Sub { /// Where its MoveTo is in the path's elements. @@ -28,7 +42,9 @@ struct Sub { segs: usize, anchors: usize, closed: bool, - /// The box of each run of [`RUN`] segments ([`segment_bounds`]). + /// The segment after the last of each run of segments. + ends: Vec, + /// The box of each run of segments ([`segment_bounds`]). boxes: Vec>, /// The box of the miter tips of `tips_of` at the joints whose first segment is in each run. tips: Vec>, @@ -72,8 +88,14 @@ pub(crate) fn kept(n: &Node) -> bool { /// Whether anchors `a` and `b` have the same points, bit for bit. fn same(a: &Anchor, b: &Anchor) -> bool { - let bits = |a: &Anchor| [a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits); - bits(a) == bits(b) + same_drawn(a, b, true, true) +} + +/// Whether anchors `a` and `b` have the same point, bit for bit, and the same incoming handle when +/// `h_in` and outgoing handle when `h_out`. +fn same_drawn(a: &Anchor, b: &Anchor, h_in: bool, h_out: bool) -> bool { + let bits = |p: Point| [p.x, p.y].map(f64::to_bits); + bits(a.p) == bits(b.p) && (!h_in || bits(a.h_in) == bits(b.h_in)) && (!h_out || bits(a.h_out) == bits(b.h_out)) } /// The path element of segment `i` of `sp`, as [`SubPath::to_bezpath_into`] writes it. @@ -82,15 +104,62 @@ fn element(sp: &SubPath, i: usize) -> PathEl { if sp.segment_is_line(i) { PathEl::LineTo(c.p3) } else { PathEl::CurveTo(c.p1, c.p2, c.p3) } } +/// Element `o` of the elements [`SubPath::to_bezpath_into`] writes for `sp`, a subpath with +/// anchors: its MoveTo, then its segments, then its ClosePath. +fn element_at(sp: &SubPath, o: usize) -> PathEl { + match o { + 0 => PathEl::MoveTo(sp.anchors.first().map_or(Point::ORIGIN, |a| a.p)), + o if o <= sp.segment_count() => element(sp, o - 1), + _ => PathEl::ClosePath, + } +} + /// The point a path element ends at (`None` for a ClosePath). -fn end(el: &PathEl) -> Option { +fn end(el: &PathEl) -> Option { match *el { PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), PathEl::ClosePath => None, } } +/// The ends of the runs of a subpath of `segs` segments measured whole: [`RUN`] segments each. +fn whole_runs(segs: usize) -> Vec { + (1..=segs.div_ceil(RUN)).map(|r| (r * RUN).min(segs)).collect() +} + +/// The paths `ps` written over the `len` elements at `at` in `els`, and their subpaths measured +/// whole with the tips of `st`. `at` moves past them. +fn made_again(ps: &[&PathData], len: usize, els: &mut Vec, at: &mut usize, st: Option<&StrokeLayer>) -> Vec> { + let mut bp = BezPath::new(); + ps.iter().flat_map(|p| &p.subpaths).for_each(|sp| sp.to_bezpath_into(&mut bp)); + let to = (*at + len).min(els.len()); + els.splice((*at).min(to)..to, bp.into_elements()); + let mut measure = |sp: &SubPath| { + let sub = Sub::measured(sp, *at, els, st); + *at += sub.len(); + sub + }; + ps.iter().map(|p| p.subpaths.iter().map(&mut measure).collect()).collect() +} + impl Sub { + /// Subpath `sp`, its MoveTo at `start` in `els`, measured whole, with the tips of `st`. + fn measured(sp: &SubPath, start: usize, els: &[PathEl], st: Option<&StrokeLayer>) -> Self { + let segs = sp.segment_count(); + let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, ends: whole_runs(segs), boxes: vec![], tips: vec![] }; + sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); + if let Some(st) = st { + sub.tips = (0..sub.runs()).map(|r| sub.run_tips(els, r, st)).collect(); + } + sub + } + + /// Its elements in the path: none without anchors, otherwise its MoveTo, its segments and + /// its ClosePath when closed. + fn len(&self) -> usize { + if self.anchors == 0 { 0 } else { 1 + self.segs + usize::from(self.closed) } + } + /// Segment `i`, as kurbo's `segments` makes it from the path's elements. fn seg(&self, els: &[PathEl], i: usize) -> Option { let p0 = end(els.get(self.start + i)?)?; @@ -103,12 +172,23 @@ impl Sub { } fn runs(&self) -> usize { - self.segs.div_ceil(RUN) + self.ends.len() + } + + /// The segments of run `r`. + fn range(&self, r: usize) -> std::ops::Range { + let from = r.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0); + from..self.ends.get(r).copied().unwrap_or(from) + } + + /// The run that holds segment `i` (the last run for a segment past the end). + fn run_of(&self, i: usize) -> usize { + self.ends.partition_point(|&e| e <= i).min(self.runs().saturating_sub(1)) } /// The box of the segments of run `r`. fn run_box(&self, els: &[PathEl], r: usize) -> Option { - (r * RUN..((r + 1) * RUN).min(self.segs)).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) + self.range(r).filter_map(|i| self.seg(els, i)).map(segment_bounds).reduce(|a, b| a.union(b)) } /// The segment with length that follows segment `i` (round to the start when closed), or @@ -140,7 +220,7 @@ impl Sub { /// ([`StrokeLayer::miter_tip`]). fn run_tips(&self, els: &[PathEl], r: usize, st: &StrokeLayer) -> Option { let mut out: Option = None; - for i in r * RUN..((r + 1) * RUN).min(self.segs) { + for i in self.range(r) { let Some(a) = self.seg(els, i).filter(has_length) else { continue }; let Some(b) = self.next_drawn(els, i) else { continue }; if let Some(tip) = st.miter_tip(self.closed, &a, &b) { @@ -149,6 +229,229 @@ impl Sub { } out } + + /// Bring the subpath, its MoveTo now at `at` in `els`, up to date from `was` to `now`, with the + /// tips of `st`. + fn update(&mut self, was: &SubPath, now: &SubPath, at: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + self.start = at; + if was.anchors.len() == now.anchors.len() && was.closed == now.closed { + self.moved(was, now, els, st); + } else if was.anchors.len() < 2 || now.anchors.len() < 2 { + self.remade(now, at, self.len(), els, st); + } else { + let mut span = self.len(); + if self.spliced(was, now, els, st, &mut span).is_none() { + self.remade(now, at, span, els, st); + } + } + } + + /// Write the elements of `now` over the `span` elements at `at` in `els` that the subpath holds, + /// and measure it whole with the tips of `st`. + fn remade(&mut self, now: &SubPath, at: usize, span: usize, els: &mut Vec, st: Option<&StrokeLayer>) { + let to = at.saturating_add(span).min(els.len()); + let len = if now.anchors.is_empty() { 0 } else { 1 + now.segment_count() + usize::from(now.closed) }; + els.splice(at.min(to)..to, (0..len).map(|o| element_at(now, o))); + *self = Sub::measured(now, at, els, st); + } + + /// [`Self::update`] for a subpath with the same anchor count and closed state: the elements of + /// the segments that start or end at an anchor that moved are made again, with the boxes of + /// their runs and the tips of those runs and of the runs of the segments with length before + /// them. + fn moved(&mut self, was: &SubPath, now: &SubPath, els: &mut [PathEl], st: Option<&StrokeLayer>) { + let (mut first, mut segs) = (false, vec![]); + for (k, (a, b)) in was.anchors.iter().zip(&now.anchors).enumerate() { + if same(a, b) { + continue; + } + if k >= 1 && k - 1 < self.segs { + segs.push(k - 1); + } + if k == 0 { + first = true; + if self.closed && self.segs > 0 { + segs.push(self.segs - 1); + } + } + if k < self.segs { + segs.push(k); + } + } + if !first && segs.is_empty() { + return; + } + segs.sort_unstable(); + segs.dedup(); + if first && let (Some(a), Some(el)) = (now.anchors.first(), els.get_mut(self.start)) { + *el = PathEl::MoveTo(a.p); + } + for &i in &segs { + if let Some(el) = els.get_mut(self.start + 1 + i) { + *el = element(now, i); + } + } + let els: &[PathEl] = els; + // Many moved: the subpath is measured again whole. + let all = segs.len() * 4 > self.segs; + let mut boxes: Vec = if all { (0..self.runs()).collect() } else { segs.iter().map(|&i| self.run_of(i)).collect() }; + boxes.dedup(); + for r in boxes { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return }; + // A joint's tip changes with its segments and with which segment with length comes next: + // the runs of the moved segments and of the segments with length before them. + let mut runs = vec![]; + let mut whole = all; + for &i in &segs { + runs.push(self.run_of(i)); + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + } + + /// [`Self::update`] for a subpath of at least two anchors before and after that gained or lost + /// anchors or was closed or opened. Its elements from the first anchor that changed to the + /// last are written again, and the closing segment and the ClosePath when the first or last + /// anchor changed or it was closed or opened; the elements before and after stay. The runs + /// that held the segments written are measured again, with the tips of the runs of the + /// segments with length before them. `span` is the count of elements the subpath holds in + /// `els`, kept up to date as they are written. `None` when the segments and runs kept do not + /// fit `was`: the caller then makes the subpath again from those `span` elements. + fn spliced(&mut self, was: &SubPath, now: &SubPath, els: &mut Vec, st: Option<&StrokeLayer>, span: &mut usize) -> Option<()> { + let (n0, n1) = (was.anchors.len(), now.anchors.len()); + let least = n0.min(n1); + // On a subpath open before and after, the handle before the first anchor and the one after + // the last draw nothing. + let open = !was.closed && !now.closed; + let a = was.anchors.iter().zip(&now.anchors).enumerate().take_while(|(i, (x, y))| same_drawn(x, y, !open || *i > 0, true)).count().min(least); + let b = was + .anchors + .iter() + .rev() + .zip(now.anchors.iter().rev()) + .take(least - a) + .enumerate() + .take_while(|(i, (x, y))| same_drawn(x, y, true, !open || *i > 0)) + .count(); + let (s0, s1) = (self.segs, now.segment_count()); + let (c0, c1) = (self.closed, now.closed); + let (len0, len1) = (1 + s0 + usize::from(c0), 1 + s1 + usize::from(c1)); + // Elements `a..mid` change: the MoveTo when the first anchor changed and the segments up + // to the first of those between the last `b` anchors. + let (mid0, mid1) = ((1 + n0.checked_sub(b)?).min(1 + s0), (1 + n1.checked_sub(b)?).min(1 + s1)); + // Elements `tail..len` follow the segments between the last `b` anchors: the closing + // segment and the ClosePath. They stay when the anchors either side of the closing segment + // stayed and the subpath was neither closed nor opened. + let (tail0, tail1) = if b >= 1 { (n0, n1) } else { (mid0, mid1) }; + let keep_tail = c0 == c1 && (!c1 || b == 0 || a >= 1); + // The `old` segments from segment `lo` become `new` segments, and when the tail is written, + // the segments from the one before it do too. + let lo = a.saturating_sub(1); + let (old, new) = (mid0.checked_sub(1)?.checked_sub(lo)?, mid1.checked_sub(1)?.checked_sub(lo)?); + let tail = match keep_tail { + true => None, + false => Some((tail0.checked_sub(1)?, (1 + s0).saturating_sub(tail0), (1 + s1).saturating_sub(tail1), tail1.checked_sub(1)?)), + }; + let at = self.start; + let mut stale = vec![false; self.runs()]; + let tips = st.is_some(); + // Writes elements `e0..e1` of `now` over elements `o0..o1` of the subpath and updates `span`. + let mut write = |els: &mut Vec, (o0, o1): (usize, usize), (e0, e1): (usize, usize)| { + let to = at.saturating_add(o1).min(els.len()); + let from = at.saturating_add(o0).min(to); + els.splice(from..to, (e0..e1).map(|o| element_at(now, o))); + *span = from.saturating_sub(at) + e1.saturating_sub(e0) + at.saturating_add(*span).saturating_sub(to); + }; + if let Some((lo, old, new, _)) = tail { + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (tail0, len0), (tail1, len1)); + } + self.resize(lo, old, new, &mut stale, tips)?; + write(els, (a, mid0), (a, mid1)); + self.anchors = n1; + self.closed = c1; + let els: &[PathEl] = els; + for (r, _) in stale.iter().enumerate().filter(|(_, s)| **s) { + let b = self.run_box(els, r); + if let Some(slot) = self.boxes.get_mut(r) { + *slot = b; + } + } + let Some(st) = st else { return Some(()) }; + let mut runs: Vec = stale.iter().enumerate().filter(|(_, s)| **s).map(|(r, _)| r).collect(); + // Closed or opened: the tips of every joint change when the stroke reaches farther from one + // than from the other. + let mut whole = c0 != c1 && st.side_reach(c0).to_bits() != st.side_reach(c1).to_bits(); + for i in [lo].into_iter().chain(tail.map(|(.., last)| last)) { + match self.prev_drawn(els, i) { + Ok(Some(j)) => runs.push(self.run_of(j)), + Ok(None) => {} + Err(()) => whole = true, + } + } + self.measure_tips(els, runs, whole, st); + Some(()) + } + + /// Replace the `old` segments from segment `lo` with `new` segments in the runs: the runs that + /// held them become one run, split into runs of [`RUN`] segments when longer than twice that, + /// whose boxes and (with `tips`) tips are marked in `stale` to be measured again. `None`, and + /// nothing changed, when the runs kept do not hold those `old` segments. + fn resize(&mut self, lo: usize, old: usize, new: usize, stale: &mut Vec, tips: bool) -> Option<()> { + if old == 0 && new == 0 { + return Some(()); + } + let (r0, r1, first, last) = match self.runs() { + 0 => (0, 0, 0, new), + _ => { + let r0 = self.run_of(lo); + let r1 = if old == 0 { r0 } else { self.run_of(lo + old - 1) }; + let last = self.ends.get(r1).copied().unwrap_or(lo + old).checked_add(new)?.checked_sub(old)?; + (r0, r1 + 1, self.range(r0).start, last) + } + }; + let len = last.checked_sub(first)?; + let segs = self.segs.checked_add(new)?.checked_sub(old)?; + let after: Vec = self.ends.get(r1..)?.iter().map(|&e| e.checked_add(new)?.checked_sub(old)).collect::>()?; + if r1 > self.boxes.len() || r1 > stale.len() { + return None; + } + let count = if len > 2 * RUN { len.div_ceil(RUN) } else { usize::from(len > 0) }; + self.ends.truncate(r1); + self.ends.extend(after); + self.ends.splice(r0..r1, (1..=count).map(|j| if j == count { last } else { first + j * RUN })); + self.boxes.splice(r0..r1, std::iter::repeat_n(None, count)); + if tips { + self.tips.splice(r0.min(self.tips.len())..r1.min(self.tips.len()), std::iter::repeat_n(None, count)); + } + stale.splice(r0..r1, std::iter::repeat_n(true, count)); + self.segs = segs; + Some(()) + } + + /// Measure again the tips of `st` in `runs`, or in every run when `whole`. + fn measure_tips(&mut self, els: &[PathEl], mut runs: Vec, whole: bool, st: &StrokeLayer) { + if whole { + runs = (0..self.runs()).collect(); + } + runs.sort_unstable(); + runs.dedup(); + for r in runs { + let t = self.run_tips(els, r, st); + if let Some(slot) = self.tips.get_mut(r) { + *slot = t; + } + } + } } /// What [`KeptPath::tips`] measures `st`'s tips by: its reach from an open and a closed path and @@ -157,6 +460,24 @@ fn tips_key(st: &StrokeLayer) -> [u64; 3] { [st.side_reach(false).to_bits(), st.side_reach(true).to_bits(), st.miter_limit.to_bits()] } +/// Whether the subpaths of `was` and `now` differ: in number, in anchors or in being closed. +fn differs(was: &PathData, now: &PathData) -> bool { + !std::ptr::eq(was, now) + && (was.subpaths.len() != now.subpaths.len() + || was.subpaths.iter().zip(&now.subpaths).any(|(w, p)| { + w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.iter().zip(&p.anchors).any(|(a, b)| !same(a, b)) + })) +} + +/// The subpaths of `was` and `now`, paths with as many subpaths, whose anchors were added or +/// deleted or that were closed or opened. +fn splices(was: &PathData, now: &PathData) -> usize { + if std::ptr::eq(was, now) || was.subpaths.len() != now.subpaths.len() { + return 0; + } + was.subpaths.iter().zip(&now.subpaths).filter(|(w, p)| w.anchors.len() != p.anchors.len() || w.closed != p.closed).count() +} + impl KeptPath { /// The kept path of `n`, or `None` when it has none ([`kept`]). pub(crate) fn new(n: &Arc, stamp: u64) -> Option { @@ -170,12 +491,8 @@ impl KeptPath { for pd in paths(n)? { let mut subs = vec![]; for sp in &pd.subpaths { - let segs = sp.segment_count(); - let mut sub = Sub { start, segs, anchors: sp.anchors.len(), closed: sp.closed, boxes: vec![], tips: vec![] }; - sub.boxes = (0..sub.runs()).map(|r| sub.run_box(els, r)).collect(); - if !sp.anchors.is_empty() { - start += 1 + segs + usize::from(sp.closed); - } + let sub = Sub::measured(sp, start, els, None); + start += sub.len(); subs.push(sub); } parts.push(subs); @@ -183,106 +500,90 @@ impl KeptPath { (start == els.len()).then(|| Self { node: n.clone(), path: Arc::new(path), parts, tips_of: None, stamp }) } - /// Bring the path up to date with `n`, a path with the same subpaths and anchor counts as the - /// object it was made from: the elements of the segments that start or end at an anchor that - /// moved are made again, with the boxes of their runs and the tips of those runs and of the - /// runs of the segments with length before them. False, and nothing changed, when `n` has - /// other subpaths, other anchor counts or no kept path. + /// Bring the path up to date with `n`, a later version of the object it was made from. The + /// subpaths whose anchors moved change as [`Sub::moved`] says, and those whose anchors were + /// added or deleted or that were closed or opened as [`Sub::spliced`] says. A member of a + /// compound path that gained or lost subpaths is made again, and so are the members added + /// between the first and the last member that the edit left as they were, when the edit added + /// or removed members. False, and nothing changed, when `n` has no kept path, or when the edit + /// added or deleted anchors in or closed or opened more than [`SPLICES`] subpaths, or when the + /// members kept do not pair with those of `n`. A subpath whose segments or runs kept do not fit + /// its anchors before the edit is made again whole ([`Sub::spliced`]). False as well + /// when the path written does not end where the subpaths measured end. The renderer makes the + /// path again whole after a false. pub(crate) fn update(&mut self, n: &Arc) -> bool { let old = self.node.clone(); let (Some(was), Some(now)) = (paths(&old), paths(n)) else { return false }; - let shape = - |ps: &[&PathData]| ps.iter().map(|p| p.subpaths.iter().map(|s| (s.anchors.len(), s.closed)).collect::>()).collect::>(); - if !kept(n) || shape(&was) != shape(&now) { + if !kept(n) || self.parts.len() != was.len() || self.parts.iter().zip(&was).any(|(s, p)| s.len() != p.subpaths.len()) { return false; } - // Per subpath whose anchors moved: (member, subpath, whether its first anchor moved, the - // segments that start or end at a moved anchor). - let mut moved: Vec<(usize, usize, bool, Vec)> = vec![]; - for (pi, (w, p)) in was.iter().zip(&now).enumerate() { - if std::ptr::eq(*w, *p) { - continue; - } - for (si, (ws, ps)) in w.subpaths.iter().zip(&p.subpaths).enumerate() { - let Some(sub) = self.parts.get(pi).and_then(|s| s.get(si)) else { return false }; - let (mut first, mut segs) = (false, vec![]); - for (k, (a, b)) in ws.anchors.iter().zip(&ps.anchors).enumerate() { - if same(a, b) { - continue; - } - if k >= 1 && k - 1 < sub.segs { - segs.push(k - 1); - } - if k == 0 { - first = true; - if sub.closed && sub.segs > 0 { - segs.push(sub.segs - 1); - } - } - if k < sub.segs { - segs.push(k); - } - } - if first || !segs.is_empty() { - segs.sort_unstable(); - segs.dedup(); - moved.push((pi, si, first, segs)); - } - } + // The members paired with one of `was`: all when there are as many, otherwise those + // before the first and after the last that is not the same. The others are made again. + let (head, tail) = if was.len() == now.len() { + (was.len(), 0) + } else { + let head = was.iter().zip(&now).take_while(|(w, p)| std::ptr::eq(**w, **p)).count(); + let rest = (was.len() - head).min(now.len() - head); + (head, was.iter().rev().zip(now.iter().rev()).take(rest).take_while(|(w, p)| std::ptr::eq(**w, **p)).count()) + }; + // Where the members that are not paired end in `was` and in `now`. + let (Some(was_end), Some(now_end)) = (was.len().checked_sub(tail), now.len().checked_sub(tail)) else { return false }; + if head > was_end || head > now_end { + return false; + } + let paired = |i: usize| match i < head { + true => Some(i), + false => now.len().checked_sub(i).filter(|&back| back <= tail).and_then(|back| was.len().checked_sub(back)), + }; + let spliced: usize = (0..now.len()).filter_map(|i| paired(i).map(|w| splices(was[w], now[i]))).sum(); + if spliced > SPLICES { + return false; } self.node = n.clone(); - if moved.is_empty() { + // Nothing to change: the path is left as it is, shared or not. + if was.len() == now.len() && was.iter().zip(&now).all(|(w, p)| !differs(w, p)) { return true; } + let st = self.tips_of.clone(); + let st = st.as_ref(); let path = Arc::make_mut(&mut self.path); - let els = path.elements_mut(); - for (pi, si, first, segs) in &moved { - let (Some(sub), Some(sp)) = (self.parts.get(*pi).and_then(|s| s.get(*si)), now.get(*pi).and_then(|p| p.subpaths.get(*si))) else { + let mut els = std::mem::take(path).into_elements(); + let mut old_parts: Vec>> = std::mem::take(&mut self.parts).into_iter().map(Some).collect(); + let mut at = 0; + let mut parts = Vec::with_capacity(now.len()); + for (i, p) in now.iter().enumerate() { + if i == head { + // The members of `was` that are not paired give way to those of `now`. + let gone: usize = + old_parts.get_mut(head..was_end).into_iter().flatten().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(now.get(head..now_end).unwrap_or_default(), gone, &mut els, &mut at, st)); + } + let Some(w) = paired(i) else { continue }; + let Some(mut subs) = old_parts.get_mut(w).and_then(Option::take) else { continue }; + if was[w].subpaths.len() != p.subpaths.len() { + let len = subs.iter().map(Sub::len).sum(); + parts.extend(made_again(&[*p], len, &mut els, &mut at, st)); continue; - }; - if *first && let (Some(a), Some(el)) = (sp.anchors.first(), els.get_mut(sub.start)) { - *el = PathEl::MoveTo(a.p); } - for &i in segs { - if let Some(el) = els.get_mut(sub.start + 1 + i) { - *el = element(sp, i); + let moved = !std::ptr::eq(was[w], *p); + for (sub, (ws, ps)) in subs.iter_mut().zip(was[w].subpaths.iter().zip(&p.subpaths)) { + if moved { + sub.update(ws, ps, at, &mut els, st); } + sub.start = at; + at += sub.len(); } + parts.push(subs); } - let els = path.elements(); - for (pi, si, _, segs) in moved { - let tips_of = self.tips_of.as_ref(); - let Some(sub) = self.parts.get_mut(pi).and_then(|s| s.get_mut(si)) else { continue }; - // Many moved: the subpath is measured again whole. - let all = segs.len() * 4 > sub.segs; - let mut boxes: Vec = if all { (0..sub.runs()).collect() } else { segs.iter().map(|i| i / RUN).collect() }; - boxes.dedup(); - for r in boxes { - sub.boxes[r] = sub.run_box(els, r); - } - let Some(st) = tips_of else { continue }; - // A joint's tip changes with its segments and with which segment with length comes - // next: the runs of the moved segments and of the segments with length before them. - let mut runs = vec![]; - let mut whole = all; - for &i in &segs { - runs.push(i / RUN); - match sub.prev_drawn(els, i) { - Ok(Some(j)) => runs.push(j / RUN), - Ok(None) => {} - Err(()) => whole = true, - } - } - if whole { - runs = (0..sub.runs()).collect(); - } - runs.sort_unstable(); - runs.dedup(); - for r in runs { - sub.tips[r] = sub.run_tips(els, r, st); - } + if head == now.len() && head < was.len() { + // Members were removed from the end. + let gone: usize = old_parts[head..].iter_mut().flat_map(|s| s.take().into_iter().flatten()).map(|s| s.len()).sum(); + parts.extend(made_again(&[], gone, &mut els, &mut at, st)); } - true + let made = at == els.len(); + *path = BezPath::from_vec(els); + self.parts = parts; + made } /// The object's geometric bounds ([`Node::geometric_bounds`]): each path's as @@ -318,9 +619,25 @@ impl KeptPath { self.parts.iter().flatten().flat_map(|s| s.tips.iter().flatten()).copied().reduce(|a, b| a.union(b)) } - /// The boxes and tips kept per run of each subpath, and the stroke the tips were measured for. + /// Each subpath's MoveTo, segments and anchors, whether it is closed, and the segments of each + /// of its runs. #[cfg(test)] - pub(crate) fn runs(&self) -> (Vec, Option) { - (self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(), self.tips_of.clone()) + pub(crate) fn layout(&self) -> Vec { + let runs = |s: &Sub| (0..s.runs()).map(|r| s.range(r).len()).collect(); + self.parts.iter().flatten().map(|s| ((s.start, s.segs, s.anchors, s.closed), runs(s))).collect() + } + + /// The boxes and tips kept per run of each subpath, the same measured again from the path + /// over the same runs, and the stroke the tips were measured for. + #[cfg(test)] + pub(crate) fn runs(&self) -> (Vec, Vec, Option) { + let els = self.path.elements(); + let kept = self.parts.iter().flatten().map(|s| (s.boxes.clone(), s.tips.clone())).collect(); + let again = self.parts.iter().flatten().map(|s| { + let boxes = (0..s.runs()).map(|r| s.run_box(els, r)).collect(); + let tips = self.tips_of.as_ref().map_or(vec![], |st| (0..s.runs()).map(|r| s.run_tips(els, r, st)).collect()); + (boxes, tips) + }); + (kept, again.collect(), self.tips_of.clone()) } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index a145ebad1b..46a0ca64a2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -24,6 +24,7 @@ pub use paint::{decode_failures, image_decodes, reduced_size}; mod pattern; pub mod placed_document; pub mod proof; +mod stroke; use std::collections::HashMap; use std::sync::Arc; @@ -52,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, Arc)>, + /// 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, /// The [`vectorcraft_text::FontDb::generation`] `texts` was laid out with: type lays out /// again when fonts are added or rescanned. text_fonts: u64, @@ -74,6 +78,9 @@ pub struct Renderer { /// Expanded stroke outlines keyed by ([`Self::stroke_owner`], stroke layer address, width bits, /// tolerance level): panning re-renders reuse them instead of re-expanding every stroke. strokes: PtrMap, + /// The key in `strokes` of the latest outline of each stroke of an object, under its + /// [`frame::MovedKey`]: a moved copy of the object draws that outline moved ([`Self::moved_outline`]). + moved_strokes: PtrMap, /// Expanded character stroke outlines, with the glyph geometry kept in `texts` they belong to, /// keyed by ([`Self::stroke_owner`] of that geometry, run, width bits, tolerance level): type /// that doesn't change draws them again instead of expanding its strokes in every frame. Within @@ -165,7 +172,11 @@ pub struct Renderer { clip_paints: FrameCache, /// Gradients along or across strokes (see [`Self::fill_path_gradient`]), keyed by /// ([`Self::stroke_owner`], stroke layer address, tolerance level). - stroke_slices: PtrMap<(usize, usize, i32), SliceEntry>, + stroke_slices: PtrMap, + /// The key in `stroke_slices` of the latest slices of each stroke of an object, under its + /// [`frame::MovedSliceKey`]: a moved copy of the object draws those slices moved + /// ([`Self::moved_slices`]). + moved_slices: PtrMap, /// What the image keys colour adjustments give their recoloured images name: the image /// recoloured and the adjustment, with its hash (see [`Self::adjusted_image`]). adjusts: HashMap, diff --git a/crates/render/src/lru.rs b/crates/render/src/lru.rs index 42ab5799b4..bb4808d0e9 100644 --- a/crates/render/src/lru.rs +++ b/crates/render/src/lru.rs @@ -101,6 +101,33 @@ impl FrameCache { 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(&mut self, k: &Q, stamp: u64, accept: impl FnOnce(&V) -> bool) -> Option<&V> + where + K: Borrow, + 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(&mut self, k: &Q) + where + K: Borrow, + 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 FrameCache { self.bytes } - #[cfg(test)] pub(crate) fn contains_key(&self, k: &Q) -> bool where K: Borrow, diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index 0eb25b720e..15d5b4644a 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -135,7 +135,7 @@ pub(crate) fn plate_image(lut: &PlateLut, key: &ImageKey, pm: &Pixmap, blob: Opt return (want, p); } let size = (u32::from(pm.width()), u32::from(pm.height())); - let raw = blob.filter(|_| key.luts.0 != 0 && key.adjust.is_none() && !key.grey).and_then(ImageBlob::cmyk).filter(|i| (i.width, i.height) == size); + let raw = crate::ink::key_inks(key, blob).filter(|i| (i.width, i.height) == size); let mut out = pm.clone(); match raw { Some(inks) => { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 87c283f321..e22d4df5e4 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -18,6 +18,9 @@ use super::{ group, ink, kurbo, live, lru, peniko, proof, vello_cpu, }; +#[cfg(test)] +pub(crate) use paint::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; + mod images; mod nodes; mod paint; @@ -30,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(), @@ -38,6 +42,7 @@ impl Renderer { symbols: vec![], plugin_revision: 0, strokes: PtrMap::default(), + moved_strokes: PtrMap::default(), char_strokes: FrameCache::new(lru::CHAR_STROKE_BUDGET, 0), cur: None, made_again: false, @@ -72,6 +77,7 @@ impl Renderer { twice_drawn: 0, clip_paints: FrameCache::new(lru::CLIP_BUDGET, 256), stroke_slices: PtrMap::default(), + moved_slices: PtrMap::default(), adjusts: HashMap::new(), dim_images: None, inline_depth: 0, @@ -186,9 +192,13 @@ impl Renderer { self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node))); if self.strokes.len() > 1024 { self.strokes.retain(|_, e| g - e.stamp <= 3); + let strokes = &self.strokes; + self.moved_strokes.retain(|_, k| strokes.contains_key(k)); } if self.stroke_slices.len() > 256 { self.stroke_slices.retain(|_, e| g - e.stamp <= 3); + let slices = &self.stroke_slices; + self.moved_slices.retain(|_, k| slices.contains_key(k)); } if self.shadows.len() > 256 { self.shadows.retain(|_, e| g - e.stamp <= 3); @@ -199,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); diff --git a/crates/render/src/renderer/images.rs b/crates/render/src/renderer/images.rs index 6cabfc5bfc..a604481dd4 100644 --- a/crates/render/src/renderer/images.rs +++ b/crates/render/src/renderer/images.rs @@ -1,14 +1,20 @@ use super::{ - Affine, Arc, BezPath, Document, FillRule, Frame, HashMap, Ink, Node, Pixmap, Rect, RenderContext, Renderer, Shape, blob_key, blob_pixmap, - fill_rule, image_mip, ink, lookup, mip_level, peniko, proof, vello_cpu, + Affine, Arc, BezPath, Document, FillRule, Frame, HashMap, Ink, Node, NodeKind, Pixmap, Rect, RenderContext, Renderer, Shape, blob_key, + blob_pixmap, fill_rule, image_mip, ink, lookup, mip_level, peniko, proof, vello_cpu, }; use crate::images; -/// The color image node `n` is colorized with ([`vectorcraft_doc::NodeExtras::colorize`]), if it -/// is, as `ink` paints it: the display color, or on an ink plane the color's own inks, as a fill -/// of that color paints them. -pub(super) fn image_tint(n: &Node, ink: Ink) -> Option<[u8; 3]> { +/// The color image node `n` of `doc` is colorized with ([`vectorcraft_doc::NodeExtras::colorize`]), +/// if it is and its pixels take it ([`vectorcraft_doc::ImageBlob::takes_colorize`]), as `ink` +/// paints it: the display color, or on an ink plane the color's own inks, as a fill of that color +/// paints them. +pub(super) fn image_tint(doc: &Document, n: &Node, ink: Ink) -> Option<[u8; 3]> { let c = n.extras().colorize.as_deref()?.color()?; + if let NodeKind::Image(im) = &n.kind + && doc.image_blob(im).is_some_and(|b| !b.takes_colorize()) + { + return None; + } Some(ink.rgb(&c).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)) } @@ -65,42 +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)| { - let (key, pm) = match tint { - Some(rgb) => colorized_pixmap(key, &pm, rgb, !mips), - 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, f.doc.image_blob(im), !mips) }; - let (key, pm) = match f.plates.filter(|_| !outline && tint.is_none()) { - Some(lut) => proof::plate_image(lut, &key, &pm, f.doc.image_blob(im), !mips), - None => (key, pm), - }; - if mips { image_mip(&key, pm, unit) } else { 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); + // 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(); @@ -298,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, + level: (u32, u32), + at: (u32, u32), +} + +impl Shown { + /// All of the pixels of a level. + fn whole(pm: Arc) -> 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, + grey: bool, + tint: Option<[u8; 3]>, + blob: Option<&vectorcraft_doc::ImageBlob>, +) -> Arc { + 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. @@ -314,10 +437,10 @@ fn shown_key(f: &Frame, key: images::ImageKey, grey: bool, tint: Option<[u8; 3]> } /// Image pixels `pm` (kept as `key`) colorized with `rgb` ([`images::colorized`]), kept with the -/// images, and their key. `touch` marks them used there. -fn colorized_pixmap(key: images::ImageKey, pm: &Pixmap, rgb: [u8; 3], touch: bool) -> (images::ImageKey, Arc) { +/// images and marked used there, and their key. +fn colorized_pixmap(key: images::ImageKey, pm: &Pixmap, rgb: [u8; 3]) -> (images::ImageKey, Arc) { let key = images::ImageKey { tint: Some(rgb), ..key }; - if let Some(p) = lookup(&key, touch) { + if let Some(p) = lookup(&key, true) { return (key, p); } let pm = images::store().insert(key.clone(), Arc::new(images::colorized(pm, rgb))); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index b69ecb10f0..176739c31b 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -218,7 +218,7 @@ impl Renderer { && let Some(region) = self.clip_of(&m.art) && shape_masked_image(a, im, ®ion.0) { - self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(a, f.ink), a.extras().pixelated); + self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(f.doc, a, f.ink), a.extras().pixelated); self.stats.drawn += 1; return; } @@ -486,7 +486,7 @@ impl Renderer { && let NodeKind::Image(im) = &image.kind && plain_image(image, im, ®ion.0) { - self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(image, f.ink), image.extras().pixelated); + self.draw_image_in(ctx, f, im, Some(®ion), images::image_tint(f.doc, image, f.ink), image.extras().pixelated); self.stats.drawn += 1; return; } @@ -536,7 +536,7 @@ impl Renderer { } } NodeKind::Text(t) => self.draw_text(ctx, f, n, t), - NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(n, f.ink), n.extras().pixelated), + NodeKind::Image(im) => self.draw_image_in(ctx, f, im, None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated), NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { // The instance draws when the frame has room for its art's objects; a symbol diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index f31863aa1c..fd205496ae 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -3,6 +3,7 @@ use super::{ Slices, StrokeAlign, StrokeEntry, StrokeLayer, TextGeom, blend_mode, drawable, effects, fill_rule, fx, kurbo, lru, owns_stroke, peniko, rects_overlap, }; +use crate::frame::{MovedKey, MovedSliceKey, StrokeKey}; use crate::paint; impl Renderer { @@ -133,9 +134,9 @@ impl Renderer { } else if paint::set_paint(ctx, &st.paint, paint_bounds, f) { self.fold_alpha(ctx, f.ink, &st.paint); ctx.set_fill_rule(peniko::Fill::NonZero); - match self.cached_stroke(f, chars, &pieces.line, st, width) { + match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => ctx.fill_path(&o), - None => ctx.fill_path(&effects::stroke::line_outline(&pieces.line, st, width, f.px * 0.25)), + None => ctx.fill_path(&crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)), } for head in &pieces.heads { ctx.fill_path(&head.outline); @@ -163,7 +164,9 @@ impl Renderer { /// Paint the line and arrowheads (`pieces`) of stroke `st` of `bp` (filled with `rule`) with /// its gradient `g` laid along or across the path ([`effects::stroke::gradient_slices`]). Each /// piece clips the slices, grown a pixel into each other and each replacing what it covers, so - /// neighbours meet without seams and translucent colours paint once. + /// neighbours meet without seams and translucent colours paint once. The slices of a stroke + /// of `self.cur` are kept in `stroke_slices`, and a moved copy of the object draws the slices + /// made before it moved, moved by the same offset ([`Self::moved_slices`]). #[allow(clippy::too_many_arguments)] fn fill_path_gradient( &mut self, @@ -179,6 +182,8 @@ impl Renderer { ) { let level = (f.px * 0.25).log2().floor() as i32; let make = || -> Slices { + #[cfg(test)] + SLICES_MADE.with(|n| n.set(n.get() + 1)); let tol = 2f64.powi(level); // Reach a pixel past the stroke, so its antialiased edge has colour under it. let slices = effects::stroke::gradient_slices(bp, rule, st, tol, f.px + tol, f.px); @@ -192,26 +197,41 @@ impl Renderer { .collect(), ) }; - let slices = match self.cur.clone().filter(|n| owns_stroke(n, st)) { + let (slices, by) = match self.cur.clone().filter(|n| owns_stroke(n, st)) { Some(node) => { let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, level); match self.stroke_slices.get_mut(&key) { Some(e) if Arc::ptr_eq(&e.node, &node) => { e.stamp = self.stamp; - e.slices.clone() + (e.slices.clone(), e.by) } _ => { - let slices = make(); - self.stroke_slices.insert(key, SliceEntry { node, slices: slices.clone(), stamp: self.stamp }); - slices + // Under its object's id, the stroke's place and the tolerance level, the key + // of the stroke's latest slices is kept, except for art made again in every + // frame. + let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); + let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, level)); + let kept = moved.and_then(|mk| self.moved_slices(mk, &node, st, rule, bp)); + let (made, slices, by, own) = match kept { + Some((made, slices, by)) => (made, slices, by, true), + None => { + let own = moved.is_some() && self.own_path(&node, bp); + (node.clone(), make(), kurbo::Vec2::ZERO, own) + } + }; + self.stroke_slices.insert(key, SliceEntry { node, made, slices: slices.clone(), by, rule, own, stamp: self.stamp }); + if let Some(mk) = moved { + self.moved_slices.insert(mk, key); + } + (slices, by) } } } - None => make(), + None => (make(), kurbo::Vec2::ZERO), }; - let line = match self.cached_stroke(f, chars, &pieces.line, st, width) { + let line = match self.cached_stroke(f, chars, bp, &pieces.line, st, width) { Some(o) => o, - None => Arc::new(effects::stroke::line_outline(&pieces.line, st, width, f.px * 0.25)), + None => Arc::new(crate::stroke::outline(&pieces.line, st, width, f.px * 0.25)), }; ctx.set_fill_rule(peniko::Fill::NonZero); for clip in std::iter::once(&*line).chain(pieces.heads.iter().map(|h| &h.outline)) { @@ -222,8 +242,18 @@ impl Renderer { ctx.push_clip_layer(clip); ctx.set_blend_mode(BlendMode::new(Mix::Normal, Compose::Copy)); for (shape, paint, b) in slices.iter() { - if rects_overlap(*b, cb) && paint::set_paint(ctx, paint, *b, f) { - ctx.fill_path(shape); + let b = *b + by; + if !rects_overlap(b, cb) { + continue; + } + if by == kurbo::Vec2::ZERO { + if paint::set_paint(ctx, paint, b, f) { + ctx.fill_path(shape); + } + } else if paint::set_paint(ctx, &moved_paint(paint, by), b, f) { + let mut shape = shape.clone(); + shape.apply_affine(Affine::translate(by)); + ctx.fill_path(&shape); } } ctx.set_blend_mode(BlendMode::default()); @@ -236,17 +266,18 @@ impl Renderer { /// stroke of `self.cur` in `strokes` (under [`Self::stroke_owner`] and the stroke layer). The /// tolerance (vello's 0.25 device px) is bucketed to powers of two, never coarser than needed, /// so zooming reuses outlines until the level changes. Other strokes aren't cached: for them - /// this returns `None`. + /// this returns `None`. `line` is the line of `st` along `path` ([`effects::stroke::stroke_pieces`]). fn cached_stroke( &mut self, f: &Frame, chars: Option<(&Arc, usize)>, + path: &BezPath, line: &BezPath, st: &StrokeLayer, width: f64, ) -> Option> { let level = (f.px * 0.25).log2().floor() as i32; - let expand = || Arc::new(effects::stroke::line_outline(line, st, width, 2f64.powi(level))); + let expand = || Arc::new(crate::stroke::outline(line, st, width, 2f64.powi(level))); if let Some((g, run)) = chars { let key = (self.stroke_owner(Arc::as_ptr(g) as usize), run, width.to_bits(), level); if let Some((kept, outline)) = self.char_strokes.get(&key, self.stamp) @@ -269,11 +300,38 @@ impl Renderer { e.stamp = self.stamp; return Some(e.outline.clone()); } - // 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). + // Under its object's id, the stroke's place and the outline's width and tolerance, the key + // of the stroke's latest outline is kept, except for art made again in every frame. + let place = node.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(s) if std::ptr::eq(s, st))); + let moved = place.filter(|_| !self.made_again).map(|place| (node.id.0, place, width.to_bits(), level)); + let own = moved.is_some() && self.own_path(&node, path); + if let Some(mk) = moved + && let Some((outline, crop)) = self.moved_outline(mk, &node, st, line, v) + { + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); + return Some(outline); + } + #[cfg(test)] + STROKES_OUTLINED.with(|n| n.set(n.get() + 1)); + // 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() @@ -281,20 +339,117 @@ impl Renderer { && let Some(outline) = crop_dashed(line, st, width, region, crop_reach(st, width, f.px, tol), tol) { let outline = Arc::new(outline); - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region) }); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop: Some(region), own }, moved); return Some(outline); } let cropped = (crops() && line.elements().len() > CROP_ELEMENTS && st.dash.is_none() && st.profile.is_none()) .then(|| crop_line(line, region, crop_reach(st, width, f.px, tol), width)) .flatten(); let (outline, crop) = match cropped { - Some(part) => (Arc::new(effects::stroke::line_outline(&part, st, width, tol)), Some(region)), + Some(part) => (Arc::new(crate::stroke::outline(&part, st, width, tol)), Some(region)), None => (expand(), None), }; - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop }); + self.keep_stroke(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop, own }, moved); Some(outline) } + /// Whether `path` is the path that `geom` keeps for `node` ([`Self::path_of`]), the path + /// [`Node::stroke_path`] makes from its anchors. + fn own_path(&self, node: &Arc, path: &BezPath) -> bool { + self.geom + .get(&(Arc::as_ptr(node) as usize)) + .is_some_and(|g| Arc::ptr_eq(&g.node, node) && g.path.as_deref().is_some_and(|p| std::ptr::eq(p, path))) + } + + /// Keeps outline `e` in `strokes` under `key`, and lists `key` as the latest outline under + /// `moved` ([`MovedKey`]). + fn keep_stroke(&mut self, key: StrokeKey, e: StrokeEntry, moved: Option) { + self.strokes.insert(key, e); + if let Some(mk) = moved { + self.moved_strokes.insert(mk, key); + } + } + + /// The outline of stroke `st` of `node` along `line`, made from the latest outline kept under + /// `mk` ([`MovedKey`]) when that outline was made along a line of its object's own path, its + /// object is `node` changed, its stroke differs from `st` in its paint at most, and its line is + /// `line` moved (to within rounding): that outline moved by the same offset, with the region it + /// was cropped to moved too. The anchors of the two objects are compared first + /// ([`anchors_moved`]), and the earlier line is made again from its object and stroke only when + /// they match. `None` when there is no such outline, or when its region does not hold the view + /// `v`. + fn moved_outline(&self, mk: MovedKey, node: &Node, st: &StrokeLayer, line: &BezPath, v: Rect) -> Option<(Arc, Option)> { + let e = self.strokes.get(self.moved_strokes.get(&mk)?)?; + if !e.own || e.node.id != node.id { + return None; + } + let Some(AppearanceItem::Stroke(old)) = e.node.appearance.items.get(mk.1) else { + return None; + }; + let unpainted = |s: &StrokeLayer| StrokeLayer { paint: vectorcraft_color::Paint::None, ..s.clone() }; + if !std::ptr::eq(old, st) && unpainted(old) != unpainted(st) { + return None; + } + if !anchors_moved(&e.node, node) { + return None; + } + let path = e.node.stroke_path()?; + let by = offset_between(&effects::stroke::stroke_pieces(&path, old).line, line)?; + let crop = e.crop.map(|r| r + by); + if crop.is_some_and(|r| r.x0 > v.x0 || r.y0 > v.y0 || r.x1 < v.x1 || r.y1 < v.y1) { + return None; + } + if by == kurbo::Vec2::ZERO { + return Some((e.outline.clone(), crop)); + } + let mut outline = (*e.outline).clone(); + outline.apply_affine(Affine::translate(by)); + Some((Arc::new(outline), crop)) + } + + /// The slices of stroke `st` of `node` along `bp` (filled with `rule`), made from the latest + /// slices kept under `mk` ([`MovedSliceKey`]) when those were made along their object's own + /// path, their object is `node` changed, its stroke there differs from `st` at most in where + /// its gradient is placed, its fill rule is `rule`, and `bp` is its path moved (to within + /// rounding): the node they were made from, those slices, and the offset from that node to + /// `bp`, which the slices are drawn moved by. The anchors of the two objects are compared first + /// ([`anchors_moved`]), and the earlier path is made again from its object only when they + /// match. `None` when there are no such slices. + fn moved_slices( + &self, + mk: MovedSliceKey, + node: &Node, + st: &StrokeLayer, + rule: FillRule, + bp: &BezPath, + ) -> Option<(Arc, Slices, kurbo::Vec2)> { + let e = self.stroke_slices.get(self.moved_slices.get(&mk)?)?; + if !e.own || e.rule != rule || e.made.id != node.id { + return None; + } + let Some(AppearanceItem::Stroke(old)) = e.made.appearance.items.get(mk.1) else { + return None; + }; + // The slices take only the gradient's stops and kind, not where it is placed, which a move + // moves too. + let unplaced = |s: &StrokeLayer| { + let mut s = s.clone(); + if let vectorcraft_color::Paint::Gradient(g) = &mut s.paint { + g.geom = None; + g.angle = 0.0; + } + s + }; + if !std::ptr::eq(old, st) && unplaced(old) != unplaced(st) { + return None; + } + if !anchors_moved(&e.made, node) { + return None; + } + let by = offset_between(&e.made.stroke_path()?, bp)?; + Some((e.made.clone(), e.slices.clone(), by)) + } + /// What the `strokes`, `char_strokes` and `stroke_slices` keys hold for a stroke owner at /// `address` (`self.cur` or kept glyph geometry): the address, or 0 while art made again in /// every frame is drawn ([`Self::made_again`]). @@ -311,6 +466,121 @@ pub(crate) const CROP_ELEMENTS: usize = 1024; thread_local! { /// Whether long strokes are outlined near the view only on this thread ([`crop_line`]). pub(crate) static CROP_STROKES: std::cell::Cell = const { std::cell::Cell::new(true) }; + /// How many stroke outlines of nodes [`Renderer::cached_stroke`] has made on this thread. + pub(crate) static STROKES_OUTLINED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many sets of gradient stroke slices [`Renderer::fill_path_gradient`] has made on this + /// thread. + pub(crate) static SLICES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Paint `p` of a slice ([`Slices`]) moved by `by`: a gradient's start, end and focal point moved. +fn moved_paint(p: &vectorcraft_color::Paint, by: kurbo::Vec2) -> vectorcraft_color::Paint { + let mut p = p.clone(); + if let vectorcraft_color::Paint::Gradient(g) = &mut p + && let Some(geom) = &mut g.geom + { + geom.start += by; + geom.end += by; + if let Some(focal) = &mut geom.focal { + *focal += by; + } + } + p +} + +/// The offset that moves path `was` onto path `now`, when `now` is `was` moved (each point within +/// the rounding that [`Offset::holds`] allows). `None` otherwise, and for an empty path. +pub(crate) fn offset_between(was: &BezPath, now: &BezPath) -> Option { + if !matches!(was.elements().first(), Some(kurbo::PathEl::MoveTo(_))) { + return None; + } + let mut offset = Offset::new(); + (path_pairs(was, now, |a, b| offset.takes(a, b)) && path_pairs(was, now, |a, b| offset.holds(a, b))).then(|| offset.by()) +} + +/// Whether `was` and `now` have the same elements, and `f` holds for each pair of their points. +/// Stops at the first pair for which `f` does not hold. +fn path_pairs(was: &BezPath, now: &BezPath, mut f: impl FnMut(kurbo::Point, kurbo::Point) -> bool) -> bool { + use kurbo::PathEl; + let (was, now) = (was.elements(), now.elements()); + was.len() == now.len() + && was.iter().zip(now).all(|pair| match pair { + (PathEl::MoveTo(a), PathEl::MoveTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => f(*a, *b), + (PathEl::QuadTo(a0, a1), PathEl::QuadTo(b0, b1)) => f(*a0, *b0) && f(*a1, *b1), + (PathEl::CurveTo(a0, a1, a2), PathEl::CurveTo(b0, b1, b2)) => f(*a0, *b0) && f(*a1, *b1) && f(*a2, *b2), + (PathEl::ClosePath, PathEl::ClosePath) => true, + _ => false, + }) +} + +/// One offset between pairs of points. Pairs are read once with [`Offset::takes`], which measures +/// the offset on each axis at the pair with the smallest coordinates on that axis, and once more +/// with [`Offset::holds`], which checks every pair against that offset. +struct Offset { + by: [f64; 2], + size: [f64; 2], +} + +impl Offset { + fn new() -> Self { + Self { by: [0.0; 2], size: [f64::INFINITY; 2] } + } + + /// Whether `b` is `a` moved by the offset measured so far, on each axis within 3 units in the + /// last place of the larger of the pair's coordinates and those of the pair the offset was + /// measured at. A pair with smaller coordinates than any before it on an axis then measures the + /// offset on that axis. + fn takes(&mut self, a: kurbo::Point, b: kurbo::Point) -> bool { + [(a.x, b.x), (a.y, b.y)].into_iter().zip(self.by.iter_mut().zip(&mut self.size)).all(|((a, b), (by, size))| { + let at = a.abs().max(b.abs()); + if at.is_nan() || at >= *size { + return (b - a - *by).abs() <= 3.0 * ulp(at); + } + let near = size.is_infinite() || (b - a - *by).abs() <= 3.0 * ulp(*size); + (*by, *size) = (b - a, at); + near && by.is_finite() + }) + } + + /// Whether `b` is `a` moved by the offset, on each axis within 3 units in the last place of the + /// larger of the pair's coordinates: the most that rounding `b`, the pair the offset was measured + /// at (whose coordinates are no larger), and the two offsets can make together. + fn holds(&self, a: kurbo::Point, b: kurbo::Point) -> bool { + let near = |a: f64, b: f64, by: f64| (b - a - by).abs() <= 3.0 * ulp(a.abs().max(b.abs())); + near(a.x, b.x, self.by[0]) && near(a.y, b.y, self.by[1]) + } + + fn by(&self) -> kurbo::Vec2 { + kurbo::Vec2::new(self.by[0], self.by[1]) + } +} + +/// The distance from `x`, which is 0 or more, to the next larger `f64`. +fn ulp(x: f64) -> f64 { + f64::from_bits(x.to_bits() + 1) - x +} + +/// Whether the anchors and handles of path `now` are those of path `was` moved by one offset, +/// measured as [`offset_between`] measures it, with the same subpaths, anchor counts and closed +/// subpaths. It reads the anchors without making either path ([`Node::stroke_path`]), and stops at +/// the first anchor that differs. `false` for objects other than paths. +pub(crate) fn anchors_moved(was: &Node, now: &Node) -> bool { + let (vectorcraft_doc::NodeKind::Path { path: was, .. }, vectorcraft_doc::NodeKind::Path { path: now, .. }) = (&was.kind, &now.kind) else { + return false; + }; + let mut offset = Offset::new(); + anchor_pairs(was, now, |a, b| offset.takes(a, b)) && anchor_pairs(was, now, |a, b| offset.holds(a, b)) +} + +/// Whether `was` and `now` have the same subpaths, anchor counts and closed subpaths, and `f` holds +/// for each pair of their anchors and handles. Stops at the first pair for which `f` does not hold. +fn anchor_pairs(was: &vectorcraft_geom::PathData, now: &vectorcraft_geom::PathData, mut f: impl FnMut(kurbo::Point, kurbo::Point) -> bool) -> bool { + was.subpaths.len() == now.subpaths.len() + && was.subpaths.iter().zip(&now.subpaths).all(|(a, b)| { + a.closed == b.closed + && a.anchors.len() == b.anchors.len() + && a.anchors.iter().zip(&b.anchors).all(|(a, b)| f(a.p, b.p) && f(a.h_in, b.h_in) && f(a.h_out, b.h_out)) + }) } fn crops() -> bool { diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index a2488556a9..cc0302deeb 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -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, g: Arc) -> 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, kept: bool) { @@ -304,13 +337,14 @@ impl Renderer { /// decoded once and kept with the images' pixels. fn draw_glyph_image(&mut self, ctx: &mut RenderContext, f: &Frame, image: &vectorcraft_text::GlyphImage, xf: Affine) { let Some((key, pm)) = blob_pixmap(&image.blob, true) else { return }; - let (key, pm) = ink::ink_image(&key, &pm, f.ink, Some(&image.blob), true); - let (key, pm) = match f.plates { - Some(lut) => proof::plate_image(lut, &key, &pm, Some(&image.blob), true), - None => (key, pm), - }; + // Shrunk before it is inked, as images are (`draw_image_in`). let unit = f.view * xf * Affine::scale_non_uniform(image.width as f64, image.height as f64); - let pm = image_mip(&key, pm, unit); + let (key, pm) = image_mip(key, pm, unit); + let (key, pm) = ink::ink_image(&key, &pm, f.ink, Some(&image.blob), true); + let pm = match f.plates { + Some(lut) => proof::plate_image(lut, &key, &pm, Some(&image.blob), true).1, + None => pm, + }; let sx = image.width as f64 / pm.width().max(1) as f64; let sy = image.height as f64 / pm.height().max(1) as f64; let quality = if f.opts.smooth_images { peniko::ImageQuality::Medium } else { peniko::ImageQuality::Low }; diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs new file mode 100644 index 0000000000..137bb10abd --- /dev/null +++ b/crates/render/src/stroke.rs @@ -0,0 +1,21 @@ +//! Raster-only stroke fitting: preserve thin curved bands through fill flattening. + +use crate::effects; +use vectorcraft_doc::StrokeLayer; +use vectorcraft_geom::BezPath; + +/// Vello flattens the two sides of a filled stroke independently at 0.25 device pixels. +/// For strokes narrower than four times the raster tolerance, fit and preflatten the +/// band more tightly. Wider strokes and the document/export geometry are unchanged. +pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> BezPath { + if width >= tol * 4.0 { + return effects::stroke::line_outline(line, st, width, tol); + } + // Closed endpoint rounding must not consume a substantial part of a subpixel band. + let fine = (tol / 8.0).min(width / 32.0).max(1e-4); + let outline = effects::stroke::line_outline(line, st, width, fine); + let mut flat = BezPath::new(); + // Keep upstream's per-curve work cap for untrusted or extreme coordinates. + vectorcraft_geom::flatten(outline.iter(), fine, |el| flat.push(el)); + flat +} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ffeb6cc6f7..82a1374dab 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -24,11 +24,13 @@ mod knockout; mod layeropts; mod longstroke; mod memory; +mod movedstroke; mod objectfx; mod placed_document; mod rasterize; mod setup; mod strokegradient; +mod thincoverage; mod tileedge; mod viewraster; mod widthzoom; diff --git a/crates/render/src/tests/charstroke.rs b/crates/render/src/tests/charstroke.rs index 1dd1d86463..aaa16a74c9 100644 --- a/crates/render/src/tests/charstroke.rs +++ b/crates/render/src/tests/charstroke.rs @@ -2,9 +2,9 @@ //! take every stroke option, as path strokes do. use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::text::{CharStyle, TextObject}; -use vectorcraft_doc::{AppearanceItem, Dash, LineJoin, Node, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::text::{CharStyle, TextKind, TextObject}; +use vectorcraft_doc::{AppearanceItem, AreaFit, Dash, LineJoin, Node, NodeKind}; +use vectorcraft_geom::{PathData, Point}; use crate::tests_fontchange::fonts_steady; use crate::*; @@ -164,6 +164,71 @@ fn character_stroke_outlines_are_kept_between_frames() { assert!(changed.len() == 1 && !Arc::ptr_eq(&changed[0], &first[0]), "the changed text is expanded again"); } +#[test] +fn moving_type_reuses_character_strokes_without_changing_pixels() { + let _fonts = fonts_steady(); + let (mut d, id) = stroked_text_doc("Type"); + let opts = RenderOptions::default(); + let mut r = Renderer::new(); + r.render(&d, SIZE, SIZE, Affine::IDENTITY, &opts); + let first = character_outlines(&r); + assert_eq!(first.len(), 1); + if let Some(Node { kind: NodeKind::Text(t), .. }) = d.node_mut(id) { + t.xf = Affine::translate((10.0, 0.0)) * t.xf; + } + let moved = r.render(&d, SIZE, SIZE, Affine::IDENTITY, &opts); + let again = character_outlines(&r); + assert!(again.len() == 1 && Arc::ptr_eq(&again[0], &first[0]), "a move reuses the character stroke outline"); + assert_eq!(moved.pixels, Renderer::new().render(&d, SIZE, SIZE, Affine::IDENTITY, &opts).pixels); + // The entry moved to the node shown, so the next frames find it without comparing the text. + let node = d.node_arc(id).unwrap(); + assert!(r.texts.contains_key(&(Arc::as_ptr(node) as usize)), "kept under the moved node"); + assert_eq!(r.texts.len(), 1, "and not also under the old one"); +} + +#[test] +fn scaling_fitted_area_type_rebuilds_its_glyph_geometry() { + let _fonts = fonts_steady(); + // 2 pt type, drawn 20× zoomed in. Shrink Text to Fit steps the size in tenths of a document + // point, so at 2 pt and at 3 pt it fits the same words at different fractions of full size. + let (mut d, id) = stroked_text_doc("Type"); + if let Some(Node { kind: NodeKind::Text(t), .. }) = d.node_mut(id) { + t.xf = Affine::IDENTITY; + t.runs[0].style.size = 2.0; + t.runs[0].style.stroke_width = 0.05; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 3.0, 3.0).to_path(0.1)) }; + t.area.fit = AreaFit::ShrinkText { min_percent: 30.0 }; + } + let text = |d: &Document| match d.node(id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => (**t).clone(), + _ => panic!("the text object"), + }; + let fit = |d: &Document| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(d)).fit_scale; + let view = Affine::scale(20.0); + let opts = RenderOptions::default(); + let mut r = Renderer::new(); + r.render(&d, SIZE, SIZE, view, &opts); + let first = r.texts.used_in(r.stamp).next().unwrap().1.clone(); + let before = fit(&d); + if let Some(Node { kind: NodeKind::Text(t), .. }) = d.node_mut(id) { + t.xf = Affine::scale(1.5) * t.xf; + } + let after = fit(&d); + assert!(before > 0.3 && before < 1.0 && after > 0.3 && after < 1.0, "it fits above the minimum both times: {before}, {after}"); + assert!((before - after).abs() > 0.01, "the scale changes the fitted size: {before}, {after}"); + let scaled = r.render(&d, SIZE, SIZE, view, &opts); + let again = r.texts.used_in(r.stamp).next().unwrap().1.clone(); + assert!(!Arc::ptr_eq(&first, &again), "changing area type's scale lays it out again"); + assert_eq!(scaled.pixels, Renderer::new().render(&d, SIZE, SIZE, view, &opts).pixels); + // The words set at the earlier fit, which reusing the earlier layout would draw, draw other pixels. + let mut stale = d.clone(); + if let Some(Node { kind: NodeKind::Text(t), .. }) = stale.node_mut(id) { + **t = vectorcraft_text::scaled(t, before); + } + assert_eq!(fit(&stale), 1.0, "the earlier fit's words fit as they are"); + assert_ne!(scaled.pixels, Renderer::new().render(&stale, SIZE, SIZE, view, &opts).pixels, "the new fit changes the pixels"); +} + /// Frames that draw character strokes from the cache draw the same pixels, and what a renderer /// draws whose glyph cache has no room, so that it expands them in every frame: exactly at 100%, /// where both take a tolerance of 1/4 device pixel, and within antialiasing at 105% and 150%, diff --git a/crates/render/src/tests/colorize.rs b/crates/render/src/tests/colorize.rs index 15eb3c5a02..49e14e5e68 100644 --- a/crates/render/src/tests/colorize.rs +++ b/crates/render/src/tests/colorize.rs @@ -142,6 +142,27 @@ fn colorize_dims_with_the_grays() { assert!(px[1].abs_diff(128) <= 3 && px[2].abs_diff(127) <= 3 && px[0] <= 2, "got {px:?}"); } +/// A linked image showing the missing-link placeholder draws it in its own colors though it keeps +/// a colorize paint for its file; a grayscale preview still draws colorized. +#[test] +fn a_colorized_missing_link_placeholder_draws_in_its_own_colors() { + let proxy = |bytes: Vec| { + let bytes = std::sync::Arc::new(bytes); + ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) } + }; + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let sharp = RenderOptions { smooth_images: false, ..Default::default() }; + let placeholder = proxy(vectorcraft_doc::links::missing_placeholder().unwrap()); + // 64 pixels at 0.5 pt: (16, 5) is the light tile, (5, 5) the cross. + let d = doc_of(placeholder, Some(blue.clone()), (64, 64), 0.5); + let out = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &sharp); + assert!(near(out.pixel(16, 5), [236, 236, 236, 255], 2), "the light tile, got {:?}", out.pixel(16, 5)); + assert!(near(out.pixel(5, 5), [200, 60, 60, 255], 2), "the red cross, got {:?}", out.pixel(5, 5)); + let d = doc(proxy(gray_png()), Some(blue)); + let px = Renderer::new().render(&d, 40, 20, Affine::IDENTITY, &sharp).pixel(10, 10); + assert!(px[2] >= 250 && px[0] <= 5 && px[1] <= 5, "a grayscale preview takes the color, got {px:?}"); +} + /// Separations Preview shows a spot-colorized image on its ink's plate only. #[test] fn separations_preview_shows_the_image_on_its_spot_plate() { diff --git a/crates/render/src/tests/keptpath.rs b/crates/render/src/tests/keptpath.rs index 94c5621b97..a2f8b3ad85 100644 --- a/crates/render/src/tests/keptpath.rs +++ b/crates/render/src/tests/keptpath.rs @@ -71,19 +71,43 @@ fn check(r: &mut Renderer, d: &Document, id: NodeId, what: &str) { } let k = r.kept.get(&id).unwrap_or_else(|| panic!("{what}: its path kept")); assert!(std::ptr::eq(Arc::as_ptr(&k.node), n), "{what}: its path kept"); - // The boxes and miter tips kept, run by run, are those of the path measured whole. - let (runs, tips_of) = k.runs(); - let mut whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); - if let Some(st) = &tips_of { - whole.tips(st); + // The subpaths kept are those of the path measured whole, each run holds from one segment to + // twice the segments of a run, and the boxes and miter tips kept, run by run, are those + // measured again from the path. + let whole = crate::kept_paths::KeptPath::new(&Arc::new(n.clone()), 0).unwrap(); + let (layout, fresh) = (k.layout(), whole.layout()); + assert!(layout.iter().map(|l| l.0).eq(fresh.iter().map(|l| l.0)), "{what}: the same subpaths as the path measured whole"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&fresh) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); +} + +/// Check `d` as [`check`] does, then the document before the edit (undone) and `d` again (redone). +fn check_undo(r: &mut Renderer, before: &Document, d: &Document, id: NodeId, what: &str) { + check(r, d, id, what); + check(r, before, id, &format!("{what}, undone")); + check(r, d, id, &format!("{what}, redone")); +} + +/// The members of compound path `id` of `d`. +fn members(d: &mut Document, id: NodeId) -> &mut Vec> { + match d.node_mut(id).map(|n| &mut n.kind) { + Some(NodeKind::Compound { children, .. }) => children, + _ => panic!("a compound path"), } - assert!(runs == whole.runs().0, "{what}: the same boxes and tips as the path measured whole"); } fn path_of(d: &mut Document, id: NodeId) -> &mut PathData { d.node_mut(id).and_then(|n| n.path_data_mut()).unwrap() } +fn corner(x: f64, y: f64) -> Anchor { + Anchor::corner(Point::new(x, y)) +} + fn moved(a: &mut Anchor, by: Vec2) { *a = a.transform(Affine::translate(by)); } @@ -194,6 +218,352 @@ fn edits_in_runs_of_segments_without_length_measure_as_when_the_path_is_made_aga } } +#[test] +fn a_long_path_draws_and_culls_after_anchors_are_added_or_deleted_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let path = PathData::new(vec![ + zigzag(3000, 0.0), + ring(1200, Point::new(12_000.0, 15.0), 45.0), + SubPath::new(vec![Anchor::corner(Point::new(11_990.0, 20.0))], false), + SubPath::new(vec![], false), + SubPath::new(vec![Anchor::corner(Point::new(11_995.0, 0.0)), Anchor::corner(Point::new(12_005.0, 30.0))], false), + ]); + let n = Node::path(d.alloc_id(), path, look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt), stroke(14.0, LineJoin::Round, LineCap::Round)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 28] = [ + // Anchor 1,152, a corner at (9,032, 30), ends the segments of the first nine runs: the + // joint there is in the run before. + ("an anchor added where a run of segments starts", |p| p.subpaths[0].anchors.insert(1153, corner(9_036.0, -30.0))), + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)), + ("an anchor added at the start", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 30.0))), + ("an anchor added at the end", |p| p.subpaths[0].anchors.push(corner(24_100.0, 0.0))), + ("the first anchor deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("an anchor added onto the one before it", |p| { + let a = p.subpaths[0].anchors[1499]; + p.subpaths[0].anchors.insert(1500, Anchor::corner(a.p)); + }), + ("300 anchors deleted", |p| _ = p.subpaths[0].anchors.drain(1100..1400)), + ("400 anchors added", |p| { + let at: Vec = (0..400).map(|i| corner(8_800.0 + f64::from(i) * 0.5, if i % 2 == 0 { -20.0 } else { 50.0 })).collect(); + p.subpaths[0].anchors.splice(1100..1100, at); + }), + ("anchors moved and others deleted", |p| { + p.subpaths[0].anchors[10] = corner(80.0, -40.0); + p.subpaths[0].anchors.drain(2000..2010); + }), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ("an anchor added at the start of the closed subpath", |p| p.subpaths[0].anchors.insert(0, corner(-8.0, 60.0))), + ("an anchor added after the first of the closed subpath", |p| p.subpaths[0].anchors.insert(1, corner(-20.0, -30.0))), + ("an anchor added at the end of the closed subpath", |p| p.subpaths[0].anchors.push(corner(24_000.0, 60.0))), + ("the first anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.remove(0)), + ("the last anchor of the closed subpath deleted", |p| _ = p.subpaths[0].anchors.pop()), + ("the subpath opened", |p| p.subpaths[0].closed = false), + ("an anchor of the ring added in the view", |p| p.subpaths[1].anchors.insert(300, corner(12_010.0, 10.0))), + ("an anchor of the ring deleted", |p| _ = p.subpaths[1].anchors.remove(600)), + ("the ring opened", |p| p.subpaths[1].closed = false), + ("the ring closed", |p| p.subpaths[1].closed = true), + ("the one-anchor subpath given a second anchor", |p| p.subpaths[2].anchors.push(corner(12_000.0, 40.0))), + ("the second anchor deleted again", |p| _ = p.subpaths[2].anchors.pop()), + ("the one-anchor subpath emptied", |p| p.subpaths[2].anchors.clear()), + ("the empty subpath given an anchor", |p| p.subpaths[3].anchors.push(corner(12_015.0, 5.0))), + ("the two-anchor subpath closed", |p| p.subpaths[4].closed = true), + ("an anchor deleted from the two-anchor subpath", |p| _ = p.subpaths[4].anchors.remove(0)), + ]; + for (what, edit) in edits { + let before = d.clone(); + edit(path_of(&mut d, id)); + check_undo(&mut r, &before, &d, id, what); + } +} + +#[test] +fn a_long_compound_path_draws_and_culls_after_members_are_added_or_removed_as_when_its_path_is_made_again() { + let mut d = Document::new(1000.0, 1000.0); + let none = Appearance::default(); + let member = |d: &mut Document, p: PathData| Arc::new(Node::path(d.alloc_id(), p, none.clone())); + let children = vec![ + member(&mut d, PathData::single(zigzag(1500, 6000.0))), + member(&mut d, PathData::single(ring(1500, Point::new(12_000.0, 15.0), 45.0))), + member(&mut d, PathData::single(SubPath::new(vec![Anchor::corner(Point::new(11_980.0, 0.0))], false))), + ]; + let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![stroke(4.0, LineJoin::Miter, LineCap::Square)]).into(); + let id = add(&mut d, n); + let mut r = Renderer::new(); + check(&mut r, &d, id, "drawn first"); + let edits: [(&str, PathData, usize); 4] = [ + ("a member added at the end", PathData::single(ring(40, Point::new(12_010.0, 20.0), 8.0)), 3), + ("a member added at the start", PathData::single(zigzag(30, 11_950.0)), 0), + ("a member added between", PathData::new(vec![]), 2), + ("a member of two subpaths added between", PathData::new(vec![ring(5, Point::new(11_990.0, 25.0), 4.0), zigzag(3, 11_970.0)]), 1), + ]; + for (what, p, at) in edits { + let before = d.clone(); + let m = member(&mut d, p); + members(&mut d, id).insert(at, m); + check_undo(&mut r, &before, &d, id, what); + } + // Seven members: the first, the last, then the third removed. + for (what, at) in [("the first member removed", 0), ("the last member removed", 5), ("a member removed between", 2)] { + let before = d.clone(); + members(&mut d, id).remove(at); + check_undo(&mut r, &before, &d, id, what); + } + // Left: the member of two subpaths, the zigzag, the ring and the one-anchor member. + let ids: Vec = members(&mut d, id).iter().map(|m| m.id).collect(); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths.push(SubPath::new(vec![corner(12_020.0, 30.0)], false)); + check_undo(&mut r, &before, &d, id, "a subpath added to a member"); + let before = d.clone(); + path_of(&mut d, ids[1]).subpaths[0].anchors.insert(10, corner(12_000.0, 60.0)); + path_of(&mut d, ids[2]).subpaths[0].anchors.remove(700); + check_undo(&mut r, &before, &d, id, "anchors added and deleted in two members"); +} + +#[test] +fn adding_and_deleting_anchors_of_a_long_path_changes_its_kept_path_in_place() { + let mut d = Document::new(1000.0, 1000.0); + let n = Node::path(d.alloc_id(), PathData::single(zigzag(3000, 0.0)), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let kept = |r: &Renderer| r.kept.get(&id).map(|k| Arc::as_ptr(&k.path) as usize); + let before = kept(&r); + assert!(before.is_some(), "the path is kept"); + type Edit = fn(&mut PathData); + let edits: [(&str, Edit); 3] = [ + ("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1500, 0.5)), + ("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1700)), + ("the subpath closed", |p| p.subpaths[0].closed = true), + ]; + for (what, edit) in edits { + edit(path_of(&mut d, id)); + check(&mut r, &d, id, what); + assert_eq!(kept(&r), before, "{what}: the kept path changed in place"); + } + // An edit that leaves the anchors as they were leaves the kept path as it is, also while + // something else holds it. + let held = r.kept.get(&id).map(|k| k.path.clone()).unwrap(); + d.node_mut(id).unwrap().appearance = look(vec![stroke(8.0, LineJoin::Miter, LineCap::Butt)]).into(); + check(&mut r, &d, id, "the stroke changed"); + assert!(Arc::ptr_eq(&held, &r.kept.get(&id).unwrap().path), "the stroke changed: the kept path left as it is"); +} + +#[test] +fn deleting_an_anchor_of_an_open_path_and_clearing_the_handles_past_its_ends_measures_one_run_again() { + let mut d = Document::new(1000.0, 1000.0); + let mut sp = zigzag(3000, 0.0); + if let Some(a) = sp.anchors.last_mut() { + a.h_out = a.p + Vec2::new(3.0, 4.0); + } + assert!(sp.anchors[0].has_in(), "the first anchor has a handle before it"); + let n = Node::path(d.alloc_id(), PathData::single(sp), look(vec![stroke(6.0, LineJoin::Miter, LineCap::Butt)])); + let id = add(&mut d, n); + let mut r = Renderer::new(); + render(&mut r, &d); + let runs = |r: &Renderer| r.kept.get(&id).map(|k| k.layout()[0].1.clone()).unwrap(); + let before = runs(&r); + // Anchor 1,500 deleted, and the handles before the first anchor and after the last cleared: + // they draw nothing on an open subpath. + let p = &mut path_of(&mut d, id).subpaths[0]; + p.anchors.remove(1500); + if let Some(a) = p.anchors.first_mut() { + a.h_in = a.p; + } + if let Some(a) = p.anchors.last_mut() { + a.h_out = a.p; + } + check(&mut r, &d, id, "an anchor deleted and the end handles cleared"); + let after = runs(&r); + let changed: Vec = (0..before.len().max(after.len())).filter(|&i| before.get(i) != after.get(i)).collect(); + assert_eq!(changed, vec![1499 / crate::kept_paths::RUN], "only the run that held the anchor changed: {before:?} -> {after:?}"); +} + +/// Numbers from a fixed seed (a linear congruential generator). +struct Seeded(u64); + +impl Seeded { + /// A number below `m` (0 when `m` is 0). + fn below(&mut self, m: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as usize % m.max(1) + } + + /// A whole number of points from -`r` to `r`. + fn offset(&mut self, r: usize) -> f64 { + self.below(2 * r + 1) as f64 - r as f64 + } + + /// Where in a subpath of `n` anchors to edit: at the start, at the end, where a run of segments + /// ends, or anywhere. + fn at(&mut self, n: usize) -> usize { + match self.below(4) { + 0 => self.below(3).min(n), + 1 => n.saturating_sub(self.below(3)), + 2 => (crate::kept_paths::RUN * (1 + self.below(24)) + self.below(3)).min(n), + _ => self.below(n + 1), + } + } +} + +/// An anchor to add after `before`: on it (a segment without length), a corner near it, or a +/// smooth anchor near it. +fn anchor_after(g: &mut Seeded, before: Point) -> Anchor { + let p = before + Vec2::new(g.offset(20), g.offset(40)); + match g.below(5) { + 0 => Anchor::corner(before), + 1 => Anchor::smooth(p, p + Vec2::new(g.offset(6), g.offset(6))), + _ => Anchor::corner(p), + } +} + +/// Edit `p` at random: anchors added or deleted at the start, middle or end of a subpath, a +/// subpath closed or opened, an anchor or a handle moved, or many anchors moved. Says what it did. +fn random_edit(g: &mut Seeded, p: &mut PathData) -> String { + let s = g.below(p.subpaths.len()); + let Some(sp) = p.subpaths.get_mut(s) else { return "nothing".into() }; + let n = sp.anchors.len(); + match g.below(6) { + 0 | 1 => { + let (at, k) = (g.at(n), 1 + g.below(3)); + for j in 0..k { + let before = sp.anchors.get((at + j).saturating_sub(1)).map_or(Point::new(12_000.0, 15.0), |a| a.p); + let a = anchor_after(g, before); + sp.anchors.insert(at + j, a); + } + format!("{k} anchors added at {at} of subpath {s} of {n}") + } + 2 | 3 if n > 0 => { + let at = g.at(n - 1); + let k = (1 + g.below(3)).min(n - at); + sp.anchors.drain(at..at + k); + format!("{k} anchors deleted at {at} of subpath {s} of {n}") + } + 4 => { + sp.closed = !sp.closed; + format!("subpath {s} of {n} closed: {}", sp.closed) + } + _ if n > 0 => { + let at = g.below(n); + match g.below(3) { + 0 => moved(&mut sp.anchors[at], Vec2::new(g.offset(30), g.offset(30))), + 1 => sp.anchors[at].h_out = sp.anchors[at].p + Vec2::new(g.offset(10), g.offset(10)), + _ => sp.anchors[at..].iter_mut().take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))), + } + format!("anchors moved at {at} of subpath {s} of {n}") + } + _ => "nothing".into(), + } +} + +/// Bring `k` up to date with `n` and check that it holds what [`KeptPath::new`] makes from `n`: +/// the same path elements and subpaths, runs that hold each subpath's segments, the boxes and miter +/// tips of `st` measured again over its runs, and the same bounds and tips in all. +fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc, st: &StrokeLayer, what: &str) { + assert!(k.update(n), "{what}: brought up to date"); + let mut fresh = crate::kept_paths::KeptPath::new(n, 0).unwrap_or_else(|| panic!("{what}: kept")); + assert!(*k.path == *fresh.path, "{what}: the same path elements"); + let (layout, whole) = (k.layout(), fresh.layout()); + assert!(layout.iter().map(|l| l.0).eq(whole.iter().map(|l| l.0)), "{what}: the same subpaths: {layout:?}"); + for ((sub, runs), ((_, segs, ..), _)) in layout.iter().zip(&whole) { + assert_eq!(runs.iter().sum::(), *segs, "{what}: the runs of {sub:?} hold its segments"); + assert!(runs.iter().all(|&s| (1..=2 * crate::kept_paths::RUN).contains(&s)), "{what}: the runs of {sub:?}: {runs:?}"); + } + let (runs, again, _) = k.runs(); + assert!(runs == again, "{what}: the same boxes and tips as measured again"); + assert_eq!(k.geometric(), fresh.geometric(), "{what}: the same bounds"); + assert_eq!(k.tips(st), fresh.tips(st), "{what}: the same miter tips"); +} + +#[test] +fn random_edits_of_a_long_path_keep_what_making_its_path_again_makes() { + let st = stroke(6.0, LineJoin::Miter, LineCap::Butt); + let mut g = Seeded(5744); + let closed = |sp: SubPath| SubPath::new(sp.anchors, true); + let path = PathData::new(vec![ + zigzag(2, 11_990.0), + closed(zigzag(3, 12_000.0)), + zigzag(7, 11_960.0), + closed(zigzag(40, 11_800.0)), + ring(300, Point::new(12_000.0, 15.0), 60.0), + zigzag(3000, 0.0), + closed(zigzag(2000, 4000.0)), + ]); + let mut n = Arc::new(Node::path(NodeId(1), path, look(vec![st.clone()]))); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let what = random_edit(&mut g, next.path_data_mut().unwrap()); + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + +#[test] +fn random_edits_of_a_long_compound_path_keep_what_making_its_path_again_makes() { + let st = stroke(4.0, LineJoin::Miter, LineCap::Square); + let mut g = Seeded(1050); + let ids = std::cell::Cell::new(10); + let member = |p: PathData| { + ids.set(ids.get() + 1); + Arc::new(Node::path(NodeId(ids.get()), p, Appearance::default())) + }; + let children = vec![ + member(PathData::new(vec![SubPath::new(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])), + member(PathData::single(zigzag(3000, 0.0))), + member(PathData::single(ring(40, Point::new(12_000.0, 15.0), 30.0))), + member(PathData::single(zigzag(2, 12_020.0))), + ]; + let mut n = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd }); + n.appearance = look(vec![st.clone()]).into(); + let mut n = Arc::new(n); + let mut k = crate::kept_paths::KeptPath::new(&n, 0).unwrap(); + k.tips(&st); + for step in 0..300 { + let mut next = (*n).clone(); + let NodeKind::Compound { children, .. } = &mut next.kind else { panic!("a compound path") }; + let what = match g.below(8) { + 0 => { + let at = [0, children.len(), g.below(children.len() + 1)][g.below(3)]; + let size = [1, 2, 4, 30, 200][g.below(5)]; + let mut sp = zigzag(size, 11_900.0 + g.offset(100)); + sp.closed = g.below(2) == 0; + children.insert(at, member(PathData::single(sp))); + format!("a member of {size} anchors added at {at}") + } + // The member of 3,000 anchors stays, so that the path stays kept. + 1 if children.len() > 2 => { + let at = [0, children.len() - 1, g.below(children.len())][g.below(3)]; + if children[at].path_data().is_some_and(|p| p.subpaths.iter().map(|s| s.anchors.len()).sum::() > 1000) { + "nothing".into() + } else { + children.remove(at); + format!("member {at} removed") + } + } + 2 => { + let at = g.below(children.len()); + let m = Arc::make_mut(&mut children[at]).path_data_mut().unwrap(); + m.subpaths.push(zigzag(1 + g.below(4), 12_030.0)); + format!("a subpath added to member {at}") + } + _ => { + let at = g.below(children.len()); + let what = random_edit(&mut g, Arc::make_mut(&mut children[at]).path_data_mut().unwrap()); + format!("member {at}: {what}") + } + }; + n = Arc::new(next); + same_as_made_again(&mut k, &n, &st, &format!("step {step}, {what}")); + } +} + #[test] fn moving_one_anchor_of_a_long_path_changes_its_kept_path_in_place() { let mut d = Document::new(1000.0, 1000.0); diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index ffabf0a264..8a6567f399 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -2,7 +2,7 @@ //! and for dashes `dash_kept`), and draws the same pixels as when it is outlined whole. use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, Node, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, Node, StrokeLayer, WidthProfile}; use vectorcraft_geom::{PathData, Point, Vec2}; use crate::renderer::{CROP_STROKES, crop_line}; @@ -66,6 +66,47 @@ fn zigzag() -> BezPath { bp } +#[test] +fn a_long_profile_stroke_keeps_its_widths_when_outlined_near_the_view() { + let mut lens = stroke(16.0, LineJoin::Miter, LineCap::Square); + lens.profile = WidthProfile::preset("lens"); + let mut taper = stroke(12.0, LineJoin::Round, LineCap::Round); + taper.profile = WidthProfile::preset("taperEnd"); + let mut asymmetric = stroke(12.0, LineJoin::Miter, LineCap::Square); + asymmetric.profile = Some(WidthProfile { points: vec![(0.0, 2.0, 0.1), (1.0, 0.1, 2.0)] }); + let mut two = zigzag(); + two.move_to(Point::new(0.0, 100.0)); + for i in 1..3000 { + two.line_to(Point::new(i as f64 * 8.0, 100.0)); + } + for (name, d, at, cropped) in [ + ("open zigzag, lens at middle", doc(&zigzag(), lens), Point::new(12_000.0, 15.0), true), + ("open zigzag, taper at start", doc(&zigzag(), taper.clone()), Point::new(0.0, 15.0), true), + ("open zigzag, taper at end", doc(&zigzag(), taper.clone()), Point::new(23_990.0, 15.0), true), + ("open zigzag, asymmetric profile", doc(&zigzag(), asymmetric), Point::new(12_000.0, 15.0), true), + ("two open subpaths", doc(&two, taper.clone()), Point::new(12_000.0, 60.0), true), + ("closed ring at seam", doc(&ring(4000, 5000.0), taper.clone()), Point::new(5000.0, 0.0), false), + ("closed ring away from seam", doc(&ring(4000, 5000.0), taper), Point::new(0.0, 5000.0), false), + ] { + let mut renderer = Renderer::new(); + let near = render(&mut renderer, &d, at); + assert_eq!(renderer.strokes.values().any(|e| e.crop.is_some()), cropped, "{name}: crop choice"); + let full = whole(&d, at); + let mismatched: Vec<_> = near + .pixels + .as_chunks::<4>() + .0 + .iter() + .zip(full.pixels.as_chunks::<4>().0.iter()) + .enumerate() + .filter(|(_, (a, b))| a != b) + .take(8) + .map(|(i, (a, b))| (i % SIZE as usize, i / SIZE as usize, a.to_vec(), b.to_vec())) + .collect(); + assert!(mismatched.is_empty(), "{name}: pixels differ at {mismatched:?}"); + } +} + /// A closed polygon of `n` anchors round a circle of radius `r` about the origin. fn ring(n: usize, r: f64) -> BezPath { let mut bp = BezPath::new(); diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index f0c4b40e1f..d8b267cb9e 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2422,3 +2422,125 @@ fn compound_paths_draw_from_kept_paths_and_let_old_ones_go() { assert!(r.geom.len() < 1024); assert_eq!(Arc::strong_count(&old), 1, "the renderer no longer keeps the compound path drawn before the move"); } + +/// A `w`×`h` CMYK document showing `blob` as image `key` of `w`×`h` pixels, one point a pixel. +fn cmyk_doc_with(key: &str, blob: ImageBlob, w: u32, h: u32) -> Document { + let mut d = Document::new_with_mode(w as f64, h as f64, vectorcraft_doc::ColorMode::Cmyk); + d.images.insert(key.into(), blob); + let (id, layer) = (d.alloc_id(), d.layers[0].id); + let im = ImageObject { key: key.into(), width: w, height: h, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + d +} + +/// #4155: an image drawn reduced on the ink planes is separated from the mip it draws, never at +/// its full size. Separating a 141-megapixel image for each plane before shrinking it took +/// seconds a frame, and its full-size planes overflowed the store, so every frame did it again. +#[test] +fn a_reduced_image_is_separated_from_its_mip_not_its_full_pixels() { + let _fonts = fonts_steady(); + let d = cmyk_doc_with("img", ImageBlob::new("image/png", png(64, 64, 111)), 64, 64); + let on = RenderOptions { image_mips: true, ..Default::default() }; + let _ = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 64.0, 64.0), 0.25, &on); + let full = blob_key(&d.images["img"]).0; + let quarter = images::ImageKey { mip: 2, ..full.clone() }; + let s = images::store(); + for plane in [Ink::Cmy, Ink::K] { + assert!(s.peek(&ink::ink_key(&full, plane)).is_none(), "the {plane:?} plane was made at full size"); + let made = s.peek(&ink::ink_key(&quarter, plane)).unwrap_or_else(|| panic!("no {plane:?} plane of the quarter mip")); + assert_eq!((made.width(), made.height()), (16, 16)); + } +} + +/// A CMYK image drawn reduced paints its own inks, averaged, as at full size: not its displayed +/// colours separated again, which would change how much of its dark is black ink. +#[test] +fn a_reduced_cmyk_image_paints_its_own_inks() { + let _fonts = fonts_steady(); + // Inks a separation of their displayed colour would not give back: rich in black. + let ink = [0u8, 102, 255, 140]; + let blob = ImageBlob::cmyk_tiff(&vectorcraft_doc::cmyk::Inks::new(8, 8, ink.repeat(64)).unwrap()).unwrap(); + let d = cmyk_doc_with("inks", blob, 8, 8); + let on = RenderOptions { image_mips: true, ..Default::default() }; + let inks = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 8.0, 8.0), 0.25, &on); + for px in inks.as_chunks::<4>().0 { + assert!(px.iter().zip(ink).all(|(a, b)| a.abs_diff(b) <= 1), "{px:?} vs {ink:?}"); + } +} + +/// On the ink planes, a reduced image shows the average of its pixels as they show at full size: +/// 1-pixel black and white lines show as the mid grey they make. Separating the full pixels and +/// averaging the planes made that grey a dark brown, 44 levels off. +#[test] +fn a_reduced_image_on_the_ink_planes_shows_its_average() { + let _fonts = fonts_steady(); + let lines = image::RgbaImage::from_fn(64, 64, |x, _| image::Rgba(if x % 2 == 0 { [0, 0, 0, 255] } else { [255; 4] })); + let mut bytes = vec![]; + lines.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let mut d = cmyk_doc_with("lines", ImageBlob::new("image/png", bytes), 64, 64); + // Transparency beside the image: the document blends in CMYK, drawing on its ink planes. + let shape = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 0.0, 110.0, 10.0)); + let mut veil = Node::path(d.alloc_id(), shape, vectorcraft_doc::Appearance::basic(Paint::solid(Color::gray(0.5)), Paint::None, 0.0)); + veil.opacity = 0.5; + let layer = d.layers[0].id; + d.insert(Some(layer), 1, veil).unwrap(); + let full = Renderer::new().render(&d, 64, 64, Affine::IDENTITY, &RenderOptions::default()).pixels; + let on = RenderOptions { image_mips: true, ..Default::default() }; + let reduced = Renderer::new().render(&d, 16, 16, Affine::scale(0.25), &on).pixels; + for (i, px) in reduced.as_chunks::<4>().0.iter().enumerate() { + let (bx, by) = (i % 16 * 4, i / 16 * 4); + let block = |c: usize| (0..16).map(|j| u32::from(full[((by + j / 4) * 64 + bx + j % 4) * 4 + c])).sum::().div_ceil(16) as u8; + let want = [block(0), block(1), block(2)]; + assert!(px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2), "pixel {i}: {px:?}, the full frame averages {want:?}"); + } +} + +/// A `w`×`h` PNG with a different colour in every pixel, so a pixel drawn from the wrong place +/// shows; its pixels depend on `seed` (each test its own image: the store is shared). +fn varied_png(w: u32, h: u32, seed: u8) -> Vec { + let img = image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x * 5 + y) as u8, (x / 3 + y * 7) as u8, (x ^ y) as u8 ^ seed, 255])); + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// #4155: an image drawn larger than a tile with its colours made again (here separated into ink +/// planes) has them made only for the tiles in view. Zoomed in on a 141-megapixel photo, the whole +/// photo was separated for every view, taking seconds each time. +#[test] +fn a_zoomed_in_image_is_separated_only_where_it_shows() { + let _fonts = fonts_steady(); + let (w, h) = (2 * images::TILE + 100, 40); + let d = cmyk_doc_with("wide", ImageBlob::new("image/png", varied_png(w, h, 1)), w, h); + let on = RenderOptions { image_mips: true, ..Default::default() }; + let _ = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 300.0, 40.0), 1.0, &on); + let full = blob_key(&d.images["wide"]).0; + let s = images::store(); + for plane in [Ink::Cmy, Ink::K] { + assert!(s.peek(&ink::ink_key(&full, plane)).is_none(), "the whole {plane:?} plane was made"); + let tile = |col: u16| ink::ink_key(&images::ImageKey { tile: Some((col, 0)), ..full.clone() }, plane); + assert!(s.peek(&tile(0)).is_some(), "the {plane:?} plane of the tile in view was made"); + assert!(s.peek(&tile(1)).is_none() && s.peek(&tile(2)).is_none(), "tiles out of view were made"); + } +} + +/// An image drawn from tiles draws the pixels it draws whole, across the tiles' edges too. +#[test] +fn a_tiled_image_draws_what_the_whole_image_draws() { + let _fonts = fonts_steady(); + let (w, h) = (2 * images::TILE + 100, 40); + let d = cmyk_doc_with("seams", ImageBlob::new("image/png", varied_png(w, h, 2)), w, h); + let on = RenderOptions { image_mips: true, ..Default::default() }; + // Across the edge between the first two tiles. + let (x0, x1) = (f64::from(images::TILE) - 150.0, f64::from(images::TILE) + 150.0); + let drawn = Renderer::new().render_region_inks(&d, Rect::new(x0, 0.0, x1, 40.0), 1.0, &on); + let (key, full) = crate::blobs::blob_pixmap(&d.images["seams"], false).unwrap(); + let plane = |ink| ink::ink_image(&key, &full, ink, d.images.get("seams"), false).1; + let bytes = |pm: &Pixmap| pm.data().iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect::>(); + let whole = ink::amounts(&bytes(&plane(Ink::Cmy)), &bytes(&plane(Ink::K))); + for (i, got) in drawn.as_chunks::<4>().0.iter().enumerate() { + let (x, y) = (x0 as usize + i % 300, i / 300); + let want = &whole[(y * w as usize + x) * 4..][..4]; + assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(*b) <= 1), "pixel ({x}, {y}): {got:?}, whole {want:?}"); + } +} diff --git a/crates/render/src/tests/movedstroke.rs b/crates/render/src/tests/movedstroke.rs new file mode 100644 index 0000000000..f08e341c25 --- /dev/null +++ b/crates/render/src/tests/movedstroke.rs @@ -0,0 +1,465 @@ +//! A moved object draws its stroke from the outline made for it before it moved, and a gradient +//! along or across its stroke from the slices made for it before it moved, moved by the same +//! offset, with the pixels a new renderer draws. A change other than a move outlines the stroke +//! and makes the slices again. + +use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, FillLayer, LineCap, LineJoin, Node, NodeId, NodeKind, StrokeGradientMode, StrokeLayer, + WidthProfile, +}; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::renderer::{SLICES_MADE, STROKES_OUTLINED, anchors_moved, offset_between}; +use crate::*; + +const SIZE: u32 = 200; + +/// The view that shows `at` in the middle of the 200×200 frame. +fn view_at(at: Point) -> Affine { + Affine::translate((100.0 - at.x, 100.0 - at.y)) +} + +fn render(r: &mut Renderer, d: &Document, at: Point) -> Rendered { + r.render(d, SIZE, SIZE, view_at(at), &RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }) +} + +/// How many stroke outlines the renderers on this thread have made. +fn outlined() -> usize { + STROKES_OUTLINED.with(std::cell::Cell::get) +} + +/// A document holding `path` painted with `items`, and the path's id. +fn doc(path: &BezPath, items: Vec) -> (Document, NodeId) { + let mut d = Document::new(1000.0, 1000.0); + let id = d.alloc_id(); + let n = Node::path(id, PathData::from_bezpath(path), Appearance { items, ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + (d, id) +} + +fn stroke(width: f64, join: LineJoin, cap: LineCap) -> StrokeLayer { + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), width); + st.join = join; + st.cap = cap; + st.miter_limit = 10.0; + st +} + +fn dashed(mut st: StrokeLayer, pattern: &[f64]) -> StrokeLayer { + st.dash = Some(Dash { pattern: pattern.to_vec(), offset: 0.0, align_corners: false }); + st +} + +/// `n` anchors 8 pt apart, up and down by 30 pt, every third segment curved. +fn zigzag(n: usize) -> BezPath { + let mut bp = BezPath::new(); + let at = |i: usize| Point::new(i as f64 * 8.0, if i.is_multiple_of(2) { 0.0 } else { 30.0 }); + bp.move_to(at(0)); + for i in 1..n { + if i % 3 == 0 { + bp.curve_to(at(i - 1) + Vec2::new(6.0, 0.0), at(i) + Vec2::new(-6.0, 10.0), at(i)); + } else { + bp.line_to(at(i)); + } + } + bp +} + +/// A closed polygon of `n` anchors round a circle of radius `r` about the origin. +fn ring(n: usize, r: f64) -> BezPath { + let mut bp = BezPath::new(); + for i in 0..n { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = Point::new(r * t.cos(), r * t.sin()); + if i == 0 { bp.move_to(p) } else { bp.line_to(p) } + } + bp.close_path(); + bp +} + +/// The documents of the cases: open and closed paths, short and long (outlined near the view), plain, +/// dashed, with a width profile, with arrowheads, and filled with a gradient (which a move changes, so the moved +/// object has an appearance of its own), each with the point the view is centered on. +fn cases() -> Vec<(&'static str, (Document, NodeId), Point)> { + let round = stroke(6.0, LineJoin::Round, LineCap::Round); + let mut lens = stroke(10.0, LineJoin::Round, LineCap::Butt); + lens.profile = Some(WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] }); + let mut arrows = stroke(4.0, LineJoin::Miter, LineCap::Butt); + arrows.start_arrow = Some(Arrowhead::Triangle); + arrows.end_arrow = Some(Arrowhead::Circle); + arrows.arrow_align = ArrowAlign::Tip; + let gradient = FillLayer::new(Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())))); + let only = |st: StrokeLayer| vec![AppearanceItem::Stroke(st)]; + vec![ + ("a short open path", doc(&zigzag(20), only(stroke(5.0, LineJoin::Miter, LineCap::Square))), Point::new(70.0, 15.0)), + ("a short closed path, dashed", doc(&ring(40, 80.0), only(dashed(round.clone(), &[12.0, 7.0]))), Point::new(0.0, 0.0)), + ("a long open path", doc(&zigzag(3000), only(stroke(6.0, LineJoin::Miter, LineCap::Square))), Point::new(12_000.0, 15.0)), + ("a long closed path", doc(&ring(4000, 5000.0), only(round.clone())), Point::new(0.0, 5000.0)), + ( + "a long open path, dashed", + doc(&zigzag(3000), only(dashed(stroke(5.0, LineJoin::Bevel, LineCap::Butt), &[30.0, 12.0]))), + Point::new(8000.0, 15.0), + ), + ( + "a long closed path, dashed, filled with a gradient", + doc(&ring(4000, 5000.0), vec![AppearanceItem::Fill(gradient), AppearanceItem::Stroke(dashed(round, &[25.0, 15.0]))]), + Point::new(-5000.0, 0.0), + ), + ("a long open path, a width profile", doc(&zigzag(3000), only(lens)), Point::new(12_000.0, 15.0)), + // The heads shorten the line, so the line is not the path itself. + ("a short open path, arrowheads", doc(&zigzag(20), only(arrows.clone())), Point::new(70.0, 15.0)), + ("a long open path, arrowheads", doc(&zigzag(3000), only(arrows)), Point::new(40.0, 15.0)), + ] +} + +/// Draws `d` after `change` with `r` and with a new renderer, checks that the two draw the same +/// pixels, and returns how many stroke outlines `r` made. +fn after(r: &mut Renderer, d: &mut Document, id: NodeId, at: Point, change: impl FnOnce(&mut Node)) -> usize { + change(d.node_mut(id).unwrap()); + let before = outlined(); + let img = render(r, d, at); + let made = outlined() - before; + assert!(img.pixels == render(&mut Renderer::new(), d, at).pixels, "the same pixels as a new renderer"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "the stroke shows"); + made +} + +#[test] +fn a_moved_path_draws_its_stroke_from_the_outline_made_before() { + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + for by in [Vec2::new(1.0, 0.0), Vec2::new(0.25, -0.5), Vec2::new(-3.0, 2.0), Vec2::new(0.1, 0.0)] { + let made = after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate(by), true)); + assert_eq!(made, 0, "{what}, moved by {by:?}: no new outline"); + } + // A fill of another color keeps the path where it is. + let made = after(&mut r, &mut d, id, at, |n| { + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + } + }); + assert_eq!(made, 0, "{what}, a fill changed: no new outline"); + } +} + +#[test] +fn a_path_changed_otherwise_outlines_its_stroke_again() { + let edit_anchor = |n: &mut Node| { + let NodeKind::Path { path, .. } = &mut n.kind else { + panic!("not a path"); + }; + let mut bp = path.to_bezpath(); + let mut els = bp.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + *p += Vec2::new(0.0, 3.0); + } + bp = BezPath::from_vec(els); + *path = PathData::from_bezpath(&bp); + }; + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + // A move, then an edit of an anchor near the path's start. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved"); + assert_eq!(after(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // A move after the edit uses the outline made for the edited path. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((0.5, 0.0)), true)), 0, "{what}: moved after the edit"); + // Scaled and rotated about the view's center, stroke weights kept. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); + // Another join. + let rejoin = |n: &mut Node| { + for i in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = i { + s.join = if s.join == LineJoin::Round { LineJoin::Bevel } else { LineJoin::Round }; + } + } + }; + assert_eq!(after(&mut r, &mut d, id, at, rejoin), 1, "{what}: another join"); + // Back to the first join and moved again: the outline of the join before is not used. + assert_eq!( + after(&mut r, &mut d, id, at, |n| { + rejoin(n); + n.transform(Affine::translate((1.0, 0.0)), true); + }), + 1, + "{what}: the join changed back and moved" + ); + } +} + +/// Checks that each case, drawn once and then changed by `change` (given the point the view is +/// centered on), is drawn with one new outline and the pixels of a new renderer. +fn outlined_again(change: impl Fn(&mut Node, Point)) { + for (what, (mut d, id), at) in cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + assert_eq!(after(&mut r, &mut d, id, at, |n| change(n, at)), 1, "{what}"); + } +} + +/// Applies `change` to every stroke of `n`. +fn restroke(n: &mut Node, change: impl Fn(&mut StrokeLayer)) { + for i in n.appearance.items.iter_mut() { + if let AppearanceItem::Stroke(s) = i { + change(s); + } + } +} + +#[test] +fn a_sheared_path_outlines_its_stroke_again() { + // Sheared about the view's center, stroke weights kept. + outlined_again(|n, at| n.transform(Affine::translate(at.to_vec2()) * Affine::skew(0.001, 0.0) * Affine::translate(-at.to_vec2()), false)); +} + +#[test] +fn another_stroke_width_outlines_the_stroke_again() { + outlined_again(|n, _| restroke(n, |s| s.width += 1.0)); +} + +#[test] +fn another_cap_outlines_the_stroke_again() { + outlined_again(|n, _| restroke(n, |s| s.cap = if s.cap == LineCap::Round { LineCap::Butt } else { LineCap::Round })); +} + +#[test] +fn another_dash_pattern_outlines_the_stroke_again() { + outlined_again(|n, _| { + restroke(n, |s| match &mut s.dash { + Some(d) => d.pattern[0] += 4.0, + None => s.dash = Some(Dash { pattern: vec![9.0, 5.0], offset: 0.0, align_corners: false }), + }) + }); +} + +#[test] +fn another_width_profile_outlines_the_stroke_again() { + outlined_again(|n, _| { + restroke(n, |s| match &mut s.profile { + Some(p) => p.points[1].1 = 0.5, + None => s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.25, 0.25)] }), + }) + }); +} + +#[test] +fn a_small_edit_far_from_the_origin_is_not_taken_for_a_move() { + for (far, edits) in [(1e9, &[0.5, 0.0005][..]), (1e15, &[0.5][..])] { + let was = Affine::translate((far, -far)) * zigzag(20); + let by = Vec2::new(0.25, 3.0); + let moved = Affine::translate(by) * was.clone(); + assert_eq!( + offset_between(&was, &moved), + Some(moved.elements()[0].end_point().unwrap() - was.elements()[0].end_point().unwrap()), + "at {far}: moved" + ); + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let mut moved_node = node(&was); + moved_node.transform(Affine::translate(by), true); + assert!(anchors_moved(&node(&was), &moved_node), "at {far}: anchors moved"); + for &edit in edits { + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + p.y += edit; + } + let edited = BezPath::from_vec(els); + assert_eq!(offset_between(&was, &edited), None, "at {far}: an anchor moved by {edit} pt"); + assert!(!anchors_moved(&node(&was), &node(&edited)), "at {far}: an anchor moved by {edit} pt, read from the anchors"); + // The third segment is a curve: its first handle. + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::CurveTo(h, _, _)) = els.get_mut(3) { + h.x += edit; + } + assert!(!anchors_moved(&node(&was), &node(&BezPath::from_vec(els))), "at {far}: a handle moved by {edit} pt"); + } + } +} + +#[test] +fn an_edit_near_the_origin_is_not_taken_for_a_move_when_the_path_starts_far_from_it() { + // A subpath at 1e16 pt, where coordinates step by 2 pt, then one near the origin. + let mut was = BezPath::new(); + was.move_to((1e16, 1e16)); + was.line_to((1e16 + 64.0, 1e16)); + was.extend(zigzag(20)); + let by = Vec2::new(0.25, 3.0); + let moved = Affine::translate(by) * was.clone(); + assert_eq!(offset_between(&was, &moved), Some(by), "moved: the offset of the subpath near the origin"); + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let mut moved_node = node(&was); + moved_node.transform(Affine::translate(by), true); + assert!(anchors_moved(&node(&was), &moved_node), "anchors moved"); + // The first and the third anchor of the subpath near the origin. + for at in [2, 4] { + for edit in [1.0, 0.5] { + let mut els = moved.elements().to_vec(); + if let Some(kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p)) = els.get_mut(at) { + p.y += edit; + } + let edited = BezPath::from_vec(els); + assert_eq!(offset_between(&was, &edited), None, "element {at} moved by {edit} pt"); + assert!(!anchors_moved(&node(&was), &node(&edited)), "element {at} moved by {edit} pt, read from the anchors"); + } + } +} + +#[test] +fn points_each_near_the_one_before_are_checked_against_one_offset() { + let path = |xs: [f64; 3]| { + let mut bp = BezPath::new(); + bp.move_to((xs[0], 0.0)); + bp.line_to((xs[1], 0.0)); + bp.line_to((xs[2], 0.0)); + bp + }; + let node = |bp: &BezPath| Node::path(NodeId(1), PathData::from_bezpath(bp), Appearance::default()); + let was = path([1e16, 1e15, 1e14]); + // Coordinates step by 2, 0.125 and 0.015625 pt there. + let moved = Affine::translate((6.25, 0.0)) * was.clone(); + assert_eq!(offset_between(&was, &moved), Some(Vec2::new(6.25, 0.0)), "moved"); + assert!(anchors_moved(&node(&was), &node(&moved)), "anchors moved"); + // Each point is within rounding of the one before it, but the first did not move. + let edited = path([1e16, 1e15 + 6.0, 1e14 + 6.25]); + assert_eq!(offset_between(&was, &edited), None); + assert!(!anchors_moved(&node(&was), &node(&edited))); +} + +/// How many sets of gradient stroke slices the renderers on this thread have made. +fn sliced() -> usize { + SLICES_MADE.with(std::cell::Cell::get) +} + +/// A stroke of `width` whose black to blue gradient runs `mode` (along or across the path). +fn gradient_stroke(width: f64, mode: StrokeGradientMode) -> StrokeLayer { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]); + let mut st = stroke(width, LineJoin::Round, LineCap::Butt); + st.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + st.gradient_mode = mode; + st +} + +/// The documents of the gradient cases: open and closed paths, short and long (their line outlined +/// near the view), each with a gradient along and across the stroke, with the point the view is +/// centered on. +fn gradient_cases() -> Vec<(String, (Document, NodeId), Point)> { + let mut out = vec![]; + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + let only = || vec![AppearanceItem::Stroke(gradient_stroke(12.0, mode))]; + out.push((format!("a short open path, {mode:?}"), doc(&zigzag(20), only()), Point::new(70.0, 15.0))); + out.push((format!("a short closed path, {mode:?}"), doc(&ring(40, 80.0), only()), Point::new(80.0, 0.0))); + out.push((format!("a long open path, {mode:?}"), doc(&zigzag(3000), only()), Point::new(12_000.0, 15.0))); + out.push((format!("a long closed path, {mode:?}"), doc(&ring(4000, 5000.0), only()), Point::new(0.0, 5000.0))); + // A placed gradient, whose start and end a move moves too. + let mut st = gradient_stroke(12.0, mode); + if let Paint::Gradient(g) = &mut st.paint { + g.geom = Some(GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(140.0, 30.0), aspect: 1.0, focal: None }); + g.angle = 12.0; + } + out.push(( + format!("a short open path with a placed gradient, {mode:?}"), + doc(&zigzag(20), vec![AppearanceItem::Stroke(st)]), + Point::new(70.0, 15.0), + )); + } + out +} + +/// Draws `d` after `change` with `r` and with a new renderer, checks that the two draw the same +/// pixels, and returns how many sets of slices `r` made. +fn after_sliced(r: &mut Renderer, d: &mut Document, id: NodeId, at: Point, change: impl FnOnce(&mut Node)) -> usize { + change(d.node_mut(id).unwrap()); + let before = sliced(); + let img = render(r, d, at); + let made = sliced() - before; + assert!(img.pixels == render(&mut Renderer::new(), d, at).pixels, "the same pixels as a new renderer"); + assert!(img.pixels.chunks(4).any(|p| p[0] < 128), "the stroke shows"); + made +} + +/// Sets the color of the last stop of each stroke's gradient in `n`. +fn recolor(n: &mut Node, color: Color) { + restroke(n, |s| { + if let Paint::Gradient(g) = &mut s.paint + && let Some(stop) = g.gradient.stops.last_mut() + { + stop.color = color; + } + }) +} + +#[test] +fn a_moved_path_draws_its_gradient_stroke_from_the_slices_made_before() { + for (what, (mut d, id), at) in gradient_cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + for by in [Vec2::new(1.0, 0.0), Vec2::new(0.25, -0.5), Vec2::new(-3.0, 2.0), Vec2::new(0.1, 0.0)] { + let made = after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::translate(by), true)); + assert_eq!(made, 0, "{what}, moved by {by:?}: no new slices"); + } + assert_eq!(after_sliced(&mut r, &mut d, id, at, |_| {}), 0, "{what}: drawn again after the moves"); + } +} + +#[test] +fn a_path_changed_otherwise_makes_its_gradient_stroke_slices_again() { + let edit_anchor = |n: &mut Node| { + let NodeKind::Path { path, .. } = &mut n.kind else { + panic!("not a path"); + }; + let mut els = path.to_bezpath().elements().to_vec(); + if let Some(kurbo::PathEl::LineTo(p)) = els.get_mut(2) { + *p += Vec2::new(0.0, 3.0); + } + *path = PathData::from_bezpath(&BezPath::from_vec(els)); + }; + for (what, (mut d, id), at) in gradient_cases() { + let mut r = Renderer::new(); + render(&mut r, &d, at); + let nudge = |n: &mut Node| n.transform(Affine::translate((0.5, 0.0)), true); + assert_eq!(after_sliced(&mut r, &mut d, id, at, nudge), 0, "{what}: moved"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, edit_anchor), 1, "{what}: an anchor moved"); + // A move after the edit uses the slices made for the edited path. + assert_eq!(after_sliced(&mut r, &mut d, id, at, nudge), 0, "{what}: moved after the edit"); + // Scaled and rotated about the view's center, stroke weights kept. + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::scale_about(1.001, at), false)), 1, "{what}: scaled"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| n.transform(Affine::rotate_about(0.001, at), false)), 1, "{what}: rotated"); + assert_eq!(after_sliced(&mut r, &mut d, id, at, |n| recolor(n, Color::rgb(0.0, 0.5, 0.0))), 1, "{what}: another gradient"); + // Moved with the gradient changed back: the slices of that gradient made before are not used. + assert_eq!( + after_sliced(&mut r, &mut d, id, at, |n| { + recolor(n, Color::rgb(0.0, 0.0, 1.0)); + nudge(n); + }), + 1, + "{what}: the gradient changed back and moved" + ); + // Moved with the gradient laid the other way. + let turn = |s: &mut StrokeLayer| { + s.gradient_mode = if s.gradient_mode == StrokeGradientMode::Along { StrokeGradientMode::Across } else { StrokeGradientMode::Along } + }; + assert_eq!( + after_sliced(&mut r, &mut d, id, at, |n| { + restroke(n, turn); + nudge(n); + }), + 1, + "{what}: the gradient laid the other way and moved" + ); + } +} + +#[test] +fn a_path_moved_out_of_the_region_its_outline_was_cropped_to_is_outlined_again() { + let (mut d, id) = doc(&zigzag(3000), vec![AppearanceItem::Stroke(stroke(6.0, LineJoin::Miter, LineCap::Square))]); + let at = Point::new(12_000.0, 15.0); + let mut r = Renderer::new(); + render(&mut r, &d, at); + assert!(r.strokes.values().any(|e| e.crop.is_some()), "outlined near the view"); + // The outline reaches the view's size past each side of it: 200 pt. + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((150.0, 0.0)), true)), 0, "moved within the region"); + assert_eq!(after(&mut r, &mut d, id, at, |n| n.transform(Affine::translate((150.0, 0.0)), true)), 1, "moved past it"); +} diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs new file mode 100644 index 0000000000..05bbc23573 --- /dev/null +++ b/crates/render/src/tests/thincoverage.rs @@ -0,0 +1,124 @@ +use super::*; +use crate::stroke::outline as raster_stroke_outline; +use vectorcraft_doc::StrokeLayer; + +/// Independently integrate coverage in radial/angle bins of an original notched ring. Checking +/// only the outline geometry misses raster flattening that cancels its two nearby contours. +#[test] +fn fractional_curved_strokes_retain_coverage_between_notches() { + for rounded in [false, true] { + for (weight, rotation, phase, opacity) in + [(1.0 / 3.0, 0.0, 0.0, 1.0), (0.5, 30.0, 0.25, 1.0), (0.75, 75.0, 0.5, 0.5), (1.0, 135.0, 0.75, 1.0)] + { + let mut d = Document::new(1000.0, 1000.0); + let mut path = BezPath::new(); + let mut radius = 450.0; + let mut previous = 0.0; + path.move_to((950.0, 500.0)); + let mut arcs = Vec::new(); + let point = |r: f64, a: f64| vectorcraft_geom::Point::new(500.0 + r * a.cos(), 500.0 + r * a.sin()); + for degrees in [17.0_f64, 64.0, 119.0, 147.0, 201.0, 242.0, 313.0, 360.0] { + let a = degrees.to_radians(); + let k = 4.0 / 3.0 * ((a - previous) / 4.0).tan(); + let start = point(radius, previous); + let end = point(radius, a); + path.curve_to( + start + kurbo::Vec2::new(-previous.sin(), previous.cos()) * (k * radius), + end + kurbo::Vec2::new(a.sin(), -a.cos()) * (k * radius), + end, + ); + arcs.push((radius, previous + 0.06, a - 0.06)); + radius = if radius == 450.0 { 438.0 } else { 450.0 }; + path.line_to(point(radius, a)); + previous = a; + } + path.close_path(); + // Match a parser's f32 coordinate round-trip and exact closed endpoint as well as the + // original f64 construction. A near-coincident final anchor must not hide this case. + let q = |p: kurbo::Point| kurbo::Point::new(f64::from(p.x as f32), f64::from(p.y as f32)); + let path = if rounded { + BezPath::from_vec( + path.iter() + .map(|el| match el { + kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(q(p)), + kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(q(p)), + kurbo::PathEl::QuadTo(a, b) => kurbo::PathEl::QuadTo(q(a), q(b)), + kurbo::PathEl::CurveTo(a, b, c) => kurbo::PathEl::CurveTo(q(a), q(b), q(c)), + kurbo::PathEl::ClosePath => kurbo::PathEl::ClosePath, + }) + .collect(), + ) + } else { + path + }; + { + use kurbo::{ParamCurve, ParamCurveDeriv}; + let st = StrokeLayer::new(Paint::solid(Color::BLACK), weight); + let outline = raster_stroke_outline(&path, &st, weight.max(0.5), 0.25); + for segment in path.segments() { + if let kurbo::PathSeg::Cubic(c) = segment { + for step in 1..20 { + let t = step as f64 / 20.0; + let p = c.eval(t); + let v = c.deriv().eval(t).to_vec2().normalize(); + let n = kurbo::Vec2::new(-v.y, v.x); + for side in [-1.0, 1.0] { + assert_ne!(outline.winding(p + n * (side * weight.max(0.5) * 0.4)), 0, "missing geometric band, rounded={rounded}"); + assert_eq!(outline.winding(p + n * (side * weight.max(0.5) * 0.6)), 0, "outside geometric band, rounded={rounded}"); + } + } + } + } + } + let mut node = Node::path( + d.alloc_id(), + vectorcraft_geom::PathData::from_bezpath(&path), + Appearance::basic(Paint::None, Paint::solid(Color::BLACK), weight), + ); + node.opacity = opacity; + d.insert(Some(d.layers[0].id), 0, node).unwrap(); + let view = + Affine::translate((500.0 + phase, 500.0 + phase)) * Affine::rotate(f64::to_radians(rotation)) * Affine::translate((-500.0, -500.0)); + let image = + Renderer::new().render(&d, 1000, 1000, view, &RenderOptions { background: Some([255; 4]), artboards: false, ..Default::default() }); + // Collect only the measured radial bands once, in the original row-major order. + // Each bin then adds the same pixels in the same order without rescanning the image. + let mut ring = Vec::new(); + for y in 0..1000 { + for x in 0..1000 { + let dx = x as f64 + 0.5 - 500.0 - phase; + let dy = y as f64 + 0.5 - 500.0 - phase; + let distance = dx.hypot(dy); + if !arcs.iter().any(|(r, _, _)| (distance - r).abs() <= 3.0) { + continue; + } + let angle = (dy.atan2(dx) - f64::to_radians(rotation)).rem_euclid(std::f64::consts::TAU); + ring.push((distance, angle, f64::from(255 - image.pixel(x, y)[0]) / 255.0)); + } + } + for (r, begin, end) in arcs { + // 3 bins per arc avoid averaging away a washed-out section. The expected ink area + // is independently r * angle * displayed weight, with the existing half-pixel floor. + for bin in 0..3 { + let lo = begin + (end - begin) * bin as f64 / 3.0; + let hi = begin + (end - begin) * (bin + 1) as f64 / 3.0; + let mut ink = 0.0; + for &(distance, angle, value) in &ring { + if (distance - r).abs() > 3.0 { + continue; + } + if angle >= lo && angle < hi { + ink += value; + } + } + let expected = r * (hi - lo) * weight.max(0.5) * f64::from(opacity); + assert!( + (ink / expected - 1.0).abs() < 0.15, + "weight {weight}, rotation {rotation}, phase {phase}, opacity {opacity}, arc {r} {lo}..{hi}: coverage {}", + ink / expected + ); + } + } + } + } +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 44b8c696e4..7c506d2bb3 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -17,6 +17,7 @@ vectorcraft-doc = { workspace = true } vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } +vectorcraft-pathops = { workspace = true } kurbo = { workspace = true } usvg = { workspace = true } thiserror = { workspace = true } diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 1b19da8019..78113dcd8c 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -668,7 +668,7 @@ impl Rules<'_> { RasterFx::InnerGlow { opacity, blur, color, center: false, .. } if !text => { shadows.push(format!("inset 0 0 {} {}", self.len(blur), color_css(&color, opacity))) } - RasterFx::GaussianBlur { radius } => filter = Some(format!("blur({})", self.len(radius / 2.0))), + RasterFx::GaussianBlur { radius, .. } => filter = Some(format!("blur({})", self.len(radius / 2.0))), RasterFx::InnerGlow { .. } | RasterFx::Feather { .. } => art.unsupported("inner glows or feathering"), RasterFx::Pixel(_) | RasterFx::Rasterize(_) => art.unsupported("pixel effects"), } diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 7be7483919..adcd3fd259 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -2,8 +2,8 @@ use super::output::{sanitize_id, valid_xml_value, xml_attr_escape, xml_attr_vali use super::paint::{StrokePlan, has_raster, pixel_gradient}; use super::text::OUTLINE_TOLERANCE; use super::{ - Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeLayer, Writer, Written, - WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, + Affine, AppearanceItem, BezPath, BlendMode, Document, FillRule, Node, NodeKind, Paint, PathData, Props, Rect, StrokeAlign, StrokeLayer, Writer, + Written, WrittenShape, blend_css, css, fmt_num, stroke, xml_escape, }; /// A symbol's `` def and the instance transforms that can `` it. @@ -32,6 +32,22 @@ pub(crate) struct Reuse { /// How deep symbols may sit in one another's art (deeper instances are left out). const MAX_SYMBOL_NEST: u32 = 8; +/// Gradient placement and outside-aligned stroke masks need the shape's geometric box. +/// Solid colours and patterns do not, so avoid walking their path geometry for a box. +fn export_shape_bounds(n: &Node) -> Option { + n.appearance + .items + .iter() + .any(|item| match item { + AppearanceItem::Fill(f) => f.visible && matches!(f.paint, Paint::Gradient(_)), + AppearanceItem::Stroke(s) => { + s.visible && s.width > 0.0 && !s.paint.is_none() && (matches!(s.paint, Paint::Gradient(_)) || s.align == StrokeAlign::Outside) + } + }) + .then(|| n.geometric_bounds()) + .flatten() +} + impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; @@ -578,7 +594,7 @@ impl Writer<'_> { let dashed = n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.dash.as_ref().is_some_and(|d| d.is_dashed()))); let basic = self.basic_shape(path, self.xf, dashed); - self.shape(n, &d, basic, &[path], *rule, n.geometric_bounds()); + self.shape(n, &d, basic, &[path], *rule, export_shape_bounds(n)); } NodeKind::Compound { children, rule } => { let paths: Vec<&PathData> = children.iter().filter(|c| c.visible).filter_map(|c| c.path_data()).filter(|p| !p.is_empty()).collect(); @@ -586,7 +602,7 @@ impl Writer<'_> { return; } let d: Vec = paths.iter().map(|p| self.path_d(p, self.xf)).collect(); - self.shape(n, &d.join(" "), None, &paths, *rule, n.geometric_bounds()); + self.shape(n, &d.join(" "), None, &paths, *rule, export_shape_bounds(n)); } NodeKind::Text(t) => self.text_node(n, t), NodeKind::Image(im) => { diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 462387d70f..902bfc7e1b 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -601,7 +601,10 @@ impl Writer<'_> { "", sd(*radius) ), - RasterFx::GaussianBlur { radius } => format!("", sd(*radius)), + RasterFx::GaussianBlur { radius, linear } => { + let space = if *linear { " color-interpolation-filters=\"linearRGB\"" } else { "" }; + format!("", sd(*radius)) + } RasterFx::Pixel(_) | RasterFx::Rasterize(_) => continue, }; // Filters composite normally: a shadow's or glow's other blend mode is recorded for import. diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 11795b83fa..fbc4c2836c 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -48,6 +48,7 @@ mod css_transform; mod depth; mod files; mod fx; +mod linear_rgb; mod spread; mod symbol_units; mod text; @@ -150,6 +151,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions, max_nodes: usize) -> Resul slots, patterns: HashMap::new(), midpoints: midpoint_stops(&xml), + linear_rgb: linear_rgb::linear_rgb_ids(&xml, &tree), labels: labels(&xml), hidden: found.hidden, uses: found.uses, @@ -299,6 +301,8 @@ struct Importer { patterns: HashMap, /// Midpoint stops by gradient id (see [`midpoint_stops`]). midpoints: HashMap>>, + /// Ids of the gradients mixed in linear light (see [`linear_rgb::linear_rgb_ids`]). + linear_rgb: HashSet, /// Object names by element id (see [`labels`]). labels: HashMap, /// Ids of the undisplayed objects shown for usvg ([`prepass`]). diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 92f5234ee6..d8cf3bcd58 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -186,22 +186,85 @@ pub(super) fn drawn_ellipse(p: &usvg::tiny_skia_path::Path) -> Option Some(PathData::single(SubPath::new(anchors, true))) } +const MAX_CLIP_DEPTH: usize = 16; + +/// Most clip paths read for one clip. They are shared, so children that each name the next one +/// multiply the work at every level: without this, a few lines of SVG would never finish. +const MAX_CLIP_READS: usize = 1024; + /// The shapes of clip path `cp` on an element whose user space `ts` maps to the document. pub(super) fn clip_shapes(cp: &usvg::ClipPath, ts: Affine) -> Vec<(BezPath, FillRule)> { - fn collect(g: &usvg::Group, m: Affine, out: &mut Vec<(BezPath, FillRule)>) { + let mut reads = MAX_CLIP_READS; + clip_shapes_depth(cp, ts, 0, &mut reads) +} + +/// Recursively collect shapes for `cp` in document space up to `MAX_CLIP_DEPTH`, and while `reads` +/// are left. +fn clip_shapes_depth(cp: &usvg::ClipPath, ts: Affine, depth: usize, reads: &mut usize) -> Vec<(BezPath, FillRule)> { + if depth > MAX_CLIP_DEPTH || *reads == 0 { + return Vec::new(); + } + *reads -= 1; + fn collect(g: &usvg::Group, m: Affine, depth: usize, reads: &mut usize, out: &mut Vec<(BezPath, FillRule)>) { for c in g.children() { match c { - usvg::Node::Group(g) => collect(g, m * aff(g.transform()), out), + usvg::Node::Group(g) => { + let m_child = m * aff(g.transform()); + if let Some(child_cp) = g.clip_path() { + let mut child_shapes = Vec::new(); + collect(g, m_child, depth + 1, reads, &mut child_shapes); + if !child_shapes.is_empty() { + let clip_paths = clip_shapes_depth(child_cp, m_child, depth + 1, reads); + intersect_shapes(&child_shapes, &clip_paths, out); + } + } else { + collect(g, m_child, depth, reads, out); + } + } usvg::Node::Path(p) => out.push((bezpath(p.data(), m), p.fill().map(|f| rule(f.rule())).unwrap_or_default())), _ => {} } } } let mut shapes = Vec::new(); - collect(cp.root(), ts * aff(cp.transform()), &mut shapes); + collect(cp.root(), ts * aff(cp.transform()), depth, reads, &mut shapes); + if !shapes.is_empty() + && depth > 0 + && depth < MAX_CLIP_DEPTH + && *reads > 0 + && let Some(parent_cp) = cp.clip_path() + { + let parent_shapes = clip_shapes_depth(parent_cp, ts, depth + 1, reads); + let mut intersected = Vec::new(); + intersect_shapes(&shapes, &parent_shapes, &mut intersected); + shapes = intersected; + } shapes } +/// Intersect `shapes` with `clips`: SVG 1.1 §14.3.5 specifies that a clip path clips to the union +/// of its children, each child first clipped by its own clip-path if present. +fn intersect_shapes(shapes: &[(BezPath, FillRule)], clips: &[(BezPath, FillRule)], out: &mut Vec<(BezPath, FillRule)>) { + if shapes.is_empty() || clips.is_empty() { + return; + } + let clip_data = match clips { + [(bp, rule)] => (PathData::from_bezpath(bp), *rule), + _ => { + let paths: Vec<(PathData, FillRule)> = clips.iter().map(|(bp, r)| (PathData::from_bezpath(bp), *r)).collect(); + let refs: Vec<(&PathData, FillRule)> = paths.iter().map(|(p, r)| (p, *r)).collect(); + (vectorcraft_pathops::unite_all(&refs), FillRule::NonZero) + } + }; + for (bp, r) in shapes { + let child_data = PathData::from_bezpath(bp); + let inter = vectorcraft_pathops::boolean(&child_data, *r, &clip_data.0, clip_data.1, vectorcraft_pathops::BoolOp::Intersect); + if !inter.subpaths.is_empty() { + out.push((inter.to_bezpath(), FillRule::NonZero)); + } + } +} + /// Does clip path `cp` (on an element whose user space `ts` maps to the document) leave `art`, /// placed by `xf`, whole? (Only its bounds are checked: the box must be inside a clip shape.) pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> bool { @@ -217,6 +280,7 @@ pub(super) fn uncut(cp: &usvg::ClipPath, ts: Affine, art: &Node, xf: Affine) -> corners.iter().all(|c| shapes.iter().any(|(s, _)| kurbo::Shape::contains(s, xf * *c))) } +/// Convert a usvg fill rule to the document model fill rule. pub(super) fn rule(r: usvg::FillRule) -> FillRule { match r { usvg::FillRule::NonZero => FillRule::NonZero, diff --git a/crates/svg/src/import/fx.rs b/crates/svg/src/import/fx.rs index 8c809f0cd7..e5da2936d6 100644 --- a/crates/svg/src/import/fx.rs +++ b/crates/svg/src/import/fx.rs @@ -347,7 +347,9 @@ pub(super) fn effects(filters: &[Arc], ts: Affine, blends: &HashMap continue, - V::Blurred(sd, _) => ("blur.gaussian", json!({ "radius": blur(sd) })), + // SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`). + V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })), + V::Blurred(sd, false) => ("blur.gaussian", json!({ "radius": blur(sd) })), V::Feathered(sd) => ("stylize.feather", json!({ "radius": blur(sd) })), V::Stack(layers) => match layers.as_slice() { [V::Paint { shape, color, opacity, clipped: false }, V::Graphic] if !shape.inverted => { diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 0a0372e3f4..49bcfaab75 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -7,6 +7,7 @@ use super::{ StrokeLayer, Vec2, fnv1a, fx, shapes, spread, text, vector_effect, }; use crate::SvgError; +use kurbo::BezPath; /// How many clip paths deep (``) an object's clip is read. const MAX_CLIP_NEST: usize = 16; @@ -103,9 +104,10 @@ impl Importer { } } - /// A gradient's stops, midpoints restored. + /// A gradient's stops, midpoints restored, and mixed in linear light when it asks for that. fn stops(&self, g: &usvg::BaseGradient) -> Vec { - gradient_stops(g, self.midpoints.get(g.id()).map(Vec::as_slice)) + let stops = gradient_stops(g, self.midpoints.get(g.id()).map(Vec::as_slice)); + if self.linear_rgb.contains(g.id()) { super::linear_rgb::bake(stops) } else { stops } } /// The object name for an element id: its label (see [`labels`]), else the id itself. @@ -143,7 +145,10 @@ impl Importer { let url = self.links.get(g.id()).cloned(); let mut n = match self.instance(g, acc) { Some(n) => n, - None => self.group_node(g, acc)?, + None => { + let n = self.group_node(g, acc)?; + self.filter_regions(g, acc * aff(g.transform()), n)? + } }; if let Some(url) = url { link(&mut n, &url); @@ -359,6 +364,58 @@ impl Importer { Some(n) } + /// `n`, made of group `g` (whose user space `ts` maps to the document), clipped to the regions + /// of the filters it imported as effects: SVG 1.1 §15.5 + /// () cuts a filter's result at + /// its region. A filter that didn't import (drawn without it) clips nothing. + fn filter_regions(&mut self, g: &usvg::Group, ts: Affine, mut n: Node) -> Option { + if g.filters().is_empty() || fx::effects(g.filters(), ts, &self.blends).is_none() { + return Some(n); + } + for f in g.filters() { + n = self.region_clipped(n, f.rect(), ts)?; + } + Some(n) + } + + /// `n` in a clip group cut to `region` (a filter's or mask's, in the user space `ts` maps to + /// the document), unless all it paints (its visual bounds, grown by the reach of its effects) + /// lies inside the region. `None` only past the object limit. + fn region_clipped(&mut self, n: Node, region: usvg::NonZeroRect, ts: Affine) -> Option { + let r = Rect::new(region.left() as f64, region.top() as f64, region.right() as f64, region.bottom() as f64); + let det = ts.determinant(); + let Some(bounds) = n.visual_bounds_with(&self.doc.symbol_boxes()) else { return Some(n) }; + if !det.is_finite() || det.abs() < 1e-12 { + return Some(n); + } + // A clip group paints inside its clipping path; anything else as far as its effects reach + // (as export sizes the filter regions it writes: an Outer Glow grows by a quarter of a + // raster pixel first). + let reach = if matches!(n.kind, NodeKind::Group { clip: true, .. }) { + 0.0 + } else { + let grow = 18.0 / self.doc.raster_ppi(); + vectorcraft_effects::raster_effects(&n.appearance.effects) + .iter() + .map(|f| f.outset(bounds) + if matches!(f, vectorcraft_effects::RasterFx::OuterGlow { .. }) { grow } else { 0.0 }) + .sum() + }; + let painted = bounds.inflate(reach, reach); + let to_user = ts.inverse(); + let eps = 1e-6 * (1.0 + r.width().max(r.height())); + let inside = + [(painted.x0, painted.y0), (painted.x1, painted.y0), (painted.x1, painted.y1), (painted.x0, painted.y1)].into_iter().all(|(x, y)| { + let p = to_user * Point::new(x, y); + p.x >= r.x0 - eps && p.x <= r.x1 + eps && p.y >= r.y0 - eps && p.y <= r.y1 + eps + }); + if inside { + return Some(n); + } + let path = shapes::rectangle(r).transformed(ts); + let clip = self.named("", NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false })?; + self.named("", NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true }) + } + /// `` → opacity mask. An alpha mask's art comes in white with its opacity kept, so its /// luminance is its alpha (images in it keep their colours, with a warning). A mask our export wrote gets its /// options back ([`mask_flags`]) and its art without what stands for them: the inverting @@ -368,6 +425,7 @@ impl Importer { self.warn(format!("nested mask on {label} ignored")); } let (clip, invert) = self.mask_flags.get(m.id()).copied().unwrap_or((true, false)); + let user = ts; let (mut nodes, mut ts) = (m.root().children(), ts); if invert && let [usvg::Node::Group(g)] = nodes @@ -395,6 +453,9 @@ impl Importer { 1 => Arc::unwrap_or_clone(children.pop()?), _ => self.named("", NodeKind::Group { children, clip: false })?, }; + // SVG 1.1 §14.4 (https://www.w3.org/TR/SVG11/masking.html#MaskElement): the mask's art + // counts only inside its region. + let art = self.region_clipped(art, m.rect(), user)?; let mut mask = vectorcraft_doc::OpacityMask::new(art, clip); mask.invert = invert; Some(Box::new(mask)) @@ -446,19 +507,32 @@ impl Importer { } fn clip_node(&mut self, cp: &usvg::ClipPath, ts: Affine) -> Option { - let shapes = clip_shapes(cp, ts); - if shapes.is_empty() { + let mut shapes = clip_shapes(cp, ts); + let id = cp.id().to_string(); + if shapes.len() == 1 { + let (bp, r) = shapes.pop()?; + let kind = self.clip_shape(&bp, r, true)?; + return self.named(&id, kind); + } + // SVG 1.1 §14.3.5: the clip is the union of the children's silhouettes, each under its own + // clip-rule, so they don't cancel or share one rule: a group of them, which clips to that + // union (`Node::clip_shapes`). + let mut children = Vec::with_capacity(shapes.len()); + for (bp, r) in &shapes { + let kind = self.clip_shape(bp, *r, false)?; + children.push(Arc::new(Node::new(self.alloc_id()?, kind))); + } + if children.is_empty() { return None; } - let r = shapes[0].1; - let mut subs = Vec::new(); - for (bp, _) in &shapes { - subs.extend(PathData::from_bezpath(bp).subpaths); - } - let id = cp.id().to_string(); + self.named(&id, NodeKind::Group { children, clip: false }) + } + + /// One clip path child: a path, or a compound path of its subpaths when it has several. + fn clip_shape(&mut self, bp: &BezPath, r: FillRule, clipping: bool) -> Option { + let subs = PathData::from_bezpath(bp).subpaths; if subs.len() == 1 { - let path = PathData::new(subs); - return self.named(&id, NodeKind::Path { path, rule: r, live: None, clipping: true, guide: false }); + return Some(NodeKind::Path { path: PathData::new(subs), rule: r, live: None, clipping, guide: false }); } let mut children = Vec::with_capacity(subs.len()); for sp in subs { @@ -466,7 +540,7 @@ impl Importer { children .push(Arc::new(Node::new(nid, NodeKind::Path { path: PathData::single(sp), rule: r, live: None, clipping: false, guide: false }))); } - self.named(&id, NodeKind::Compound { children, rule: r }) + Some(NodeKind::Compound { children, rule: r }) } /// A usvg paint mapped by `m`, for art covering `area` (after `m`: where a reflected or @@ -714,6 +788,7 @@ mod tests { slots: TextSlots::default(), patterns: HashMap::new(), midpoints: HashMap::new(), + linear_rgb: HashSet::new(), labels: HashMap::new(), hidden: HashSet::new(), uses: HashMap::new(), diff --git a/crates/svg/src/import/linear_rgb.rs b/crates/svg/src/import/linear_rgb.rs new file mode 100644 index 0000000000..8286e0a94b --- /dev/null +++ b/crates/svg/src/import/linear_rgb.rs @@ -0,0 +1,170 @@ +//! Gradients drawn with `color-interpolation="linearRGB"` (SVG 1.1 §11.7.1, +//! ): their stops mix in +//! linear light, which a document gradient (mixed in display RGB) shows through extra stops. + +use super::{Color, GradientStop, HashMap, HashSet, css, roxmltree}; +use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear}; + +/// How far (display RGB, 0..1) the straight line between neighbouring baked stops may stray from +/// the linear-light mix: under half a colour level. +const TOLERANCE: f32 = 0.4 / 255.0; +/// Most times a span between two stops is halved to keep within [`TOLERANCE`]. +const MAX_DEPTH: u32 = 8; +/// Most stops a baked gradient has: a file with very many stops keeps the rest of its spans as +/// they are rather than growing without bound. +pub(super) const MAX_STOPS: usize = 4096; + +/// The ids (as usvg names them) of the gradients whose `color-interpolation` is `linearRGB`. +/// +/// usvg gives a gradient used by several objects a made-up id (`linearGradient2`…) for each user +/// but the last; those are found by their stops and geometry, matching an original gradient's +/// only when no other original gradient with the same stops and geometry interpolates otherwise. +pub(super) fn linear_rgb_ids(xml: &roxmltree::Document, tree: &usvg::Tree) -> HashSet { + if !xml.input_text().contains("linearRGB") { + return HashSet::new(); + } + let styles = css::Styles::new(xml); + let mut linear = HashSet::new(); + let mut named = HashSet::new(); + for g in xml.descendants().filter(|n| matches!(n.tag_name().name(), "linearGradient" | "radialGradient")) { + let Some(id) = g.attribute("id") else { continue }; + named.insert(id); + if styles.prop(g, "color-interpolation").as_deref() == Some("linearRGB") { + linear.insert(id.to_string()); + } + } + if linear.is_empty() { + return linear; + } + let gradients = || { + let lin = tree.linear_gradients().iter().map(|g| (g.id(), signature(g, &[g.x1(), g.y1(), g.x2(), g.y2()]))); + let rad = tree.radial_gradients().iter().map(|g| (g.id(), signature(g, &[g.cx(), g.cy(), g.r().get(), g.fx(), g.fy(), g.fr().get()]))); + lin.chain(rad) + }; + // Each original gradient's look → whether all the originals that look so are linearRGB. + let mut by_look: HashMap, bool> = HashMap::new(); + for (id, sig) in gradients().filter(|(id, _)| named.contains(id)) { + let is_linear = linear.contains(id); + by_look.entry(sig).and_modify(|v| *v &= is_linear).or_insert(is_linear); + } + let copies: Vec = + gradients().filter(|(id, sig)| !named.contains(id) && by_look.get(sig) == Some(&true)).map(|(id, _)| id.to_string()).collect(); + linear.extend(copies); + linear +} + +/// What tells two usvg gradients apart but for their id, units and transform (what usvg changes +/// on the copies it makes): their geometry `geom`, spread method and stops. +fn signature(g: &usvg::BaseGradient, geom: &[f32]) -> Vec { + let spread = match g.spread_method() { + usvg::SpreadMethod::Pad => 0, + usvg::SpreadMethod::Reflect => 1, + usvg::SpreadMethod::Repeat => 2, + }; + let mut sig: Vec = geom.iter().map(|v| v.to_bits()).collect(); + sig.push(spread); + for s in g.stops() { + let c = s.color(); + sig.extend([s.offset().get().to_bits(), u32::from_be_bytes([0, c.red, c.green, c.blue]), s.opacity().get().to_bits()]); + } + sig +} + +/// `stops`, mixed in linear light: between each two stops, stops where the display-RGB line +/// strays from the linear-light mix (opacity still mixes evenly). Spans with a moved midpoint +/// (only our own export writes those, never with linearRGB) keep their midpoint unbaked. +pub(super) fn bake(stops: Vec) -> Vec { + let mut out: Vec = Vec::with_capacity(stops.len()); + let mut it = stops.into_iter().peekable(); + while let Some(a) = it.next() { + let next = it.peek().cloned(); + out.push(a.clone()); + let Some(b) = next else { break }; + if b.offset <= a.offset || (a.midpoint - 0.5).abs() > 1e-6 || a.color.to_rgb() == b.color.to_rgb() { + continue; + } + let mut ts = Vec::new(); + steps(&a.color, &b.color, (0.0, 1.0), 1, &mut ts); + let room = MAX_STOPS.saturating_sub(out.len() + it.len()); + for t in ts.into_iter().take(room) { + let opacity = a.opacity + (b.opacity - a.opacity) * t; + out.push(GradientStop { opacity, ..GradientStop::new(a.offset + (b.offset - a.offset) * t, mix(&a.color, &b.color, t)) }); + } + } + out +} + +/// `a` and `b` mixed at `t` (0..1) in linear light, as display RGB. +fn mix(a: &Color, b: &Color, t: f32) -> Color { + let (p, q) = (a.to_rgb(), b.to_rgb()); + let ch = |k: usize| { + let (x, y) = (srgb_to_linear(p[k]), srgb_to_linear(q[k])); + let v = linear_to_srgb(x + (y - x) * t); + if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } + }; + Color::rgb(ch(0), ch(1), ch(2)) +} + +/// The mix positions (after `t0`, before `t1`) between which display RGB mixed straight stays +/// within [`TOLERANCE`] of the linear-light mix of `a` and `b`, in order. +fn steps(a: &Color, b: &Color, (t0, t1): (f32, f32), depth: u32, out: &mut Vec) { + let at = |t: f32| mix(a, b, t).to_rgb(); + let (c0, c1) = (at(t0), at(t1)); + let stray = [0.25, 0.5, 0.75] + .into_iter() + .flat_map(|u: f32| { + let c = at(t0 + (t1 - t0) * u); + (0..3).map(move |k| (c0[k] + (c1[k] - c0[k]) * u - c[k]).abs()) + }) + .fold(0.0, f32::max); + if depth <= MAX_DEPTH && stray > TOLERANCE { + let m = (t0 + t1) / 2.0; + steps(a, b, (t0, m), depth + 1, out); + out.push(m); + steps(a, b, (m, t1), depth + 1, out); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(stops: &[GradientStop], x: f32) -> [f32; 3] { + vectorcraft_color::Gradient::new(vectorcraft_color::GradientKind::Linear, stops.to_vec()).sample(x).0.to_rgb() + } + + #[test] + fn black_to_white_is_brighter_mid_way() { + let baked = bake(vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]); + assert!(baked.len() > 2 && baked.len() < 300, "{}", baked.len()); + // A balanced linear-light mix of black and white encodes to about 188/255. + let mid = sample(&baked, 0.5)[0] * 255.0; + assert!((mid - 188.0).abs() < 1.0, "{mid}"); + for i in 0..=100 { + let x = i as f32 / 100.0; + let want = linear_to_srgb(x); + assert!((sample(&baked, x)[0] - want).abs() < 1.0 / 255.0, "at {x}"); + } + assert!(baked.windows(2).all(|w| w[0].offset <= w[1].offset)); + } + + #[test] + fn equal_colours_and_moved_midpoints_stay_as_they_are() { + let same = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::BLACK)]; + assert_eq!(bake(same.clone()), same); + let moved = vec![GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::BLACK) }, GradientStop::new(1.0, Color::WHITE)]; + assert_eq!(bake(moved.clone()), moved); + } + + #[test] + fn opacity_mixes_evenly_and_the_stop_count_is_capped() { + let a = GradientStop { opacity: 0.0, ..GradientStop::new(0.0, Color::BLACK) }; + let baked = bake(vec![a, GradientStop::new(1.0, Color::WHITE)]); + assert!(baked.iter().all(|s| (s.opacity - s.offset).abs() < 1e-5)); + let many: Vec = + (0..3000).map(|i| GradientStop::new(i as f32 / 2999.0, if i % 2 == 0 { Color::BLACK } else { Color::WHITE })).collect(); + let baked = bake(many); + assert_eq!(baked.len(), MAX_STOPS); + assert_eq!(baked.last().map(|s| s.offset), Some(1.0), "every original stop is kept"); + } +} diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index 57a156b82e..2502bd2bd6 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -503,6 +503,53 @@ impl Ctx { out.spans[slot].1 = start..out.chars.len(); } + /// `textLength` and `lengthAdjust` (SVG 1.1 §10.9.1, + /// https://www.w3.org/TR/SVG11/text.html#TextElementTextLengthAttribute): the characters of + /// each element with a `textLength` are fitted to that advance, by adding the difference evenly + /// between them (`spacing`, the default; it becomes kerning) or by stretching them + /// (`spacingAndGlyphs`; it becomes horizontal scale, kept within 1–10000%). Innermost elements + /// first, so an element's length takes in its children's. Vertical type is spaced out only. + fn fit_lengths(&self, spans: &[(XNode, Range)], cells: &mut [Cell], vertical: bool, label: &str, warnings: &mut Vec) { + let n = cells.len(); + for (el, r) in spans.iter().rev() { + let Some(want) = el.attribute("textLength").and_then(|v| self.length(v, self.font_size(*el), self.viewport.0)).filter(|w| *w >= 0.0) + else { + continue; + }; + // Past the largest coordinate, the characters would only be out of reach. + let want = want.min(vectorcraft_doc::MAX_COORD); + let Some(part) = cells.get_mut(r.start.min(n)..r.end.min(n)) else { continue }; + let Some(gaps) = part.len().checked_sub(1) else { continue }; + let stretch = el.attribute("lengthAdjust").map(str::trim) == Some("spacingAndGlyphs"); + if stretch && vertical { + warnings.push(format!("{label}: lengthAdjust=\"spacingAndGlyphs\" on vertical text spaces the characters out instead")); + } + // Kerning and scale change shaping (manual kerning turns pair kerning off): measure again. + for _ in 0..4 { + let have = advance(&point_text(part)); + if !have.is_finite() || (want - have).abs() < 0.01 { + break; + } + if stretch && !vertical { + let k = want / have; + if !k.is_finite() || k <= 0.0 { + break; + } + for c in part.iter_mut() { + c.style.h_scale = (c.style.h_scale * k).clamp(1.0, 10_000.0); + } + } else if gaps > 0 { + let d = (want - have) / gaps as f64; + for c in part.iter_mut().take(gaps) { + c.kern += d; + } + } else { + break; + } + } + } + } + /// The path a `` follows, in the text's user space. fn text_path(&self, xml: &roxmltree::Document, tp: XNode) -> Option { let mut bp = match tp.attribute("path") { @@ -730,6 +777,7 @@ impl Ctx { } }); let vertical = self.css.prop(t, "writing-mode").is_some_and(|m| m.starts_with("tb") || m.starts_with("vertical")); + self.fit_lengths(&cs.spans, &mut cells, vertical, label, warnings); let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default()); let mut breaks: Vec = vec![]; let mut para_styles: Vec = vec![]; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ccc154a383..58cb434ed2 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -624,6 +624,49 @@ pub fn xml_escape(s: &str) -> String { o } +/// [`push_num`] through integer arithmetic, for the values it writes the same as the decimal +/// formatter: `decimals` of at most 9, and `v` scaled by 10^`decimals` below 2^53 and further from +/// halfway between two integers than the scaling's rounding error. Returns false, writing nothing, +/// for any other value. +fn push_num_scaled(out: &mut String, v: f64, decimals: u8) -> bool { + const SCALE: [f64; 10] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + let Some(&scale) = SCALE.get(usize::from(decimals)) else { return false }; + // Each power of ten here is exact, so `x` is within half an ulp (`x * EPSILON / 2`) of |v| × 10^decimals. + let x = v.abs() * scale; + if x.is_nan() || x >= 9.0e15 { + return false; + } + let whole = x.floor(); + let frac = x - whole; + if (frac - 0.5).abs() <= x * f64::EPSILON { + return false; + } + let mut n = whole as u64 + u64::from(frac > 0.5); + let places = usize::from(decimals); + // The digits of `n` from the last one, at least one more than `places` of them. + let mut digits = [0u8; 24]; + let mut len = 0; + for d in digits.iter_mut() { + if n == 0 && len > places { + break; + } + *d = b'0' + (n % 10) as u8; + n /= 10; + len += 1; + } + let Some((fraction, int)) = digits.get(..len).and_then(|d| d.split_at_checked(places)) else { return false }; + let zeros = fraction.iter().take_while(|&&d| d == b'0').count(); + if v < 0.0 && (zeros < places || int.iter().any(|&d| d != b'0')) { + out.push('-'); + } + out.extend(int.iter().rev().map(|&d| char::from(d))); + if zeros < places { + out.push('.'); + out.extend(fraction.iter().skip(zeros).rev().map(|&d| char::from(d))); + } + true +} + /// Format a number with at most `decimals` places, trimming trailing zeros. pub fn fmt_num(v: f64, decimals: u8) -> String { let mut s = String::new(); @@ -635,6 +678,9 @@ pub fn fmt_num(v: f64, decimals: u8) -> String { pub fn push_num(out: &mut String, v: f64, decimals: u8) { use std::fmt::Write as _; let v = if v.is_finite() { v } else { 0.0 }; + if push_num_scaled(out, v, decimals) { + return; + } let start = out.len(); let _ = write!(out, "{:.*}", decimals as usize, v); // writing to a String can't fail let s = out.get(start..).unwrap_or_default(); @@ -674,4 +720,48 @@ mod tests { fn escaping() { assert_eq!(xml_escape("a&\"'"), "a<b>&"'"); } + + /// `v` at `decimals` places by the decimal formatter, trailing zeros trimmed. + fn formatted(v: f64, decimals: u8) -> String { + let s = format!("{:.*}", usize::from(decimals), if v.is_finite() { v } else { 0.0 }); + let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s }; + if matches!(s, "-0" | "") { "0".into() } else { s.into() } + } + + #[test] + fn numbers_match_the_decimal_formatter() { + let mut values = + vec![0.0, -0.0, 0.5, -0.5, 2.5, 0.0005, -0.0005, 1.0005, 0.125, 1e-12, 9.0e15, 4503599627370495.5, 1e20, f64::NAN, f64::INFINITY]; + // Coordinates of every size, and values on and just off the halfway points between written numbers. + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + for _ in 0..20_000 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let unit = (seed >> 11) as f64 / (1u64 << 53) as f64; + let v = (unit - 0.5) * 10f64.powi((seed % 13) as i32 - 3); + let tie = ((v * 1000.0).trunc() + 0.5) / 1000.0; + values.extend([v, tie, f64::from_bits(tie.to_bits() + 1), f64::from_bits(tie.to_bits() - 1)]); + } + for v in values { + for d in 0..=12 { + assert_eq!(fmt_num(v, d), formatted(v, d), "{v:e} at {d} decimals"); + } + } + } + + #[test] + fn coordinates_are_written_through_integers() { + for (v, d, want) in [(123.4567, 3, "123.457"), (-0.25, 3, "-0.25"), (-0.0004, 3, "0"), (1600.0, 3, "1600"), (7.0, 0, "7")] { + let mut s = String::new(); + assert!(push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert_eq!(s, want); + } + // Halfway as stored, too large, or too many places: the decimal formatter writes them. + for (v, d) in [(0.5, 0), (0.125, 2), (1e16, 0), (1.0, 10)] { + let mut s = String::new(); + assert!(!push_num_scaled(&mut s, v, d), "{v} at {d} decimals"); + assert!(s.is_empty()); + } + } } diff --git a/crates/svg/tests/it/gradients.rs b/crates/svg/tests/it/gradients.rs index efbbc30e64..f56b39c968 100644 --- a/crates/svg/tests/it/gradients.rs +++ b/crates/svg/tests/it/gradients.rs @@ -100,3 +100,64 @@ fn midpoints_come_back() { assert!((g.gradient.stops[0].midpoint - 0.25).abs() < 1e-6); assert!((g.gradient.stops[1].midpoint - 0.5).abs() < 1e-6); } + +/// The gradient fills of every path `svg` imports to, in order. +fn imported_gradients(svg: &str) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if let Paint::Gradient(g) = n.appearance.fill_paint() { + out.push(g.gradient.clone()); + } + for c in n.children().into_iter().flatten() { + walk(c, out); + } + } + let d = import(svg).unwrap(); + let mut out = vec![]; + for l in &d.layers { + walk(l, &mut out); + } + out +} + +/// SVG 1.1 §11.7.1 (https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationProperty): +/// `color-interpolation="linearRGB"` mixes a gradient's stops in linear light (#5878). +#[test] +fn linear_rgb_gradients_mix_in_linear_light() { + let svg = |interp: &str| { + format!( + r#" + + "# + ) + }; + let mid = |g: &Gradient| g.sample(0.5).0.to_rgb()[0] * 255.0; + let linear = imported_gradients(&svg("linearRGB")); + assert_eq!(linear.len(), 1); + assert!(linear[0].stops.len() > 2); + // A balanced linear-light mix of black and white encodes to about 188/255. + assert!((mid(&linear[0]) - 188.0).abs() < 1.0, "{}", mid(&linear[0])); + let srgb = imported_gradients(&svg("sRGB")); + assert_eq!(srgb[0].stops.len(), 2); + assert!((mid(&srgb[0]) - 127.5).abs() < 1.0, "{}", mid(&srgb[0])); +} + +/// The property inherits and cascades; a gradient several objects share (which usvg copies) is +/// mixed in linear light on every one of them, and one asking for sRGB with the same stops isn't. +#[test] +fn linear_rgb_inherits_cascades_and_holds_for_every_user() { + let svg = r#" + + + + + + + + + "#; + let counts: Vec = imported_gradients(svg).iter().map(|g| g.stops.len()).collect(); + assert_eq!(counts.len(), 5); + assert!(counts[..3].iter().all(|&n| n > 2), "{counts:?}"); + assert_eq!(counts[3], 2, "{counts:?}"); + assert!(counts[4] > 2, "{counts:?}"); +} diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 8b36458609..13518a6fd4 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -213,6 +213,186 @@ fn nested_clips_intersect() { assert_ne!(mine.over_white(90, 60), [255, 255, 255]); } +/// SVG 1.1 §14.3.5: a clip path clips to the union of its children's silhouettes, each under its +/// own `clip-rule` (https://www.w3.org/TR/SVG11/masking.html#EstablishingANewClippingPath). +#[test] +fn clip_path_children_unite_under_their_own_rules() { + // Two squares wound in opposite directions overlap at 60–100: the overlap stays clipped in. + let opposite = r##" + "##; + // A small non-zero square first, then an even-odd ring: the ring's hole stays out. + let ring = r##" + + "##; + let page = |body: &str| format!(r#"{body}"#); + for body in [opposite, ring] { + let (d, w) = import_with_report(&page(body)).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mine = render_artboard(&d); + assert_similar(&mine, &resvg_render(&page(body), 200, 200), 24.0, 0.003); + // Written back out, the clip is still the union. + let out = vectorcraft_svg::export(&d, &Default::default()); + assert_similar(&render_artboard(&vectorcraft_svg::import(&out).unwrap()), &mine, 24.0, 0.003); + } + let (d, _) = import_with_report(&page(opposite)).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(80, 80), [255, 0, 0], "the overlap is clipped in"); + assert_eq!(mine.over_white(120, 120), [255, 0, 0]); + assert_eq!(mine.over_white(130, 30), [255, 255, 255]); + let (d, _) = import_with_report(&page(ring)).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(100, 80), [255, 255, 255], "the even-odd hole stays out"); + assert_eq!(mine.over_white(50, 80), [255, 0, 0]); + assert_eq!(mine.over_white(5, 5), [255, 0, 0]); + // Each child keeps its own rule in the clipping group, still named after the clip path. + let clip = &art(&d)[1]; + assert_eq!(clip.name.as_deref(), Some("c")); + let NodeKind::Group { children, clip: false } = &clip.kind else { panic!("{clip:?}") }; + assert!(matches!(children[0].kind, NodeKind::Path { rule: vectorcraft_geom::FillRule::NonZero, .. })); + assert!(matches!(children[1].kind, NodeKind::Compound { rule: vectorcraft_geom::FillRule::EvenOdd, .. })); +} + +/// SVG 1.1 §14.3.5: a child of a clipPath element with its own clip-path is clipped by it before +/// contributing to the clip (https://www.w3.org/TR/SVG11/masking.html#EstablishingANewClippingPath). +#[test] +fn clip_path_child_clip_path_clips_child() { + let page = r##" + + + + + + + + "##; + let (d, w) = import_with_report(page).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mine = render_artboard(&d); + assert_similar(&mine, &resvg_render(page, 200, 200), 24.0, 0.003); + assert_eq!(mine.over_white(25, 25), [255, 0, 0], "the left strip is clipped in"); + assert_eq!(mine.over_white(100, 100), [255, 255, 255], "the right side is cut by inner clip"); + // Written back out, the clip stays identical. + let out = vectorcraft_svg::export(&d, &Default::default()); + assert_similar(&render_artboard(&vectorcraft_svg::import(&out).unwrap()), &mine, 24.0, 0.003); +} + +#[test] +fn clip_path_child_with_chained_clip_path_intersects() { + let page = r##" + + + + + + + + + "##; + let (d, w) = import_with_report(page).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let mine = render_artboard(&d); + assert_similar(&mine, &resvg_render(page, 200, 200), 24.0, 0.003); + assert_eq!(mine.over_white(25, 25), [255, 0, 0], "top left quadrant is inside both clips"); + assert_eq!(mine.over_white(25, 150), [255, 255, 255], "bottom left is cut by base clip"); + assert_eq!(mine.over_white(100, 25), [255, 255, 255], "top right is cut by inner clip"); +} + +/// Clip paths are shared, so children that each name the next one multiply at every level: ten +/// children on seven levels would take 10^7 reads unbounded. The import must still finish. +#[test] +fn clip_paths_whose_children_fan_out_still_import() { + let mut defs = String::from(r#""#); + for n in 1..8 { + let kids = format!(r#""#, n - 1).repeat(10); + defs += &format!(r#"{kids}"#); + } + let svg = format!( + r#"{defs}"# + ); + assert!(import_with_report(&svg).is_ok()); +} + +#[test] +fn clip_path_deep_chain_preserves_art() { + let mut defs = String::from(r#""#); + for n in 1..=20 { + defs += &format!(r#""#, n - 1); + } + let svg = format!( + r##"{defs}"## + ); + let (d, w) = import_with_report(&svg).unwrap(); + assert!(!w.is_empty(), "expected warning about deep clip nesting"); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 0, 0], "red rect should be preserved despite depth limit"); +} + +#[test] +fn clip_path_child_deep_chain_preserves_art() { + let mut defs = String::from(r#""#); + for n in 1..=20 { + defs += &format!(r#""#, n - 1); + } + defs += r#""#; + let svg = format!( + r##"{defs}"## + ); + let (d, _w) = import_with_report(&svg).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 0, 0], "red rect should be preserved despite depth limit in child clip"); +} + +#[test] +fn clip_path_preserves_union_when_read_budget_exhausted() { + let mut defs = String::from(r#""#); + let mut kids = String::new(); + for i in 0..1100 { + let x = (i % 20) * 10; + let y = (i / 20) * 10; + kids += &format!(r##""##); + } + defs += &format!(r#"{kids}"#); + let svg = format!( + r##"{defs}"## + ); + let (d, _w) = import_with_report(&svg).unwrap(); + let mine = render_artboard(&d); + // Early tiles processed within the 1024 read budget must be preserved in the union. + assert_eq!(mine.over_white(5, 5), [255, 0, 0], "early tile inside read budget is preserved"); +} + +#[test] +fn clip_path_empty_clips_everything() { + let page = r##" + + + + + "##; + let (d, _w) = import_with_report(page).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 255, 255], "genuinely empty clip path clips away all art"); +} + +#[test] +fn clip_path_child_with_empty_linked_clip_clips_everything() { + let page = r##" + + + + + + + + + + + "##; + let (d, _w) = import_with_report(page).unwrap(); + let mine = render_artboard(&d); + assert_eq!(mine.over_white(50, 50), [255, 255, 255], "empty linked clip path clips away all art"); +} + #[test] fn undisplayed_objects_import_hidden() { let body = r##" diff --git a/crates/svg/tests/it/import_live.rs b/crates/svg/tests/it/import_live.rs index b4dd58256d..b93314b54d 100644 --- a/crates/svg/tests/it/import_live.rs +++ b/crates/svg/tests/it/import_live.rs @@ -111,7 +111,9 @@ fn resvg_render(svg: &str, w: u32, h: u32) -> Image { /// The effects of the only object. fn effects(d: &Document) -> Vec { - let a = art(d); + // Not the clip group a filter's region may put it in (SVG 1.1 §15.5), nor its clipping path. + let a: Vec<&Node> = + art(d).into_iter().filter(|n| !matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Path { clipping: true, .. })).collect(); assert_eq!(a.len(), 1, "{a:?}"); a[0].appearance.effects.clone() } @@ -239,7 +241,7 @@ fn a_figma_blurred_shape_filter_becomes_gaussian_blur() { assert!(w.is_empty(), "{w:?}"); let fx = effects(&d); assert_eq!(fx.len(), 1); - assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0}))); + assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0, "linear": true}))); } #[test] @@ -274,7 +276,7 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert!(w.is_empty(), "{w:?}"); let fx = effects(&d); assert_eq!(fx.len(), 1); - assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0}))); + assert_eq!((fx[0].id.as_str(), &fx[0].params), ("blur.gaussian", &json!({"radius": 6.0, "linear": true}))); // In a scaled group, the radius scales too. let (d, _) = open( r##""##, @@ -282,6 +284,98 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() { assert_eq!(effects(&d)[0].params["radius"], json!(12.0)); } +/// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB: +/// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the +/// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they +/// are (#5877). +#[test] +fn a_gaussian_blur_keeps_its_colour_space() { + let blur = |filter: &str, primitive: &str| { + let (d, w) = open(&format!( + r##""## + )); + assert!(w.is_empty(), "{w:?}"); + effects(&d)[0].params.clone() + }; + let linear = json!({"radius": 20.0, "linear": true}); + let srgb = json!({"radius": 20.0}); + assert_eq!(blur("", r#" color-interpolation-filters="linearRGB""#), linear); + assert_eq!(blur("", ""), linear, "linearRGB is the initial value"); + assert_eq!(blur("", r#" color-interpolation-filters="sRGB""#), srgb); + assert_eq!(blur(r#" color-interpolation-filters="sRGB""#, ""), srgb, "inherited from the filter"); + // Export writes the space back on the blur, so it survives a round trip. + let (d, _) = + open(r##""##); + let svg = export(&d, &ExportOptions::default()); + assert!(svg.contains(r#"color-interpolation-filters="linearRGB"/>"#), "{svg}"); + assert_eq!(effects(&import(&svg).unwrap())[0].params, linear); + // Drawn, black beside white meets as resvg (which blurs in either space) draws it. + for space in ["linearRGB", "sRGB"] { + let source = format!( + r##""## + ); + let (ours, theirs) = (render_artboard(&import(&source).unwrap()), resvg_render(&source, 200, 200)); + for x in [95, 99, 100, 105] { + let at = 4 * (100 * 200 + x) as usize; + assert!(ours.rgba[at].abs_diff(theirs.rgba[at]) <= 6, "{space} at {x}: {} vs {}", ours.rgba[at], theirs.rgba[at]); + } + } +} + +/// The colour of pixel (`x`, `y`) of `svg` imported and drawn on white. +fn drawn_at(svg: &str, x: u32, y: u32) -> [u8; 4] { + let img = render_artboard(&import(svg).unwrap()); + let at = 4 * (y * img.width + x) as usize; + [img.rgba[at], img.rgba[at + 1], img.rgba[at + 2], img.rgba[at + 3]] +} + +/// SVG 1.1 §15.5 (https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion): a filter's +/// result is cut at its region, so a blurred square shows only inside it (#5876). A region that +/// holds the whole blur adds no clip. +#[test] +fn a_blur_is_cut_at_its_filter_region() { + let doc = |width: u32| { + format!( + r##""## + ) + }; + let red = |p: [u8; 4]| p[0] > 240 && p[1] < 30 && p[2] < 30; + assert!(red(drawn_at(&doc(50), 25, 100))); + assert_eq!(drawn_at(&doc(50), 100, 100), [255, 255, 255, 255], "outside the region"); + assert!(red(drawn_at(&doc(200), 100, 100))); + // With room for the blur all round, the object is as before: no clip group. + let roomy = r##""##; + let d = import(roomy).unwrap(); + assert_eq!(art(&d).len(), 1); + // Our own export sizes the region to the blur: it comes back unclipped. + let back = import(&export(&d, &ExportOptions::default())).unwrap(); + assert_eq!(art(&back).len(), 1); +} + +/// SVG 1.1 §14.4 (https://www.w3.org/TR/SVG11/masking.html#MaskElement): a mask's art counts +/// only inside the mask's region, in user space or the object's bounding box (#5875). +#[test] +fn a_mask_counts_only_inside_its_region() { + let doc = |region: &str| { + format!( + r##""## + ) + }; + let red = [255, 0, 0, 255]; + for region in + [r#"maskUnits="userSpaceOnUse" x="0" y="0" width="50" height="200""#, r#"maskUnits="objectBoundingBox" x="0" y="0" width="0.25" height="1""#] + { + assert_eq!(drawn_at(&doc(region), 25, 100), red, "{region}"); + assert_eq!(drawn_at(&doc(region), 100, 100), [255, 255, 255, 255], "{region}"); + } + let wide = doc(r#"maskUnits="userSpaceOnUse" x="0" y="0" width="200" height="200""#); + assert_eq!(drawn_at(&wide, 100, 100), red); + // The default region (-10% to 120% of the object) holds the art: the mask art is as before. + let d = import(&doc("")).unwrap(); + let mask = art(&d)[0].extras().mask.clone().unwrap(); + assert!(matches!(mask.art.kind, NodeKind::Path { .. }), "{:?}", mask.art.kind); +} + /// The one drop shadow of the only object: (dx, dy, blur, colour, opacity %). fn shadow(d: &Document) -> (f64, f64, f64, Color, f32) { let fx = vectorcraft_effects::raster_effects(&effects(d)); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 5fa2b5d7f2..7d0e08c0be 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -693,3 +693,40 @@ fn flowed_text_that_cannot_be_read_is_reported() { assert!(w.iter().any(|w| w.contains(id) && w.contains("flowRoot")), "{id}: {w:?}"); } } + +/// Total advance of a single-line text. +fn advance(t: &TextObject) -> f64 { + layout(FontDb::global(), t).glyphs.iter().map(|g| g.advance).sum() +} + +/// SVG 1.1 §10.9.1: `textLength` fits the characters to that advance, by spacing them out +/// (`lengthAdjust="spacing"`, the default) or by stretching them (`spacingAndGlyphs`). +/// https://www.w3.org/TR/SVG11/text.html#TextElementTextLengthAttribute +#[test] +fn text_length_fits_the_advance() { + let natural = advance(only_text(&open(r#"Hello World"#))); + for adjust in ["spacingAndGlyphs", "spacing"] { + for want in [50.0, 150.0, 300.0] { + let (d, w) = import_with_report(&svg(&format!( + r#"Hello World"# + ))) + .unwrap(); + assert!(w.is_empty(), "{w:?}"); + let t = only_text(&d); + assert_eq!(t.plain_text(), "Hello World"); + let got = advance(t); + assert!(close(got, want, 0.05), "{adjust} {want}: {got} (natural {natural})"); + let scaled = t.runs.iter().all(|r| close(r.style.h_scale, 100.0 * want / natural, 0.5)); + assert_eq!(scaled, adjust == "spacingAndGlyphs", "{adjust} {want}: {:?}", t.runs); + } + } + // On a tspan, only its characters are fitted; units and percentages of the viewport resolve. + let t = open(r#"Hi there!"#); + let t = only_text(&t); + let lay = layout(FontDb::global(), t); + let span: f64 = lay.glyphs.iter().filter(|g| (3..8).contains(&g.byte)).map(|g| g.advance).sum(); + assert!(close(span, 100.0, 0.05), "{span}"); + // A negative length is ignored. + let t = open(r#"Hello World"#); + assert!(close(advance(only_text(&t)), natural, 1e-6)); +} diff --git a/crates/svg/tests/it/prop_svg.rs b/crates/svg/tests/it/prop_svg.rs index a25aec175e..2dd7ceec13 100644 --- a/crates/svg/tests/it/prop_svg.rs +++ b/crates/svg/tests/it/prop_svg.rs @@ -82,6 +82,27 @@ proptest! { let _ = import(&format!("{s}")); } + /// Any `textLength` and `lengthAdjust`, on the text or a tspan (vertical too), imports to a + /// valid document without panicking. + #[test] + fn import_random_text_lengths( + len in "-?[0-9]{0,12}(\\.[0-9]{0,4})?(e[+-]?[0-9]{1,3})?(%|px|em|pt)?|[a-z ]{0,6}", + adjust in "spacing|spacingAndGlyphs|[a-zA-Z]{0,8}", + text in "[A-Za-z \u{5d0}-\u{5ea}]{0,12}", + on_span in any::(), + vertical in any::(), + ) { + let attrs = format!("textLength=\"{len}\" lengthAdjust=\"{adjust}\""); + let (outer, inner) = if on_span { ("", attrs.as_str()) } else { (attrs.as_str(), "") }; + let wm = if vertical { " writing-mode=\"tb\"" } else { "" }; + let svg = format!( + "a{text}b" + ); + if let Ok(doc) = import(&svg) { + check_document(&doc).map_err(TestCaseError::fail)?; + } + } + /// Importing random path data never panics and gives a valid document. #[test] fn import_random_path_data(d in "[MLCQZHVAmlcqzhva0-9 .,eE+-]{0,80}") { diff --git a/crates/text/src/fontdb/names.rs b/crates/text/src/fontdb/names.rs index b4eb8711b8..6ed1b44a2c 100644 --- a/crates/text/src/fontdb/names.rs +++ b/crates/text/src/fontdb/names.rs @@ -27,7 +27,7 @@ pub const THAI_FAMILIES: &[&str] = &[ ]; /// The families tried first for character `c`, in a script whose text only fonts made for it set -/// well (Thai, Lao, Khmer, Myanmar); none for other characters. +/// well (Thai, Lao, Khmer, Myanmar, Devanagari); none for other characters. pub(super) fn script_families(c: char) -> &'static [&'static str] { use unicode_script::{Script, UnicodeScript}; match c.script() { @@ -35,6 +35,15 @@ pub(super) fn script_families(c: char) -> &'static [&'static str] { Script::Lao => &["Lao UI", "Leelawadee UI", "Lao Sangam MN", "Noto Sans Lao", "Noto Sans Lao UI", "Phetsarath OT"], Script::Khmer => &["Khmer UI", "Khmer Sangam MN", "Noto Sans Khmer", "Noto Sans Khmer UI", "Khmer OS"], Script::Myanmar => &["Myanmar Text", "Myanmar Sangam MN", "Noto Sans Myanmar", "Noto Sans Myanmar UI", "Padauk"], + Script::Devanagari => &[ + "Nirmala UI", + "Kohinoor Devanagari", + "Devanagari Sangam MN", + "Noto Sans Devanagari", + "Noto Sans Devanagari UI", + "Lohit Devanagari", + "Mangal", + ], _ => &[], } } @@ -138,6 +147,14 @@ pub(super) fn norm(s: &str) -> String { mod tests { use super::*; + /// Devanagari takes a font made for it, not whichever face covering it loaded first. + #[test] + fn devanagari_prefers_fonts_made_for_it() { + assert_eq!(script_families('ह').first(), Some(&"Nirmala UI")); + assert!(script_families('ह').contains(&"Noto Sans Devanagari")); + assert!(script_families('a').is_empty()); + } + #[test] fn a_name_table_of_many_records_is_cut_short() { let many: Vec<(u16, &str)> = (0..2000).map(|_| (1, "Short")).collect(); diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index 16aa674ca6..bcf758706d 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -7,6 +7,11 @@ //! Preferences › Hyphenation › Exceptions (comma separated) override the points for named words: //! `typography` never breaks, `ty-pog-ra-phy` breaks only where the hyphens mark. See //! [`set_hyphenation_exceptions`]. +//! +//! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English is +//! the only language with break points so far: text in any other language, or in a language a +//! file names that isn't known, doesn't hyphenate, apart from the words in the Exceptions list +//! ([`language_has_patterns`]). use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -144,6 +149,12 @@ fn onset_pair(a: char, b: char) -> bool { ) } +/// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for +/// the default, English: USA) has break points of its own. +pub fn language_has_patterns(language: Option<&str>) -> bool { + language.is_none_or(|l| l.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("en")) && matches!(l.as_bytes().get(2), None | Some(b'-'))) +} + /// Allowed hyphenation points in `word`, as char indices (a hyphen goes *before* the char), with /// the default Hyphenation options. pub fn hyphen_points(word: &str) -> Vec { @@ -157,12 +168,21 @@ pub fn hyphen_points(word: &str) -> Vec { /// (other than a trailing apostrophe) are not hyphenated. Preferences exceptions override the /// pattern and these options for a matching word. pub fn hyphen_points_with(word: &str, opts: &HyphenationOptions) -> Vec { + hyphen_points_in(word, opts, true) +} + +/// [`hyphen_points_with`] for a word in a language with or without break points of its own +/// ([`language_has_patterns`]): without them, only a word in the Exceptions list breaks. +pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) -> Vec { if let Some(ex) = exception_for(word) { return match ex { Exception::Never => vec![], Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; } + if !patterns { + return vec![]; + } let c: Vec = word.chars().collect(); let n = c.len(); let longer_than = usize::try_from(opts.words_longer_than).unwrap_or(usize::MAX); @@ -235,6 +255,31 @@ mod tests { with_hyphenation_exceptions_for_test(source, f); } + /// #394: English in any region has break points; other languages, and a tag from a file that + /// isn't a known language, have none. + #[test] + fn only_english_has_break_points() { + for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] { + assert!(language_has_patterns(l), "{l:?}"); + } + for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { + assert!(!language_has_patterns(l), "{l:?}"); + } + } + + /// #394: a language without break points leaves words whole, but the Exceptions list is the + /// user's own and applies in every language. + #[test] + fn a_language_without_break_points_keeps_only_the_exceptions() { + let opts = HyphenationOptions::default(); + assert_eq!(hyphen_points_in("typography", &opts, true), vec![4, 7]); + assert!(hyphen_points_in("typography", &opts, false).is_empty()); + with_exceptions("ty-pog-ra-phy, happen", || { + assert_eq!(hyphen_points_in("typography", &opts, false), vec![2, 5, 7]); + assert!(hyphen_points_in("happen", &opts, false).is_empty()); + }); + } + /// #394 Preferences › Hyphenation › Exceptions contract (parse + override). #[test] fn hyphenation_exceptions_override_the_pattern() { diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index b814506e6d..50e1ce0b27 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -14,7 +14,7 @@ use vectorcraft_geom::{ArcPath, PathData}; use crate::GlyphBend; use crate::composer::{Breakpoint, Params, compose}; use crate::fontdb::FontDb; -use crate::hyphen::hyphen_points_with; +use crate::hyphen::hyphen_points_in; use crate::justify::{Flex, LineFit, apply_desired, fit_line, is_word_space}; use crate::kashida; use crate::shape::{ diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 54d8941e83..90d6555a00 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -1,7 +1,7 @@ use super::region::Region; use super::{ Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, LeadingModel, SGlyph, hyphen_glyph, - hyphen_points_with, no_line_end, no_line_start, soft_line_start, + hyphen_points_in, no_line_end, no_line_start, soft_line_start, }; /// Vertical metrics of a line: (ascent, descent, leading, cap height, x height). @@ -518,7 +518,8 @@ fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() { } } -/// Glyph indices inside `g[ws..we]` (a word) where a hyphenated break may go under `opts`. +/// Glyph indices inside `g[ws..we]` (a word) where a hyphenated break may go under `opts`, in the +/// language of the word's first letter. fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &HyphenationOptions) -> Vec { // Strip leading/trailing punctuation (quotes, commas). let (mut a, mut b) = (ws, we); @@ -542,7 +543,7 @@ fn hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyphenat starts.entry(g[k].byte).or_insert(k); } } - hyphen_points_with(word, opts).into_iter().filter_map(|ci| starts.get(offs.get(ci)?).copied()).collect() + hyphen_points_in(word, opts, g[a].hyphenates).into_iter().filter_map(|ci| starts.get(offs.get(ci)?).copied()).collect() } /// Break candidates for the every-line composer: hyphenation points under `hyphenate` (the diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 9f1a048b38..cdf5855390 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -39,6 +39,7 @@ fn synthetic_glyphs(specs: &[(usize, usize, f64, char)]) -> Vec { no_break: false, vertical_roman: false, cursive: false, + hyphenates: true, }) .collect() } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 6ecd515db3..f37c7443ec 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -80,6 +80,8 @@ pub(crate) struct SGlyph { /// decided for the whole segment it was shaped in ([`joins`]): on a curved path it is bent /// along the path so its joins meet. pub cursive: bool, + /// The glyph's language has hyphenation break points ([`crate::hyphen::language_has_patterns`]). + pub hyphenates: bool, } /// Does `script` join its letters (a cursive script, whose neighbouring glyphs touch)? @@ -947,6 +949,7 @@ fn inline_glyph( no_break: st.no_break, vertical_roman: false, cursive: false, + hyphenates: false, } } @@ -1327,6 +1330,7 @@ fn shape_segment(text: &str, context: &Range, seg: &Segment, feats: &OtFe no_break: gst.no_break, vertical_roman: gst.standard_vertical_roman, cursive, + hyphenates: crate::hyphen::language_has_patterns(gst.language.as_deref()), }); } } diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index f92ce67a6a..478bc9c97b 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1013,6 +1013,33 @@ fn hyphenation_rules() { } } +/// #394: each run hyphenates in its own language. English breaks words, a language without break +/// points doesn't, and text saved without a language breaks as it always did. +#[test] +fn each_run_hyphenates_in_its_own_language() { + let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; + let frame = Rect::new(0.0, 0.0, 120.0, 600.0); + let hyphens = |language: Option<&str>| { + let st = CharStyle { language: language.map(str::to_string), ..style(14.0) }; + let mut t = area(text, st, frame, Justify::Left); + t.para.hyphenate = true; + layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count() + }; + let saved_without_one = hyphens(None); + assert!(saved_without_one > 0, "some words hyphenated"); + assert_eq!(hyphens(Some("en-GB")), saved_without_one); + assert_eq!(hyphens(Some("de")), 0, "German has no break points yet"); + assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation"); + + // both in one paragraph: the English run breaks and the German one doesn't + let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left); + t.para.hyphenate = true; + edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into())); + let l = layout(db(), &t); + let at: Vec = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); + assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}"); +} + #[test] fn hyphenated_layout_adds_hyphens() { let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; diff --git a/crates/text/src/thread.rs b/crates/text/src/thread.rs index 27c6a2e70a..191963107d 100644 --- a/crates/text/src/thread.rs +++ b/crates/text/src/thread.rs @@ -20,21 +20,31 @@ pub fn story(frames: &[&TextObject]) -> Vec { /// paragraph shares that paragraph with the next frame (its first one): the earlier frame's style /// wins unless `later_wins[k]` says frame `k`'s first paragraph should (it was just restyled), or /// the earlier frame's part of the paragraph is empty (its slice ends with a paragraph break). +/// An empty frame that was just restyled keeps its style against unedited empty frames after it. pub fn story_paras(frames: &[&TextObject], later_wins: &[bool]) -> Vec { let mut out: Vec = vec![]; let mut prev_empty_tail = true; + let mut empty_tail_restyled = false; for (k, f) in frames.iter().enumerate() { + let text = f.plain_text(); + let restyled = later_wins.get(k).copied().unwrap_or(false); let mut styles = f.paragraph_styles().into_iter(); if k > 0 && let Some(first) = styles.next() - && (prev_empty_tail || later_wins.get(k).copied().unwrap_or(false)) + && (restyled || (prev_empty_tail && !(text.is_empty() && empty_tail_restyled))) && let Some(last) = out.last_mut() { *last = first; } out.extend(styles); - let text = f.plain_text(); - prev_empty_tail = text.is_empty() || text.ends_with('\n') || out.is_empty(); + // An empty frame has no paragraph boundary of its own. Keep the preceding frame's + // boundary state so another empty frame cannot replace a paragraph's edited style. + if !text.is_empty() { + prev_empty_tail = text.ends_with('\n') || out.is_empty(); + empty_tail_restyled = false; + } else if restyled { + empty_tail_restyled = true; + } } out } diff --git a/crates/text/src/thread/tests.rs b/crates/text/src/thread/tests.rs index cc07dcec1e..222df20c2a 100644 --- a/crates/text/src/thread/tests.rs +++ b/crates/text/src/thread/tests.rs @@ -144,6 +144,58 @@ fn paragraph_styles_flow_with_their_paragraphs() { assert_eq!(story_paras(&[&fa, &fb], &[false, false])[0].justify, Left); } +#[test] +fn empty_frames_do_not_replace_an_earlier_paragraph_style() { + let mut first = frame(0.0); + first.runs = vec![TextRun { text: "First".into(), style: CharStyle::default(), inline: None }]; + first.set_all_paras(ParaStyle { justify: Justify::Right, ..Default::default() }); + let middle = frame(200.0); + let last = frame(400.0); + assert_eq!(story_paras(&[&first, &middle, &last], &[true, false, false])[0].justify, Justify::Right); + + // An empty frame between two parts of the same paragraph changes no style either. + let mut last_with_text = last.clone(); + last_with_text.runs = vec![TextRun { text: "Tail".into(), style: CharStyle::default(), inline: None }]; + assert_eq!(story_paras(&[&first, &middle, &last_with_text], &[true, false, false])[0].justify, Justify::Right); + + let mut restyled_middle = middle.clone(); + restyled_middle.set_all_paras(ParaStyle { justify: Justify::Center, ..Default::default() }); + assert_eq!(story_paras(&[&first, &restyled_middle, &last], &[false, true, false])[0].justify, Justify::Center); +} + +/// When the earlier frame ends with a paragraph break, a restyled empty frame keeps its style +/// against an unedited empty frame after it. An unedited empty frame before it, a frame with +/// text after it, or a restyled frame after it still gives the paragraph its own style. +#[test] +fn a_restyled_empty_frame_keeps_its_style_after_a_paragraph_break() { + let style = |j| ParaStyle { justify: j, ..Default::default() }; + let mut first = frame(0.0); + first.runs = vec![TextRun { text: "First\n".into(), style: CharStyle::default(), inline: None }]; + first.set_all_paras(style(Justify::Right)); + let mut restyled = frame(200.0); + restyled.set_all_paras(style(Justify::Center)); + let empty = frame(400.0); + let tail_style = |frames: &[&TextObject], wins: &[bool]| story_paras(frames, wins).last().map(|p| p.justify); + + assert_eq!(tail_style(&[&first, &restyled, &empty], &[false, true, false]), Some(Justify::Center)); + assert_eq!(tail_style(&[&first, &restyled, &empty, &empty], &[false, true, false, false]), Some(Justify::Center)); + // An unedited empty frame before the restyled one gives way to it. + assert_eq!(tail_style(&[&first, &empty, &restyled, &empty], &[false, false, true, false]), Some(Justify::Center)); + // A restyled first frame of an empty thread keeps its style as well. + assert_eq!(tail_style(&[&restyled, &empty, &empty], &[true, false, false]), Some(Justify::Center)); + + // Without an edit, the last empty frame still gives the empty paragraph its style. + assert_eq!(tail_style(&[&first, &restyled, &empty], &[false, false, false]), Some(Justify::Left)); + // A later frame with text still gives the paragraph it holds its style. + let mut with_text = empty.clone(); + with_text.runs = vec![TextRun { text: "Tail".into(), style: CharStyle::default(), inline: None }]; + assert_eq!(tail_style(&[&first, &restyled, &with_text], &[false, true, false]), Some(Justify::Left)); + // A later restyled frame wins over the earlier one. + let mut right = empty.clone(); + right.set_all_paras(style(Justify::Right)); + assert_eq!(tail_style(&[&first, &restyled, &right], &[false, true, true]), Some(Justify::Right)); +} + /// Numbered list paragraphs count on from one frame to the next: the second frame's first /// whole paragraph takes the next number. A paragraph split between the frames has its number /// in the first frame only, and the paragraph after it takes the next number. diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index 42643538ed..e88721b04e 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -3,6 +3,8 @@ //! submenu selects them. Tool gestures emit engine commands. pub mod anchor_eraser; +pub mod box3d; +pub mod contour; pub mod corner_tool; pub mod enclosing_lasso; pub mod extend_path; @@ -28,14 +30,19 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ /// Smart Pen's tool, a flyout group of its own. pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; +pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; + pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; +pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; + /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso")]; +const HEADED: &[(&[ToolInfo], &str)] = + &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour"), (BOX_3D, "3D Box")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -54,6 +61,8 @@ pub fn create(id: &str) -> Option> { slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()), smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()), enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), + contour::ID => Box::new(contour::ContourTool::default()), + box3d::ID => Box::new(box3d::Box3dTool::default()), _ => return None, }) } @@ -74,6 +83,8 @@ mod tests { assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); + assert_eq!(heading(contour::ID), Some("Contour")); + assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(GROUPS.len(), HEADED.len()); assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID)); assert!(create("pen").is_none() && heading("pen").is_none()); diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs new file mode 100644 index 0000000000..b0ecdc350e --- /dev/null +++ b/crates/tools/src/addons/box3d.rs @@ -0,0 +1,732 @@ +//! 3D Box tool (`box3d`) and customizable shape state (`vc-shape-tools`), a built-in add-on. +//! +//! Dragging with the 3D Box tool draws a rotatable 3D box (`addon.shapes.box3d`) whose X, Y and Z +//! rotation angles and parallel/perspective projection flags are configurable in the Control bar +//! (`addon.shapes.configure` and `tool.setOption`). Extended parameters for rectangles, ellipses, +//! polygons, stars, spirals and 3D boxes are stored in the object's `vc-shape-tools` attribute +//! entry (left out of SVG export) while keeping standard `LiveShape` variants synced. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, Node, NodeKind}; +use vectorcraft_geom::corners::cut_corners; +use vectorcraft_geom::shapes::{self, CornerKind, EllipseMode}; +use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; + +use crate::guides::{DrawSnap, Leave}; +use crate::shape::{box_params, space_moves, turned_box}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The 3D Box tool's id. +pub const ID: &str = "box3d"; + +/// Object data entry (`Node::extras`) that stores extended customizable shape parameters. +/// The `vc-` prefix marks it as internal so SVG export omits it from `data-*` attributes. +pub const KEY: &str = "vc-shape-tools"; + +/// Maximum stored JSON length read back from a file. +const MAX_STORED: usize = 4096; + +fn whole_mode() -> EllipseMode { + EllipseMode::Whole +} + +fn default_pie() -> (f64, f64) { + (0.0, 360.0) +} + +/// Parse an [`EllipseMode`] from a command or tool option string (`"slice"`/`"pie"`, `"arc"`/`"open"`, +/// `"chord"`, `"whole"`/`"full"`/`"closed"`). +pub fn parse_arc_mode(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "slice" | "pie" => Some(EllipseMode::Slice), + "arc" | "open" => Some(EllipseMode::Arc), + "chord" => Some(EllipseMode::Chord), + "whole" | "full" | "closed" => Some(EllipseMode::Whole), + _ => None, + } +} + +/// Canonical string name for an [`EllipseMode`]. +pub fn arc_mode_str(m: EllipseMode) -> &'static str { + match m { + EllipseMode::Slice => "slice", + EllipseMode::Arc => "arc", + EllipseMode::Chord => "chord", + EllipseMode::Whole => "whole", + } +} + +/// Customizable shape state for rectangles, ellipses, polygons, stars, spirals and 3D boxes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape", rename_all = "camelCase")] +pub enum CustomShape { + Rectangle { + w: f64, + h: f64, + radii: [f64; 4], + #[serde(default)] + kinds: [CornerKind; 4], + #[serde(default)] + radii_relative: bool, + xf: Affine, + #[serde(default = "default_pie")] + pie: (f64, f64), + #[serde(default = "whole_mode")] + arc_mode: EllipseMode, + }, + Ellipse { + w: f64, + h: f64, + #[serde(default = "default_pie")] + pie: (f64, f64), + #[serde(default)] + arc_mode: EllipseMode, + xf: Affine, + }, + Polygon { + radius: f64, + sides: u32, + xf: Affine, + #[serde(default)] + radii: Vec, + #[serde(default)] + kinds: Vec, + #[serde(default)] + radii_relative: bool, + #[serde(default)] + spoke_ratio: Option, + #[serde(default)] + rounded: f64, + #[serde(default)] + randomized: f64, + #[serde(default = "default_pie")] + pie: (f64, f64), + #[serde(default = "whole_mode")] + arc_mode: EllipseMode, + }, + Spiral { + center: Point, + radius: f64, + turns: f64, + divergence: f64, + inner_radius: f64, + clockwise: bool, + }, + Box3d { + w: f64, + h: f64, + angle_x: f64, + angle_y: f64, + angle_z: f64, + parallel_x: bool, + parallel_y: bool, + parallel_z: bool, + xf: Affine, + }, +} + +impl CustomShape { + /// Regenerate the path for this customizable shape. + pub fn to_path(&self) -> PathData { + match self { + CustomShape::Rectangle { w, h, radii, kinds, radii_relative, xf, pie, arc_mode } => { + let base = shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = vectorcraft_doc::corners::resolve_stored_radii(&base, radii, *radii_relative); + let r = std::array::from_fn(|i| resolved.get(i).copied().unwrap_or(0.0)); + let rect_path = shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), r, *kinds); + let cut = shapes::apply_shape_arc(rect_path, Point::new(*w / 2.0, *h / 2.0), pie.0, pie.1, *arc_mode); + cut.transformed(*xf) + } + CustomShape::Ellipse { w, h, pie, arc_mode, xf } => { + shapes::ellipse_arc(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1, *arc_mode).transformed(*xf) + } + CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode } => { + let raw = match spoke_ratio { + Some(ratio) => { + let r2 = (*radius * ratio.clamp(0.01, 1.0)).max(0.01); + shapes::star_configured(Point::ZERO, *radius, r2, *sides, 0.0, *rounded, *randomized) + } + None => shapes::polygon_configured(Point::ZERO, *radius, *sides, 0.0, *rounded, *randomized), + }; + let outline = raw.transformed(*xf); + let cornered = if rounded.abs() < 1e-9 && !radii.is_empty() { + let resolved = vectorcraft_doc::corners::resolve_stored_radii(&outline, radii, *radii_relative); + cut_corners(&outline, &resolved, kinds).0 + } else { + outline + }; + let center = *xf * Point::ZERO; + shapes::apply_shape_arc(cornered, center, pie.0, pie.1, *arc_mode) + } + CustomShape::Spiral { center, radius, turns, divergence, inner_radius, clockwise } => { + shapes::spiral_configured(*center, *radius, *turns, *divergence, *inner_radius, *clockwise) + } + CustomShape::Box3d { w, h, angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, xf } => { + shapes::box3d(Rect::new(0.0, 0.0, *w, *h), *angle_x, *angle_y, *angle_z, *parallel_x, *parallel_y, *parallel_z).transformed(*xf) + } + } + } + + /// Standard [`LiveShape`] representation when the shape is in a state that `LiveShape` natively + /// models (so Live Corners and Pie widgets work on it directly). + pub fn to_live_shape(&self) -> Option { + match self { + CustomShape::Rectangle { w, h, radii, kinds, radii_relative, xf, arc_mode, .. } if *arc_mode == EllipseMode::Whole => { + Some(LiveShape::Rectangle { w: *w, h: *h, radii: *radii, kinds: *kinds, radii_relative: *radii_relative, xf: *xf }) + } + CustomShape::Ellipse { w, h, pie, arc_mode, xf } if matches!(arc_mode, EllipseMode::Whole | EllipseMode::Slice) => { + let p = if *arc_mode == EllipseMode::Whole { (0.0, 360.0) } else { *pie }; + Some(LiveShape::Ellipse { w: *w, h: *h, pie: p, xf: *xf }) + } + CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, arc_mode, .. } + if spoke_ratio.is_none() && rounded.abs() < 1e-9 && randomized.abs() < 1e-9 && *arc_mode == EllipseMode::Whole => + { + Some(LiveShape::Polygon { + radius: *radius, + sides: *sides, + xf: *xf, + radii: radii.clone(), + kinds: kinds.clone(), + radii_relative: *radii_relative, + }) + } + _ => None, + } + } + + /// Whether this shape uses extended add-on parameters beyond what `LiveShape` stores on its own. + pub fn needs_extra_storage(&self) -> bool { + self.to_live_shape().is_none() + } + + /// Write this shape's regenerated path, `LiveShape` (if standard) and `vc-shape-tools` attribute + /// entry onto path node `n`. + pub fn write_to_node(&self, n: &mut Node) { + let new_path = self.to_path(); + let new_live = self.to_live_shape().map(Box::new); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = new_path; + *live = new_live; + } + if self.needs_extra_storage() { + if let Ok(entry) = serde_json::to_string(self) { + n.edit_attrs(|a| match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = entry, + None => a.data.push((KEY.into(), entry)), + }); + } + } else { + n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY)); + } + } + + /// Read a [`CustomShape`] from `n`: either from its `vc-shape-tools` attribute entry (synced with + /// `LiveShape` if both exist), from its `LiveShape`, or by detecting a star path. + pub fn read(n: &Node) -> Option { + let NodeKind::Path { path, live, guide: false, .. } = &n.kind else { return None }; + let stored = n + .extras() + .attrs + .as_deref() + .and_then(|a| a.data.iter().find(|(k, _)| k == KEY)) + .filter(|(_, text)| text.len() <= MAX_STORED) + .and_then(|(_, text)| serde_json::from_str::(text).ok()); + match (stored, live.as_deref()) { + (Some(s), None) => Some(s), + (stored_opt, Some(l)) => Self::from_live_shape(l, stored_opt), + (None, None) => Self::detect_star_from_path(path), + } + } + + /// Read a [`CustomShape`] from `n`, or upgrade an open spiral path when spiral parameters are + /// being configured. + pub fn read_for_update(n: &Node, spiral_hint: bool) -> Option { + if let Some(cs) = Self::read(n) { + return Some(cs); + } + if spiral_hint + && let NodeKind::Path { path, live: None, guide: false, .. } = &n.kind + && let Some(sp) = path.subpaths.first() + && !sp.closed + && sp.anchors.len() >= 3 + && let Some(last) = sp.anchors.last() + && let Some(first) = sp.anchors.first() + { + let center = last.p; + let radius = first.p.distance(center).max(1.0); + return Some(CustomShape::Spiral { + center, + radius, + turns: ((sp.anchors.len().saturating_sub(1)) as f64 / 4.0).max(0.25), + divergence: 1.0, + inner_radius: 0.0, + clockwise: true, + }); + } + None + } + + fn from_live_shape(l: &LiveShape, stored: Option) -> Option { + match l.folded() { + LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } => { + let (pie, arc_mode) = match stored { + Some(CustomShape::Rectangle { pie, arc_mode, .. }) => (pie, arc_mode), + _ => ((0.0, 360.0), EllipseMode::Whole), + }; + Some(CustomShape::Rectangle { w, h, radii, kinds, radii_relative, xf, pie, arc_mode }) + } + LiveShape::Ellipse { w, h, pie, xf } => { + let span = (pie.1 - pie.0).rem_euclid(360.0); + let default_mode = if span < 1e-9 || 360.0 - span < 1e-9 { EllipseMode::Whole } else { EllipseMode::Slice }; + let arc_mode = match stored { + Some(CustomShape::Ellipse { arc_mode, .. }) if default_mode != EllipseMode::Slice => arc_mode, + _ => default_mode, + }; + Some(CustomShape::Ellipse { w, h, pie, arc_mode, xf }) + } + LiveShape::Polygon { radius, sides, xf, radii, kinds, radii_relative } => { + let (spoke_ratio, rounded, randomized, pie, arc_mode) = match stored { + Some(CustomShape::Polygon { spoke_ratio, rounded, randomized, pie, arc_mode, .. }) => { + (spoke_ratio, rounded, randomized, pie, arc_mode) + } + _ => (None, 0.0, 0.0, (0.0, 360.0), EllipseMode::Whole), + }; + Some(CustomShape::Polygon { radius, sides, xf, radii, kinds, radii_relative, spoke_ratio, rounded, randomized, pie, arc_mode }) + } + LiveShape::Line { .. } | LiveShape::Path { .. } => stored, + } + } + + /// Detect a regular star path (even vertex count ≥ 6 with alternating outer/inner radii around + /// its centroid) so plain stars created by `shape.star` can be customized live. + pub fn detect_star_from_path(path: &PathData) -> Option { + let sp = path.subpaths.first()?; + let n = sp.anchors.len(); + if path.subpaths.len() != 1 || !sp.closed || n < 6 || !n.is_multiple_of(2) { + return None; + } + let mut cx = 0.0; + let mut cy = 0.0; + for a in &sp.anchors { + cx += a.p.x; + cy += a.p.y; + } + let center = Point::new(cx / (n as f64), cy / (n as f64)); + let r0 = sp.anchors.first()?.p.distance(center); + let r1 = sp.anchors.get(1)?.p.distance(center); + let (r_outer, r_inner) = if r0 >= r1 { (r0, r1) } else { (r1, r0) }; + if r_outer <= 1e-3 || (r_outer - r_inner).abs() <= 1e-3 * r_outer { + return None; + } + for (i, a) in sp.anchors.iter().enumerate() { + let d = a.p.distance(center); + let target = if i % 2 == 0 { r0 } else { r1 }; + if (d - target).abs() > 0.15 * r_outer { + return None; + } + } + let ratio = (r_inner / r_outer).clamp(0.01, 1.0); + let first = sp.anchors.first()?.p - center; + let rot = first.y.atan2(first.x) + std::f64::consts::FRAC_PI_2; + Some(CustomShape::Polygon { + radius: r_outer, + sides: (n / 2) as u32, + xf: Affine::translate((center.x, center.y)) * Affine::rotate(rot), + radii: vec![], + kinds: vec![], + radii_relative: false, + spoke_ratio: Some(ratio), + rounded: 0.0, + randomized: 0.0, + pie: (0.0, 360.0), + arc_mode: EllipseMode::Whole, + }) + } +} + +/// The customizable shapes & rotatable 3D Box add-on tool (`box3d`). +pub struct Box3dTool { + start: Option, + last: Point, + mods: Mods, + began: bool, + pub shape: &'static str, + pub corner_radius: f64, + pub corner_radii: [f64; 4], + pub corner_symmetry: bool, + pub arc_start: f64, + pub arc_end: f64, + pub arc_mode: &'static str, + pub sides: u32, + pub points: u32, + pub poly_is_star: bool, + pub star_ratio: f64, + pub rounded: f64, + pub randomized: f64, + pub turns: f64, + pub divergence: f64, + pub inner_radius: f64, + pub clockwise: bool, + pub angle_x: f64, + pub angle_y: f64, + pub angle_z: f64, + pub parallel_x: bool, + pub parallel_y: bool, + pub parallel_z: bool, + snap: DrawSnap, +} + +impl Default for Box3dTool { + fn default() -> Self { + Self { + start: None, + last: Point::ZERO, + mods: Mods::default(), + began: false, + shape: "box3d", + corner_radius: 12.0, + corner_radii: [12.0; 4], + corner_symmetry: true, + arc_start: 0.0, + arc_end: 0.0, + arc_mode: "whole", + sides: 6, + points: 5, + poly_is_star: false, + star_ratio: 0.5, + rounded: 0.0, + randomized: 0.0, + turns: 3.0, + divergence: 1.0, + inner_radius: 0.0, + clockwise: true, + angle_x: 30.0, + angle_y: 35.0, + angle_z: 0.0, + parallel_x: true, + parallel_y: true, + parallel_z: true, + snap: DrawSnap::default(), + } + } +} + +impl Box3dTool { + pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) { + let mut out = match self.shape { + "rectangle" => { + let mut v = box_params(start, p, m, base); + if self.corner_symmetry { + v["radius"] = json!(self.corner_radius); + } else { + v["radii"] = json!(self.corner_radii); + } + ("addon.shapes.rectangle".into(), v) + } + "ellipse" => { + let v = box_params(start, p, m, base); + ("addon.shapes.ellipse".into(), v) + } + "polygon" | "star" => { + let d = p - start; + let r = d.hypot().max(0.01); + let rot = if m.shift { vectorcraft_geom::constrain_rotation(base).unwrap_or(0.0) } else { (d.atan2().to_degrees() + 90.0) % 360.0 }; + let is_star = self.shape == "star" || self.poly_is_star; + let count = if is_star { self.points } else { self.sides }; + let mut v = if is_star { + json!({ + "cx": start.x, + "cy": start.y, + "radius1": r, + "radius2": r * self.star_ratio, + "points": count, + "rotation": rot, + }) + } else { + json!({ + "cx": start.x, + "cy": start.y, + "radius": r, + "sides": count, + "rotation": rot, + }) + }; + if self.rounded.abs() > 1e-6 { + v["rounded"] = json!(self.rounded); + } + if self.randomized.abs() > 1e-6 { + v["randomized"] = json!(self.randomized); + } + (if is_star { "addon.shapes.star" } else { "addon.shapes.polygon" }.into(), v) + } + "spiral" => { + let r = p.distance(start).max(0.01); + ( + "addon.shapes.spiral".into(), + json!({ + "cx": start.x, + "cy": start.y, + "radius": r, + "turns": self.turns, + "divergence": self.divergence, + "innerRadius": self.inner_radius, + "clockwise": self.clockwise, + }), + ) + } + _ => { + let mut v = box_params(start, p, m, base); + v["angleX"] = json!(self.angle_x); + v["angleY"] = json!(self.angle_y); + v["angleZ"] = json!(self.angle_z); + v["parallelX"] = json!(self.parallel_x); + v["parallelY"] = json!(self.parallel_y); + v["parallelZ"] = json!(self.parallel_z); + return ("addon.shapes.box3d".into(), v); + } + }; + if matches!(self.shape, "rectangle" | "ellipse" | "polygon" | "star") { + let span = (self.arc_end - self.arc_start).rem_euclid(360.0); + if self.arc_mode != "whole" || (span > 1e-4 && (span - 360.0).abs() > 1e-4) { + out.1["startAngle"] = json!(self.arc_start); + out.1["endAngle"] = json!(self.arc_end); + out.1["arcMode"] = json!(self.arc_mode); + } + } + out + } + + fn undo_label(&self) -> &'static str { + match self.shape { + "rectangle" => "Rounded Rectangle", + "ellipse" => "Ellipse", + "polygon" => "Polygon", + "star" => "Star", + "spiral" => "Spiral", + _ => "3D Box", + } + } +} + +impl Tool for Box3dTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.start.is_some() + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Move => { + self.snap.hover(cx, ev.pos, &[], None); + vec![] + } + PointerKind::Down => { + let p = self.snap.press(cx, ev.pos, &[], None); + self.start = Some(p); + self.last = ev.pos; + self.began = false; + vec![] + } + PointerKind::Drag => { + let Some(mut s) = self.start else { return vec![] }; + let radial = matches!(self.shape, "polygon" | "star" | "spiral"); + let leave = (!radial).then(|| Leave::diagonal(s, ev.mods.shift && vectorcraft_geom::constrain_axes(cx.constrain_angle).is_none())); + let pos = self.snap.drag(cx, ev.pos, leave.as_ref()); + let ev = &PointerEvent { pos, ..*ev }; + space_moves(&mut s, &mut self.last, ev, self.began); + self.start = Some(s); + self.mods = ev.mods; + let mut out = vec![]; + if !self.began { + if ev.pos.distance(s) < cx.tol(2.0) { + return out; + } + self.began = true; + out.push(Action::Begin(self.undo_label().into())); + } + let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); + out.push(Action::Preview(c, v)); + out + } + PointerKind::Up => { + let Some(s) = self.start.take() else { return vec![] }; + self.snap.clear(); + if self.began { + self.began = false; + vec![Action::Commit] + } else { + let (c, v) = self.command_at(s, s + Vec2::new(100.0, 100.0), ev.mods, cx.constrain_angle); + vec![Action::Begin(self.undo_label().into()), Action::Preview(c, v), Action::Commit] + } + } + _ => vec![], + } + } + + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + let Some(s) = self.start.filter(|_| self.began) else { return vec![] }; + let changed = match (self.shape, key) { + ("polygon", ToolKey::Up) => { + self.sides = (self.sides + 1).min(1000); + true + } + ("polygon", ToolKey::Down) => { + self.sides = self.sides.saturating_sub(1).max(3); + true + } + ("star", ToolKey::Up) => { + self.points = (self.points + 1).min(1000); + true + } + ("star", ToolKey::Down) => { + self.points = self.points.saturating_sub(1).max(3); + true + } + (_, ToolKey::Up) => { + self.angle_x = (self.angle_x + 5.0).clamp(-180.0, 180.0); + true + } + (_, ToolKey::Down) => { + self.angle_x = (self.angle_x - 5.0).clamp(-180.0, 180.0); + true + } + (_, ToolKey::Right) => { + self.angle_y = (self.angle_y + 5.0).clamp(-180.0, 180.0); + true + } + (_, ToolKey::Left) => { + self.angle_y = (self.angle_y - 5.0).clamp(-180.0, 180.0); + true + } + _ => false, + }; + if changed { + let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle); + vec![Action::Preview(c, v)] + } else if key == ToolKey::Escape { + self.start = None; + self.began = false; + self.snap.clear(); + vec![Action::Cancel] + } else { + vec![] + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { + let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); + let (r, _) = turned_box(s, self.last, self.mods, cx.constrain_angle); + o.push(Overlay::Measure { p, text: cx.size_label(r.width(), r.height()) }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ + "shape": self.shape, + "cornerRadius": self.corner_radius, + "cornerRadii": self.corner_radii, + "cornerSymmetry": self.corner_symmetry, + "arcStart": self.arc_start, + "arcEnd": self.arc_end, + "arcMode": self.arc_mode, + "sides": self.sides, + "points": self.points, + "polyIsStar": self.poly_is_star, + "starRatio": self.star_ratio, + "rounded": self.rounded, + "randomized": self.randomized, + "turns": self.turns, + "divergence": self.divergence, + "innerRadius": self.inner_radius, + "clockwise": self.clockwise, + "angleX": self.angle_x, + "angleY": self.angle_y, + "angleZ": self.angle_z, + "parallelX": self.parallel_x, + "parallelY": self.parallel_y, + "parallelZ": self.parallel_z, + }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + let finite = v.as_f64().filter(|n| n.is_finite()); + match key { + "shape" => { + if let Some(s) = v.as_str() { + self.shape = match s { + "rectangle" => "rectangle", + "ellipse" => "ellipse", + "polygon" => "polygon", + "star" => "star", + "spiral" => "spiral", + _ => "box3d", + }; + } + } + "cornerRadius" => { + self.corner_radius = finite.unwrap_or(self.corner_radius).clamp(0.0, crate::shape::MAX_CORNER_RADIUS); + if self.corner_symmetry { + self.corner_radii = [self.corner_radius; 4]; + } + } + "cornerSymmetry" => { + self.corner_symmetry = v.as_bool().unwrap_or(self.corner_symmetry); + if self.corner_symmetry { + self.corner_radii = [self.corner_radius; 4]; + } + } + "cornerRadii" => { + if let Some(arr) = v.as_array() + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + if let Some(r) = item.as_f64().filter(|n| n.is_finite()) { + self.corner_radii[i] = r.clamp(0.0, crate::shape::MAX_CORNER_RADIUS); + } + } + self.corner_radius = self.corner_radii[0]; + } + } + "arcStart" => self.arc_start = finite.map_or(self.arc_start, |n| n.rem_euclid(360.0)), + "arcEnd" => self.arc_end = finite.map_or(self.arc_end, |n| n.rem_euclid(360.0)), + "arcMode" => { + if let Some(s) = v.as_str() { + self.arc_mode = match s { + "pie" => "pie", + "chord" => "chord", + "arc" => "arc", + _ => "whole", + }; + } + } + "sides" => self.sides = v.as_u64().unwrap_or(6).clamp(3, 1000) as u32, + "points" => self.points = v.as_u64().unwrap_or(5).clamp(3, 1000) as u32, + "polyIsStar" => self.poly_is_star = v.as_bool().unwrap_or(self.poly_is_star), + "starRatio" => self.star_ratio = finite.unwrap_or(self.star_ratio).clamp(0.01, 1.0), + "rounded" => self.rounded = finite.unwrap_or(self.rounded).clamp(-10.0, 10.0), + "randomized" => self.randomized = finite.unwrap_or(self.randomized).clamp(-10.0, 10.0), + "turns" => self.turns = finite.unwrap_or(self.turns).clamp(0.01, 1024.0), + "divergence" => self.divergence = finite.unwrap_or(self.divergence).clamp(0.0, 1000.0), + "innerRadius" => self.inner_radius = finite.unwrap_or(self.inner_radius).clamp(0.0, 0.999), + "clockwise" => self.clockwise = v.as_bool().unwrap_or(self.clockwise), + "angleX" => self.angle_x = finite.unwrap_or(self.angle_x).clamp(-180.0, 180.0), + "angleY" => self.angle_y = finite.unwrap_or(self.angle_y).clamp(-180.0, 180.0), + "angleZ" => self.angle_z = finite.unwrap_or(self.angle_z).clamp(-180.0, 180.0), + "parallelX" => self.parallel_x = v.as_bool().unwrap_or(self.parallel_x), + "parallelY" => self.parallel_y = v.as_bool().unwrap_or(self.parallel_y), + "parallelZ" => self.parallel_z = v.as_bool().unwrap_or(self.parallel_z), + _ => {} + } + } +} diff --git a/crates/tools/src/addons/contour.rs b/crates/tools/src/addons/contour.rs new file mode 100644 index 0000000000..e77bb29eed --- /dev/null +++ b/crates/tools/src/addons/contour.rs @@ -0,0 +1,254 @@ +//! The Contour tool: drag away from a selected shape's edge to grow a live copy of it, or toward the +//! inside to shrink it (`addon.contour.set`). The copy is the original's outline offset by the distance +//! the pointer has moved from the edge, previewed while the button is down and kept as one undo step +//! on release. Nothing is baked: the copy carries a live Offset Path effect, so it keeps being +//! editable (a second drag on a selected Contour changes its distance instead of nesting another), +//! and Expand Appearance bakes it. While a Contour is selected the tool draws the outline the +//! shape had before as a dashed guide. +//! +//! The distance is how far the pointer has moved from the shape's edge since the press, so a press +//! anywhere changes nothing until the pointer moves, and a Contour that already stands at some +//! distance continues from there. Shift rounds the distance to whole points. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::{BezPath, FillRule, Point, hit}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "contour"; + +/// The live effect a Contour is made of (the one `addon.contour.set` applies). +const EFFECT: &str = "path.offsetPath"; +/// The largest distance, in points, `addon.contour.set` accepts. +const MAX_OFFSET: f64 = 1e5; +/// The guide showing the shape a Contour was made from. +const GUIDE: [u8; 3] = [0x1e, 0x88, 0xe5]; + +/// A selected shape's outline, in the document. +struct Base { + path: BezPath, + rule: FillRule, +} + +fn base_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, rule, .. } => Some(Base { path: path.to_bezpath(), rule: *rule }), + NodeKind::Compound { children, rule } => { + let mut path = BezPath::new(); + for c in children { + if let Some(p) = c.path_data() { + path.extend(p.to_bezpath().elements().iter().copied()); + } + } + Some(Base { path, rule: *rule }) + } + _ => None, + } +} + +/// The Offset Path distance of a Contour (a shape that carries the effect). +fn contour_offset(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + Some(e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0)) +} + +/// The corner style and miter limit of a Contour's Offset Path effect, as `addon.contour.set` takes +/// them. +fn contour_style(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + let corners = match e.params.get("joins").and_then(Value::as_str) { + Some("round") => "round", + Some("bevel") => "square", + _ => "sharp", + }; + let mut style = json!({ "corners": corners }); + if let Some(m) = e.params.get("miterLimit").and_then(Value::as_f64) { + style["miterLimit"] = json!(m); + } + Some(style) +} + +/// How far `p` is from the nearest of `bases`' edges: positive outside, negative inside. +fn signed_distance(bases: &[Base], p: Point) -> Option { + let mut nearest = f64::INFINITY; + let mut inside = false; + for b in bases { + nearest = nearest.min(hit::distance_to_outline(&b.path, p)); + inside |= hit::fill_contains(&b.path, b.rule, p); + } + nearest.is_finite().then_some(if inside { -nearest } else { nearest }) +} + +/// A press in progress. +struct Drag { + bases: Vec, + /// Where the pointer stood against the edge at the press. + pressed_at: f64, + /// The Contour's distance at the press (0 for a shape that is not one yet). + start: f64, + /// The corner style and miter limit every preview carries: the pressed Contour's own, else the + /// tool's options. + style: Value, + /// The distance last previewed. + last: Option, + /// Where the pointer is, for the distance label. + pos: Point, +} + +#[derive(Default)] +pub struct ContourTool { + drag: Option, + corners: Corners, + miter_limit: Option, +} + +/// How a Contour treats the corners of the shape. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Corners { + /// Pointed (mitered) corners. + #[default] + Sharp, + Round, + /// Corners cut off flat. + Square, +} + +impl Corners { + fn id(self) -> &'static str { + match self { + Corners::Sharp => "sharp", + Corners::Round => "round", + Corners::Square => "square", + } + } + + fn parse(s: &str) -> Option { + [Corners::Sharp, Corners::Round, Corners::Square].into_iter().find(|c| c.id().eq_ignore_ascii_case(s)) + } +} + +impl ContourTool { + /// The corner style and miter limit of a new Contour: the tool's options. + fn style(&self) -> Value { + let mut p = json!({ "corners": self.corners.id() }); + if let Some(m) = self.miter_limit { + p["miterLimit"] = json!(m); + } + p + } +} + +/// The selected shapes a Contour can be made of. +fn selected_shapes<'a>(cx: &'a ToolContext) -> Vec<&'a Node> { + cx.selection + .objects + .iter() + .filter_map(|id| cx.doc.node(*id)) + .filter(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })) + .collect() +} + +fn round_distance(v: f64, mods: Mods) -> f64 { + let v = if mods.shift { v.round() } else { (v * 100.0).round() / 100.0 }; + v.clamp(-MAX_OFFSET, MAX_OFFSET) +} + +impl Tool for ContourTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + match ev.kind { + PointerKind::Down => { + let shapes = selected_shapes(cx); + let start = shapes.first().and_then(|n| contour_offset(n)).unwrap_or(0.0); + // A Contour keeps its own corners; a new one takes the tool's. + let style = shapes.first().and_then(|n| contour_style(n)).unwrap_or_else(|| self.style()); + let bases: Vec = shapes.into_iter().filter_map(base_of).collect(); + let Some(pressed_at) = signed_distance(&bases, ev.pos) else { return vec![] }; + self.drag = Some(Drag { bases, pressed_at, start, style, last: None, pos: ev.pos }); + vec![Action::Begin("Contour".into())] + } + PointerKind::Drag => { + let Some(drag) = self.drag.as_mut() else { return vec![] }; + drag.pos = ev.pos; + let Some(now) = signed_distance(&drag.bases, ev.pos) else { return vec![] }; + let offset = round_distance(drag.start + now - drag.pressed_at, ev.mods); + // Nothing is previewed until the distance has left where it started: a drag along + // the edge (or one Shift rounds back) would otherwise leave an unchanged copy. + if !offset.is_finite() || drag.last == Some(offset) || (drag.last.is_none() && offset == drag.start) { + return vec![]; + } + drag.last = Some(offset); + let mut params = drag.style.clone(); + params["offset"] = json!(offset); + vec![Action::Preview("addon.contour.set".into(), params)] + } + PointerKind::Up => match self.drag.take() { + Some(d) if d.last.is_some() => vec![Action::Commit], + Some(_) => vec![Action::Cancel], + None => vec![], + }, + _ => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape if self.drag.take().is_some() => vec![Action::Cancel], + _ => vec![], + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + // The outline each selected Contour was made from. + for n in selected_shapes(cx) { + if contour_offset(n).is_none() { + continue; + } + if let Some(b) = base_of(n) { + // A white halo under the dashes, so the guide shows over any fill. + out.push(Overlay::Path { path: b.path.clone(), color: [255, 255, 255], width: 3.0, dashed: false }); + out.push(Overlay::Path { path: b.path, color: GUIDE, width: 1.0, dashed: true }); + } + } + if let Some(d) = &self.drag + && let Some(offset) = d.last + { + out.push(Overlay::Measure { p: d.pos, text: format!("{offset:+.2} pt") }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({"corners": self.corners.id(), "miterLimit": self.miter_limit.unwrap_or(4.0)}) + } + + fn set_option(&mut self, key: &str, value: &Value) { + match key { + "corners" => { + if let Some(c) = value.as_str().and_then(Corners::parse) { + self.corners = c; + } + } + "miterLimit" => { + if let Some(m) = value.as_f64().filter(|m| m.is_finite()) { + self.miter_limit = Some(m.clamp(1.0, 500.0)); + } + } + _ => {} + } + } + + fn busy(&self) -> bool { + self.drag.is_some() + } +} diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index ddcbcb310e..b1ccfa949d 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -81,8 +81,9 @@ impl BuilderMap { }) .collect() }; - // A line keeps its pieces under the outline of a closed path in front of it, so a merge - // or an erase removes them as it does the rest of the line. + // A line keeps its pieces under the outline of a closed path or along a line in front of + // it, so a merge or an erase removes them as it does the rest of the line. The pieces in + // front come first, so a hit where pieces lie on each other takes the one in front. let lines = arr.lines.into_iter().chain(arr.lines_under).collect(); Self { shapes, regions: faces_of(arr.regions), lines: bounded(lines), edges: bounded(arr.edges) } } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 2104609cf7..fc3ed294c3 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -363,6 +363,30 @@ fn shape_builder_keeps_a_line_under_an_edge_in_front_and_alt_click_there_takes_t assert!(matches!(map.hit(Point::new(150.0, 51.0), Some(4.0)), Some(Hit::Line(_)))); } +#[test] +fn shape_builder_alt_click_on_coincident_lines_takes_the_front_one() { + // Two lines from (0, 50) to (200, 50), crossed by a line at x = 100: each keeps its own + // pieces, and a hit where they lie on each other takes the piece of the line in front. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mut s = Selection::default(); + let line = |a: (f64, f64), b: (f64, f64)| PathData::new(vec![SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)]); + let paths = [line((0.0, 50.0), (200.0, 50.0)), line((0.0, 50.0), (200.0, 50.0)), line((100.0, 0.0), (100.0, 100.0))]; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, Node::path(id, path, Appearance::default_art())).unwrap(); + s.add(id); + } + let map = map_of(&d, &s); + for key in [0, 1] { + assert_eq!(map.lines.iter().filter(|(piece, _)| piece.key == key).count(), 2, "line {key}: {:?}", map.lines); + } + for x in [50.0, 150.0] { + let Some(Hit::Line(i)) = map.hit(Point::new(x, 51.0), Some(4.0)) else { panic!("no line hit at {x}") }; + assert_eq!(map.lines.get(i).map(|(piece, _)| piece.key), Some(1), "at {x}"); + } +} + #[test] fn shape_builder_erase_drag_across_an_overlap_narrower_than_twice_the_tolerance_touches_it() { let (d, s) = sliver_rects(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index ffb3a6560b..d7bd9c4950 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -25,8 +25,9 @@ //! Both pick the key objects of a blend, and click or drag ruler guides ([`crate::rulerguide`]). //! A Cmd/Ctrl+Shift double-click with either one releases the ruler guide or guide path under the //! pointer ([`release_guide_at`]). -//! Direct Selection also edits a blend's spine: drag its points (a key object on a point moves -//! with it) and, once a point is clicked, its handles; and the points of selected gradient meshes +//! Direct Selection also edits a blend's spine: drag its points (Shift-click picks several, which +//! drag together; a key object on a point moves with it) and, once a point is clicked, its +//! handles; and the points of selected gradient meshes //! and mesh envelopes and their handles ([`MeshEdit`]): Shift-clicks and the marquee pick several, //! a click on a gradient mesh's line picks its two ends and one inside a patch the four points //! around it, a drag of picked points moves them all, the arrow keys nudge them, and a solid fill @@ -49,7 +50,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{HitKind, compound_part_at, hit_test, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; @@ -182,6 +183,9 @@ pub struct DirectSelectionTool { state: State, /// The spine point last clicked (blend, anchor): its handles show and can be dragged. spine: Option<(NodeId, usize)>, + /// Other points of that spine picked with it (Shift-click adds or takes one away); dragging + /// a picked point moves them all (#5285). + spine_more: Vec, mesh: MeshEdit, /// Smart guides of the handle, anchors or objects being dragged. guides: Vec, @@ -215,8 +219,8 @@ pub struct DirectSelectionTool { click: Option<(NodeId, usize, usize)>, /// A click on a whole path picks the segment on release; a drag still moves the whole path. click_segment: Option<(NodeId, usize, usize)>, - /// An Alt-click on a path selected whole adds this enclosing group on release, as a Group - /// Selection click does; an Alt-drag still copies the selection. + /// A Group Selection click, or an Alt-click on a path selected whole, adds this enclosing + /// group on release. A drag keeps the selection; an Alt-drag still copies it. click_group: Option, /// The selected anchors of area type's frames, picked by a click or a marquee: they show /// filled, a drag of one moves them all, and the arrow keys nudge them. They stay selected @@ -237,6 +241,7 @@ impl DirectSelectionTool { group, state: State::Idle, spine: None, + spine_more: vec![], mesh: MeshEdit::default(), guides: vec![], anchor_snap: None, @@ -391,8 +396,13 @@ fn hit_spine_handle(cx: &ToolContext, sel: (NodeId, usize), p: Point, tol: f64) /// Anchor `sel.1` of blend `sel.0`'s spine. fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option { + spine_path(cx, id)?.subpaths.first()?.anchors.get(ai).copied() +} + +/// Blend `id`'s spine, built once for callers that look up several of its points. +fn spine_path(cx: &ToolContext, id: NodeId) -> Option { match &cx.doc.node(id)?.kind { - NodeKind::Blend { children, spec } => vectorcraft_doc::live::blend_spine(children, spec)?.0.subpaths.first()?.anchors.get(ai).copied(), + NodeKind::Blend { children, spec } => Some(vectorcraft_doc::live::blend_spine(children, spec)?.0), _ => None, } } @@ -773,7 +783,8 @@ impl Tool for DirectSelectionTool { self.state = State::SpineHandle { id: sel.0, anchor: sel.1, out }; return vec![Action::Begin("Reshape Spine".into())]; } - self.spine = None; + let held = self.spine.take().filter(|(id, _)| cx.selection.contains(*id)); + let more = std::mem::take(&mut self.spine_more); self.snapped = false; if let Some(g) = self.mesh.hit(cx, &cx.selection.objects, p) { self.state = State::Mesh; @@ -789,7 +800,24 @@ impl Tool for DirectSelectionTool { return vec![Action::Begin("Reshape".into())]; } if let Some((id, anchor, from)) = hit_spine_point(cx, p, point) { + // The points of this spine picked before: Shift-click adds the point or takes + // it away; a plain click on one of them keeps them all, to drag together. + let mut picked: Vec = + held.filter(|(h, _)| *h == id).map(|(_, a)| more.into_iter().chain([a]).collect()).unwrap_or_default(); + if ev.mods.shift + && let Some(k) = picked.iter().position(|a| *a == anchor) + { + picked.remove(k); + self.spine = picked.pop().map(|a| (id, a)); + self.spine_more = picked; + return vec![]; + } + if !ev.mods.shift && !picked.contains(&anchor) { + picked.clear(); + } + picked.retain(|a| *a != anchor); self.spine = Some((id, anchor)); + self.spine_more = picked; self.state = State::SpinePoint { id, anchor, from, start: p, began: false }; return if cx.selection.contains(id) { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } @@ -873,7 +901,14 @@ impl Tool for DirectSelectionTool { self.state = State::SpinePoint { id, anchor, from, start, began: true }; } let q = from + move_delta(start, p, ev.mods.shift, cx.constrain_angle); - out.push(Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": id.0, "anchor": anchor, "x": q.x, "y": q.y}))); + let mut params = json!({"id": id.0, "anchor": anchor, "x": q.x, "y": q.y}); + let spine = spine_path(cx, id); + let count = spine.as_ref().and_then(|sp| sp.subpaths.first()).map_or(0, |sp| sp.anchors.len()); + let with: Vec = self.spine_more.iter().copied().filter(|a| *a < count).collect(); + if !with.is_empty() { + params["with"] = json!(with); + } + out.push(Action::Preview("object.blend.spine.moveAnchor".into(), params)); out } (PointerKind::Drag, State::SpineSegment { id, seg, t, start, began }) => { @@ -1033,7 +1068,8 @@ impl DirectSelectionTool { } // A selected path's anchors or the anchors of the path under the pointer, as Highlight // anchors on mouse over finds them: walking every path on each hover is too slow. - if let Some((id, _)) = hovered_anchor(cx, p) { + let hit = hit_test(cx.doc, p, cx.selection_hit_options()); + if let Some((id, _)) = hovered_anchor_with_hit(cx, p, hit.as_ref()) { return Some(if cx.selection.contains(id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); } if hit_frame_edge(cx, p, tol).is_some() { @@ -1045,7 +1081,7 @@ impl DirectSelectionTool { if m.shift || self.guide.cursor(cx, p).is_some() { return None; } - let h = hit_test(cx.doc, p, cx.selection_hit_options())?; + let h = hit?; let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none(); let curved = matches!(h.kind, HitKind::Stroke | HitKind::Outline) && segment_at(cx, h.leaf, p).is_some_and(|s| s.curved); (!whole && curved).then_some(Cursor::ReshapeSegment) @@ -1055,9 +1091,13 @@ impl DirectSelectionTool { /// The anchor within a press's reach of `p` ([`ToolContext::point_tol`]), of a selected path or the /// path under `p`: what Highlight anchors on mouse over marks (a press there picks it). fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> { + let hit = hit_test(cx.doc, p, cx.selection_hit_options()); + hovered_anchor_with_hit(cx, p, hit.as_ref()) +} + +fn hovered_anchor_with_hit(cx: &ToolContext, p: Point, hit: Option<&Hit>) -> Option<(NodeId, Point)> { let tol = cx.point_tol(); - let under = - hit_test(cx.doc, p, cx.selection_hit_options()).map(|h| cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf)); + let under = hit.map(|h| cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf)); cx.selection.objects.iter().copied().filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { let path = cx.doc.node(id).and_then(editable_path)?; nearest_anchor(&path, p, tol).map(|(.., a)| (id, a)) @@ -1131,7 +1171,9 @@ impl DirectSelectionTool { /// The clicked spine point, filled, with its handles. fn spine_overlays(&self, cx: &ToolContext) -> Vec { let Some(sel) = self.spine.filter(|(id, _)| cx.selection.contains(*id)) else { return vec![] }; - let Some(a) = spine_anchor(cx, sel) else { return vec![] }; + let Some(spine) = spine_path(cx, sel.0) else { return vec![] }; + let Some(points) = spine.subpaths.first().map(|sp| &sp.anchors) else { return vec![] }; + let Some(a) = points.get(sel.1).copied() else { return vec![] }; let color = cx.doc.layer_color(sel.0); let mut out = vec![]; for h in [a.h_in, a.h_out].into_iter().filter(|h| h.distance(a.p) > 1e-6) { @@ -1139,6 +1181,7 @@ impl DirectSelectionTool { out.push(Overlay::Handle { p: h, color }); } out.push(Overlay::Anchor { p: a.p, color, filled: true, size: 5.0 }); + out.extend(self.spine_more.iter().filter_map(|i| points.get(*i)).map(|m| Overlay::Anchor { p: m.p, color, filled: true, size: 5.0 })); out } } @@ -1159,6 +1202,7 @@ impl DirectSelectionTool { Some(vec![]) } fn press_group(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point, tol: f64) -> Vec { + self.click_group = None; if let Some(out) = self.guide.press(cx, ev) { self.state = State::Idle; return out; @@ -1188,7 +1232,8 @@ impl DirectSelectionTool { } } else if !cx.selection.contains(target) { if cx.selection.contains(h.leaf) { - out.push(Action::Exec("select.add".into(), json!({"ids": [target.0]}))); + // A completed click climbs the group; a drag moves only the selected art. + self.click_group = Some(target); } else { out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index ef60102200..c1748cac9f 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -182,6 +182,45 @@ fn dragging_a_spine_point_moves_it() { assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Anchor { filled: true, .. })), "the clicked point shows"); } +/// #5285: Shift-click picks several points of a blend's spine, as of a path; dragging one of them +/// moves them all (`with`), and Shift-click on a picked point takes it away again. +#[test] +fn shift_click_picks_several_spine_points_which_drag_together() { + let (mut d, g, _) = blend_doc(); + let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(160.0, 310.0), Point::new(210.0, 310.0)], false); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![0, 2]); + let mut s = Selection::default(); + s.set([g]); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let filled = |t: &DirectSelectionTool| t.overlays(&cx).iter().filter(|o| matches!(o, Overlay::Anchor { filled: true, .. })).count(); + let mut t = DirectSelectionTool::new(false); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 310.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0).with_mods(shift)); + assert_eq!(filled(&t), 2, "both picked points show"); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 210.0, 330.0)); + assert_eq!( + a.last(), + Some(&Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": g.0, "anchor": 2, "x": 210.0, "y": 330.0, "with": [1]}))) + ); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 330.0)), vec![Action::Commit]); + // A plain press on a picked point keeps both. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 160.0, 300.0)); + assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 1 && v["with"] == json!([2])), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 160.0, 300.0)); + // Shift-click takes one away; a plain click on another point picks it alone. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 210.0, 310.0).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 210.0, 310.0).with_mods(shift)); + assert_eq!(filled(&t), 1); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 310.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 110.0, 330.0)); + assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["anchor"] == 0 && v.get("with").is_none()), "{a:?}"); +} + /// #1111: the Anchor Point tool bends a selected blend's straight spine; Direct Selection /// reshapes a curved spine segment and leaves a straight one alone, as it does a path's. #[test] @@ -755,11 +794,17 @@ fn group_selection_picks_a_path_of_a_compound_path() { d.insert(Some(l), 0, c).unwrap(); let p = paint(); let none = Selection::default(); - let click = |s: &Selection, x, y| DirectSelectionTool::new(true).pointer(&cx(&d, s, &p), &PointerEvent::new(PointerKind::Down, x, y)); + let click = |s: &Selection, x, y| { + let mut t = DirectSelectionTool::new(true); + let context = cx(&d, s, &p); + let mut actions = t.pointer(&context, &PointerEvent::new(PointerKind::Down, x, y)); + actions.extend(t.pointer(&context, &PointerEvent::new(PointerKind::Up, x, y))); + actions + }; let set = |id: NodeId| vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]; assert_eq!(click(&none, 25.0, 100.0), set(outer), "the fill between the outline and the hole"); assert_eq!(click(&none, 50.0, 100.0), set(hole), "the hole's outline"); - assert!(click(&none, 100.0, 100.0).is_empty(), "inside the hole nothing is hit"); + assert_eq!(click(&none, 100.0, 100.0), vec![Action::Exec("select.none".into(), json!({}))], "a click inside the hole clears selection"); let mut s = Selection::default(); s.set([outer]); assert_eq!(click(&s, 25.0, 100.0), vec![Action::Exec("select.add".into(), json!({"ids": [compound.0]}))]); @@ -813,6 +858,30 @@ fn nested_group_doc() -> (vectorcraft_doc::Document, NodeId, NodeId, NodeId, Nod (d, inside, outside, inner, outer) } +/// A selected component drags independently; only a completed click adds its group. +#[test] +fn group_selection_distinguishes_selected_leaf_drags_from_clicks() { + let (d, inside, _, inner, _) = nested_group_doc(); + let paint = paint(); + let mut selected = Selection::default(); + selected.set([inside]); + let context = cx(&d, &selected, &paint); + let mut t = DirectSelectionTool::new(true); + let down = PointerEvent::new(PointerKind::Down, 150.0, 150.0); + assert!(t.pointer(&context, &down).is_empty()); + let actions = t.pointer(&context, &PointerEvent::new(PointerKind::Drag, 180.0, 165.0)); + assert!(matches!(actions.as_slice(), [Action::Begin(_), Action::Preview(command, _)] if command=="object.transform")); + assert_eq!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 180.0, 165.0)), vec![Action::Commit]); + assert!(t.pointer(&context, &down).is_empty()); + assert_eq!( + t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)), + vec![Action::Exec("select.add".into(), json!({"ids":[inner.0]}))] + ); + assert!(t.pointer(&context, &down).is_empty()); + assert_eq!(t.key(&context, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty()); +} + /// Isolation mode: a marquee and an anchor click take the path inside the isolated group and /// leave the path beside it. Group Selection stops at the isolated group instead of adding /// the group around it. diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 23e61e602c..123082aa25 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -26,10 +26,14 @@ pub use gesture::GestureTool; /// Colour of tool feedback (Illustrator's selection blue). pub const FEEDBACK: [u8; 3] = [0x4f, 0x9d, 0xff]; -/// The lowest Fidelity (points) the Pencil and Paintbrush take (#3328); the Smooth tool keeps -/// [`SMOOTH_MIN_FIDELITY`]. +/// The lowest Fidelity the Pencil and Paintbrush take (#3328; screen pixels, points for the Blob +/// Brush); the Smooth tool keeps [`SMOOTH_MIN_FIDELITY`]. pub const MIN_FIDELITY: f64 = 0.01; +/// The finest tolerance (points) `path.freehand` fits a Pencil or Paintbrush stroke at: the lowest +/// Fidelity at the highest zoom (64000 %), whose screen pixels the tools send in points (#5729). +pub const MIN_FIT_TOLERANCE: f64 = MIN_FIDELITY / 640.0; + /// The lowest Fidelity (points) the Smooth tool takes. pub const SMOOTH_MIN_FIDELITY: f64 = 0.05; diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 80d9ac9b1c..495e932a4b 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -66,7 +66,9 @@ pub struct GestureTool { /// Pencil/Paintbrush starting on a selected path away from its ends: (path, Edit Selected /// Paths' distance in points); the stroke redraws the section it ends on (#2850). redraw: Option<(NodeId, f64)>, - /// Fit tolerance in points (Pencil/Paintbrush/Smooth/Blob Brush "Fidelity"). + /// Fit tolerance (Pencil/Paintbrush/Smooth/Blob Brush "Fidelity"): in screen pixels for the + /// Pencil and the Paintbrush, so a stroke keeps as many points at any zoom (#5729), in points + /// for the others. pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, @@ -453,11 +455,12 @@ impl GestureTool { self.draws_path() && !self.smoothing && !self.straight && self.extend.is_none() && self.redraw.is_none() && self.ends_near_start(cx, end) } - /// Parameters of `path.freehand` for the current stroke. - pub fn freehand_params(&self, closed: bool) -> Value { + /// Parameters of `path.freehand` for the current stroke, fitted at Fidelity on screen. Only the + /// Pencil and the Paintbrush (`draws_path`) send it; the Blob Brush's Fidelity stays in points. + pub fn freehand_params(&self, cx: &ToolContext, closed: bool) -> Value { let mut v = json!({ "points": self.stroke_json(), - "fidelity": self.fidelity, + "fidelity": cx.tol(self.fidelity), "closed": closed, "style": if self.id == "paintbrush" { "brush" } else { "pencil" }, "fill": self.fill, @@ -494,7 +497,7 @@ impl GestureTool { let near = pts.last().is_some_and(|&end| self.ends_near_start(cx, end)); // A straight line has two points: closing it would draw it back over itself. let closed = !self.straight && ((m.alt && (self.id == "paintbrush" || !self.alt_smooth)) || (self.extend.is_none() && near)); - let mut params = self.freehand_params(closed); + let mut params = self.freehand_params(cx, closed); // A Pencil stroke that continues a selected path and ends on an open end of another // path selected at the press connects the two. let connect = pts.last().and_then(|&end| self.find_end(cx, end, &self.connect_to)); @@ -649,9 +652,9 @@ impl Tool for GestureTool { } // With the Pencil's Live preview off a thin line shows instead (`overlays`). if self.previews() && crate::previews_at(self.points.len()) { - let mut v = self.freehand_params(false); - let fidelity = self.fidelity.max(cx.tol(PREVIEW_FIDELITY_PX)); - v["fidelity"] = json!(fidelity); + let mut v = self.freehand_params(cx, false); + let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX); + v["fidelity"] = json!(cx.tol(fidelity)); // A preview fitted coarser than the stroke kept is stale (`deactivate`). self.previewed = if fidelity > self.fidelity { 0 } else { self.points.len() }; if !self.live_fit { @@ -748,13 +751,13 @@ impl Tool for GestureTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.tip_at = None; } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { let began = self.began; self.tip_at = None; // Drags past the last preview are in the stroke kept, too, and with Live curve fitting // off the stroke kept is fitted. let stale = (began && (self.previewed != self.points.len() || !self.live_fit) && self.draws_path() && !self.smoothing) - .then(|| Action::Preview("path.freehand".into(), self.freehand_params(false))); + .then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false))); self.snap.clear(); self.active = false; self.near_start = false; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 20cc489af5..c0ef91d240 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -154,7 +154,8 @@ fn pencil_with_live_curve_fitting_off_previews_the_stroke_unfitted() { /// A stroke whose Fidelity is finer than half a screen pixel previews fitted at half a pixel, which /// looks the same at a fraction of the fit's cost (#4565); the release, and another tool chosen -/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. +/// while it is drawn, fit it at its own Fidelity. A coarser Fidelity previews as it is kept. Fidelity +/// is in screen pixels, so the stroke is fitted in points at Fidelity / zoom (#5729). #[test] fn fine_fidelity_previews_at_half_a_pixel() { let (d, _) = doc_with_rect(); @@ -166,26 +167,83 @@ fn fine_fidelity_previews_at_half_a_pixel() { acts.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect() }; for id in ["pencil", "paintbrush"] { - for (zoom, fidelity, drawn) in [(1.0, 0.01, 0.5), (4.0, 0.01, 0.125), (1.0, 1.5, 1.5)] { + for (zoom, fidelity, drawn, kept) in [(1.0, 0.01, 0.5, 0.01), (4.0, 0.01, 0.125, 0.0025), (1.0, 1.5, 1.5, 1.5), (4.0, 1.5, 0.375, 0.375)] { cx.zoom = zoom; let mut t = GestureTool::new(id); t.set_option("fidelity", &json!(fidelity)); let acts = drag(&mut t, &cx, &stroke, Mods::default()); let (release, during) = acts.split_last().unwrap(); - assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} pt"); - assert_eq!(fidelities(release), [fidelity], "{id} at {zoom}x, {fidelity} pt: the release"); + assert_eq!(fidelities(&during.concat()), [drawn; 3], "{id} at {zoom}x, {fidelity} px"); + assert_eq!(fidelities(release), [kept], "{id} at {zoom}x, {fidelity} px: the release"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); for &(x, y) in &stroke[1..] { t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); } let acts = t.deactivate(&cx); - let kept = if drawn > fidelity { [fidelity].to_vec() } else { vec![] }; - assert_eq!(fidelities(&acts), kept, "{id} at {zoom}x, {fidelity} pt: another tool chosen"); + let stale = if drawn > kept { [kept].to_vec() } else { vec![] }; + assert_eq!(fidelities(&acts), stale, "{id} at {zoom}x, {fidelity} px: another tool chosen"); assert_eq!(acts.last(), Some(&Action::Commit)); } } } +/// #5729: the Pencil's and the Paintbrush's Fidelity is in screen pixels. The same stroke drawn on +/// screen at 1x and at 4x is fitted at the same tolerance on screen, so it keeps as many points +/// whatever the zoom (another tool chosen mid-stroke: `fine_fidelity_previews_at_half_a_pixel`). +#[test] +fn fidelity_is_in_screen_pixels_at_any_zoom() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let screen = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)]; + for id in ["pencil", "paintbrush"] { + let on_screen = |cx: &ToolContext, zoom: f64| { + let pts: Vec<_> = screen.iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + let mut t = GestureTool::new(id); + t.set_option("fidelity", &json!(1.5)); + let acts = drag(&mut t, cx, &pts, Mods::default()); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + v["fidelity"].as_f64().unwrap() * zoom + }; + cx.zoom = 1.0; + let at_1 = on_screen(&cx, 1.0); + cx.zoom = 4.0; + let at_4 = on_screen(&cx, 4.0); + assert_eq!(at_1, 1.5, "{id}"); + assert_eq!(at_4, at_1, "{id}: fidelity in screen px at 1x vs 4x"); + } +} + +/// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its +/// stroke, and another tool chosen while it is drawn, send it as set at any zoom. +#[test] +fn blob_brush_fidelity_stays_in_points_at_any_zoom() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + let stroke = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)]; + for zoom in [1.0, 4.0] { + cx.zoom = zoom; + let mut t = GestureTool::new("blobBrush"); + t.set_option("fidelity", &json!(1.5)); + let acts = drag(&mut t, &cx, &stroke, Mods::default()); + let sent: Vec<_> = acts + .concat() + .into_iter() + .filter_map(|a| if let Action::Exec(_, v) | Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }) + .collect(); + assert_eq!(sent, [1.5], "at {zoom}x"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0)); + for &(x, y) in &stroke[1..] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + let acts = t.deactivate(&cx); + assert!(!acts.iter().any(|a| matches!(a, Action::Preview(id, _) if id == "path.freehand")), "at {zoom}x: {acts:?}"); + } +} + /// Keep selected is on by default, and every Pencil and Paintbrush preview sends it. #[test] fn pencil_and_paintbrush_send_keep_selected() { diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 36947c9314..6fed43337e 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -964,7 +964,14 @@ impl Targets { /// ([`Self::for_move`]) is spaced evenly along an axis that lines up with nothing /// ([`Self::even_spacing`]). Returns the shift and the guides. pub fn snap_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec) { + let (d, ov, _) = self.snap_rects_axes(rects, tol); + (d, ov) + } + + /// [`Self::snap_rects`], also saying which axes (x, y) lined up or were spaced evenly. + pub(crate) fn snap_rects_axes(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec, [bool; 2]) { let (mut d, mut ov, aligned) = self.align_rects(rects, tol); + let mut taken = aligned; if let [r] = rects && !self.boxes.is_empty() { @@ -973,6 +980,7 @@ impl Targets { for (x, lined_up) in [true, false].into_iter().zip(aligned) { if let Some((shift, _)) = self.even_spacing(moved, x, tol).filter(|_| !lined_up) { *(if x { &mut d.x } else { &mut d.y }) += shift; + taken[usize::from(!x)] = true; spaced = true; } } @@ -985,7 +993,7 @@ impl Targets { } } } - (d, ov) + (d, ov, taken) } /// Spacing Guides along the x axis (`x`) or the y axis for the moved rectangle `r`, among the @@ -1088,6 +1096,50 @@ impl Targets { (d, ov, [best_x.is_some(), best_y.is_some()]) } + /// Snap a selection grabbed at `p` and moved as a whole, its bounds now `r`, to the ruler + /// guides: the grabbed point goes into line with a guide running within `tol` of it + /// ([`Self::snap_point`]), and on an axis where none does and that is not `taken` (x, y) + /// already, the edge or centre of `r` nearest a guide running past it within `tol` goes onto it + /// (#5746). Returns the shift, the guides (none when nothing lines up) and whether a guide held + /// the grabbed point. + pub(crate) fn snap_moved_to_rulers(&self, p: Point, r: Option, tol: f64, taken: [bool; 2]) -> (Vec2, Vec, bool) { + let near = |vertical: bool| { + let v = if vertical { p.x } else { p.y }; + self.rulers.iter().any(|g| g.vertical == vertical && (g.pos - v).abs() <= tol && g.line_at(p, tol).is_some()) + }; + let held = [near(true), near(false)]; + let (q, mut ov) = if held.contains(&true) { self.snap_point(p, tol) } else { (p, vec![]) }; + let mut d = q - p; + let Some(r) = r.map(|r| r + d) else { return (d, ov, held.contains(&true)) }; + // The guide upright (`vertical`) or level nearest one of `vs`, running past `r` across. + let nearest = |vertical: bool, vs: [f64; 3]| { + let (c, half) = + if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) }; + self.rulers + .iter() + .filter(|g| g.vertical == vertical) + .filter_map(|g| g.line_at(c, tol + half)) + .flat_map(|(t, from, _)| vs.into_iter().map(move |v| (t - v, t, from))) + .filter(|(s, ..)| s.abs() <= tol) + .min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())) + }; + let hx = if held[0] || taken[0] { None } else { nearest(true, [r.x0, r.center().x, r.x1]) }; + let hy = if held[1] || taken[1] { None } else { nearest(false, [r.y0, r.center().y, r.y1]) }; + let shift = Vec2::new(hx.map_or(0.0, |h| h.0), hy.map_or(0.0, |h| h.0)); + let (r, lined) = (r + shift, hx.is_some() || hy.is_some()); + d += shift; + if let Some((_, x, from)) = hx { + ov.extend(self.line(Point::new(x, from.y.min(r.y0)), Point::new(x, from.y.max(r.y1)))); + } + if let Some((_, y, from)) = hy { + ov.extend(self.line(Point::new(from.x.min(r.x0), y), Point::new(from.x.max(r.x1), y))); + } + if lined && !held.contains(&true) { + ov.extend(self.label(p + d, "align")); + } + (d, ov, held.contains(&true)) + } + /// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for /// dragging `handle` of the box `bx` (about the centre when `from_center`), in the box's own /// frame, and so is the result. The handle lands on an anchor or centre within `tol` on the page diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index db6eae9581..ece5231bd2 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -104,6 +104,11 @@ impl PointerEvent { pub fn json_hold(e: &Value) -> f64 { e.get("holdMs").and_then(Value::as_f64).filter(|f| f.is_finite()).map_or(0.0, |ms| ms.clamp(0.0, 60_000.0) / 1000.0) } + /// Whether backquote is held, from the `backquote` of a JSON pointer event or request (control + /// channel, MCP): `default` when the key is absent, an error when it is not a boolean. + pub fn json_backquote(v: &Value, default: bool) -> Result { + v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) + } } #[cfg(test)] @@ -119,6 +124,17 @@ mod tests { value["backquote"] = serde_json::json!(true); assert!(serde_json::from_value::(value).unwrap().backquote); } + + #[test] + fn json_backquote_takes_the_default_only_when_absent() { + use serde_json::json; + assert_eq!(PointerEvent::json_backquote(&json!({}), true), Ok(true)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": false}), true), Ok(false)); + assert_eq!(PointerEvent::json_backquote(&json!({"backquote": true}), false), Ok(true)); + for bad in [json!("true"), json!(1), json!(null)] { + assert!(PointerEvent::json_backquote(&json!({"backquote": bad}), false).is_err(), "{bad}"); + } + } } /// Keys tools care about. diff --git a/crates/tools/src/params.rs b/crates/tools/src/params.rs index 8c3565ba2a..49a5a9a3c1 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -25,6 +25,9 @@ pub fn stops_json(stops: &[GradientStop]) -> Value { if let Some(n) = &s.swatch { v["swatch"] = json!(n); v["tint"] = json!(s.tint * 100.0); + if let Some(p) = s.plates { + v["plates"] = json!(p); + } } v }) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 572c667e4b..4bfd6a860a 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -206,7 +206,7 @@ pub(crate) struct MoveSnap { copy_targets: Option, copy_points: Option, /// With Smart Guides on, the ruler guides View › Snap to Point still pulls the grabbed point - /// onto (#1534); `points` holds them with Smart Guides off. + /// onto (#1534), and lines the bounds up with (#5746); `points` holds them with Smart Guides off. rulers: Option, } @@ -245,6 +245,8 @@ impl MoveSnap { d = q - start; guides = ov; } + // The axes (x, y) Smart Guides already put in line with other art. + let mut taken = [false; 2]; if let (Some(t), Some(b)) = (targets, self.bounds) { // The point the selection was grabbed by, near another object's anchor or centre, // lands on it, rather than the bounds lining up a little beside it (#955). @@ -252,18 +254,26 @@ impl MoveSnap { let (q, ov) = t.snap_point(start + d, cx.snap_tol()); d = q - start; guides = ov; + taken = [true; 2]; } else { - let (adj, ov) = t.snap_rect(b + d, cx.snap_tol()); + let (adj, ov, axes) = t.snap_rects_axes(&[b + d], cx.snap_tol()); d += adj; guides = ov; + taken = axes; } } - // A ruler guide within reach of the grabbed point wins over lining the bounds up. + // A ruler guide within reach of the grabbed point wins over lining the bounds up; on an + // axis without one that Smart Guides left free, the bounds line up with the ruler guides + // (#5746), alongside the Smart Guides. if let Some(t) = &self.rulers { - let (q, ov) = t.snap_point(start + d, cx.tol(cx.snap_tolerance)); - if q != start + d { - d = q - start; - guides = ov; + let (adj, ov, held) = t.snap_moved_to_rulers(start + d, self.bounds.map(|b| b + d), cx.tol(cx.snap_tolerance), taken); + if adj != Vec2::ZERO { + d += adj; + if held { + guides = ov; + } else { + guides.extend(ov); + } } } if cx.snap_to_pixel @@ -369,6 +379,8 @@ struct MemoState { entry: Option, /// How many measurements the memo has made. measurements: u64, + /// How many times the memo has checked its key. + checks: u64, } /// The measurements for one key; a slot holds `None` until it is measured. @@ -394,8 +406,15 @@ impl PreviewMemo { self.0.try_borrow().map_or(0, |st| st.measurements) } + /// How many times the memo has checked its key against the document. A check compares the whole + /// selection, so a hover has to make the same few however many objects are selected. + pub fn checks(&self) -> u64 { + self.0.try_borrow().map_or(0, |st| st.checks) + } + /// The measurements for the state `cx` shows, after the ones for any other state are dropped. fn current<'m>(st: &'m mut MemoState, cx: &ToolContext) -> &'m mut Measured { + st.checks += 1; let fresh = || Measured { revision: cx.revision, objects: cx.selection.objects.clone(), @@ -456,7 +475,27 @@ fn shown_box(cx: &ToolContext) -> Option { /// The bounds of object `id`, measured as [`selection_bounds`] measures the selection. fn object_bounds(cx: &ToolContext, id: NodeId) -> Option { - remembered(cx, |m| m.by_object.entry(id).or_insert(None), || vectorcraft_effects::preview::bounds_of(cx.doc, &[id], cx.preview_bounds)) + with_object_bounds(cx, |bounds| bounds(id)) +} + +/// Runs `walk` with a lookup of [`object_bounds`]. The lookups share one check of the memo's key, +/// which compares the whole selection: a walk of every selected object checking it each time takes +/// time in the square of their number. +fn with_object_bounds(cx: &ToolContext, walk: impl FnOnce(&mut dyn FnMut(NodeId) -> Option) -> R) -> R { + let mut measure = |id: NodeId| vectorcraft_effects::preview::bounds_of(cx.doc, &[id], cx.preview_bounds); + let Some(mut st) = cx.preview_memo.and_then(|memo| memo.0.try_borrow_mut().ok()) else { + return walk(&mut measure); + }; + let mut measured = 0; + let by_object = &mut PreviewMemo::current(&mut st, cx).by_object; + let out = walk(&mut |id| { + *by_object.entry(id).or_insert(None).get_or_insert_with(|| { + measured += 1; + measure(id) + }) + }); + st.measurements += measured; + out } /// The objects of `ids` that lie entirely inside marquee `r`, edges included, measured by their @@ -550,15 +589,17 @@ impl SelectionTool { }; // A press on an unselected object selects it alone: the selected ones stay behind. let selected = if under.is_none_or(|u| cx.selection.contains(u)) { &cx.selection.objects[..] } else { &[] }; - under.into_iter().chain(selected.iter().copied()).find_map(|id| { - let n = cx.doc.node(id)?; - let anchor = n.path_data().and_then(|pd| nearest(&mut pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)))); - anchor.map(|q| (q, "anchor")).or_else(|| { - if !cx.smart_guides { - return None; - } - let c = object_bounds(cx, id)?.center(); - (c.distance(p) <= reach).then_some((c, "center")) + with_object_bounds(cx, |bounds| { + under.into_iter().chain(selected.iter().copied()).find_map(|id| { + let n = cx.doc.node(id)?; + let anchor = n.path_data().and_then(|pd| nearest(&mut pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)))); + anchor.map(|q| (q, "anchor")).or_else(|| { + if !cx.smart_guides { + return None; + } + let c = bounds(id)?.center(); + (c.distance(p) <= reach).then_some((c, "center")) + }) }) }) } @@ -1018,10 +1059,16 @@ impl Tool for SelectionTool { if self.guide.busy() { return self.guide.cursor(cx, p).unwrap_or_default(); } - if over_widget(cx, p, false) { + // Corner widgets sit inside selected art, and pie widgets extend at most 17 screen + // pixels beyond it. A distant pointer cannot take either one, so avoid building their + // widgets for every selected object on each cursor move. + let near_selected = cx.selection.objects.len() <= 128 + || cx.preview_bounds + || selection_bounds(cx).is_none_or(|b| b.inflate(cx.tol(32.0), cx.tol(32.0)).contains(p)); + if near_selected && over_widget(cx, p, false) { return Cursor::CornerRadius; } - if pie::over_widget(cx, p) { + if near_selected && pie::over_widget(cx, p) { return Cursor::ArrowHollow; } if over_rotate_all(cx, p) { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 6638083aca..714975bb04 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -545,6 +545,65 @@ fn the_rotate_cursor_wraps_the_corner_it_is_at() { assert_eq!(Cursor::rotate_about(Point::ORIGIN, Point::new(0.0, -5.0)), Cursor::RotateToward(0), "straight up"); } +#[test] +fn a_rotated_large_selection_keeps_handles_outside_its_axis_aligned_bounds() { + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::shapes; + + let mut d = vectorcraft_doc::Document::new(4000.0, 500.0); + let layer = d.layers[0].id; + let mut ids = vec![]; + for i in 0..129 { + let id = d.alloc_id(); + let x = 100.0 + i as f64 * 25.0; + let mut node = Node::path(id, shapes::rectangle(Rect::new(x, 100.0, x + 20.0, 120.0)), Appearance::default_art()); + node.bbox_angle = 45.0; + d.insert(Some(layer), usize::MAX, node).unwrap(); + ids.push(id); + } + let mut selection = Selection::default(); + selection.set(ids); + let paint = paint(); + let cx = cx(&d, &selection, &paint); + let bx = selection_box(&cx).unwrap(); + let bounds = selection_bounds(&cx).unwrap().inflate(cx.tol(32.0), cx.tol(32.0)); + let p = [Point::new(bx.rect.x0, bx.rect.y0), Point::new(bx.rect.x1, bx.rect.y0), Point::new(bx.rect.x1, bx.rect.y1)] + .into_iter() + .map(|q| bx.to_doc() * q) + .find(|q| !bounds.contains(*q)) + .unwrap(); + assert!(matches!(box_hit(&cx, &bx, p), Some(BoxHit::Handle(_)))); + assert_ne!(SelectionTool::default().cursor(&cx, p, Mods::default()), Cursor::Arrow); +} + +#[test] +fn a_large_selection_keeps_a_pie_widget_just_outside_the_art() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + use vectorcraft_geom::{Affine, shapes}; + + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let layer = d.layers[0].id; + let live = LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf: Affine::translate((100.0, 100.0)) }; + let id = d.alloc_id(); + let mut ellipse = Node::path(id, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut ellipse.kind { + *slot = Some(Box::new(live)); + } + d.insert(Some(layer), 0, ellipse).unwrap(); + let mut ids = vec![id]; + for _ in 0..128 { + let id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(120.0, 120.0, 140.0, 140.0)), Appearance::default_art())) + .unwrap(); + ids.push(id); + } + let mut selection = Selection::default(); + selection.set(ids); + let paint = paint(); + let cx = cx(&d, &selection, &paint); + assert_eq!(SelectionTool::default().cursor(&cx, Point::new(312.0, 150.0), Mods::default()), Cursor::ArrowHollow); +} + #[test] fn turned_cursors_step_with_the_view() { assert_eq!(Cursor::ResizeH.turned(90.0), Cursor::ResizeV); diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index f8594226ce..f48625a6ac 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -6,11 +6,19 @@ //! Ctrl/Cmd keeps the inner radius where it is while the outer one follows the pointer, and Alt //! keeps the star's shoulders straight (#812). The start point and //! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. +//! +//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, +//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at +//! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on +//! a live ellipse's pie widget sets its pie angle, as with the Selection tool; a press anywhere +//! else draws a new shape (#5477). use serde_json::{Value, json}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use crate::corners::{self, CornerDrag}; use crate::guides::{DrawSnap, Leave, square}; +use crate::pie::{self, PieDrag}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The largest corner radius the Rounded Rectangle tool draws, points: the range of General › @@ -18,6 +26,18 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// value stop there too. pub const MAX_CORNER_RADIUS: f64 = 1296.0; +/// Does tool `id` keep the selection's bounding box and Live Shape widgets on show and let its +/// corner and pie widgets be dragged (#5477)? The shape tools that draw a box: not Line Segment. +pub fn shows_shape_widgets(id: &str) -> bool { + matches!(id, "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star") +} + +/// A drag on a Live Shape widget of the selection, taken by a shape tool. +enum WidgetDrag { + Corner(CornerDrag), + Pie(PieDrag), +} + pub struct ShapeTool { id: &'static str, start: Option, @@ -37,6 +57,8 @@ pub struct ShapeTool { pub line_angle: f64, pub fill_line: bool, snap: DrawSnap, + /// A widget of the selection is being dragged instead of a shape drawn. + widget: Option, } /// The inner-to-outer radius ratio that keeps a star of `points` points' shoulders straight (each @@ -72,9 +94,41 @@ impl ShapeTool { line_length: 100.0, line_angle: 0.0, fill_line: false, + widget: None, } } + /// A press on a corner or pie widget of the selection: the drag adjusts it. + fn press_widget(&mut self, cx: &ToolContext, ev: &PointerEvent) -> bool { + if !shows_shape_widgets(self.id) { + return false; + } + self.widget = CornerDrag::hit(cx, ev, false).map(WidgetDrag::Corner).or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie)); + self.widget.is_some() + } + + /// Is `p` over a corner or pie widget of the selection that a press would drag? + fn over_widget(&self, cx: &ToolContext, p: Point) -> bool { + shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p)) + } + + /// The pointer and keys while a widget is dragged: `None` when none is. + fn widget_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + let w = self.widget.as_mut()?; + Some(match ev.kind { + PointerKind::Drag => match w { + WidgetDrag::Corner(c) => c.drag(cx, ev.pos), + WidgetDrag::Pie(d) => d.drag(cx, ev.pos), + }, + PointerKind::Up => match self.widget.take() { + Some(WidgetDrag::Corner(c)) => c.finish(), + Some(WidgetDrag::Pie(d)) => d.finish(), + None => vec![], + }, + _ => vec![], + }) + } + /// Ctrl/Cmd in a star drag from `start` to `p`, where the last drag showed a star with the inner /// radius `shown`: once the star has begun, the inner radius stays as the star showed it when /// the key went down, so the ratio follows the outer radius (and stays so once the key is let @@ -214,15 +268,27 @@ impl Tool for ShapeTool { self.id } fn busy(&self) -> bool { - self.start.is_some() + self.start.is_some() || self.widget.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if let Some(out) = self.widget_pointer(cx, ev) { + return out; + } match ev.kind { PointerKind::Move => { - self.snap.hover(cx, ev.pos, &[], None); + // Over a widget a press would drag, no Smart Guide for a new shape's start. + if self.over_widget(cx, ev.pos) { + self.snap.clear(); + } else { + self.snap.hover(cx, ev.pos, &[], None); + } vec![] } PointerKind::Down => { + if self.press_widget(cx, ev) { + self.snap.clear(); + return vec![]; + } let p = self.snap.press(cx, ev.pos, &[], None); self.start = Some(p); self.last = ev.pos; @@ -274,6 +340,19 @@ impl Tool for ShapeTool { } } fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + // A widget drag: Up and Down step a corner's kind; Escape cancels it, as with the + // Selection tool. + if let Some(w) = &mut self.widget { + return match (key, w) { + (ToolKey::Up | ToolKey::Down, WidgetDrag::Corner(c)) => c.step_kind(key == ToolKey::Up), + (ToolKey::Escape, _) => match self.widget.take() { + Some(WidgetDrag::Corner(c)) if c.adjusting() => vec![Action::Cancel], + Some(WidgetDrag::Pie(d)) if d.adjusting() => vec![Action::Cancel], + _ => vec![], + }, + _ => vec![], + }; + } let Some(s) = self.start.filter(|_| self.began) else { return vec![] }; let changed = match (self.id, key) { ("polygon", ToolKey::Up) => { @@ -315,7 +394,23 @@ impl Tool for ShapeTool { vec![] } } + /// Adjusting a widget (the canvas hides the bounding box meanwhile, as for the Selection tool). + fn transforming(&self) -> bool { + match &self.widget { + Some(WidgetDrag::Corner(c)) => c.adjusting(), + Some(WidgetDrag::Pie(d)) => d.adjusting(), + None => false, + } + } + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + matches!(self.widget, Some(WidgetDrag::Corner(_))) && matches!(key, ToolKey::Up | ToolKey::Down) + } fn overlays(&self, cx: &ToolContext) -> Vec { + match &self.widget { + Some(WidgetDrag::Corner(c)) => return c.overlays(cx), + Some(WidgetDrag::Pie(d)) => return d.overlays(cx), + None => {} + } let mut o = self.snap.guides().to_vec(); if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); @@ -347,8 +442,16 @@ impl Tool for ShapeTool { } o } - fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { - Cursor::Crosshair + fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { + // Over a widget a press would drag (or dragging one), the Selection tool's pointer for it. + let idle = self.start.is_none(); + match &self.widget { + Some(WidgetDrag::Corner(_)) => Cursor::CornerRadius, + Some(WidgetDrag::Pie(_)) => Cursor::ArrowHollow, + None if idle && shows_shape_widgets(self.id) && corners::over_widget(cx, p, false) => Cursor::CornerRadius, + None if idle && self.over_widget(cx, p) => Cursor::ArrowHollow, + None => Cursor::Crosshair, + } } fn options(&self) -> Value { json!({ diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index da4916576e..f51cf117f9 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -353,3 +353,73 @@ fn line_segment_options_and_fill_line() { ); assert_eq!(t.command(a, b, Mods::default()).1["fill"], json!(true)); } + +/// #5477: with a shape tool, a drag on a selected live rectangle's corner widget rounds its +/// corners (one undo step) and a drag on a live ellipse's pie widget sets its pie angle, as with +/// the Selection tool; the pointer over a widget is the Selection tool's. A press anywhere else, or +/// with Line Segment, draws. +#[test] +fn a_shape_tool_drags_the_selected_shapes_widgets() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let xf = Affine::translate((100.0, 100.0)); + let (d, s) = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(110.0, 110.0); + for id in ["rectangle", "roundedRectangle", "polygon", "star", "ellipse"] { + let mut t = ShapeTool::new(id); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::CornerRadius, "{id}"); + // Hovering a widget shows no Smart Guide for a new shape. + t.pointer(&c, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + assert!(t.overlays(&c).is_empty(), "{id}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty(), "{id}"); + assert!(t.busy(), "{id}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0)); + assert_eq!(a.first(), Some(&Action::Begin("Corner Radius".into())), "{id}: {a:?}"); + assert!( + matches!(a.last(), Some(Action::Preview(cmd, v)) if cmd == "object.setLiveShape" && v["radius"].as_f64().is_some_and(|r| r > 0.0)), + "{id}: {a:?}" + ); + assert!(t.transforming(), "{id}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 130.0)), vec![Action::Commit], "{id}"); + assert!(!t.busy() && !t.transforming(), "{id}"); + // Escape cancels a widget drag. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0)); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{id}"); + assert!(!t.busy(), "{id}"); + // Away from the widgets the tool draws. + assert_eq!(t.cursor(&c, Point::new(300.0, 300.0), Mods::default()), Cursor::Crosshair, "{id}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 350.0, 340.0)); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd.starts_with("shape.")), "{id}: {a:?}"); + } + // Line Segment draws from a widget, as it always did. + let mut t = ShapeTool::new("lineSegment"); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::Crosshair); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0)); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "shape.line"), "{a:?}"); + // A whole live ellipse's pie widgets sit 12 px right of (300, 150). + let (d, s) = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let c = cx(&d, &s, &p); + let mut t = ShapeTool::new("ellipse"); + assert_eq!(t.cursor(&c, Point::new(312.0, 150.0), Mods::default()), Cursor::ArrowHollow); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 312.0, 150.0)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 200.0, 20.0)); + assert_eq!(a.first(), Some(&Action::Begin("Live Shape".into())), "{a:?}"); + assert!(matches!(a.last(), Some(Action::Preview(cmd, v)) if cmd == "object.setLiveShape" && v.get("pieEnd").is_some()), "{a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]); +} diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 04755740a6..d4f553039c 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -276,7 +276,12 @@ fn paint_sample(s: &mut Sampler, levels: &mut [Option], n: &Node, on_s // path's strokes, only the ones that reach `p` count, when any does (a click within the hit // tolerance of a stroke may reach none). let mut visible: Vec = items.into_iter().filter(|&i| n.appearance.items.get(i).is_some_and(|it| it.visible())).collect(); - if stroke && let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }, Some(bp)) = (&n.kind, n.stroke_path()) { + // With at most one visible stroke, reach testing cannot change which paint is sampled. + // Avoid rebuilding a long path just to keep that same stroke in the list. + if stroke + && visible.len() > 1 + && let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }, Some(bp)) = (&n.kind, n.stroke_path()) + { let reach = |i: &usize| matches!(n.appearance.items.get(*i), Some(vectorcraft_doc::AppearanceItem::Stroke(st)) if st.hits(&bp, *rule, p, 0.0)); if visible.iter().any(&reach) { diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index d9c86240ad..6cacf1c0d6 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -3,11 +3,14 @@ pub mod arrange; pub mod cleanup; pub mod color; +pub mod compounds; +pub mod contour; pub mod document; pub mod enclosing_lasso; pub mod pathtools; pub mod pen; pub mod select; +pub mod shapes; pub mod typetools; use crate::menus::Item; @@ -15,9 +18,12 @@ use crate::menus::Item; /// The add-ons' submenus, then a separator: the head of Object › Plug-ins. pub fn plugin_menu() -> Vec { vec![ + Item::Sub("3D Box", shapes::menu()), Item::Sub("Arrange Tools", arrange::menu()), Item::Sub("Artwork Cleanup", cleanup::menu()), Item::Sub("Color Effects", color::menu()), + Item::Sub("Compound Shapes", compounds::menu()), + Item::Sub("Contour", contour::menu()), Item::Sub("Document Tools", document::menu()), Item::Sub("Enclosing Lasso", enclosing_lasso::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index 9ea6530474..39c73e8c64 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -104,6 +104,10 @@ pub fn menu() -> Vec { Item::Cmd("Find Nearest Swatch…", nearest::COMMAND, Value::Null), Item::Cmd("Create Swatch Legend…", legend::COMMAND, Value::Null), Item::Sep, + // Each selected object's stroke takes its own fill, or the other way (#5530). + Item::Cmd("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})), + Item::Cmd("Apply Stroke to Fill", "addon.color.strokeToFill", json!({})), + Item::Sep, Item::Sub( "Select by Color Kind", [ diff --git a/crates/ui-egui/src/addons/compounds.rs b/crates/ui-egui/src/addons/compounds.rs new file mode 100644 index 0000000000..00336013a8 --- /dev/null +++ b/crates/ui-egui/src/addons/compounds.rs @@ -0,0 +1,19 @@ +//! Compound Shapes in the interface: its submenu (Object › Plug-ins › Compound Shapes) puts Make, +//! Release and Expand Compound Shape (also in the Pathfinder panel's menu) in the menus, and holds the +//! setting that makes the Pathfinder panel's Shape Mode buttons make compound shapes on a click. It +//! acts through `object.compoundShape.*` and `window.pathfinder.compoundShapes`; nothing else +//! about the Pathfinder panel changes. + +use serde_json::{Value, json}; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![ + Item::Cmd("Make Compound Shape", "object.compoundShape.make", json!({})), + Item::Cmd("Release Compound Shape", "object.compoundShape.release", json!({})), + Item::Cmd("Expand Compound Shape", "object.compoundShape.expand", json!({})), + Item::Sep, + Item::Cmd("Shape Mode Buttons Make Compound Shapes", "window.pathfinder.compoundShapes", Value::Null), + ] +} diff --git a/crates/ui-egui/src/addons/contour.rs b/crates/ui-egui/src/addons/contour.rs new file mode 100644 index 0000000000..084a8b98c1 --- /dev/null +++ b/crates/ui-egui/src/addons/contour.rs @@ -0,0 +1,12 @@ +//! The Contour add-on in the interface: its submenu (Object › Plug-ins › Contour), which selects the +//! Contour tool. The Contour bar (`canvas/contour_bar.rs`) shows over the selection while the tool is +//! active. Everything acts through `addon.contour.set` and Expand Appearance. + +use serde_json::json; +use vectorcraft_tools::addons::contour; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![Item::Cmd("Contour Tool", "tool.select", json!({"tool": contour::ID}))] +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 2e5306677b..f59984ccdc 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,5 +1,5 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), -//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Divide into +//! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into //! Dashes ([`dashes`]), Expand Dashes into Paths and Convert to Parametric Shape; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel @@ -8,6 +8,7 @@ pub mod corner; pub mod dashes; +pub mod set_corners; pub mod shape; pub mod shared_edge; @@ -56,6 +57,7 @@ pub fn menu() -> Vec { tool("Measure & Inspect Tool", measure_inspect::ID), tool("Parametric Shape Tool", parametric_shape::ID), Item::Cmd("Corner Tool", corner::COMMAND, json!({})), + Item::Cmd("Set Corners…", set_corners::COMMAND, Value::Null), tool("Slide Anchor Along Path", slide_anchor::ID), Item::Cmd("Shared Edge Merge Tool", shared_edge::COMMAND, json!({})), Item::Sep, diff --git a/crates/ui-egui/src/addons/pathtools/corner.rs b/crates/ui-egui/src/addons/pathtools/corner.rs index dce1363359..36ee1bd1c9 100644 --- a/crates/ui-egui/src/addons/pathtools/corner.rs +++ b/crates/ui-egui/src/addons/pathtools/corner.rs @@ -1,5 +1,6 @@ //! The Anchor Inspector panel's Corners section: the Corner Tool's radius and kind, how many corners -//! the selection holds, and Apply (`addon.pathtools.cornerSet`). +//! the selection holds, Apply (`addon.pathtools.cornerSet`) and Set Corners… (its dialog, which +//! can also take every other anchor, or only the corners in an angle range). use egui::Ui; use serde_json::{Value, json}; @@ -55,10 +56,14 @@ pub(super) fn section(app: &mut VectorcraftApp, ui: &mut Ui) { }); let width = ui.available_width(); let apply = ui.add_enabled_ui(count > 0, |ui| widgets::flat_button(ui, tl!("Apply to Selected Anchors"), width).clicked()).inner; + let dialog = ui.add_enabled_ui(count > 0, |ui| widgets::flat_button(ui, tl!("Set Corners…"), width).clicked()).inner; if let Some(values) = set { run(app, "tool.setOption", json!({ "tool": ID, "values": values })); } if apply { run(app, "addon.pathtools.cornerSet", json!({ "radius": radius, "kind": kind })); } + if dialog { + crate::menus::invoke(app, super::set_corners::COMMAND, json!({})); + } } diff --git a/crates/ui-egui/src/addons/pathtools/set_corners.rs b/crates/ui-egui/src/addons/pathtools/set_corners.rs new file mode 100644 index 0000000000..59ba7035a2 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/set_corners.rs @@ -0,0 +1,150 @@ +//! Set Corners in the interface: its dialog (radius, corner kind, which anchors: all, the +//! odd-numbered or the even-numbered ones, and the range of corner angles to round), which +//! previews on the canvas and runs `addon.pathtools.cornerSet` on OK, one undo step. It opens on +//! the Corner Tool's radius and kind, every corner angle (0° to 180°). + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_tools::addons::corner_tool::{ID, MAX_RADIUS, RADIUS}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.cornerSet"; +pub const KIND: &str = "setCorners"; +/// The corner kinds, as the command names them, and their labels. +const KINDS: [(&str, &str); 3] = [("round", "Round"), ("invertedRound", "Inverted Round"), ("chamfer", "Chamfer")]; +/// Which anchors, as the command's `every` names them, and their labels. +const EVERY: [(&str, &str); 3] = [("all", "All Anchors"), ("odd", "Odd-Numbered Anchors"), ("even", "Even-Numbered Anchors")]; +const LABEL_W: f32 = 64.0; +const FIELD_W: f32 = 170.0; +const ANGLE_W: f32 = 64.0; +/// The corner angles the command takes (degrees). +const ANGLES: std::ops::RangeInclusive = 0.0..=180.0; + +/// The dialog's fields to start with: the Corner Tool's radius and kind, every anchor, Preview on. +pub(crate) fn fields(app: &VectorcraftApp) -> Value { + let options = app.session.tool_options_of(ID); + let radius = options["radius"].as_f64().unwrap_or(RADIUS); + let kind = options["kind"].as_str().unwrap_or("round").to_string(); + json!({ "radius": radius, "kind": kind, "every": "all", "minAngle": 0.0, "maxAngle": 180.0, "preview": true }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Set Corners").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + form::length_within(ui, d, "radius", unit, FIELD_W, Some(0.0..=MAX_RADIUS)); + }); + form::choice(ui, d, "kind", tl!("Corner:"), (LABEL_W, FIELD_W), &KINDS); + form::choice(ui, d, "every", tl!("Anchors:"), (LABEL_W, FIELD_W), &EVERY); + // Only the corners whose sides meet at an angle in this range: small for a sharp spike, near + // 180° for a shallow bend. Typing one end past the other moves the other along. + let (min, max) = (d.f64("minAngle", 0.0), d.f64("maxAngle", 180.0)); + widgets::label_row(ui, tl!("Angle:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field_named(ui, "set-corners-min-angle", Some(tl!("Minimum angle")), min, ANGLES, "°", 1, ANGLE_W) { + d.fields.insert("minAngle".into(), json!(v)); + if v > max { + d.fields.insert("maxAngle".into(), json!(v)); + } + } + ui.label(tl!("to")); + if let Some(v) = widgets::range_field_named(ui, "set-corners-max-angle", Some(tl!("Maximum angle")), max, ANGLES, "°", 1, ANGLE_W) { + d.fields.insert("maxAngle".into(), json!(v)); + if v < min { + d.fields.insert("minAngle".into(), json!(v)); + } + } + }); + form::preview(app, ui, d, "Set Corners", COMMAND, form::params(d)); + false +} + +/// OK: keep the preview (or run the command) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, form::params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + /// The anchor indices of `id`'s uncut outline with a corner drawn. + fn cut(app: &VectorcraftApp, id: u64) -> Vec { + let doc = &app.session.doc().unwrap().doc; + let lc = LiveCorners::of(doc.node(NodeId(id)).unwrap()).unwrap(); + (0..lc.base.anchor_count()).filter(|k| lc.drawn_radius(*k) > 0.0).collect() + } + + #[test] + fn set_corners_opens_from_the_menu_previews_odd_anchors_and_commits_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}, {"x": -50, "y": 50}]); + let id = app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Set Corners…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Set Corners", "Radius:", "Corner:", "Anchors:", "All Anchors", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(cut(&app, id), vec![0, 1, 2, 3, 4], "all previewed"); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("every".into(), json!("odd")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("Odd-Numbered Anchors"), "{shown}"); + assert_eq!(cut(&app, id), vec![0, 2, 4], "odd previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(cut(&app, id), Vec::::new(), "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("every".into(), json!("even")); + d.fields.insert("radius".into(), json!(6)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(cut(&app, id), vec![1, 3]); + } + + #[test] + fn set_corners_previews_only_the_corners_in_its_angle_range() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // A house: square corners at 0, 1 and 3, the roof's 135° corners at 2 and 4. + let anchors = json!([{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 50, "y": 150}, {"x": 0, "y": 100}]); + let id = app.run("path.create", json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + menus::invoke(&mut app, super::COMMAND, json!({})); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Angle:", "to", "0°", "180°"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let n = app.session.doc().unwrap().history.undo.len(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("minAngle".into(), json!(120)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(cut(&app, id), vec![2, 4], "the roof previewed"); + app.ui.dialog.as_mut().unwrap().fields.insert("maxAngle".into(), json!(100)); + app.ui.dialog.as_mut().unwrap().fields.insert("minAngle".into(), json!(80)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(cut(&app, id), vec![0, 1, 3], "the square corners previewed"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(cut(&app, id), vec![0, 1, 3]); + } +} diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 8f6b258269..c61eb0537d 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,7 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen. +//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status +//! ([`link_status`], #5526). use egui::{Sense, Ui, vec2}; use serde_json::{Value, json}; @@ -13,6 +14,8 @@ use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; +pub mod link_status; + /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; pub const KIND: &str = "selectByArtboards"; @@ -25,7 +28,9 @@ const LIST_H: f32 = 220.0; /// Object › Plug-ins › Selection Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null)] + let mut v = vec![Item::Cmd("Select by Artboards…", COMMAND, Value::Null), Item::Sep]; + v.extend(link_status::menu()); + v } /// The dialog's fields to start with: the active artboard chosen, Overlapping. diff --git a/crates/ui-egui/src/addons/select/link_status.rs b/crates/ui-egui/src/addons/select/link_status.rs new file mode 100644 index 0000000000..0b367a7ba0 --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status.rs @@ -0,0 +1,289 @@ +//! Select by Link Status in the interface (#5526): Select Linked, Embedded, Missing and Modified +//! (in Object › Plug-ins › Selection Tools and the Links panel's menu; Shift adds to the +//! selection), the Select by Link Status dialog, and the status bar's line saying what was +//! selected and what was left out. Everything goes through `addon.select.byLinkStatus`; the dialog +//! lists what `links.list` reports. + +use egui::{Ui, vec2}; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// Select by Link Status, and its dialog's kind. +pub const COMMAND: &str = "addon.select.byLinkStatus"; +pub const KIND: &str = "selectByLinkStatus"; +/// The statuses, as the command names them, with their menu items' and the dialog's labels. +pub const STATUSES: [(&str, &str, &str); 4] = [ + ("linked", "Select Linked", "Linked"), + ("embedded", "Select Embedded", "Embedded"), + ("missing", "Select Missing", "Missing"), + ("modified", "Select Modified", "Modified"), +]; +/// The dialog's Show choices: (value, label). +const SHOW: [(&str, &str); 5] = [("all", "All"), ("linked", "Linked"), ("embedded", "Embedded"), ("missing", "Missing"), ("modified", "Modified")]; +/// How often the statuses are looked at again while the document stays as it is (s): files +/// change on disk without the document knowing. +const RECHECK: f64 = 2.0; +/// The least time between two looks while the document keeps changing (s). +const SETTLE: f64 = 0.5; +const ROW_H: f32 = 22.0; +const LIST_H: f32 = 240.0; +const STATUS_W: f32 = 80.0; +const FORMAT_W: f32 = 70.0; + +/// The menu items: one per status, then the dialog. +pub fn menu() -> Vec { + let mut v: Vec = STATUSES.iter().map(|&(status, label, _)| Item::Cmd(label, COMMAND, json!({ "status": status }))).collect(); + v.push(Item::Cmd("Select by Link Status…", COMMAND, Value::Null)); + v +} + +/// Which statuses ([`STATUSES`] order) the active document's images and placed documents have, +/// for the document and revision it was read for and when. +#[derive(Clone, Debug, Default)] +pub struct Present { + key: Option<(u64, u64)>, + at: f64, + pub has: [bool; 4], +} + +/// The statuses the `links.list` result `list` holds, in [`STATUSES`] order. +pub(crate) fn statuses_in(list: &Value) -> [bool; 4] { + let rows = list["links"].as_array().map_or(&[][..], Vec::as_slice); + STATUSES.map(|(status, ..)| rows.iter().any(|r| command_status(r) == status)) +} + +/// The status of a `links.list` row as the command names it (`ok` is `linked`). +fn command_status(row: &Value) -> &str { + match row["status"].as_str().unwrap_or_default() { + "ok" => "linked", + s => s, + } +} + +/// Keep [`Present`] up to date: at once when another document comes to the front, at most every +/// [`SETTLE`] seconds while its revision changes (a drag changes it every frame, and each look +/// asks the file system about every linked file), and every [`RECHECK`] seconds while it has +/// linked files. +pub fn refresh(app: &mut VectorcraftApp, now: f64) { + let key = app.session.active().map(|st| (st.uid, st.revision)); + let p = &app.ui.link_statuses; + let linked = p.has.iter().zip(STATUSES).any(|(on, (status, ..))| *on && status != "embedded"); + let other_document = p.key.map(|k| k.0) != key.map(|k| k.0); + let due = if p.key == key { linked && now - p.at >= RECHECK } else { other_document || now - p.at >= SETTLE }; + if !due { + return; + } + let has = if key.is_some() { app.session.execute("links.list", &json!({})).map(|l| statuses_in(&l)).unwrap_or_default() } else { [false; 4] }; + app.ui.link_statuses = Present { key, at: now, has }; +} + +/// Is menu item `status` (a [`STATUSES`] value) on: does an image or placed document have it? +pub(crate) fn enabled(app: &VectorcraftApp, p: &Value) -> bool { + let Some(status) = p.get("status").and_then(Value::as_str) else { return true }; + STATUSES.iter().position(|(s, ..)| *s == status).and_then(|i| app.ui.link_statuses.has.get(i).copied()).unwrap_or(false) +} + +/// A menu item's params with Shift held: add to the selection. +pub(crate) fn with_shift(mut p: Value) -> Value { + if let Some(o) = p.as_object_mut() + && o.contains_key("status") + { + o.insert("add".into(), json!(true)); + } + p +} + +/// Run the command; with `zoom` and something selected, Zoom to Selection; the status bar says +/// what was selected and what was left out. Without params (the menu's "Select by Link Status…") +/// it opens the dialog instead. +pub(crate) fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + if p.as_object().is_none_or(serde_json::Map::is_empty) { + if app.session.active().is_none() { + return Err("no document".into()); + } + let fields = fields(app); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + return Ok(json!({ "dialog": KIND })); + } + let r = app.session.execute(COMMAND, p).map_err(|e| e.to_string())?; + let count = r["count"].as_u64().unwrap_or(0); + if r["zoom"] == true && count > 0 { + crate::addons::arrange::zoom(app)?; + } + let statuses: Vec<&str> = match &p["status"] { + Value::Array(v) => v.iter().filter_map(Value::as_str).collect(), + v => v.as_str().into_iter().collect(), + }; + let reasons: Vec<&str> = r["skipped"].as_array().map_or(vec![], |v| v.iter().filter_map(|k| k["reason"].as_str()).collect()); + app.status(message(&statuses, count, &reasons)); + Ok(r) +} + +/// The status bar's line: `count` objects of `statuses` selected, and the `reasons` the others +/// were left out for (e.g. "Selected 9 missing images; 3 more are hidden or locked"). +pub(crate) fn message(statuses: &[&str], count: u64, reasons: &[&str]) -> String { + let n = count; + let selected = match statuses { + ["linked"] => crate::i18n::msg_n(n, "Selected {n} linked image", "Selected {n} linked images", &[]), + ["embedded"] => crate::i18n::msg_n(n, "Selected {n} embedded image", "Selected {n} embedded images", &[]), + ["missing"] => crate::i18n::msg_n(n, "Selected {n} missing image", "Selected {n} missing images", &[]), + ["modified"] => crate::i18n::msg_n(n, "Selected {n} modified image", "Selected {n} modified images", &[]), + _ => crate::i18n::msg_n(n, "Selected {n} image", "Selected {n} images", &[]), + }; + let Some(first) = reasons.first() else { return selected }; + // Hidden and locked go together; a template layer, or the isolated group, alone. + /// The group reason `r` is told in: hidden and locked are one. + fn kind(r: &str) -> &str { + match r { + "hidden" | "locked" => "locked", + r => r, + } + } + let (one, other) = match kind(first) { + k if reasons.iter().any(|r| kind(r) != k) => ("{selected}; {n} more can't be selected now", "{selected}; {n} more can't be selected now"), + "template" => ("{selected}; {n} more is on a template layer", "{selected}; {n} more are on template layers"), + "isolation" => ("{selected}; {n} more is outside the isolated group", "{selected}; {n} more are outside the isolated group"), + _ => ("{selected}; {n} more is hidden or locked", "{selected}; {n} more are hidden or locked"), + }; + crate::i18n::msg_n(reasons.len() as u64, one, other, &[("selected", &selected)]) +} + +/// The dialog's fields to start with: every image and placed document (`__rows`, as `links.list` +/// lists them, read once), those selected chosen, All shown, Zoom to Selection on. +pub(crate) fn fields(app: &mut VectorcraftApp) -> Value { + let list = app.session.execute("links.list", &json!({})).unwrap_or_default(); + let rows: Vec = list["links"].as_array().cloned().unwrap_or_default(); + let selected: Vec = app.session.active().map(|st| st.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default(); + let chosen: Vec = rows.iter().filter_map(|r| r["id"].as_u64()).filter(|id| selected.contains(id)).collect(); + json!({ "__rows": rows, "ids": chosen, "show": "all", "zoom": true }) +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Select by Link Status").to_string(), + body, + confirm, + ok: Some("Select"), + min_width: 420.0, + max_width: Some(480.0), + ok_enabled: Some(|_, d| !chosen(d).is_empty()), + ..DialogSpec::FORM +}; + +/// The ids chosen in dialog `d`. +pub(crate) fn chosen(d: &Dialog) -> Vec { + d.fields.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect() +} + +/// The rows of `rows` the name search `query` (ignoring case) and the Show choice `show` let through. +pub(crate) fn shown<'a>(rows: &'a [Value], query: &str, show: &str) -> Vec<&'a Value> { + let q = query.trim().to_lowercase(); + rows.iter() + .filter(|r| show == "all" || command_status(r) == show) + .filter(|r| q.is_empty() || r["name"].as_str().unwrap_or_default().to_lowercase().contains(&q)) + .collect() +} + +/// All (`on`) or None: choose every row `shown`, or none of them; rows the search or Show hides +/// keep their state. +pub(crate) fn choose_shown(chosen: &mut Vec, shown: &[u64], on: bool) { + if on { + for id in shown { + if !chosen.contains(id) { + chosen.push(*id); + } + } + } else { + chosen.retain(|id| !shown.contains(id)); + } +} + +/// Tick or untick row `id`. +pub(crate) fn toggle(chosen: &mut Vec, id: u64) { + match chosen.iter().position(|c| *c == id) { + Some(i) => { + chosen.remove(i); + } + None => chosen.push(id), + } +} + +/// A status's label in the list. +fn status_label(status: &str) -> &'static str { + STATUSES.iter().find(|(s, ..)| *s == status).map_or("", |&(.., label)| tl!(label)) +} + +/// The dialog: the search, the Show filter, a checkbox row per image shown (name, status, format), +/// All / None with the count chosen, and Zoom to Selection. Returns false: nothing to preview. +fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let rows: Vec = d.fields.get("__rows").and_then(Value::as_array).cloned().unwrap_or_default(); + let query = widgets::search_field(ui, ui.scope_id().with("select-by-link-status-search"), tl!("Search images")); + d.fields.insert("__search".into(), json!(query)); + ui.add_space(4.0); + form::choice(ui, d, "show", tl!("Show:"), (60.0, 140.0), &SHOW); + let show = d.str("show"); + let visible = shown(&rows, &query, &show); + let mut picked = chosen(d); + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(LIST_H).auto_shrink([false, true]).show(ui, |ui| { + if visible.is_empty() { + ui.label(egui::RichText::new(tl!("No images match.")).color(t.text_dim)); + } + for r in &visible { + let Some(id) = r["id"].as_u64() else { continue }; + let name = r["name"].as_str().unwrap_or_default(); + let status = status_label(command_status(r)); + let format = r["format"].as_str().unwrap_or_default(); + ui.horizontal(|ui| { + ui.set_min_height(ROW_H); + let on = picked.contains(&id); + let name_w = (ui.available_width() - STATUS_W - FORMAT_W - 40.0).max(60.0); + let check = ui.scope(|ui| { + ui.set_width(name_w + 24.0); + widgets::check_name(ui, name, on) + }); + if check.inner { + toggle(&mut picked, id); + } + ui.add_sized(vec2(STATUS_W, ROW_H), egui::Label::new(egui::RichText::new(status).color(t.text_dim)).truncate()); + ui.add_sized(vec2(FORMAT_W, ROW_H), egui::Label::new(egui::RichText::new(format).color(t.text_dim)).truncate()); + }); + } + }); + ui.add_space(4.0); + let ids: Vec = visible.iter().filter_map(|r| r["id"].as_u64()).collect(); + ui.horizontal(|ui| { + if widgets::flat_button_fit(ui, "All", 50.0).clicked() { + choose_shown(&mut picked, &ids, true); + } + if widgets::flat_button_fit(ui, "None", 50.0).clicked() { + choose_shown(&mut picked, &ids, false); + } + let count = crate::i18n::fmt(tl!("Chosen: {n} of {total}"), &[("n", &picked.len().to_string()), ("total", &rows.len().to_string())]); + ui.label(egui::RichText::new(count).color(t.text_dim)); + }); + d.fields.insert("ids".into(), json!(picked)); + ui.add_space(6.0); + form::check(ui, d, "zoom", tl!("Zoom to Selection")); + false +} + +/// The command's params for dialog `d`: the rows chosen, whatever their status. +pub(crate) fn params(d: &Dialog) -> Value { + json!({ "status": STATUSES.map(|(s, ..)| s), "ids": chosen(d), "zoom": d.bool("zoom") }) +} + +/// Select: select the rows chosen (and zoom to them) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + app.ui.dialog = None; + app.run(COMMAND, params(d)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/link_status/tests.rs b/crates/ui-egui/src/addons/select/link_status/tests.rs new file mode 100644 index 0000000000..8ad61f6e5a --- /dev/null +++ b/crates/ui-egui/src/addons/select/link_status/tests.rs @@ -0,0 +1,201 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{COMMAND, KIND, choose_shown, message, refresh, shown, toggle}; +use crate::tests_labels::painted_text; +use crate::{VectorcraftApp, menus}; + +/// A fresh folder for one test (removed when dropped). +struct Folder(std::path::PathBuf); + +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-select-links-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + fn file(&self, name: &str, bytes: &[u8]) -> String { + let p = self.0.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A `w` × `h` red PNG. +fn png(w: u32, h: u32) -> Vec { + let mut out = vec![]; + image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + out +} + +/// A document with `river.png` linked, `harbour.png` linked and then deleted (missing), and +/// `stamp.png` embedded → (app, river, harbour, stamp). +fn app(dir: &Folder) -> (VectorcraftApp, u64, u64, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let place = |app: &mut VectorcraftApp, path: &str, at: [u32; 2], link: bool| { + app.run("file.place", json!({"path": path, "at": at, "link": link})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (a, b, c) = (dir.file("river.png", &png(40, 30)), dir.file("harbour.png", &png(30, 20)), dir.file("stamp.png", &png(20, 20))); + let river = place(&mut app, &a, [100, 100], true); + let harbour = place(&mut app, &b, [300, 100], true); + let stamp = place(&mut app, &c, [200, 220], false); + std::fs::remove_file(&b).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, river, harbour, stamp) +} + +/// The selected objects' ids, sorted. +fn selected(app: &VectorcraftApp) -> Vec { + let mut ids: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + ids.sort_unstable(); + ids +} + +#[test] +fn the_message_says_what_was_selected_and_what_was_left_out() { + assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images"); + assert_eq!(message(&["linked"], 1, &[]), "Selected 1 linked image"); + assert_eq!(message(&["embedded", "modified"], 2, &[]), "Selected 2 images"); + assert_eq!(message(&["missing"], 9, &["hidden", "locked", "hidden"]), "Selected 9 missing images; 3 more are hidden or locked"); + assert_eq!(message(&["modified"], 0, &["template"]), "Selected 0 modified images; 1 more is on a template layer"); + assert_eq!(message(&["embedded"], 2, &["isolation", "isolation"]), "Selected 2 embedded images; 2 more are outside the isolated group"); + assert_eq!(message(&["linked"], 1, &["isolation", "locked"]), "Selected 1 linked image; 2 more can't be selected now"); +} + +#[test] +fn the_list_filters_by_name_and_status_and_all_and_none_act_on_the_rows_shown() { + let rows = vec![ + json!({"id": 1, "name": "River.png", "status": "ok"}), + json!({"id": 2, "name": "harbour.png", "status": "missing"}), + json!({"id": 3, "name": "Stamp.png", "status": "embedded"}), + json!({"id": 4, "name": "river-2.tif", "status": "modified"}), + ]; + let ids = |v: Vec<&Value>| v.iter().map(|r| r["id"].as_u64().unwrap()).collect::>(); + assert_eq!(ids(shown(&rows, "", "all")), vec![1, 2, 3, 4]); + assert_eq!(ids(shown(&rows, " RIVER ", "all")), vec![1, 4]); + assert_eq!(ids(shown(&rows, "river", "linked")), vec![1], "ok is Linked"); + assert_eq!(ids(shown(&rows, "", "missing")), vec![2]); + assert_eq!(ids(shown(&rows, "zzz", "all")), Vec::::new()); + // Row 3 is chosen but hidden: neither All nor None touches it. + let mut c = vec![3]; + choose_shown(&mut c, &[1, 4], true); + assert_eq!(c, vec![3, 1, 4]); + choose_shown(&mut c, &[1, 4], false); + assert_eq!(c, vec![3]); + toggle(&mut c, 2); + toggle(&mut c, 3); + assert_eq!(c, vec![2]); +} + +#[test] +fn menu_items_are_on_for_the_statuses_present_and_shift_adds() { + let dir = Folder::new("menu"); + let (mut app, river, harbour, stamp) = app(&dir); + refresh(&mut app, 0.0); + let entries = menus::menu_entries(&app); + let item = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap(); + for (label, on) in + [("Select Linked", true), ("Select Embedded", true), ("Select Missing", true), ("Select Modified", false), ("Select by Link Status…", true)] + { + assert_eq!(item(label).enabled, on, "{label}"); + } + let run = |app: &mut VectorcraftApp, label: &str, shift: bool| { + let e = item(label); + let target = menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let (cmd, p) = menus::with_held_keys(target, held); + menus::invoke(app, &cmd, p); + }; + run(&mut app, "Select Missing", false); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.ui.status, "Selected 1 missing image"); + run(&mut app, "Select Embedded", true); + assert_eq!(selected(&app), vec![harbour, stamp], "Shift adds"); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), vec![river], "without Shift it replaces"); + // A hidden image is left out, and the status bar says so. + app.run("object.setProps", json!({"ids": [river], "visible": false})).unwrap(); + run(&mut app, "Select Linked", false); + assert_eq!(selected(&app), Vec::::new()); + assert_eq!(app.ui.status, "Selected 0 linked images; 1 more is hidden or locked"); + // The document changes: the items follow on the next refresh. + app.run("select.set", json!({"ids": [harbour]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + refresh(&mut app, 1.0); + let entries = menus::menu_entries(&app); + let on = |label: &str| entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Selection Tools"] && e.label == label).unwrap().enabled; + assert!(!on("Select Missing")); + assert!(on("Select Embedded")); +} + +#[test] +fn the_links_panel_menu_lists_the_select_items() { + let dir = Folder::new("flyout"); + let (mut app, ..) = app(&dir); + refresh(&mut app, 0.0); + let shown = painted_text(&mut app, crate::panels::links::menu); + for s in ["Select Linked", "Select Embedded", "Select Missing", "Select Modified"] { + assert!(shown.contains(s), "{s} in {shown}"); + } +} + +#[test] +fn the_dialog_lists_filters_and_selects_with_zoom() { + let dir = Folder::new("dialog"); + let (mut app, river, harbour, stamp) = app(&dir); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(560.0, 460.0))); + let zoom_before = app.view().unwrap().zoom; + menus::invoke(&mut app, COMMAND, Value::Null); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["zoom"], &d.fields["show"]), (KIND, &json!(true), &json!("all"))); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in [ + "Select by Link Status", + "river.png", + "harbour.png", + "stamp.png", + "Linked", + "Missing", + "Embedded", + "PNG", + "Zoom to Selection", + "Chosen: 0 of 3", + "All", + "None", + "Select", + ] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert!(!(super::SPEC.ok_enabled.unwrap())(&app, app.ui.dialog.as_ref().unwrap()), "Select is off with nothing chosen"); + // Show: Missing lists only the missing image. + app.ui.dialog.as_mut().unwrap().fields.insert("show".into(), json!("missing")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("harbour.png") && !shown.contains("river.png") && !shown.contains("stamp.png"), "{shown}"); + // Choose two and Select: they are selected and the view zooms to them. + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([river, stamp])); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(selected(&app), vec![river, stamp]); + assert_eq!(app.ui.status, "Selected 2 images"); + assert_ne!(app.view().unwrap().zoom, zoom_before, "zoomed to the selection"); + // Without Zoom to Selection the view stays. + menus::invoke(&mut app, COMMAND, Value::Null); + let zoom = app.view().unwrap().zoom; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("ids".into(), json!([harbour])); + d.fields.insert("zoom".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(selected(&app), vec![harbour]); + assert_eq!(app.view().unwrap().zoom, zoom); +} diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs new file mode 100644 index 0000000000..e7971bb888 --- /dev/null +++ b/crates/ui-egui/src/addons/shapes.rs @@ -0,0 +1,311 @@ +//! The 3D Box and customizable shapes add-on in the interface: its submenu (Object › Plug-ins › +//! 3D Box), which selects the 3D Box tool, and the context-sensitive Control bar options shown +//! when a shape tool (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `spiral`, +//! `box3d`) is active. + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_geom::shapes::EllipseMode; +use vectorcraft_tools::addons::box3d::{self, CustomShape}; + +use crate::menus::Item; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +pub fn menu() -> Vec { + vec![Item::Cmd("3D Box Tool", "tool.select", json!({"tool": box3d::ID}))] +} + +/// Draw context-sensitive shape customization controls in the top Control bar when a shape tool is +/// active. Returns `true` when controls were drawn. +pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { + let tool = app.session.tool_id().to_string(); + if !matches!(tool.as_str(), "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "spiral" | "box3d") { + return false; + } + let opts = app.session.tool_options(); + let active_shape = if tool == "box3d" { opts["shape"].as_str().unwrap_or("box3d").to_string() } else { tool.clone() }; + let selected_custom: Option = app.session.active().and_then(|st| { + st.selection.objects.iter().find_map(|&id| st.doc.node(id).and_then(|n| CustomShape::read_for_update(n, active_shape == "spiral"))) + }); + + if tool == "box3d" { + for (s_id, lbl, icon) in [ + ("box3d", "3D Box", "box"), + ("rectangle", "Rectangle", "square"), + ("ellipse", "Ellipse", "dc-ellipse"), + ("polygon", "Polygon", "dc-polygon"), + ("star", "Star", "star"), + ("spiral", "Spiral", "tornado"), + ] { + if widgets::icon_button(ui, icon, tl!(lbl), active_shape == s_id, 22.0).clicked() { + app.run("tool.setOption", json!({ "key": "shape", "value": s_id })).ok(); + } + } + ui.separator(); + } + + match active_shape.as_str() { + "ellipse" => draw_ellipse_controls(app, ui, &opts, selected_custom), + "rectangle" | "roundedRectangle" => draw_rectangle_controls(app, ui, &opts, selected_custom), + "polygon" | "star" => draw_polygon_controls(app, ui, &opts, &active_shape, selected_custom), + "spiral" => draw_spiral_controls(app, ui, &opts, selected_custom), + "box3d" => draw_box3d_controls(app, ui, &opts, selected_custom), + _ => return false, + } + true +} + +fn apply_shape(app: &mut VectorcraftApp, tool_kvs: &[(&str, Value)], live_patch: Value) { + for (k, v) in tool_kvs { + app.run("tool.setOption", json!({ "key": *k, "value": v.clone() })).ok(); + } + if app.session.active().is_some_and(|st| !st.selection.is_empty()) { + app.run("addon.shapes.configure", live_patch).ok(); + } +} + +fn draw_arc_controls(app: &mut VectorcraftApp, ui: &mut Ui, start_deg: f64, end_deg: f64, mode: &str) { + let t = Tokens::get(ui.ctx()); + widgets::field_label(ui, egui::RichText::new(tl!("Start:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "arc-start"), start_deg, "°", 1, 52.0) { + let next_mode = if mode == "whole" { "pie" } else { mode }; + apply_shape(app, &[("arcStart", json!(v)), ("arcMode", json!(next_mode))], json!({ "startAngle": v, "arcMode": next_mode })); + } + widgets::field_label(ui, egui::RichText::new(tl!("End:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "arc-end"), end_deg, "°", 1, 52.0) { + let next_mode = if mode == "whole" { "pie" } else { mode }; + apply_shape(app, &[("arcEnd", json!(v)), ("arcMode", json!(next_mode))], json!({ "endAngle": v, "arcMode": next_mode })); + } + for (m_id, tip_label, icon) in + [("pie", "Slice", "circle-dot"), ("chord", "Closed", "circle-off"), ("arc", "Arc", "dc-arc"), ("whole", "Open", "dc-ellipse")] + { + if widgets::icon_button(ui, icon, tl!(tip_label), mode == m_id, 22.0).clicked() { + let (s0, e0) = if m_id == "whole" { + (0.0, 0.0) + } else if (end_deg - start_deg).abs() < 1e-4 || ((end_deg - start_deg).abs() - 360.0).abs() < 1e-4 { + (0.0, 270.0) + } else { + (start_deg, end_deg) + }; + apply_shape( + app, + &[("arcMode", json!(m_id)), ("arcStart", json!(s0)), ("arcEnd", json!(e0))], + json!({ "arcMode": m_id, "startAngle": s0, "endAngle": if m_id == "whole" { 360.0 } else { e0 } }), + ); + } + } +} + +fn draw_ellipse_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let (start_deg, end_deg, mode) = match selected_custom { + Some(CustomShape::Ellipse { pie: (a0, a1), arc_mode, .. }) => (a0, a1, mode_str(arc_mode)), + _ => (opts["arcStart"].as_f64().unwrap_or(0.0), opts["arcEnd"].as_f64().unwrap_or(0.0), opts["arcMode"].as_str().unwrap_or("whole")), + }; + draw_arc_controls(app, ui, start_deg, end_deg, mode); + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape(app, &[("arcMode", json!("whole")), ("arcStart", json!(0.0)), ("arcEnd", json!(0.0))], json!({ "reset": true })); + } + ui.separator(); +} + +fn draw_rectangle_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let unit = app.session.general_unit(); + let sym = opts["cornerSymmetry"].as_bool().unwrap_or(true); + let mut radii = [opts["cornerRadius"].as_f64().unwrap_or(12.0); 4]; + if let Some(arr) = opts["cornerRadii"].as_array() + && arr.len() == 4 + { + for (i, item) in arr.iter().enumerate() { + radii[i] = item.as_f64().unwrap_or(radii[i]); + } + } + let (mut start_deg, mut end_deg, mut mode) = + (opts["arcStart"].as_f64().unwrap_or(0.0), opts["arcEnd"].as_f64().unwrap_or(0.0), opts["arcMode"].as_str().unwrap_or("whole")); + if let Some(CustomShape::Rectangle { radii: nr, pie: (a0, a1), arc_mode, .. }) = selected_custom { + radii = nr; + start_deg = a0; + end_deg = a1; + mode = mode_str(arc_mode); + } + if widgets::icon_button(ui, if sym { "link" } else { "unlink" }, tl!("Link"), sym, 22.0).clicked() { + let next_sym = !sym; + apply_shape(app, &[("cornerSymmetry", json!(next_sym))], if next_sym { json!({ "radius": radii[0] }) } else { json!({ "radii": radii }) }); + } + if sym { + widgets::field_label(ui, egui::RichText::new(tl!("Radius:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::num_field(ui, ("cb-shape", "rect-r"), Some(radii[0]), unit, 54.0) { + let r = v.max(0.0); + apply_shape(app, &[("cornerRadius", json!(r)), ("cornerRadii", json!([r, r, r, r]))], json!({ "radius": r })); + } + } else { + for (i, lbl) in [(0, "TL"), (1, "TR"), (2, "BR"), (3, "BL")] { + widgets::field_label(ui, egui::RichText::new(lbl).size(11.0).color(t.text_dim)); + if let Some(v) = widgets::num_field(ui, ("cb-shape-r", i), Some(radii[i]), unit, 44.0) { + let mut next = radii; + next[i] = v.max(0.0); + apply_shape(app, &[("cornerRadii", json!(next))], json!({ "radii": next })); + } + } + } + ui.separator(); + draw_arc_controls(app, ui, start_deg, end_deg, mode); + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape( + app, + &[ + ("cornerRadius", json!(0.0)), + ("cornerRadii", json!([0.0, 0.0, 0.0, 0.0])), + ("arcMode", json!("whole")), + ("arcStart", json!(0.0)), + ("arcEnd", json!(0.0)), + ], + json!({ "reset": true }), + ); + } + ui.separator(); +} + +fn draw_polygon_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, active_shape: &str, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let mut is_star = if active_shape == "star" { true } else { opts["polyIsStar"].as_bool().unwrap_or(false) }; + let mut count = if is_star { opts["points"].as_u64().unwrap_or(5) } else { opts["sides"].as_u64().unwrap_or(6) } as u32; + let mut spoke = opts["starRatio"].as_f64().unwrap_or(0.5); + let mut rounded = opts["rounded"].as_f64().unwrap_or(0.0); + let mut randomized = opts["randomized"].as_f64().unwrap_or(0.0); + let (mut start_deg, mut end_deg, mut mode) = + (opts["arcStart"].as_f64().unwrap_or(0.0), opts["arcEnd"].as_f64().unwrap_or(0.0), opts["arcMode"].as_str().unwrap_or("whole")); + if let Some(CustomShape::Polygon { sides, spoke_ratio, rounded: rnd, randomized: rand, pie: (a0, a1), arc_mode, .. }) = selected_custom { + count = sides; + is_star = spoke_ratio.is_some(); + if let Some(sr) = spoke_ratio { + spoke = sr; + } + rounded = rnd; + randomized = rand; + start_deg = a0; + end_deg = a1; + mode = mode_str(arc_mode); + } + if widgets::icon_button(ui, "dc-polygon", tl!("Polygon"), !is_star, 22.0).clicked() { + apply_shape(app, &[("polyIsStar", json!(false))], json!({ "isStar": false })); + } + if widgets::icon_button(ui, "star", tl!("Star"), is_star, 22.0).clicked() { + apply_shape(app, &[("polyIsStar", json!(true))], json!({ "isStar": true, "spokeRatio": spoke })); + } + widgets::field_label(ui, egui::RichText::new(if is_star { tl!("Points:") } else { tl!("Sides:") }).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-corners"), f64::from(count), "", 0, 44.0) { + let c = (v.round() as i64).clamp(3, 1000) as u32; + apply_shape(app, &[("sides", json!(c)), ("points", json!(c))], json!({ "sides": c })); + } + if is_star { + widgets::field_label(ui, egui::RichText::new(tl!("Ratio")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-spoke"), spoke, "", 2, 46.0) { + let sr = v.clamp(0.01, 1.0); + apply_shape(app, &[("starRatio", json!(sr))], json!({ "spokeRatio": sr })); + } + } + widgets::field_label(ui, egui::RichText::new(tl!("Round")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-round"), rounded, "", 2, 46.0) { + let rnd = v.clamp(-10.0, 10.0); + apply_shape(app, &[("rounded", json!(rnd))], json!({ "rounded": rnd })); + } + widgets::field_label(ui, egui::RichText::new(tl!("Random")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "poly-rand"), randomized, "", 2, 46.0) { + let rand = v.clamp(-10.0, 10.0); + apply_shape(app, &[("randomized", json!(rand))], json!({ "randomized": rand })); + } + ui.separator(); + draw_arc_controls(app, ui, start_deg, end_deg, mode); + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape( + app, + &[("rounded", json!(0.0)), ("randomized", json!(0.0)), ("arcMode", json!("whole")), ("arcStart", json!(0.0)), ("arcEnd", json!(0.0))], + json!({ "reset": true }), + ); + } + ui.separator(); +} + +fn draw_spiral_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let (mut turns, mut divergence, mut inner_r) = + (opts["turns"].as_f64().unwrap_or(3.0), opts["divergence"].as_f64().unwrap_or(1.0), opts["innerRadius"].as_f64().unwrap_or(0.0)); + if let Some(CustomShape::Spiral { turns: t_v, divergence: div_v, inner_radius: ir_v, .. }) = selected_custom { + turns = t_v; + divergence = div_v; + inner_r = ir_v; + } + widgets::field_label(ui, egui::RichText::new(tl!("Segments")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "spiral-turns"), turns, "", 2, 50.0) { + let tv = v.clamp(0.01, 1024.0); + apply_shape(app, &[("turns", json!(tv))], json!({ "turns": tv })); + } + widgets::field_label(ui, egui::RichText::new(tl!("Ratio")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "spiral-div"), divergence, "", 2, 50.0) { + let dv = v.clamp(0.0, 1000.0); + apply_shape(app, &[("divergence", json!(dv))], json!({ "divergence": dv })); + } + widgets::field_label(ui, egui::RichText::new(tl!("Inner Radius:")).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-shape", "spiral-inner"), inner_r, "", 2, 50.0) { + let iv = v.clamp(0.0, 0.999); + apply_shape(app, &[("innerRadius", json!(iv))], json!({ "innerRadius": iv })); + } + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape(app, &[("turns", json!(3.0)), ("divergence", json!(1.0)), ("innerRadius", json!(0.0))], json!({ "reset": true })); + } + ui.separator(); +} + +fn draw_box3d_controls(app: &mut VectorcraftApp, ui: &mut Ui, opts: &Value, selected_custom: Option) { + let t = Tokens::get(ui.ctx()); + let (mut ax, mut ay, mut az) = + (opts["angleX"].as_f64().unwrap_or(30.0), opts["angleY"].as_f64().unwrap_or(30.0), opts["angleZ"].as_f64().unwrap_or(0.0)); + let (mut px, mut py, mut pz) = + (opts["parallelX"].as_bool().unwrap_or(false), opts["parallelY"].as_bool().unwrap_or(true), opts["parallelZ"].as_bool().unwrap_or(false)); + if let Some(CustomShape::Box3d { angle_x, angle_y, angle_z, parallel_x, parallel_y, parallel_z, .. }) = selected_custom { + ax = angle_x; + ay = angle_y; + az = angle_z; + px = parallel_x; + py = parallel_y; + pz = parallel_z; + } + for (lbl, a_key, p_key, a_val, p_val) in + [("X:", "angleX", "parallelX", ax, px), ("Y:", "angleY", "parallelY", ay, py), ("Angle:", "angleZ", "parallelZ", az, pz)] + { + widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); + if let Some(v) = widgets::plain_field(ui, ("cb-box3d", a_key), a_val, "°", 1, 52.0) { + apply_shape(app, &[(a_key, json!(v))], json!({ a_key: v })); + } + if widgets::icon_button(ui, "dc-line", tl!("Link"), p_val, 20.0).clicked() { + let next = !p_val; + apply_shape(app, &[(p_key, json!(next))], json!({ p_key: next })); + } + } + if widgets::flat_button(ui, tl!("Reset"), 52.0).clicked() { + apply_shape( + app, + &[ + ("angleX", json!(30.0)), + ("angleY", json!(30.0)), + ("angleZ", json!(0.0)), + ("parallelX", json!(false)), + ("parallelY", json!(true)), + ("parallelZ", json!(false)), + ], + json!({ "reset": true }), + ); + } + ui.separator(); +} + +fn mode_str(m: EllipseMode) -> &'static str { + match m { + EllipseMode::Slice => "pie", + EllipseMode::Chord => "chord", + EllipseMode::Arc => "arc", + EllipseMode::Whole => "whole", + } +} diff --git a/crates/ui-egui/src/addons/typetools.rs b/crates/ui-egui/src/addons/typetools.rs index f9bfa3ca36..859c69fa3d 100644 --- a/crates/ui-egui/src/addons/typetools.rs +++ b/crates/ui-egui/src/addons/typetools.rs @@ -34,9 +34,18 @@ const SEEDS: u64 = 1_000_000; const LABEL_W: f32 = 90.0; const FIELD_W: f32 = 90.0; +/// Release Type on a Path's command. Its menu item opens the generic command dialog +/// (`ui.paramDialog`) on these options, with a Preview (`dialogs::command`). +pub const RELEASE: &str = "addon.type.releasePath"; +/// Release Type on a Path › Keep: what the command's `mode` takes, by name. +pub const RELEASE_MODES: &[(&str, &str)] = &[("Text and Path", "both"), ("Path Only", "path"), ("Text Only", "text")]; + /// Object › Plug-ins › Type Tools. pub fn menu() -> Vec { - vec![Item::Cmd("Text Tweaker…", COMMAND, Value::Null)] + vec![ + Item::Cmd("Text Tweaker…", COMMAND, Value::Null), + Item::Cmd("Release Type on a Path…", RELEASE, json!({"mode": "both", "keepOriginal": false})), + ] } /// The attribute row of param `key` (the first, Font Size, for an unknown one). diff --git a/crates/ui-egui/src/addons/typetools/tests.rs b/crates/ui-egui/src/addons/typetools/tests.rs index 36e3ef2f31..e7118de082 100644 --- a/crates/ui-egui/src/addons/typetools/tests.rs +++ b/crates/ui-egui/src/addons/typetools/tests.rs @@ -60,3 +60,69 @@ fn another_attribute_starts_from_its_own_values() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.fields["from"].clone(), d.fields["to"].clone()), (json!(0.0), json!(30.0))); } + +/// The kind of object `id` is, and whether it is type on a path. +fn on_path(app: &VectorcraftApp, id: NodeId) -> Option { + match &app.session.doc().unwrap().doc.node(id)?.kind { + NodeKind::Text(t) => Some(matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })), + _ => None, + } +} + +/// #5532: Object › Plug-ins › Type Tools › Release Type on a Path… opens the command dialog on +/// Text and Path, Keep Original off, with Preview off. With Preview on the canvas shows the +/// release while the dialog is open; Cancel puts the type back with no step of history, and OK +/// keeps it as one step. +#[test] +fn release_type_on_a_path_previews_cancels_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let path = app.run("path.create", json!({"d": "M100 200 C200 100 400 100 500 200"})).unwrap()["id"].as_u64().unwrap(); + let id = NodeId(app.run("text.createInPath", json!({"path": path, "mode": "onPath", "text": "Release me"})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Type Tools"] && e.label == "Release Type on a Path…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::RELEASE.to_string(), "Release Type on a Path".to_string())); + assert_eq!((d.str("mode"), d.bool("keepOriginal"), d.bool("preview")), ("both".to_string(), false, false)); + assert!(crate::dialogs::accepts_field(d, "preview")); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Release Type on a Path", "Mode:", "Text and Path", "Keep Original", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(on_path(&app, id), Some(true), "no preview without the checkbox"); + + // Preview on: the type is released on the canvas; another mode replaces that preview. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(on_path(&app, id), Some(false), "previewed as point type"); + app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("path")); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(on_path(&app, id), None, "path only: the type is gone in the preview"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel restores the type"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + // OK: one step, the released objects selected. + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(on_path(&app, id), Some(false)); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "the path and the text are selected"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, start); +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7826cdfe32..4698856dfd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -54,11 +54,13 @@ impl VectorcraftApp { // ([`place::place_from_cursor`]). session.place_cursor_requests = true; let views = session.documents().iter().map(View::of).collect(); + let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); Self { session, ui: UiState::default(), views, + view_uids, services, canvas: CanvasCache { renderer: vectorcraft_render::Renderer::new(), @@ -102,6 +104,8 @@ impl VectorcraftApp { clipboard_publishing: Default::default(), pending_url: None, control_rx: None, + deferred_control: None, + synthetic_dropped_before: 0, pending_screenshots: vec![], queued_screenshots: vec![], screenshot_token: 0, @@ -192,6 +196,9 @@ impl VectorcraftApp { if let Some(read) = s.read.take() { s.read = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| read(p)))); } + if let Some(read_head) = s.read_head.take() { + s.read_head = Some(Box::new(move |p: &str, max: usize| file_access::check_read(p).and_then(|()| read_head(p, max)))); + } if let Some(mut write) = s.write.take() { s.write = Some(Box::new(move |p: &str, b: &[u8]| file_access::check_write(p).and_then(|()| write(p, b)))); } @@ -276,6 +283,7 @@ impl VectorcraftApp { let now = now_secs(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A // background thread reads it where the host installs one (an unresponsive owner must never @@ -311,6 +319,7 @@ impl VectorcraftApp { placing::poll(self); #[cfg(not(target_arch = "wasm32"))] self.tick_link_updates(ctx, now); + crate::addons::select::link_status::refresh(self, now); if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() || !self.plugin_runs.running.is_empty() diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 775248a611..0652e6d9a6 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,6 +1,7 @@ use super::fonts::MAX_RECENT_FONTS; use super::{Value, VectorcraftApp, dialogs, fileio, io, menus, panels, picks, toolbar}; use crate::placing; +use crate::state::ReplaceFontWarning; /// The last repeatable Pathfinder operation completed by a command or atomic batch. fn completed_pathfinder_operation<'a>(id: &'a str, params: &'a Value) -> Option<&'a str> { @@ -12,6 +13,63 @@ fn completed_pathfinder_operation<'a>(id: &'a str, params: &'a Value) -> Option< } } +fn substitute_style_description(font: &Value) -> Option { + if font["status"] != "substitute" { + return None; + } + let family = font["family"].as_str()?; + let style = font["style"].as_str()?; + let resolved_family = font["resolved"]["family"].as_str()?; + let resolved_style = font["resolved"]["style"].as_str()?; + Some(format!("{family} {style} is drawn in {resolved_family} {resolved_style}")) +} + +fn substitute_warnings(fonts: &[Value], styles: &[(String, String)]) -> (Vec, Vec) { + let mut missing = Vec::new(); + let mut live_styles = Vec::new(); + for font in fonts.iter().filter(|font| { + styles.iter().any(|(family, style)| { + font["family"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(family)) + && font["style"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(style)) + }) + }) { + match font["status"].as_str() { + Some("missing") => { + if let Some(family) = font["family"].as_str() { + missing.push(family.to_string()); + } + } + Some("substitute") => { + if let Some(description) = substitute_style_description(font) { + live_styles.push(description); + } + } + _ => {} + } + } + missing.sort(); + missing.dedup(); + live_styles.sort(); + live_styles.dedup(); + (missing, live_styles) +} + +#[cfg(test)] +#[test] +fn substitute_warnings_follow_current_font_inventory() { + let styles = vec![("Source Sans 3".to_string(), "Black Wide".to_string())]; + let replaced_face = serde_json::json!([{ + "family": "Source Sans 3", "style": "Black Wide", "status": "substitute", + "resolved": {"family": "Inter", "style": "Bold"} + }]); + assert_eq!( + substitute_warnings(replaced_face.as_array().unwrap(), &styles), + (Vec::::new(), vec!["Source Sans 3 Black Wide is drawn in Inter Bold".to_string()]) + ); + let removed_family = serde_json::json!([{"family": "Source Sans 3", "style": "Black Wide", "status": "missing"}]); + assert_eq!(substitute_warnings(removed_family.as_array().unwrap(), &styles), (vec!["Source Sans 3".to_string()], Vec::::new())); +} + impl VectorcraftApp { /// Run a UI or engine command by id. The single entry point for every frontend path. pub fn run(&mut self, id: &str, params: Value) -> Result { @@ -145,6 +203,7 @@ impl VectorcraftApp { self.publish_clipboard(); } self.sync_views(); + self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. self.follow_artboard_tool(artboards); match &r { @@ -188,22 +247,113 @@ impl VectorcraftApp { r.insert(0, font.to_string()); r.truncate(MAX_RECENT_FONTS); } - if id == "text.replaceFont" - && v.get("warning").is_none() - && self.ui.status.starts_with("some text is hidden or locked, so its font wasn't replaced") - { - self.ui.status.clear(); + if id == "text.replaceFont" { + self.update_replace_font_status(¶ms, v); } // A command's warning (Rasterize's when an image couldn't be decoded) shows in the // status bar, as a tool preview's does. if let Some(w) = v.get("warning").and_then(Value::as_str) { - self.ui.status = w.to_string(); + self.set_command_warning(id, w); } } } r } + fn set_command_warning(&mut self, id: &str, warning: &str) { + self.ui.status = warning.to_string(); + if id != "text.replaceFont" { + self.ui.replace_font_warning = None; + } + } + + fn update_replace_font_status(&mut self, params: &Value, result: &Value) { + if let Some(warning) = result.get("warning").and_then(Value::as_str) { + let Some((document_uid, revision)) = self.session.active().map(|doc| (doc.uid, doc.revision)) else { + return; + }; + let styles = self + .session + .execute("text.fonts", &serde_json::json!({})) + .ok() + .and_then(|value| value.as_array().cloned()) + .map(|fonts| { + fonts + .iter() + .filter_map(|font| { + let description = substitute_style_description(font)?; + if !warning.contains(&description) { + return None; + } + Some((font["family"].as_str()?.to_string(), font["style"].as_str()?.to_string())) + }) + .collect::>() + }) + .unwrap_or_default(); + let selection: Option> = (params["selectionOnly"] == true) + .then(|| self.session.active().map(|doc| doc.selection.objects.iter().map(|id| id.0).collect()).unwrap_or_default()); + self.ui.replace_font_warning = + Some(ReplaceFontWarning { document_uid, revision, request: params.clone(), selection, text: warning.to_string(), styles }); + return; + } + self.refresh_replace_font_warning(true); + } + + pub(super) fn refresh_replace_font_warning(&mut self, force: bool) { + const SKIPPED: &str = "some text is hidden or locked, so its font wasn't replaced"; + const STYLE_PREFIX: &str = "font styles that aren't available are drawn in the closest style: "; + const STYLE_SUFFIX: &str = " (pick a style the family has)"; + let Some(previous) = self.ui.replace_font_warning.as_ref() else { + return; + }; + let Some(revision) = self.session.active().filter(|doc| doc.uid == previous.document_uid).map(|doc| doc.revision) else { + return; + }; + if (!force && revision == previous.revision) || previous.text != self.ui.status { + return; + } + let had_skipped = self.ui.status.starts_with(SKIPPED); + let had_style = !previous.styles.is_empty(); + if !had_skipped && !had_style { + return; + } + let scoped_selection = previous.selection.as_ref().map(|selected| selected.iter().copied().map(vectorcraft_doc::NodeId).collect::>()); + let skipped_remains = if had_skipped { + self.session.skipped_font_ids(&previous.request, scoped_selection.as_deref()).is_ok_and(|ids| !ids.is_empty()) + } else { + false + }; + let (missing, live_styles) = if had_style { + let Some(fonts) = self.session.font_inventory(scoped_selection.as_deref()).ok().and_then(|value| value.as_array().cloned()) else { + return; + }; + substitute_warnings(&fonts, &previous.styles) + } else { + (Vec::new(), Vec::new()) + }; + let mut parts = Vec::new(); + if skipped_remains { + parts.push(SKIPPED.to_string()); + } + if !missing.is_empty() { + parts.push(format!( + "fonts that aren't available are drawn in the fallback font, {}: {} (install them, or replace them with Find Font)", + vectorcraft_text::FALLBACK_FAMILY, + missing.join(", ") + )); + } + if !live_styles.is_empty() { + parts.push(format!("{STYLE_PREFIX}{}{STYLE_SUFFIX}", live_styles.join(", "))); + } + self.ui.status = parts.join("; "); + if self.ui.status.is_empty() { + self.ui.replace_font_warning = None; + } else if let Some(warning) = &mut self.ui.replace_font_warning { + warning.revision = revision; + warning.text.clone_from(&self.ui.status); + } + } + /// Select a tool (also used by the toolbar and shortcuts). pub fn select_tool(&mut self, id: &str) { // The tip of a pen whose eraser end selected the Eraser doesn't undo this choice. diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index bbdf60befc..2f64432821 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -9,7 +9,30 @@ impl VectorcraftApp { let Some(rx) = self.control_rx.take() else { return }; let mut handled = 0; while handled < control::MAX_CONTROL_REQUESTS_PER_FRAME { - let Ok(req) = rx.try_recv() else { break }; + let Some(req) = self.deferred_control.take().or_else(|| rx.try_recv().ok()) else { break }; + // Synthetic input sent before this tool action was dropped (see + // `discard_stale_injected_batch`): it would reach the tool without that input. + let tool_action = matches!(req.method.as_str(), "ui.pointer" | "ui.tool.select"); + if tool_action && req.made_before(self.synthetic_dropped_before) { + // One its caller gave up is skipped without counting toward this frame's limit. + if req.claim() { + handled += 1; + let _ = req.reply.send(json!({ + "ok": false, + "error": "input sent before this tool action was dropped because the document, dialog or focus changed" + })); + } + continue; + } + // `ui.pointer` and `ui.tool.select` act at once, while `ui.key` and other synthetic + // input reach the tool in a later UI pass. Wait for that earlier input, so a key + // pressed during a drag reaches its tool before a pointer event or tool switch. + // One its caller gave up meanwhile is dropped below instead of holding back the rest. + if tool_action && !req.given_up() && (!self.synthetic.is_empty() || self.synthetic_injected) { + self.deferred_control = Some(req); + ctx.request_repaint(); + break; + } // Its caller stopped waiting (the app was busy or its window not drawn for too long) // and was told it won't run: an edit applied now would come from nowhere (#1725). if !req.claim() { diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2854e11d6a..29baa37d23 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -123,6 +123,9 @@ impl VectorcraftApp { self.synthetic_modifiers = false; self.synthetic_injected = false; self.synthetic_frame = false; + // The `ui.pointer` requests made after this input, waiting or still on the channel, would + // run without it: `drain_control` answers the ones made before now with an error. + self.synthetic_dropped_before = crate::control::ControlRequest::next_seq(); } /// Release the pointer buttons egui still holds down when the system reports that no mouse diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 6b5db4fb5b..9895149917 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -4,13 +4,29 @@ impl VectorcraftApp { /// Keep `views` aligned with the session's documents (a new one starts at its saved view, and /// opens in a floating window while Open Documents As Tabs is cleared). The views Window › New /// Window opened go with their documents. + /// + /// A view stays with its document when documents change order or close (`document.move`, + /// `file.close`, also several of them in one recording or batch, #5663): the views are matched + /// to the documents by the uid each was synced with, a closed document's view is dropped and a + /// new document gets its saved view. pub fn sync_views(&mut self) { let docs = self.session.documents(); + if self.view_uids.len() == self.views.len() && docs.iter().map(|d| d.uid).ne(self.view_uids.iter().copied()) { + let mut old: Vec> = std::mem::take(&mut self.views).into_iter().map(Some).collect(); + self.views = docs + .iter() + .map(|d| { + self.view_uids.iter().position(|u| *u == d.uid).and_then(|k| old.get_mut(k)).and_then(Option::take).unwrap_or_else(|| View::of(d)) + }) + .collect(); + } self.views.truncate(docs.len()); self.views.extend(docs.iter().skip(self.views.len()).map(View::of)); for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); } + self.view_uids = docs.iter().map(|d| d.uid).collect(); + panels::layers::retain_open_thumbs(&self.view_uids); crate::doc_windows::retain_views(self); crate::doc_windows::opened(self); // Undo can remove the Artboard tool's active or additionally selected boards. Repair only diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 06a9f488d3..8e3315e357 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -17,6 +17,7 @@ use crate::{CacheKey, VectorcraftApp, now_ms, widgets}; mod artboards; mod context; +mod contour_bar; mod cursor; mod drag; mod fill; @@ -360,6 +361,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.task_bar && !revolve_edit && !dragging && app.ui.screen_mode < 3 && !strip { task_bar(app, ui, &xf); } + if app.ui.screen_mode < 3 { + contour_bar::contour_bar(app, ui, &xf); + } if app.ui.screen_mode < 3 { crate::free_transform::show(app, ui, xf.rect); } @@ -460,11 +464,12 @@ fn canvas_cursor(app: &mut VectorcraftApp, ui: &Ui, view_info: vectorcraft_engin } Some(hp) if custom - && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused)) + && crate::cursors::paint_glyphs(crate::cursors::HIDES_ONLY_WHEN_KEY, ui.input(|i| i.focused), app.services.no_cursor_theme) && crate::cursors::paint(&painter, c, hp, 1.0 / ui_scale) => { - // No cursor theme (Wayland): the glyph is painted, the system pointer stays (#2450). - if crate::cursors::hide_system_pointer(app.services.no_cursor_theme) { egui::CursorIcon::None } else { cursor_icon(c) } + // The painted glyph stands in for the hidden system pointer. Without a cursor theme + // (Wayland) none is painted: the system pointer can't be hidden there (#2450). + egui::CursorIcon::None } _ => cursor_icon(c), } @@ -545,25 +550,28 @@ fn poll_worker(app: &mut VectorcraftApp, ui: &Ui, key_doc: usize) { app.canvas.fill_worker = crate::render_worker::Worker::spawn(ui.ctx().clone()); } } - // Upload finished background renders whenever they are not older than what is currently - // displayed on screen. This prevents canvas freezes during continuous edits (drags, arrow - // nudges, MCP command bursts) while ensuring obsolete out-of-order frames are dropped. - if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll()) - && done.key.doc == key_doc - { - let not_older = app.canvas.key.as_ref().filter(|k| k.doc == done.key.doc).is_none_or(|k| done.key.revision >= k.revision); - if not_older { - upload(app, ui.ctx(), done.img, done.key.pixel.is_some()); - app.canvas.key = Some(done.key); - app.canvas.shown = Some((done.doc, done.opts)); - app.perf.render_ms = done.ms; - app.canvas.last_ms = done.ms; - app.canvas.moved = done.moved > 0; - app.canvas.from_worker = true; - } + if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll()) { + show_worker_frame(app, ui.ctx(), done, key_doc); } } +/// Upload frame `done` from the render worker when it is of document `key_doc` and not older than +/// the frame shown. This prevents canvas freezes during continuous edits (drags, arrow nudges, MCP +/// command bursts) while ensuring obsolete out-of-order frames are dropped. +fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate::render_worker::Done, key_doc: usize) { + let not_older = app.canvas.key.as_ref().filter(|k| k.doc == done.key.doc).is_none_or(|k| done.key.revision >= k.revision); + if done.key.doc != key_doc || !not_older { + return; + } + upload(app, ctx, done.img, done.key.pixel.is_some()); + app.canvas.key = Some(done.key); + app.canvas.shown = Some((done.doc, done.opts)); + app.perf.render_ms = done.ms; + app.canvas.last_ms = done.ms; + app.canvas.moved = done.moved > 0; + app.canvas.from_worker = true; +} + /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. fn frame_view(pixel: Option<[i64; 4]>, (w, h): (u32, u32), v: &View, ppp: f32) -> (u32, u32, Affine) { match pixel { @@ -640,16 +648,26 @@ struct Frame<'a> { pixel: Option<[i64; 4]>, } +/// How long the UI thread waits for a document's first frame from the render worker before it +/// shows the document's paper without the art: about a frame at 60 Hz. +pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); + fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let Frame { key, doc, size: (w, h), view, opts, pixel } = frame; + // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this // thread's renderer has none, so a frame fast on the worker would be slow here. let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; - let heavy = (app.canvas.last_ms > 8.0 || settling || staying) && app.canvas.texture.is_some() && same_doc; + // A document's first frame (opened, or its tab chosen) renders on the worker too: how long it + // takes is not known yet, and a heavy one froze the window for seconds (#4155). Its paper and + // artboards show meanwhile. + let first = app.canvas.texture.is_none() || !same_doc; + let heavy = first || app.canvas.last_ms > 8.0 || settling || staying; let changed = changed_pixels(app, key, doc, &opts, view, w, h); + let mut landed = None; match (&mut app.canvas.worker, heavy, changed) { // Only the document changed since the frame shown, in a part of it: that part is // rendered again, here, into the texture. `last_ms` stays the whole frame's. @@ -666,15 +684,22 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.shown = Some((doc.clone(), opts.clone())); app.perf.render_ms = now_ms() - t0; } - (Some(worker), true, None) => worker.submit(crate::render_worker::Job { - key: key.clone(), - doc: doc.clone(), - w, - h, - view, - opts, - scope: vectorcraft_engine::file_access::ScopeHandle::capture(), - }), + (Some(worker), true, None) => { + let queued = worker.submit(crate::render_worker::Job { + key: key.clone(), + doc: doc.clone(), + w, + h, + view, + opts, + scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + }); + // A light document's first frame is ready within the grace and shows in this frame, + // with no frame of bare paper. Waited for once, when the frame is queued. + if first && queued { + landed = worker.wait(FIRST_FRAME_GRACE); + } + } _ => { let t0 = now_ms(); let img = app.canvas.renderer.render(doc, w, h, view, &opts); @@ -687,6 +712,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { app.canvas.from_worker = false; } } + if let Some(done) = landed { + show_worker_frame(app, ui.ctx(), done, key.doc); + } } /// The pasteboard, the artboards' shadows and paper, and the outline mode's white artboards, of diff --git a/crates/ui-egui/src/canvas/contour_bar.rs b/crates/ui-egui/src/canvas/contour_bar.rs new file mode 100644 index 0000000000..4b560eeba6 --- /dev/null +++ b/crates/ui-egui/src/canvas/contour_bar.rs @@ -0,0 +1,133 @@ +//! The Contour bar: a floating bar above the selection while the Contour tool is active. It has the +//! Contour's distance in a number box, its corner style (Sharp, Round or Square) and Bake, which +//! turns the live Contour into plain paths. It acts through `addon.contour.set` and +//! `effect.expandAppearance`, so everything it does is a command with its own undo step. + +use serde_json::Value; +use vectorcraft_doc::{Node, NodeKind}; + +use super::{CornerRadius, Stroke, Tokens, Ui, VectorcraftApp, Xf, json, pos2, vec2}; + +/// The live effect a Contour is made of. +const EFFECT: &str = "path.offsetPath"; + +fn bar_id() -> egui::Id { + egui::Id::unique("contour-bar") +} + +/// Where the Contour bar was last drawn (none while it isn't shown). +#[cfg(test)] +pub(super) fn bar_rect(ctx: &egui::Context) -> Option { + let id = bar_id(); + ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) +} + +/// A selected Contour's distance and corner style, read from its Offset Path effect. +struct Standing { + offset: f64, + corners: &'static str, +} + +fn standing(n: &Node) -> Option { + let e = n.appearance.effects.iter().rev().find(|e| e.id == EFFECT)?; + let offset = e.params.get("offset").and_then(Value::as_f64).unwrap_or(0.0); + let corners = match e.params.get("joins").and_then(Value::as_str) { + Some("round") => "round", + Some("bevel") => "square", + _ => "sharp", + }; + Some(Standing { offset, corners }) +} + +/// The Contour bar, over the selection's top edge (under it when the top is off the canvas). +pub(super) fn contour_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { + if app.session.tool_id() != "contour" { + return; + } + let Some(b) = app.selection_bounds() else { return }; + let Some(st) = app.session.active() else { return }; + let shapes: Vec<&Node> = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)) + .filter(|n| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })) + .collect(); + if shapes.is_empty() { + return; + } + let stand = shapes.first().and_then(|n| standing(n)); + drop(shapes); + let tool_corners = app.session.tool_options().get("corners").and_then(Value::as_str).unwrap_or("sharp").to_string(); + let corners = stand.as_ref().map_or(tool_corners.as_str(), |s| s.corners); + let shown = stand.as_ref().map_or(0.0, |s| s.offset); + // A grown Contour reaches past the outline it was made from: keep the bar clear of it. + let b = b.inflate(shown.max(0.0), shown.max(0.0)); + + let t = Tokens::get(ui.ctx()); + let quad = xf.quad(b); + let top = quad.iter().map(|c| c.y).fold(f32::INFINITY, f32::min); + let bottom = quad.iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); + let size = egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size).unwrap_or(vec2(330.0, 40.0)); + let area = xf.rect.shrink(8.0); + let above = top - size.y - 12.0; + let y = if above >= area.top() { above } else { bottom + 12.0 }; + let at = pos2(xf.to_screen(b.center()).x - size.x / 2.0, y); + let at = at.clamp(area.min, (area.max - size).max(area.min)); + + let mut run: Option<(&str, Value)> = None; + let mut corner_pick: Option<&str> = None; + egui::Area::new(bar_id()).order(egui::Order::Middle).fixed_pos(at).show(ui.ctx(), |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.tool_active)) + .corner_radius(CornerRadius::same(5)) + .inner_margin(egui::Margin::symmetric(8, 6)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: egui::Color32::from_black_alpha(70) }) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(egui::RichText::new(tl!("Contour")).color(t.text_strong)); + // The distance: a drag or typed value is applied when it ends, as one step. + let key = egui::Id::unique("contour-bar-offset"); + let mut v = ui.data(|d| d.get_temp::(key)).unwrap_or(shown); + let resp = ui.add(egui::DragValue::new(&mut v).speed(0.5).range(-1e5..=1e5).suffix(" pt")); + if resp.dragged() || resp.has_focus() { + ui.data_mut(|d| d.insert_temp(key, v)); + } + if resp.drag_stopped() || resp.lost_focus() { + ui.data_mut(|d| d.remove_temp::(key)); + if (v - shown).abs() > 1e-9 { + run = Some(("addon.contour.set", json!({"offset": v, "corners": corners}))); + } + } + for (label, id) in [(tl!("Sharp"), "sharp"), (tl!("Round"), "round"), (tl!("Square"), "square")] { + if ui.selectable_label(corners == id, label).clicked() { + corner_pick = Some(id); + } + } + let bake = ui.add_enabled(stand.is_some(), egui::Button::new(tl!("Bake"))); + if bake.on_hover_text(tl!("Turn the Contour into plain paths")).clicked() { + run = Some(("effect.expandAppearance", json!({}))); + } + }); + }); + }); + if let Some(id) = corner_pick { + // The tool keeps the style for the next Contour; a selected Contour changes now. + let mut result = app.run("tool.setOption", json!({"key": "corners", "value": id})); + if result.is_ok() + && let Some(s) = &stand + { + result = app.run("addon.contour.set", json!({"offset": s.offset, "corners": id})); + } + if let Err(e) = result { + app.ui.status = e; + } + } + if let Some((cmd, params)) = run + && let Err(e) = app.run(cmd, params) + { + app.ui.status = e; + } +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b98e186481..206b095cab 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -90,12 +90,21 @@ fn curve_point(p: &egui::Painter, c: Pos2, color: Color32, filled: bool, size: f } pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool) { - // The Selection tool's bounding box (rotated with the objects after a rotation). It hides while - // a drag moves or resizes the selection, so only the art is seen going with the pointer (#712). + // The Selection tool's bounding box (rotated with the objects after a rotation), also shown by + // the shape tools that keep a shape just drawn ready to adjust while they draw none (#5477). It + // hides while a drag moves or resizes the selection, so only the art is seen going with the + // pointer (#712). // With Real-time Drawing off the art waits for the release of a move drag, and the box moves // with the pointer instead. let moved = app.session.deferred_move(); - let show_box = app.session.tool_id() == "selection" + let shape_tool = vectorcraft_tools::shape::shows_shape_widgets(app.session.tool_id()); + // A shape tool drawing a shape shows none of this; adjusting a widget, it shows the widgets. + let drawing = shape_tool && app.session.tool_busy() && !app.session.tool_transforming(); + // Cmd held lends the Selection tool to a press (Direct Selection's included, #3901): its box + // shows while the key is down, where its handles take that press. + let held = super::drag::mods(p.ctx().input(|i| i.modifiers), false); + let lends_selection = !app.session.tool_busy() && app.session.lent_tool_id(&held) == Some("selection"); + let show_box = (app.session.tool_id() == "selection" || lends_selection || (shape_tool && !app.session.tool_busy())) && (!app.session.tool_transforming() || moved.is_some()) && app.ui.view.bounding_box && app.session.active().is_some_and(|st| !st.selection.is_empty() && st.selection.anchors.is_empty()); @@ -250,8 +259,9 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: anchor_square(p, xf.to_screen(a.p), color, false, anchor(direct)); } } - // Live Corners widgets (Selection on a live rectangle or polygon, Direct Selection on any path). - if matches!(tool, "selection" | "directSelection") + // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon, Direct + // Selection on any path). + if (matches!(tool, "selection" | "directSelection") || (shape_tool && !drawing)) && let Some(w) = vectorcraft_tools::corners::CornerWidgets::showing( &st.doc, &st.selection, @@ -287,7 +297,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: } // Pie widgets (Selection tool, with View › Show Bounding Box, on live ellipses): each joined // by a line to the outline's point at its angle. They stay while one is dragged. - if tool == "selection" && app.ui.view.bounding_box { + if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box { for w in vectorcraft_tools::pie::PieWidget::of(&st.doc, &st.selection, xf.zoom) { let (on, c, r, color) = (xf.to_screen(w.on), xf.to_screen(w.at), vectorcraft_tools::pie::RADIUS_PX, c32(st.doc.layer_color(w.id))); p.line_segment([on, c], Stroke::new(1.0, color)); diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e6579d8f31..b5f8dac668 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -48,7 +48,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let Some(b) = (if on_artboards { picked_artboards_bounds(app) } else { app.selection_bounds() }) else { return }; let Some(st) = app.session.active() else { return }; let n = st.selection.len(); - let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let is_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { .. })); let is_image = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Image(_))); let is_clip_group = first.as_ref().is_some_and(|f| matches!(f.kind, NodeKind::Group { clip: true, .. })); @@ -72,13 +72,15 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Selection tool: its properties take the place of Lock, as in the reference app // (). use vectorcraft_doc::LiveShape; - let shape = first.clone().filter(|f| { - n == 1 - && st.selection.anchors.is_empty() - && app.session.tool_id() == "selection" - && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } - if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) - }); + let shape = first + .filter(|f| { + n == 1 + && st.selection.anchors.is_empty() + && app.session.tool_id() == "selection" + && matches!(&f.kind, NodeKind::Path { live: Some(l), .. } + if matches!(**l, LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. })) + }) + .cloned(); let mut items: Vec<(&str, &str, &str, serde_json::Value)> = vec![]; // (label, icon, command, params) let none = || json!({}); if on_artboards { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index edfeebca41..ebfe960bb9 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1466,9 +1466,10 @@ fn a_huge_selection_of_type_images_symbols_or_meshes_shows_its_bounds() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.ui.task_bar = false; - // The Rectangle tool draws nothing of its own (no bounding box, no type on a path - // brackets): only the selection's overlay changes the frame. - app.select_tool("rectangle"); + // The Line Segment tool draws nothing of its own (no bounding box, no type on a path + // brackets; the box-drawing shape tools show the bounding box, #5477): only the + // selection's overlay changes the frame. + app.select_tool("lineSegment"); match kind { "point type" => { app.session.execute("text.create", &json!({"x": 20, "y": 40, "text": "Type"})).unwrap(); @@ -2878,6 +2879,7 @@ fn pixel_grid_shows_in_pixel_preview_from_600_percent() { #[test] fn grid_and_guides_take_their_preferences() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.canvas.worker_started = true; // render on this thread app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); app.ui.view.grid = true; @@ -6233,6 +6235,141 @@ fn ime_edge_orders_never_eat_committed_text_or_lose_the_composition() { assert_eq!(plain(&app, id), "雅がくらくか"); } +/// Starts editing new point type with the Type tool; returns its id. +fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + typing_frame(app, ctx, vec![]); + app.select_tool("type"); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = xf.to_screen(Point::new(100.0, 100.0)); + let click = + |p: Pos2, pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + typing_frame(app, ctx, vec![egui::Event::PointerMoved(at), click(at, true)]); + typing_frame(app, ctx, vec![click(at, false)]); + assert!(app.session.tool_wants_text()); + app.session.active().unwrap().selection.objects[0].0 +} + +/// Returns a key press and its release. +fn tap(key: egui::Key) -> [egui::Event; 2] { + [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) +} + +/// Arrows, Home, End, Tab, Enter and clipboard events go to the Type tool in order with the text +/// of the same frame, and each Enter types a line break. +#[test] +fn the_type_tool_takes_text_and_editing_keys_in_the_order_they_came() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + typing_frame(&mut app, &ctx, vec![text("ax")]); + // ← moves the caret before the text that follows it goes in. + typing_frame(&mut app, &ctx, [tap(egui::Key::ArrowLeft).to_vec(), vec![text("b")]].concat()); + assert_eq!(plain(&app, id), "abx"); + // Home and End move the caret before the text that follows each goes in. + typing_frame(&mut app, &ctx, [tap(egui::Key::Home).to_vec(), vec![text("0")], tap(egui::Key::End).to_vec(), vec![text("9")]].concat()); + assert_eq!(plain(&app, id), "0abx9"); + // Tab and a paste go in between the texts around them. + let paste = egui::Event::Paste("p".into()); + typing_frame(&mut app, &ctx, [vec![text("t")], tap(egui::Key::Tab).to_vec(), vec![text("u"), paste, text("q")]].concat()); + assert_eq!(plain(&app, id), "0abx9t\tupq"); + // Enter types its line break between the texts around it, once for each press. + typing_frame(&mut app, &ctx, [vec![text("1")], tap(egui::Key::Enter).to_vec(), tap(egui::Key::Enter).to_vec(), vec![text("2")]].concat()); + assert_eq!(plain(&app, id), "0abx9t\tupq1\n\n2"); + // A key that comes before a composition starts in the same frame still moves the caret. + typing_frame(&mut app, &ctx, [tap(egui::Key::Home).to_vec(), vec![preedit("k", 1)]].concat()); + typing_frame(&mut app, &ctx, vec![preedit("", 0), egui::Event::Ime(egui::ImeEvent::Commit("k".into()))]); + assert_eq!(plain(&app, id), "0abx9t\tupq1\n\nk2"); +} + +/// Enter keeps each key event's modifiers while sharing a frame with typed text. +#[test] +fn shift_enter_types_a_soft_return_in_order_with_plain_enter() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + let enter = + |modifiers| [true, false].map(|pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers }); + typing_frame( + &mut app, + &ctx, + [vec![text("a")], enter(egui::Modifiers::SHIFT).to_vec(), vec![text("b")], enter(egui::Modifiers::NONE).to_vec(), vec![text("c")]].concat(), + ); + assert_eq!(plain(&app, id), "a\u{2028}b\nc"); +} + +/// Within one frame, Home between two texts, Tab inside a line, and Backspace after a paste each +/// act on the text as the events before them left it. +#[test] +fn home_tab_and_backspace_act_on_the_text_before_them_in_the_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + typing_frame(&mut app, &ctx, vec![text("abc")]); + typing_frame(&mut app, &ctx, [vec![text("d")], tap(egui::Key::Home).to_vec(), vec![text("0")]].concat()); + assert_eq!(plain(&app, id), "0abcd"); + typing_frame(&mut app, &ctx, [tap(egui::Key::ArrowRight).to_vec(), tap(egui::Key::Tab).to_vec(), vec![text("t")]].concat()); + assert_eq!(plain(&app, id), "0a\ttbcd"); + typing_frame(&mut app, &ctx, [tap(egui::Key::End).to_vec(), vec![egui::Event::Paste("pq".into())], tap(egui::Key::Backspace).to_vec()].concat()); + assert_eq!(plain(&app, id), "0a\ttbcdp"); +} + +/// In a frame that began composing, an editing key after the IME's commit applies before the text +/// that follows it; a key before the commit and an Enter after it stay the IME's. +#[test] +fn editing_keys_after_an_ime_commit_apply_in_the_same_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let text = |t: &str| egui::Event::Text(t.into()); + let commit = |t: &str| egui::Event::Ime(egui::ImeEvent::Commit(t.into())); + typing_frame(&mut app, &ctx, vec![text("ab")]); + typing_frame(&mut app, &ctx, vec![preedit("漢", 1)]); + typing_frame(&mut app, &ctx, [vec![preedit("", 0), commit("漢")], tap(egui::Key::ArrowLeft).to_vec(), vec![text("x")]].concat()); + assert_eq!(plain(&app, id), "abx漢"); + typing_frame(&mut app, &ctx, vec![preedit("字", 1)]); + let keys = [tap(egui::Key::ArrowLeft).to_vec(), vec![preedit("", 0), commit("字")], tap(egui::Key::Enter).to_vec()]; + typing_frame(&mut app, &ctx, keys.concat()); + assert_eq!(plain(&app, id), "abx字漢"); +} + +/// Cmd/Ctrl+Enter bound to a command runs the command and types no line break, also when a plain +/// Enter comes in the same frame. Unbound, it types a line break as Enter does. +#[test] +fn a_command_on_cmd_enter_runs_without_typing_a_line_break() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = egui::Context::default(); + let id = start_typing(&mut app, &ctx); + let cmd_enter = [true, false].map(|pressed| egui::Event::Key { + key: egui::Key::Enter, + physical_key: None, + pressed, + repeat: false, + modifiers: egui::Modifiers::COMMAND, + }); + typing_frame(&mut app, &ctx, vec![egui::Event::Text("a".into())]); + typing_frame(&mut app, &ctx, cmd_enter.to_vec()); + assert_eq!(plain(&app, id), "a\n", "nothing is bound to Cmd+Enter"); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "view.grid", "Cmd+Enter"); + crate::shortcut_editor::sync(&app.ui); + let grid = app.ui.view.grid; + typing_frame(&mut app, &ctx, cmd_enter.to_vec()); + let ran = (plain(&app, id), app.ui.view.grid); + typing_frame(&mut app, &ctx, [tap(egui::Key::Enter).to_vec(), cmd_enter.to_vec()].concat()); + app.ui.shortcut_overrides.clear(); + crate::shortcut_editor::sync(&app.ui); + assert_eq!((ran.0.as_str(), ran.1), ("a\n", !grid), "Cmd+Enter runs Show Grid only"); + assert_eq!((plain(&app, id).as_str(), app.ui.view.grid), ("a\n\n", grid), "Enter types a line break and Cmd+Enter runs Show Grid"); +} + /// Reset to a blank document, select the Type tool and click document point (100, 100), returning /// the screen position used by IME fixtures. fn type_at(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::Pos2 { @@ -8988,3 +9125,182 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra assert_eq!(set_count, 1, "settled frame 10 is uploaded to texture"); assert_eq!(app.canvas.key.as_ref().unwrap().revision, 10, "settled frame 10 is uploaded"); } + +/// The labels the Contour bar draws in a headless frame, with their rects; none while it isn't +/// shown. +fn contour_bar_labels(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, egui::Rect)> { + egui_extras::install_image_loaders(ctx); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let Some(bar) = contour_bar::bar_rect(ctx) else { return vec![] }; + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) if bar.contains(t.visual_bounding_rect().center()) => Some((t.galley.text().to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect() +} + +/// A click on the centre of the label `name` of the Contour bar, laid out by one frame before it. +fn click_contour_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let labels = contour_bar_labels(app, ctx, vec![]); + let at = labels.iter().find(|(t, _)| t == name).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{name}` in {labels:?}")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + contour_bar_labels(app, ctx, vec![egui::Event::PointerMoved(at)]); + contour_bar_labels(app, ctx, vec![button(true), button(false)]); +} + +/// The Contour bar shows with the Contour tool and a shape selected: Sharp, Round and Square set the +/// corner style (of a selected Contour at once, else of the next one), and Bake turns a Contour into +/// plain paths. +#[test] +fn the_contour_bar_sets_corners_and_bakes() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + + // Only the Contour tool shows it. + app.select_tool("selection"); + assert!(contour_bar_labels(&mut app, &ctx, vec![]).is_empty()); + app.select_tool("contour"); + contour_bar_labels(&mut app, &ctx, vec![]); + let names: Vec = contour_bar_labels(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for want in ["Contour", "Sharp", "Round", "Square", "Bake"] { + assert!(names.iter().any(|n| n == want), "{want} in {names:?}"); + } + let offsets = |app: &VectorcraftApp| { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let Some(e) = n.appearance.effects.iter().find(|e| e.id == "path.offsetPath") { + found.push(e.params["joins"].as_str().unwrap_or_default().to_string()); + } + }); + found + }; + + // No Contour yet: Round is kept for the next one, and Bake does nothing. + let steps = app.session.active().unwrap().history.undo.len(); + click_contour_bar(&mut app, &ctx, "Round"); + assert_eq!(app.session.tool_options()["corners"], json!("round")); + click_contour_bar(&mut app, &ctx, "Bake"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "nothing to bake"); + assert!(offsets(&app).is_empty()); + + // A Contour made now has round corners; Square changes the selected Contour in place. + app.session.execute("addon.contour.set", &json!({"offset": 8, "corners": "round"})).unwrap(); + assert_eq!(offsets(&app), ["round"]); + click_contour_bar(&mut app, &ctx, "Square"); + assert_eq!(offsets(&app), ["bevel"], "the selected Contour changed, none was added"); + + // Bake: the live effect is gone and the art stays. + click_contour_bar(&mut app, &ctx, "Bake"); + assert!(offsets(&app).is_empty(), "baked"); +} + +/// A frame the render worker finished for `job`: white pixels of the job's size. +fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { + let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; + crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), opts: job.opts.clone(), img, ms: 40.0, moved: 0 } +} + +/// #4155: a document's first frame renders on the render worker, not on the UI thread, where a +/// heavy one froze the window for seconds while it opened. The canvas shows the document's paper +/// meanwhile, does not queue the frame again while it renders, and shows it once it lands. +#[test] +fn a_documents_first_frame_renders_on_the_worker() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, done_tx) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let frame = |app: &mut VectorcraftApp| ctx.run_ui(raw.clone(), |ui| show(app, ui)).textures_delta.clear(); + + frame(&mut app); + let job = jobs.try_recv().expect("the first frame is queued on the worker"); + assert!(app.canvas.texture.is_none(), "not rendered on the UI thread"); + frame(&mut app); + // A placed document of a test running beside this one moves the process-wide generation in + // the key: that makes a new frame, not this one again. + assert!(jobs.try_iter().all(|j| j.key.placed != job.key.placed), "not queued again while it renders"); + assert!(app.canvas.texture.is_none()); + + done_tx.send(finished(&job)).unwrap(); + frame(&mut app); + assert!(app.canvas.texture.is_some(), "shown once it lands"); + assert_eq!(app.canvas.key.as_ref(), Some(&job.key)); + assert!(app.canvas.from_worker); +} + +/// The canvas waits for a document's first frame only briefly (`FIRST_FRAME_GRACE`): `wait` +/// returns a frame finished before or during the wait, clearing the pending job, and nothing once +/// the time is up. +#[test] +fn the_render_worker_waits_for_a_frame_only_as_long_as_asked() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + let (worker, jobs, _) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0))), ..Default::default() }; + ctx.run_ui(raw, |ui| show(&mut app, ui)).textures_delta.clear(); + let job = jobs.try_recv().expect("a job to finish"); + + let (mut w, _, done_tx) = crate::render_worker::Worker::test_channel(); + let t0 = std::time::Instant::now(); + assert!(w.wait(std::time::Duration::from_millis(20)).is_none()); + assert!(t0.elapsed() >= std::time::Duration::from_millis(20), "waited the time asked"); + + w.pending = Some(job.key.clone()); + done_tx.send(finished(&job)).unwrap(); + assert_eq!(w.wait(std::time::Duration::from_secs(5)).map(|d| d.key), Some(job.key.clone()), "finished before the wait"); + assert!(w.pending.is_none()); + + let late = finished(&job); + let sender = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(30)); + done_tx.send(late).unwrap(); + }); + assert!(w.wait(std::time::Duration::from_secs(5)).is_some(), "finished during the wait"); + sender.join().unwrap(); +} + +/// #3901: with Direct Selection, the Selection tool's bounding box shows while Cmd/Ctrl is held +/// (a press then takes its handles), and not otherwise. +#[test] +fn direct_selection_shows_the_bounding_box_while_cmd_is_held() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("directSelection"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let corner = xf.to_screen(Point::new(200.0, 150.0)); + // A frame with `modifiers` held → is a white box handle drawn at the bottom-right corner? + let handle_drawn = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + let screen = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect: screen, events: vec![egui::Event::ModifiersChanged(modifiers)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); // the render worker's frame can land in any of these + fn flat(s: Shape, out: &mut Vec) { + match s { + Shape::Vec(v) => v.into_iter().for_each(|s| flat(s, out)), + s => out.push(s), + } + } + let mut v = vec![]; + out.shapes.into_iter().for_each(|c| flat(c.shape, &mut v)); + v.iter().any(|s| matches!(s, Shape::Rect(r) if r.fill == Color32::WHITE && (r.rect.width() - 6.0).abs() < 1.0 && r.rect.center().distance(corner) < 0.5)) + }; + assert!(!handle_drawn(&mut app, egui::Modifiers::NONE), "Direct Selection alone shows no box"); + assert!(handle_drawn(&mut app, egui::Modifiers::COMMAND), "Cmd held shows the Selection tool's box"); + assert!(!handle_drawn(&mut app, egui::Modifiers::NONE), "gone once Cmd is released"); + assert!(app.ui.view.bounding_box, "View › Show Bounding Box is unchanged"); +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index eecaa22fd3..41d73ffaef 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -28,7 +28,7 @@ pub use status_bar::status_bar; #[cfg(test)] use status_bar::{StatusReadoutWidths, status_readouts}; #[cfg(test)] -use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_title}; +use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index df58c1be7a..9afbe838eb 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -172,13 +172,95 @@ fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { /// language, the four fields, the W/H link and the item spacing ahead of each of them. With less, /// only the Transform link shows. fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { - let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; - let labels: f32 = INLINE_FIELDS.iter().map(|(_, lbl)| measure(inline_label(t, lbl).into())).sum(); + let labels: f32 = INLINE_FIELDS.iter().map(|(_, lbl)| widgets::text_width(ui, inline_label(t, lbl))).sum(); let fields = INLINE_FIELD_WIDTH * INLINE_FIELDS.len() as f32; let items = 2 * INLINE_FIELDS.len() + 1; labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 } +/// The size of the Control bar's Align, Distribute and area type vertical alignment buttons. +const BUTTON: f32 = 24.0; + +/// The space ahead of the separator that ends a group of the Control bar's controls. +const GROUP_GAP: f32 = 4.0; + +/// The width of the separators of the Control bar's [`group_end`] and ahead of the Transform link. +const SEPARATOR: f32 = 6.0; + +/// The widths of the Document Setup and Preferences buttons, shown with nothing selected. +const DOCUMENT_SETUP_WIDTH: f32 = 112.0; +const PREFERENCES_WIDTH: f32 = 90.0; + +/// The room `n` of the bar's buttons take, with the spacing after each. +fn buttons_width(ui: &Ui, n: usize) -> f32 { + (BUTTON + ui.spacing().item_spacing.x) * n as f32 +} + +/// The separator that ends a group of the Control bar's controls, as [`group_end_width`] measures it. +fn group_end(ui: &mut Ui) { + ui.add_space(GROUP_GAP); + separator(ui); +} + +fn group_end_width(ui: &Ui) -> f32 { + GROUP_GAP + separator_width(ui) +} + +/// A separator [`SEPARATOR`] wide. +fn separator(ui: &mut Ui) { + ui.add(egui::Separator::default().spacing(SEPARATOR)); +} + +fn separator_width(ui: &Ui) -> f32 { + SEPARATOR + ui.spacing().item_spacing.x +} + +/// The room the controls at the end of the Control bar need: the Transform link, or Document Setup +/// and Preferences with nothing selected. The groups ahead of them (the Paragraph section, area +/// type's vertical alignment, the Align and Distribute buttons) show only while it is left, so +/// the bar trims them from its right end (#5372), after the inline X/Y/W/H fields. +fn end_width(ui: &Ui, nothing_selected: bool) -> f32 { + if nothing_selected { DOCUMENT_SETUP_WIDTH + ui.spacing().item_spacing.x + PREFERENCES_WIDTH } else { crate::panels::transform::link_width(ui) } +} + +/// Draws the Control bar's groups between its Character controls and the Transform link, and +/// returns whether the Transform link and X/Y/W/H follow (false: nothing is selected, and Document +/// Setup and Preferences, drawn here, end the bar). The groups are the Paragraph section and area +/// type's vertical alignment (#3759), then the Align buttons and, for two or more objects, the +/// Distribute buttons (a single object keeps the bar as it was); each shows only while the end of +/// the bar keeps its room. +fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize) -> bool { + let nothing = objects == 0; + if crate::panels::paragraph::control_bar(app, ui, BUTTON, |ui| group_end_width(ui) + end_width(ui, nothing)) { + group_end(ui); + } + if crate::panels::properties::vertical_align::shown(app).is_some() + && ui.available_width() >= buttons_width(ui, 4) + group_end_width(ui) + end_width(ui, nothing) + && crate::panels::properties::vertical_align::buttons(app, ui, BUTTON) + { + group_end(ui); + } + if nothing { + if widgets::flat_button(ui, tl!("Document Setup"), DOCUMENT_SETUP_WIDTH).clicked() { + app.run("file.documentSetup", json!({})).ok(); + } + if widgets::flat_button(ui, tl!("Preferences"), PREFERENCES_WIDTH).clicked() { + app.run("edit.preferences", json!({})).ok(); + } + return false; + } + let end = separator_width(ui) + end_width(ui, false); + if ui.available_width() >= buttons_width(ui, 7) + end { + crate::panels::align::align_buttons(app, ui, BUTTON); + if objects > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) + end { + ui.add_space(GROUP_GAP); + crate::panels::align::distribute_buttons(app, ui, BUTTON); + } + separator(ui); + } + true +} + /// The Control bar (Window → Control), context-sensitive like Illustrator's. pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); @@ -203,9 +285,9 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let sel = st.selection.objects.clone(); let units = app.session.general_unit(); - let first = sel.first().and_then(|id| st.doc.node(*id)).cloned(); + let first = sel.first().and_then(|id| st.doc.node(*id)); let anchors = anchor_controls(app); - let label = match &first { + let label = match first { _ if app.session.tool_id() == "artboard" => tl!("Artboard"), Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { tl!("Anchor Point") @@ -222,6 +304,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } _ => tl!(crate::panels::appearance::object_label(app)), }; + let has_first = first.is_some(); ui.label(egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text)); // With the Artboard tool in use, the bar shows the active artboard's controls in place // of the object controls. @@ -238,7 +321,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { crate::toolbar::control_bar_options(app, ui); crate::dialogs::envelope::control_bar(app, ui); crate::panels::symbols::control_bar(app, ui); - let opacity = if first.is_some() { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; + let opacity = if has_first { crate::panels::current_transparency(app).map_or(1.0, |t| t.0) } else { 1.0 }; if !image { let shown_stroke = crate::panels::current_stroke(app); let mixed = crate::panels::stroke_mixed(app, ui.ctx()); @@ -255,7 +338,8 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); ui.separator(); } - if ui.link(egui::RichText::new(tl!("Opacity:")).size(12.0).color(t.text).underline()).clicked() { + // A click opens the Transparency panel; a drag scrubs the field (#4088). + if crate::scrub::link_label(ui, egui::RichText::new(tl!("Opacity:")).size(12.0).color(t.text).underline()).clicked() { app.ui.open_panel = Some("transparency".into()); } if let Some(o) = widgets::plain_field(ui, "cb-opacity", opacity as f64 * 100.0, "%", 0, 56.0) @@ -282,28 +366,9 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); crate::panels::character::control_bar(app, ui); - // Area type: its vertical alignment in the frame (#3759). - if crate::panels::properties::vertical_align::buttons(app, ui, 24.0) { - ui.add_space(4.0); - ui.separator(); - } - if sel.is_empty() { - if widgets::flat_button(ui, tl!("Document Setup"), 112.0).clicked() { - app.run("file.documentSetup", json!({})).ok(); - } - if widgets::flat_button(ui, tl!("Preferences"), 90.0).clicked() { - app.run("edit.preferences", json!({})).ok(); - } + if !groups_before_transform(app, ui, sel.len()) { return; } - crate::panels::align::align_buttons(app, ui, 24.0); - // Two or more objects get the six Distribute Objects buttons too; a single - // object keeps the bar as it was. - if sel.len() > 1 { - ui.add_space(4.0); - crate::panels::align::distribute_buttons(app, ui, 24.0); - } - ui.separator(); // The Transform link opens the whole Transform panel (reference point, rotate, // shear, options) in a popover; X/Y/W/H follow inline while the bar has room. crate::panels::transform::link(app, ui); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index d81e2fb973..4d5f75821b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -79,6 +79,40 @@ fn tear_off(ui: &Ui, resp: &egui::Response, strip: egui::Rect) -> Option Vec<(usize, egui::Rangef)> { + let mut groups: Vec<(usize, egui::Rangef)> = vec![]; + for &(i, r) in slots { + match groups.last_mut() { + Some((d, span)) if *d == i => span.max = span.max.max(r.right()), + _ => groups.push((i, egui::Rangef::new(r.left(), r.right()))), + } + } + groups +} + +/// Where document `from`'s tabs, dragged along the strip to `x`, go among the other documents' +/// tabs in `groups` ([`tab_groups`]): before the first whose middle is right of `x`, else after +/// the last. → the document's new index among all the open documents (floating ones and those +/// whose tabs don't fit included) and the x of the gap the drop goes in; `None` when the drop +/// leaves the document where it is, or there is no other tab to drop beside. +pub(super) fn tab_drop(groups: &[(usize, egui::Rangef)], from: usize, x: f32) -> Option<(usize, f32)> { + let others: Vec<&(usize, egui::Rangef)> = groups.iter().filter(|(d, _)| *d != from).collect(); + let slot = others.iter().filter(|(_, span)| span.center() < x).count(); + let (to, gap) = match others.get(slot) { + // Before document `d`: it shifts left by one when `from` was before it. + Some(&&(d, span)) => (if from < d { d - 1 } else { d }, span.min), + // After the last tab shown. + None => { + let &&(d, span) = others.last()?; + (if from < d { d } else { d + 1 }, span.max) + } + }; + (to != from).then_some((to, gap)) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -100,7 +134,9 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] -/// above or below the strip floats its view in a window under the pointer. +/// above or below the strip floats its view in a window under the pointer; one dragged along the +/// strip moves its document among the others (`document.move`, #5663), a line marking where it +/// will go. pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; @@ -133,6 +169,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let mut close = None; let mut float = None; let mut hovering_art = false; + // The tabs shown, by document and rect, and the document whose tab is dragged (and whether + // the drag just ended), for moving it along the strip. + let mut slots: Vec<(usize, egui::Rect)> = vec![]; + let mut dragged = None; for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { if x + w > strip.left() + room && Some(k) != active { break; @@ -142,6 +182,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let is_active = Some(k) == active; let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); let resp = ui.interact(r, ui.scope_id().with(("tab", i, win.1)), Sense::click_and_drag()); + slots.push((i, r)); + if resp.dragged() || resp.drag_stopped() { + dragged = Some((i, resp.drag_stopped())); + } if is_active { ui.painter().rect_filled(r, 0.0, t.panel); } else if resp.hovered() { @@ -166,6 +210,25 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { x += w; } crate::document_drag::finish_tabs(ui.ctx(), hovering_art); + // A tab dragged along the strip (not off it, which floats it) moves its document: a line marks + // the gap it goes in, and the release moves it there. Artwork dragged over the tabs never does. + let mut reorder = None; + if let Some((from, released)) = dragged + && !crate::document_drag::carrying_artwork(ui.ctx()) + && let Some(p) = ui.input(|i| i.pointer.interact_pos().or(i.pointer.latest_pos())) + && !crate::doc_windows::torn_off(strip, p) + { + let drop = tab_drop(&tab_groups(&slots), from, p.x); + if released { + reorder = drop.map(|(to, _)| (from, to)); + } else { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if let Some((_, gap)) = drop { + let gap = gap.clamp(strip.left() + 1.0, strip.right() - 1.0); + ui.painter().vline(gap, strip.y_range().shrink(4.0), Stroke::new(2.0, t.accent)); + } + } + } // The » button: every window, floating ones included, the current one checked. The list // scrolls once it reaches the bottom of the window, so every document of a large session stays // reachable (#4017). @@ -197,6 +260,10 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if let Err(e) = app.run("window.arrange.floatInWindow", json!({"index": i, "view": n, "at": [at.x, at.y]})) { app.status(e); } + } else if let Some((from, to)) = reorder { + if let Err(e) = app.run("document.move", json!({"from": from, "to": to})) { + app.status(e); + } } else if let Some(w) = activate { crate::doc_windows::show_window(app, w); } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index c9109a17fc..86a85699d9 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -7,6 +7,56 @@ fn the_active_tab_stays_in_view() { assert_eq!(super::first_tab_shown(&widths, None, 350.0), 0); assert_eq!(super::first_tab_shown(&widths, Some(4), 50.0), 4, "a tab wider than the room still shows"); } + +/// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). +fn slots(docs: &[usize]) -> Vec<(usize, egui::Rect)> { + docs.iter().enumerate().map(|(k, &d)| (d, egui::Rect::from_min_size(egui::pos2(k as f32 * 100.0, 0.0), egui::vec2(100.0, 30.0)))).collect() +} + +/// A document's view tabs make one group, which moves as one (#5663). +#[test] +fn a_documents_view_tabs_make_one_group() { + let groups = super::tab_groups(&slots(&[0, 1, 1, 2])); + let spans: Vec<(usize, f32, f32)> = groups.iter().map(|(d, s)| (*d, s.min, s.max)).collect(); + assert_eq!(spans, vec![(0, 0.0, 100.0), (1, 100.0, 300.0), (2, 300.0, 400.0)]); + assert!(super::tab_groups(&[]).is_empty()); +} + +/// A dragged tab drops past the middles of the tabs it crossed, as an index among all the open +/// documents (#5663). +#[test] +fn a_dragged_tab_drops_past_the_middles_it_crossed() { + let groups = super::tab_groups(&slots(&[0, 1, 2, 3])); + let drop = |from, x| super::tab_drop(&groups, from, x); + assert_eq!(drop(0, 40.0), None, "still over itself"); + assert_eq!(drop(0, 140.0), None, "not yet past the next tab's middle"); + assert_eq!(drop(0, 160.0), Some((1, 200.0)), "past the second tab's middle: between it and the third"); + assert_eq!(drop(0, 900.0), Some((3, 400.0)), "past the end: last"); + assert_eq!(drop(3, -50.0), Some((0, 0.0)), "before the start: first"); + assert_eq!(drop(3, 120.0), Some((1, 100.0)), "between the first two"); + assert_eq!(drop(2, 260.0), None, "between its neighbours: where it is"); + assert_eq!(super::tab_drop(&super::tab_groups(&slots(&[0])), 0, 500.0), None, "no other tab"); + assert_eq!(super::tab_drop(&[], 0, 500.0), None); +} + +/// Documents without a tab on the strip (floating, or past its end) keep their places in the +/// documents' order; the drop names an index among all of them (#5663). +#[test] +fn a_drop_counts_the_documents_the_strip_does_not_show() { + // Documents 0, 2 and 5 have tabs; 1, 3 and 4 float. + let groups = super::tab_groups(&slots(&[0, 2, 5])); + let drop = |from, x| super::tab_drop(&groups, from, x).map(|(to, _)| to); + assert_eq!(drop(0, 260.0), Some(5), "after document 5: last, as 0 leaves its place"); + assert_eq!(drop(0, 160.0), Some(4), "between 2 and 5: just before 5, which is index 4 once 0 has left its place"); + assert_eq!(drop(5, -10.0), Some(0), "before document 0"); + assert_eq!(drop(5, 60.0), Some(2), "before document 2: index 2, the floating document 1 stays before it"); + assert_eq!(drop(2, 260.0), Some(5), "after document 5"); + // With view tabs: document 1 has two, side by side; it moves as one. + let groups = super::tab_groups(&slots(&[0, 1, 1, 2])); + assert_eq!(super::tab_drop(&groups, 1, 20.0), Some((0, 0.0)), "both views' document goes first"); + assert_eq!(super::tab_drop(&groups, 0, 220.0), Some((1, 300.0)), "past document 1's middle, which both its tabs span"); + assert_eq!(super::tab_drop(&groups, 0, 190.0), None, "not yet past it"); +} use std::sync::Arc; use super::{StatusReadoutWidths, status_readouts}; @@ -1889,7 +1939,8 @@ fn the_control_bar_shows_the_global_edit_options() { /// At any width the Control bar shows the inline X, Y, W and H fields whole inside its right margin, /// or leaves all four out and keeps the Transform link; a wider bar never leaves them out once a -/// narrower one showed them. +/// narrower one showed them. The Align buttons, and for two objects the Distribute buttons, are +/// trimmed the same way ahead of the Transform link (#5372). #[test] fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { crate::i18n::set_current(crate::i18n::Lang::EN); @@ -1904,6 +1955,33 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { ctx.enable_accesskit(); crate::theme::install_fonts(&ctx); let mut seen = false; + // The Align group, then for two objects the Distribute group (#5372): each by its controls. + let mut groups: Vec<(&str, Vec<&str>)> = vec![( + "Align", + vec![ + "Horizontal Align Left", + "Horizontal Align Center", + "Horizontal Align Right", + "Horizontal & Vertical Align Center", + "Vertical Align Top", + "Vertical Align Center", + "Vertical Align Bottom", + ], + )]; + if count == 2 { + groups.push(( + "Distribute", + vec![ + "Vertical Distribute Top", + "Vertical Distribute Center", + "Vertical Distribute Bottom", + "Horizontal Distribute Left", + "Horizontal Distribute Center", + "Horizontal Distribute Right", + ], + )); + } + let mut groups_seen = vec![false; groups.len()]; for width in (600..=2400).step_by(10) { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); let mut nodes = Vec::new(); @@ -1930,7 +2008,24 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { } assert!(!seen || fields[3].is_some(), "{count} objects, {width}: left out after a narrower bar showed them"); seen |= fields[3].is_some(); + // The Align and Distribute buttons show whole inside the margin, with the Transform + // link after them, or are left out; once shown, a wider bar keeps them. + let end = |name: &str| nodes.iter().find(|(_, n)| n.label() == Some(name)).and_then(|(_, n)| n.bounds()).map(|b| b.x1); + let inside = |x: f64| x <= f64::from(width) - 10.0; + for ((group, names), was) in groups.iter().zip(groups_seen.iter_mut()) { + let ends: Vec> = names.iter().map(|n| end(n)).collect(); + let shown = ends.iter().all(Option::is_some); + assert!(shown || ends.iter().all(Option::is_none), "{count} objects, {width}: {group} {ends:?}"); + if let Some(Some(last)) = ends.last() { + assert!(inside(*last), "{count} objects, {width}: {group} ends at {last}"); + let transform = end("Transform"); + assert!(transform.is_some_and(inside), "{count} objects, {width}: Transform after {group} ends at {transform:?}"); + } + assert!(!*was || shown, "{count} objects, {width}: {group} left out after a narrower bar showed it"); + *was |= shown; + } } assert!(seen, "{count} objects: a wide bar has room for the fields"); + assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}"); } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d25a08f94d..fccfbedab5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -10,7 +10,8 @@ //! - `ui.contextMenu.list`: the canvas context menu for the current selection, flattened //! - `ui.tool.select {tool}`, `ui.tool.list` //! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: -//! drive the active tool through the same path as the mouse +//! drive the active tool through the same path as the mouse, after the synthetic input sent +//! before it was applied //! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input //! - `ui.move {x, y}` / `ui.click {x, y, button?, count?, shift?…}` / `ui.drag {x, y, toX, toY, steps?}`: //! real egui pointer input in screen points (reaches every widget: panels, flyouts, dialogs) @@ -33,7 +34,7 @@ //! Background Save or Background Export on. A `wait` other than true, false or null is refused use std::sync::Arc; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::mpsc::Sender; use serde_json::{Value, json}; @@ -100,8 +101,13 @@ pub struct ControlRequest { pub params: Value, pub reply: Sender, state: Arc, + /// Its place in the order requests were made ([`ControlRequest::next_seq`]). + seq: u64, } +/// The sequence number of the next request made. +static NEXT_SEQ: AtomicU64 = AtomicU64::new(0); + /// A request's state: waiting to run, taken by the app ([`ControlRequest::claim`]), or given up /// by its caller before that ([`Ticket::give_up`]). It leaves `QUEUED` once, one way or the other. const QUEUED: u8 = 0; @@ -123,7 +129,18 @@ impl Ticket { impl ControlRequest { pub fn new(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver) { let (tx, rx) = std::sync::mpsc::channel(); - (Self { method: method.into(), params, reply: tx, state: Arc::new(AtomicU8::new(QUEUED)) }, rx) + let seq = NEXT_SEQ.fetch_add(1, Ordering::SeqCst); + (Self { method: method.into(), params, reply: tx, state: Arc::new(AtomicU8::new(QUEUED)), seq }, rx) + } + + /// The sequence number the next request made gets: every request made so far is before it. + pub fn next_seq() -> u64 { + NEXT_SEQ.load(Ordering::SeqCst) + } + + /// Whether this request was made before the one numbered `seq`. + pub fn made_before(&self, seq: u64) -> bool { + self.seq < seq } /// The caller's handle on this request, to give it up with. @@ -131,6 +148,11 @@ impl ControlRequest { Ticket(self.state.clone()) } + /// Whether its caller gave it up (it never runs), without taking it. + pub fn given_up(&self) -> bool { + self.state.load(Ordering::SeqCst) == GIVEN_UP + } + /// Take the request to run it → `false` when its caller gave it up meanwhile (don't run it). pub fn claim(&self) -> bool { self.state.compare_exchange(QUEUED, STARTED, Ordering::SeqCst, Ordering::SeqCst).is_ok() @@ -539,7 +561,13 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe let base_mods: Mods = p.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or_default(); let view = app.view_info(); let xf = app.canvas_rect.zip(app.view().copied()).map(|(rect, v)| Xf::new(rect, &v)); - for e in events { + let held = + PointerEvent::json_backquote(p, false).and_then(|d| events.iter().map(|e| PointerEvent::json_backquote(e, d)).collect::, _>>()); + let held = match held { + Ok(held) => held, + Err(e) => return err(e), + }; + for (e, backquote) in events.iter().zip(held) { let kind = match e.get("kind").and_then(Value::as_str).unwrap_or("") { "down" => PointerKind::Down, "drag" => PointerKind::Drag, @@ -565,7 +593,6 @@ fn pointer_events(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRe Some(xf) if screen => crate::canvas::pose_on_page(q, &xf), _ => q, }); - let backquote = e.get("backquote").and_then(Value::as_bool).unwrap_or_else(|| p.get("backquote").and_then(Value::as_bool).unwrap_or(false)); crate::canvas::dispatch(app, &PointerEvent { kind, pos, mods, backquote, pressure: PointerEvent::json_pressure(e), pen }, view); let hold = PointerEvent::json_hold(e); if hold > 0.0 { diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index d084d7ee04..e587c0489f 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -293,6 +293,29 @@ fn synthetic_pointer_backquote_keeps_solid_object_in_place() { assert_eq!(xf.as_coeffs()[4], 20.0, "synthetic backquote drag changes pattern paint"); } +/// `ui.pointer` rejects a `backquote` that is not a boolean, given for the request or for any +/// event, before any of the events runs. +#[test] +fn synthetic_pointer_rejects_a_backquote_that_is_not_a_boolean() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(input_request(&mut app, "ui.tool.select", json!({"tool": "selection"}))["ok"], true); + let before = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let down = json!({"kind": "down", "x": 125, "y": 125}); + let drag = json!({"kind": "drag", "x": 145, "y": 125}); + for params in [ + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125}], "backquote": "true"}), + json!({"events": [down, drag, {"kind": "up", "x": 145, "y": 125, "backquote": 1}]}), + ] { + let r = input_request(&mut app, "ui.pointer", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`backquote` must be a boolean")), "{r}"); + assert_eq!(app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap(), &before, "{params}"); + } +} + /// `ui.pointer` replies with the key object: a click on one of two selected objects makes it /// the key, and a click on the key again lets it go. #[test] diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 44377a2c84..eda747fc8f 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -702,23 +702,17 @@ pub fn os_cursors(build: bool, wayland: bool) -> bool { build && !wayland } -/// Does the canvas hide the system pointer to show a painted tool glyph alone? Not when there is no -/// cursor theme on Wayland ([`crate::Services::no_cursor_theme`]): winit sets no pointer then, and a -/// hidden one would not come back over the panels (#2450). The system pointer stays beside the glyph. -pub fn hide_system_pointer(no_cursor_theme: bool) -> bool { - !no_cursor_theme -} - /// Does the window hide the pointer only while it is the key window? macOS does: winit hides it with /// a cursor rect holding a transparent cursor, and macOS applies the rect only in the key window. /// Over a window behind another app or under a sheet, the system pointer shows (#2020). pub const HIDES_ONLY_WHEN_KEY: bool = cfg!(target_os = "macos"); -/// Does the window paint the glyphs over a hidden pointer, `focused` or not? Not where the system -/// shows its pointer over a window without the focus ([`HIDES_ONLY_WHEN_KEY`]): the system pointer -/// shows alone there. -pub fn paint_glyphs(hides_only_when_key: bool, focused: bool) -> bool { - focused || !hides_only_when_key +/// Does the window paint a glyph over a hidden pointer? Not where it cannot hide the system pointer +/// (no cursor theme on Wayland, [`crate::Services::no_cursor_theme`]: winit sets no pointer then, +/// and a hidden one would not come back over the panels, #2450), or where the system shows its pointer without the focus +/// ([`HIDES_ONLY_WHEN_KEY`]): the system pointer shows alone there. +pub fn paint_glyphs(hides_only_when_key: bool, focused: bool, no_cursor_theme: bool) -> bool { + !no_cursor_theme && (focused || !hides_only_when_key) } /// The cursor bitmaps handed to the OS, by (cursor, pixels per point): each glyph is rasterized diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index ece8895b44..e70f7d488a 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -387,8 +387,6 @@ fn a_wayland_window_paints_the_tool_cursor() { /// Without a cursor theme the canvas keeps the system pointer visible (#2450). #[test] fn no_cursor_theme_keeps_the_system_pointer() { - assert!(!hide_system_pointer(true)); - assert!(hide_system_pointer(false)); let mut app = VectorcraftApp::new(Session::new(), crate::Services { wayland: true, no_cursor_theme: true, ..Default::default() }); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = egui::Context::default(); @@ -472,9 +470,10 @@ fn wayland_windows_paint_the_glyphs() { #[test] fn macos_windows_paint_the_glyphs_only_with_the_focus() { - assert!(paint_glyphs(true, true), "macOS with the focus"); - assert!(!paint_glyphs(true, false), "macOS without the focus: the system pointer shows (#2020)"); - assert!(paint_glyphs(false, true) && paint_glyphs(false, false), "Wayland, the web: painted with the focus or without"); + assert!(paint_glyphs(true, true, false), "macOS with the focus"); + assert!(!paint_glyphs(true, false, false), "macOS without the focus: the system pointer shows (#2020)"); + assert!(paint_glyphs(false, true, false) && paint_glyphs(false, false, false), "Wayland, the web: painted with the focus or without"); + assert!(!paint_glyphs(false, true, true), "without a cursor theme, use the system pointer alone"); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3373ebf9ce..c0f900f67c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -417,10 +417,12 @@ registry! { RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, SelectByArtboards: [crate::addons::select::KIND] => crate::addons::select::SPEC, + SelectByLinkStatus: [crate::addons::select::link_status::KIND] => crate::addons::select::link_status::SPEC, ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), } diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 8d58f21b41..fdbf335cb6 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -249,6 +249,23 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The field of a Color Picker opened over a command dialog ([`over_effect`]): the dialog's colour +/// field its OK fills. +const COLOUR_FIELD: &str = "__colourField"; + +/// The Color Picker over the command dialog `parent`, on `colour`, that fills the dialog's `field` +/// with its OK and goes back to it, as Cancel does. It previews nothing itself: the dialog's own +/// preview shows the colour once it is back. +pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog { + let mut d = Dialog::new( + KIND, + json!({"original": color_json(&colour), "channel": Channel::default().id(), "webOnly": false, "swatches": false, COLOUR_FIELD: field}), + ); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + store(&mut d, &Picked::of(colour)); + d +} + /// The field of a Color Picker opened over Recolor Artwork ([`over_recolor`]): the row whose new /// color it picks. const RECOLOR_ROW: &str = "__recolorRow"; @@ -433,8 +450,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { /// Opened for an artboard, the picker shows the color on that artboard's paper, with or without a /// selection. fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { - // Over Recolor Artwork the art shows that dialog's preview, which this one must not replace. - if d.fields.contains_key(RECOLOR_ROW) { + // Over Recolor Artwork the art shows that dialog's preview, which this one must not replace; + // over a command dialog this picker only fills a field, and the dialog previews it. + if d.fields.contains_key(RECOLOR_ROW) || d.fields.contains_key(COLOUR_FIELD) { return; } let (cmd, params) = paint_command(app, d); @@ -632,6 +650,15 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, current: &Color, side: f32) -> /// OK with the starting color unchanged and nothing previewed closes the picker and leaves the /// artboard as it was: without a background color, or with its color in its own color model. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) { + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex())); + // The dialog previews the new colour when it comes back: end this picker's interaction, as + // Cancel does, so the dialog starts its preview afresh. + let _ = app.session.cancel_interaction(); + app.ui.dialog = Some(parent); + return Ok(Value::Null); + } if let Some(row) = d.fields.get(RECOLOR_ROW).and_then(Value::as_u64) { let parent = super::parent(d).ok_or("Recolor Artwork is no longer open")?; let c = in_document_model(app, picked(d).color); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 2dc8efd064..0a722cbcf8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -21,7 +21,9 @@ pub(super) const SPEC: DialogSpec = DialogSpec { // Area Type Options: a Row Gutter still as it opened, on rows without a gutter of their own, // follows the Gutter as it is changed. let linked = d.fields.get("__rowGutterLinked").is_some() && d.fields.get("__rowGutterLinked") == d.fields.get("rowGutter"); - form::param_fields(ui, d, &|k| lengths.contains(&k), &|k| choices(&command, k), &rank, app.session.general_unit()); + let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); + let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); + form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); if linked && d.fields.get("rowGutter") == d.fields.get("__rowGutterLinked") && let Some(g) = d.fields.get("gutter").cloned() @@ -61,12 +63,12 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// Does this dialog show a Preview checkbox? Grid Repeat Options does: the public page for the /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does -/// too (#5360), as public tutorials of the dialog show. (Cancel rolls a preview back whichever -/// dialog started it.) +/// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path +/// works the same way (#5532). (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), - "type.pathOptions" => true, + "type.pathOptions" | crate::addons::typetools::RELEASE => true, _ => false, } } @@ -114,6 +116,7 @@ fn order(command: &str) -> &'static [&'static str] { // The public Trap options' order. "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], + crate::addons::typetools::RELEASE => &["mode", "keepOriginal"], _ => &[], } } @@ -123,6 +126,7 @@ fn choices(command: &str, key: &str) -> Option { match (command, key) { ("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS), ("type.pathOptions", "alignToPath") => Some(PATH_ALIGN), + (crate::addons::typetools::RELEASE, "mode") => Some(crate::addons::typetools::RELEASE_MODES), ("text.areaOptions", "fit") => Some(AREA_FIT), ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), @@ -136,6 +140,19 @@ fn choices(command: &str, key: &str) -> Option { } } +/// Object › Rasterize › Color Model: the values `object.rasterize` takes, the document's own +/// colour model first (#5660). +fn rasterize_color_models(command: &str, key: &str, cmyk: bool) -> Option { + match (command, key) { + ("object.rasterize", "colorModel") => Some(if cmyk { RASTERIZE_CMYK } else { RASTERIZE_RGB }), + _ => None, + } +} + +/// Object › Rasterize › Color Model in an RGB and in a CMYK document. +const RASTERIZE_RGB: form::Choices = &[("RGB", "rgb"), ("Grayscale", "grayscale"), ("Bitmap", "bitmap")]; +const RASTERIZE_CMYK: form::Choices = &[("CMYK", "cmyk"), ("Grayscale", "grayscale"), ("Bitmap", "bitmap")]; + /// Type on a Path Options › Align to Path. const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")]; @@ -285,6 +302,61 @@ mod tests { assert_eq!(t.area.flow, vectorcraft_doc::TextFlow::Rows); } + /// Object › Rasterize › Color Model is a dropdown of the models `object.rasterize` takes, the + /// document's own first (#5660): every value runs, and picking Grayscale rasterizes in grays. + #[test] + fn rasterize_color_model_is_a_dropdown_of_the_models_the_command_takes() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + for (mode, own) in [("rgb", "RGB"), ("cmyk", "CMYK")] { + let models = rasterize_color_models("object.rasterize", "colorModel", mode == "cmyk").unwrap(); + assert_eq!(models.first(), Some(&(own, mode)), "the document's own model first"); + for (_, value) in models { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "colorMode": mode})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72, "colorModel": value})).unwrap_or_else(|e| panic!("{mode} {value}: {e}")); + } + } + assert!(rasterize_color_models("object.rasterize", "background", false).is_none()); + assert!(rasterize_color_models("document.rasterEffectsSettings", "colorModel", false).is_none()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(&mut app, "object.rasterize", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("colorModel"), "rgb"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + assert!(h.query_by_role_and_label(Role::TextInput, "Color Model:").is_none(), "not a text field"); + h.get_by_role_and_label(Role::ComboBox, "Color Model:").click(); + h.run_steps(3); + h.get_by_label("Grayscale").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().str("colorModel"), "grayscale"); + let app = h.state_mut(); + crate::dialogs::confirm(app).unwrap(); + let st = app.session.active().unwrap(); + let key = st.selection.objects.iter().find_map(|id| match st.doc.node(*id).map(|n| &n.kind) { + Some(NodeKind::Image(i)) => Some(i.key.clone()), + _ => None, + }); + let img = image::load_from_memory(&st.doc.images[&key.expect("the rectangle became an image")].bytes).unwrap().to_rgba8(); + let p = img.get_pixel(img.width() / 2, img.height() / 2).0; + assert!(p[0] == p[1] && p[1] == p[2] && p[0] < 128, "red in grayscale: {p:?}"); + } + /// Graph Type › Value Axis is a dropdown of the values `graph.setType` takes, and OK puts the /// value axis on the side picked. #[test] diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 273c0291ef..fa4c8dcee6 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -722,7 +722,7 @@ fn drop_shadow_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc:: d.fields.insert("shade".into(), json!("darkness")); } ui.add_enabled_ui(darkness, |ui| { - if let Some(v) = widgets::range_field(ui, "fx-darkness", d.f64("darkness", 100.0), 0.0..=100.0, "%", 0, 70.0) { + if let Some(v) = widgets::spin_range(ui, "fx-darkness", Some(d.f64("darkness", 100.0)), 0.0..=100.0, "%", 0, 86.0, 1.0) { d.fields.insert("darkness".into(), json!(v)); } }); @@ -985,4 +985,138 @@ mod tests { assert_eq!((¶ms["texture"], ¶ms["textureImage"]), (&json!("loaded"), &json!(stored))); let _ = std::fs::remove_dir_all(&dir); } + /// Effect > Stylize > Outer Glow: a swatch beside Color shows the effect's colour, typing a + /// hex recolours it, and a double-click opens the Color Picker over the dialog; its OK fills + /// Color, and the effect applies that colour. + #[test] + fn outer_glow_colour_swatch_opens_the_color_picker() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "stylize.outerGlow"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let frame = |app: &mut VectorcraftApp, time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + for n in 0..6 { + frame(&mut app, f64::from(n) * 0.01, vec![]); + } + let rect = ctx.read_response(form::colour_swatch_id("color")).expect("the colour swatch is drawn").rect; + // The colour of the swatch drawn at `rect`. + let swatch = |out: &egui::FullOutput| { + out.shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.rect == rect => Some(r.fill), + _ => None, + }) + }; + let yellow = egui::Color32::from_rgb(255, 255, 0); + assert_eq!(swatch(&frame(&mut app, 0.2, vec![])), Some(yellow), "the swatch shows the effect's #ffff00"); + // Typing a colour recolours the swatch. + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + assert_eq!(swatch(&frame(&mut app, 0.25, vec![])), Some(egui::Color32::from_rgb(255, 0, 0)), "typing a hex recolours the swatch"); + // A double-click opens the Color Picker on the field's colour. + let pos = rect.center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, 0.3, vec![egui::Event::PointerMoved(pos), button(true)]); + frame(&mut app, 0.35, vec![button(false)]); + frame(&mut app, 0.4, vec![button(true)]); + frame(&mut app, 0.45, vec![button(false)]); + frame(&mut app, 0.5, vec![]); + let d = app.ui.dialog.as_ref().expect("a dialog"); + assert_eq!(d.kind, "colorPicker", "a double-click opens the Color Picker over the effect dialog"); + assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(Color::rgb(1.0, 0.0, 0.0)), "on the field's colour"); + // Its OK fills the effect's Color, and the effect applies it. + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("the effect dialog is back"); + assert_eq!((d.kind.as_str(), d.fields.get("color")), ("effect", Some(&json!("#00ff00"))), "OK fills Color and comes back"); + frame(&mut app, 0.6, vec![]); + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + assert_eq!(fx.params.get("color"), Some(&json!("#00ff00")), "Outer Glow takes the picked colour"); + } + + /// Effect > Stylize > Drop Shadow and Outer Glow: Opacity, the offsets, Blur and Darkness have + /// spinner arrows (#5367, #5368). A click on the top half steps up, on the bottom half down; + /// Opacity stops at 100 % and Blur at 0, and OK applies the stepped values. + #[test] + fn drop_shadow_and_outer_glow_fields_have_spinner_arrows() { + for (effect, count) in [("stylize.dropShadow", 5), ("stylize.outerGlow", 2)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let time = std::cell::Cell::new(0.0); + // One frame → the spinners' bounds, top to bottom. + let frame = |app: &mut VectorcraftApp, events: Vec| { + time.set(time.get() + 0.05); + let mut out = + ctx.run_ui(egui::RawInput { time: Some(time.get()), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + let mut spinners: Vec = out + .platform_output + .accesskit_update + .map(|u| u.nodes) + .unwrap_or_default() + .iter() + .filter(|(_, n)| n.label() == Some("Step up or down")) + .filter_map(|(_, n)| n.bounds()) + .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + .collect(); + spinners.sort_by(|a, b| a.top().total_cmp(&b.top())); + spinners + }; + for _ in 0..6 { + frame(&mut app, vec![]); + } + let spinners = frame(&mut app, vec![]); + assert_eq!(spinners.len(), count, "{effect}: a spinner beside each number field: {spinners:?}"); + let click = |app: &mut VectorcraftApp, r: egui::Rect, up: bool| { + let pos = r.center() + egui::vec2(0.0, if up { -r.height() / 4.0 } else { r.height() / 4.0 }); + let button = + |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(pos), button(true)]); + frame(app, vec![button(false)]); + frame(app, vec![]); + }; + let (opacity, blur) = (spinners[0], spinners[count - 1 - usize::from(count == 5)]); + click(&mut app, opacity, true); + let field = |app: &VectorcraftApp, k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).and_then(Value::as_f64); + assert_eq!(field(&app, "opacity"), Some(76.0), "{effect}: the up arrow steps Opacity up"); + click(&mut app, blur, false); + assert_eq!(field(&app, "blur"), Some(4.0), "{effect}: the down arrow steps Blur down"); + app.ui.dialog.as_mut().unwrap().fields.insert("opacity".into(), json!(100.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("blur".into(), json!(0.0)); + frame(&mut app, vec![]); + click(&mut app, opacity, true); + click(&mut app, blur, false); + assert_eq!((field(&app, "opacity"), field(&app, "blur")), (Some(100.0), Some(0.0)), "{effect}: the arrows stop at the ends"); + click(&mut app, opacity, false); + if count == 5 { + click(&mut app, spinners[1], true); + assert_eq!(field(&app, "x"), Some(8.0), "the X offset steps up"); + let darkness = spinners[4]; + app.ui.dialog.as_mut().unwrap().fields.insert("shade".into(), json!("darkness")); + frame(&mut app, vec![]); + click(&mut app, darkness, false); + assert_eq!(field(&app, "darkness"), Some(99.0), "Darkness steps down"); + } + super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let fx = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0]; + let param = |k: &str| fx.params.get(k).and_then(Value::as_f64); + assert_eq!((param("opacity"), param("blur")), (Some(99.0), Some(0.0)), "{effect}: OK applies them"); + } + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 1d8d30d8e1..5e5b4ea9c5 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Unit; +use vectorcraft_doc::color::Color; use vectorcraft_plugins::{Manifest, Param, ParamSpec}; use crate::state::Dialog; @@ -168,6 +169,26 @@ fn choices(kind: &str, key: &str) -> Vec<(&'static str, &'static str)> { } } +/// The id of the colour swatch beside the field `key` (a test clicks it; [`colour_swatch`] draws it). +pub(super) fn colour_swatch_id(key: &str) -> egui::Id { + egui::Id::unique(("fx-colour-swatch", key)) +} + +/// The colour swatch beside the colour field `key`, showing `colour`: a double-click asks for the +/// Color Picker over this dialog, whose OK fills the field ([`super::color_picker::over_effect`]). +/// Returns whether the picker was asked for. +fn colour_swatch(ui: &mut egui::Ui, key: &str, colour: Color) -> bool { + let t = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(20.0, 18.0), egui::Sense::hover()); + let resp = ui.interact(rect, colour_swatch_id(key), egui::Sense::click()); + let [r, g, b, _] = colour.to_rgba8(1.0); + ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(r, g, b)); + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + resp.double_clicked() +} /// A text field `width` wide bound to `d.fields[key]`. Returns true when it changed. pub(super) fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> bool { text_edit(ui, d, key, width).changed() @@ -389,10 +410,16 @@ pub(crate) fn params(d: &Dialog) -> Value { /// The (label, value) choices of a parameter that picks one of some values. pub(super) type Choices = &'static [(&'static str, &'static str)]; +/// Effects whose dialogs give their number fields spinner arrows (#5367, #5368): Drop Shadow's +/// and the glows' Opacity, offsets and Blur, which are stepped more than typed. +pub(super) fn has_spinners(effect: &str) -> bool { + matches!(effect, "stylize.dropShadow" | "stylize.outerGlow" | "stylize.innerGlow") +} + /// Generic editor for command/effect parameters: numbers, booleans, strings and colours; the /// parameters `is_length` names are distances shown and typed in `unit`, those `choices` gives /// choices for are dropdowns. Fields come in `rank` order (by name among equals). Returns true when -/// a value changed. +/// a value changed. The fields of [`has_spinners`]' effects carry spinner arrows. pub(super) fn param_fields( ui: &mut egui::Ui, d: &mut Dialog, @@ -403,6 +430,8 @@ pub(super) fn param_fields( ) -> bool { let t = Tokens::get(ui.ctx()); let mut changed = false; + let mut pick: Option<(String, Color)> = None; + let spinners = has_spinners(&d.str("__effect")); egui::Grid::new("fxgrid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { let mut keys: Vec<(String, Value)> = d.fields.iter().filter(|(k, _)| !k.starts_with("__") && k.as_str() != "preview").map(|(k, v)| (k.clone(), v.clone())).collect(); @@ -424,7 +453,26 @@ pub(super) fn param_fields( if is_length(&k) { // An effect's documented range keeps the field to the distance it applies. let range = vectorcraft_effects::length_range(&d.str("__effect"), &k); - changed |= length_within(ui, d, &k, unit, 140.0, range); + if spinners { + let bounds = range.unwrap_or(if k == "blur" { 0.0..=f64::INFINITY } else { crate::widgets::ANY }); + let value = d.fields.contains_key(&k).then(|| d.f64(&k, 0.0)); + if let Some(x) = crate::widgets::spin_length_within(ui, ("dlg-len", k.as_str()), value, unit, 140.0, bounds) { + d.fields.insert(k.clone(), json!(x)); + changed = true; + } + } else { + changed |= length_within(ui, d, &k, unit, 140.0, range); + } + return; + } + // A size in pixels of the raster effects resolution (Color Halftone's Max Radius) + // stays in pixels whatever the document's units, within its documented range. + if let Some(range) = vectorcraft_effects::raster_px_range(&d.str("__effect"), &k) { + let x = v.as_f64().unwrap_or(*range.start()); + if let Some(x) = crate::widgets::range_field_named(ui, ("fx-px", &k), None, x, range, &unit_suffix("px"), 2, 140.0) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } return; } if let Some(options) = choices(&k) { @@ -440,6 +488,13 @@ pub(super) fn param_fields( return; } match v { + Value::Number(n) if spinners => { + let range = if k == "opacity" { 0.0..=100.0 } else { crate::widgets::ANY }; + if let Some(x) = crate::widgets::spin_range(ui, ("fx-num", k.as_str()), n.as_f64(), range, "", 3, 140.0, 1.0) { + d.fields.insert(k.clone(), typed_number(x)); + changed = true; + } + } Value::Number(n) => { if let Some(x) = crate::widgets::plain_field(ui, ("fx-num", &k), n.as_f64().unwrap_or(0.0), "", 3, 140.0) { d.fields.insert(k.clone(), typed_number(x)); @@ -470,18 +525,42 @@ pub(super) fn param_fields( } } Value::String(mut s) => { - if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(140.0)).changed() { - d.fields.insert(k.clone(), json!(s)); - changed = true; + // A hex colour (#rrggbb or #rgb) shows its swatch beside the field; the swatch's + // double-click opens the Color Picker over this dialog. + let mut colour = None; + let mut ask = false; + ui.horizontal(|ui| { + if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(140.0)).changed() { + d.fields.insert(k.clone(), json!(s)); + changed = true; + } + colour = crate::panels::color::parse_hex(&s); + if let Some(c) = colour { + ask = colour_swatch(ui, &k, c); + } + }); + if ask && let Some(c) = colour { + pick = Some((k.clone(), c)); } } // A color object shows as its hex; typing in the field stores the typed text. other => match color_object(&other) { Some(c) => { let mut s = c.to_hex(); - if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { - d.fields.insert(k.clone(), json!(s)); - changed = true; + let mut colour = None; + let mut ask = false; + ui.horizontal(|ui| { + if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { + d.fields.insert(k.clone(), json!(s)); + changed = true; + } + colour = crate::panels::color::parse_hex(&s); + if let Some(c) = colour { + ask = colour_swatch(ui, &k, c); + } + }); + if ask && let Some(c) = colour { + pick = Some((k.clone(), c)); } } None => { @@ -493,6 +572,9 @@ pub(super) fn param_fields( ui.end_row(); } }); + if let Some((key, colour)) = pick { + *d = super::color_picker::over_effect(d, &key, colour); + } changed } diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 7660287753..f2eb124776 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -3,7 +3,8 @@ //! preferences. OK sets them with `tool.setOption {tool, values}`. The Pencil also has `liveFit` //! (Live curve fitting, on: its preview fits the stroke while it is drawn). //! -//! Fields: `tool`; `fidelity` (points; Pencil, Paintbrush, Smooth and Blob Brush), `fill` (Pencil and +//! Fields: `tool`; `fidelity` (screen pixels for the Pencil and Paintbrush, points for Smooth and +//! Blob Brush), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows @@ -166,16 +167,19 @@ fn blob_size(ui: &mut egui::Ui, d: &mut Dialog) { fn fidelity(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let v = d.f64("fidelity", 1.5); - let rail = (vectorcraft_tools::draw2::min_fidelity(&d.str("tool")), FIDELITY_MAX); + let tool = d.str("tool"); + let rail = (vectorcraft_tools::draw2::min_fidelity(&tool), FIDELITY_MAX); + // The Pencil's and the Paintbrush's Fidelity is on screen, the same at any zoom (#5729). + let unit = if matches!(tool.as_str(), "pencil" | "paintbrush") { "px" } else { "pt" }; let rail_w = label_w(ui); let mut new = None; ui.label(egui::RichText::new(tl!("Fidelity:")).size(12.5).color(t.text)); ui.horizontal(|ui| { - let shown = widgets::SliderValue::field(v, rail.0..=rail.1, "pt", 2).with_step(fidelity_step); + let shown = widgets::SliderValue::field(v, rail.0..=rail.1, unit, 2).with_step(fidelity_step); let (x, _, keyed) = widgets::color_slider_stepped(ui, "freehand-fidelity", tl!("Fidelity:"), Some(shown), fidelity_at(v, rail), rail_w, &|_| t.input_border); new = x.map(|x| fidelity_from(x, rail)).or(keyed); - if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, "pt", 2, FIELD_W, fidelity_step) { + if let Some(x) = widgets::range_field_stepped(ui, "freehand-fidelity-field", v, rail.0..=100.0, unit, 2, FIELD_W, fidelity_step) { new = Some(x); } }); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 81aeae9b5a..35d216bc77 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -290,7 +290,7 @@ fn the_new_path_is_selected_only_with_keep_selected_on() { super::super::confirm(&mut app).unwrap(); let (selected, id) = stroke(&mut app, tool, 100.0); assert_eq!(selected, vec![id], "{tool}"); - // Off: the next stroke leaves the selection as it was. + // Off: the next stroke leaves nothing selected, the earlier path included (#5752). app.run("tool.options", json!({"tool": tool})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("keepSelected".into(), json!(false)); super::super::confirm(&mut app).unwrap(); @@ -299,7 +299,7 @@ fn the_new_path_is_selected_only_with_keep_selected_on() { assert_eq!(app.session.tool_options_of(tool)["keepSelected"].as_bool(), Some(false), "{tool}"); let (selected, new) = stroke(&mut app, tool, 200.0); assert_ne!(new, id, "{tool} drew a new path"); - assert_eq!(selected, vec![id], "{tool}"); + assert!(selected.is_empty(), "{tool}: the earlier path is no longer selected either"); } } diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index 6d9f91df33..f72383068e 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -1,8 +1,9 @@ //! The modal dialog window: a backdrop that keeps the rest of the app from taking clicks, and a //! window with no title bar that opens centred and moves by dragging its heading (the band from its -//! top edge down to the heading), as a title bar would. Where it was moved to stays, per window, for -//! the session, and the window never leaves the screen. Rows too many for the screen's height -//! scroll inside it ([`scrolled_rows`]), so its heading and buttons stay in view. +//! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where +//! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows +//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons +//! stay in view. use egui::{Id, Rect, Vec2}; @@ -60,10 +61,10 @@ pub(crate) fn drag_band(ui: &mut egui::Ui, bottom: f32) { let band = Rect::from_x_y_ranges(outer.x_range(), outer.top()..=bottom.max(outer.top())); // Not focusable (`Sense::drag()` is): Tab goes through the dialog's controls, not the band. let r = ui.interact(band, handle(id), egui::Sense::DRAG); + // Hovered, it keeps the arrow, as a title bar does (the grab cursor is Windows' four-way move + // arrows: #5246); only while it is dragged does it show the window being carried. if r.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - } else if r.hovered() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); } } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 833366b14f..c2a7aa2b1d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1984,7 +1984,7 @@ fn dialog_sliders_report_the_numbers_their_fields_show() { app.run("tool.options", json!({"tool": "pencil"})).unwrap(); set(&mut app, "fidelity", json!(2.5)); let shown = tree(|ui| show(&mut app, ui.ctx())); - assert_eq!(slider_value(&shown, "Fidelity:"), v(2.5, (0.01, 20.0), "2.5pt")); + assert_eq!(slider_value(&shown, "Fidelity:"), v(2.5, (0.01, 20.0), "2.5px"), "the Pencil's Fidelity is on screen (#5729)"); // The Smooth tool's rail starts at its own lowest Fidelity. app.ui.dialog = None; app.run("tool.options", json!({"tool": "smooth"})).unwrap(); @@ -3124,11 +3124,11 @@ fn artboard_options_selected_fit_spans_other_boards_and_off_board_art() { } /// An effect dialog keeps a distance typed outside the effect's range to the range, so the field -/// shows what the effect applies: Color Halftone's Max Radius below 4 pt is 4 pt (#4637). +/// shows what the effect applies: Crystallize's Cell Size below 3 pt is 3 pt (#4637). #[test] fn an_effect_dialog_keeps_a_typed_distance_within_the_effects_range() { let enter = || egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; - for (typed, applied) in [("1 pt", 4.0), ("0.5 px", 4.0), ("200 pt", 127.0), ("10 pt", 10.0)] { + for (typed, applied) in [("1 pt", 3.0), ("0.5 px", 3.0), ("400 pt", 300.0), ("10 pt", 10.0)] { let mut app = app(); let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); let ctx = egui::Context::default(); @@ -3139,21 +3139,23 @@ fn an_effect_dialog_keeps_a_typed_distance_within_the_effects_range() { out.textures_delta.clear(); }; app.run("select.all", json!({})).unwrap(); - app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); - // Max Radius, the first field, is focused: type over it and press Enter. + app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); + // Cell Size, the only field, is focused: type over it and press Enter. frame(&mut app, vec![]); frame(&mut app, vec![egui::Event::Text(typed.into())]); frame(&mut app, vec![enter()]); assert!(app.ui.dialog.is_none(), "{typed}"); let node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); - assert_eq!(node.appearance.effects.last().map(|e| e.params["maxRadius"].clone()), Some(json!(applied)), "{typed}"); + assert_eq!(node.appearance.effects.last().map(|e| e.params["cellSize"].clone()), Some(json!(applied)), "{typed}"); } } /// #4638: typing invalid input in an effect length field does not silently revert to a sub-minimum /// or out-of-range value; sub-minimum input is clamped immediately and invalid input clears cleanly. +/// (Crystallize's Cell Size, 3 to 300 pt: Color Halftone's Max Radius, which #4638 was found on, is +/// in pixels since #3260.) #[test] -fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { +fn effect_length_invalid_input_does_not_revert_to_sub_minimum_value() { let mut app = app(); let _id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); let ctx = egui::Context::default(); @@ -3165,20 +3167,20 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { out }; app.run("select.all", json!({})).unwrap(); - app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); frame(&mut app, vec![]); - // 1. Enter 0.5 px (sub-minimum): clamped immediately to 4 pt on commit + // 1. Enter 0.5 px (sub-minimum): clamped immediately to 3 pt on commit frame(&mut app, vec![egui::Event::Text("0.5 px".into())]); frame(&mut app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(4.0)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(3.0)); let s1 = frame(&mut app, vec![]); let shows_clamped_text = s1.shapes.iter().any(|s| match &s.shape { - egui::Shape::Text(t) => t.galley.text().trim() == "4 pt", + egui::Shape::Text(t) => t.galley.text().trim() == "3 pt", _ => false, }); - assert!(shows_clamped_text, "rendered field must show clamped '4 pt' text after sub-minimum commit"); + assert!(shows_clamped_text, "rendered field must show clamped '3 pt' text after sub-minimum commit"); - // 2. Return focus to Max Radius with Shift+Tab, type invalid text, and commit with Enter + // 2. Return focus to Cell Size with Shift+Tab, type invalid text, and commit with Enter frame( &mut app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::SHIFT }], @@ -3188,9 +3190,9 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { &mut app, vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], ); - // Dialog remains open and retains the clamped 4.0 pt rather than reverting to 0.5 px + // Dialog remains open and retains the clamped 3.0 pt rather than reverting to 0.5 px assert!(app.ui.dialog.is_some(), "dialog must remain open on invalid Enter commit"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(4.0)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(3.0)); // The field paints with rejection highlight (width 1.5, accent_strong) let next_out = frame(&mut app, vec![]); @@ -3198,12 +3200,12 @@ fn color_halftone_invalid_input_does_not_revert_to_sub_minimum_value() { egui::Shape::Rect(r) => (r.stroke.width - 1.5).abs() < 1e-3 && r.stroke.color.a() > 0, _ => false, }); - assert!(has_rejection_highlight, "Max Radius must display rejection highlight after invalid input"); + assert!(has_rejection_highlight, "Cell Size must display rejection highlight after invalid input"); let shows_clamped_after_invalid = next_out.shapes.iter().any(|s| match &s.shape { - egui::Shape::Text(t) => t.galley.text().trim() == "4 pt", + egui::Shape::Text(t) => t.galley.text().trim() == "3 pt", _ => false, }); - assert!(shows_clamped_after_invalid, "rendered field must retain '4 pt' text after invalid input rejection"); + assert!(shows_clamped_after_invalid, "rendered field must retain '3 pt' text after invalid input rejection"); } #[test] @@ -3220,13 +3222,43 @@ fn bounded_field_with_inches_does_not_clamp_point_bounds_to_inch_numbers() { out.textures_delta.clear(); }; test_app.run("select.all", json!({})).unwrap(); - test_app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + test_app.run("effect.dialog", json!({"effect": "pixelate.crystallize"})).unwrap(); frame(&mut test_app, vec![]); - // Type 1 in: 72 pt is within 4..127 pt range and must not clamp to ~1.76 pt + // Type 1 in: 72 pt is within 3..300 pt range and must not clamp to ~4.17 pt frame(&mut test_app, vec![egui::Event::Text("1 in".into())]); frame( &mut test_app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], ); - assert_eq!(test_app.ui.dialog.as_ref().unwrap().fields["maxRadius"], serde_json::json!(72.0)); + assert_eq!(test_app.ui.dialog.as_ref().unwrap().fields["cellSize"], serde_json::json!(72.0)); +} + +/// Color Halftone's Max Radius is in pixels of the raster effects resolution whatever the +/// document's units (#3260): in a document in centimetres it still shows and takes pixels, within +/// the documented 4 to 127 px. +#[test] +fn color_halftones_max_radius_stays_in_pixels_whatever_the_units() { + let tab = || egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + for (typed, applied, shown) in [("10", 10.0, "10 px"), ("2", 4.0, "4 px"), ("500", 127.0, "127 px"), ("4.5 px", 4.5, "4.5 px")] { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("document.setup", json!({"units": "Centimeters"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "pixelate.colorHalftone"})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text(typed.into())]); + frame(&mut app, vec![tab()]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["maxRadius"].as_f64(), Some(applied), "{typed}"); + let out = frame(&mut app, vec![]); + let shows = out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Text(t) if t.galley.text().trim() == shown)); + assert!(shows, "{typed} shows as {shown}, not in centimetres"); + } } diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 5408b78c24..95ff410cae 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -118,6 +118,31 @@ fn dialogs_move_by_their_heading_stay_on_screen_and_where_they_were_moved() { } } +/// #5246: the band that moves a dialog keeps the arrow when hovered, as a title bar does (the grab +/// cursor is the four-way move arrows on Windows); it shows the window held only while dragged. +#[test] +fn the_band_that_moves_a_dialog_keeps_the_arrow_until_dragged() { + let opens: [(&str, Open, egui::Id); 2] = [ + ("Offset Path", |app| crate::menus::invoke(app, "object.path.offsetPath", json!({})), egui::Id::unique(("dialog", "offsetPath"))), + ("New Document", open_new_document, egui::Id::unique(("dialog", "newDocument"))), + ]; + for (name, open, id) in opens { + let (ctx, mut app) = (ctx(), app_with_selection()); + open(&mut app); + settle(&ctx, &mut app); + let at = rect_of(&ctx, id).left_top() + vec2(40.0, 6.0); + let cursor = |ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SCREEN)), events, ..Default::default() }; + ctx.run_ui(input, |ui| show(app, ui.ctx())).platform_output.cursor_icon + }; + cursor(&ctx, &mut app, vec![Event::PointerMoved(at)]); + assert_eq!(cursor(&ctx, &mut app, vec![]), egui::CursorIcon::Default, "{name}: hovering the band"); + cursor(&ctx, &mut app, vec![button(at, true)]); + assert_eq!(cursor(&ctx, &mut app, vec![Event::PointerMoved(at + vec2(20.0, 10.0))]), egui::CursorIcon::Grabbing, "{name}: dragging it"); + cursor(&ctx, &mut app, vec![button(at + vec2(20.0, 10.0), false)]); + } +} + /// Tab goes through a dialog's controls and does not stop on the band that moves the window. #[test] fn tab_skips_the_band_that_moves_a_dialog() { diff --git a/crates/ui-egui/src/document_drag.rs b/crates/ui-egui/src/document_drag.rs index e85e95ae78..2784f29eef 100644 --- a/crates/ui-egui/src/document_drag.rs +++ b/crates/ui-egui/src/document_drag.rs @@ -44,6 +44,12 @@ fn activated_at_id() -> Id { Id::unique("document-drag-activated-at") } +/// Whether a Selection drag is carrying artwork across the document tabs, which then switch +/// documents and never move along the strip. +pub(crate) fn carrying_artwork(ctx: &Context) -> bool { + egui::DragAndDrop::payload::(ctx).is_some() +} + /// Record the Selection drag source and grab point, clearing any previous tab-hover timer. pub(crate) fn begin(app: &VectorcraftApp, ctx: &Context, grab: Point) { ctx.data_mut(|d| { diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 85309507f8..b467f05552 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -529,10 +529,24 @@ fn drop_targets_follow_the_buttons_edges() { fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; + let contour = vectorcraft_tools::addons::contour::ID; + let box3d = vectorcraft_tools::addons::box3d::ID; let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); assert_eq!( addon, - ["anchorEraserBrush", "extendPath", "measureInspect", "parametricShape", "cornerTool", "slideAnchor", "sharedEdge", "smartPen", enclosing] + [ + "anchorEraserBrush", + "extendPath", + "measureInspect", + "parametricShape", + "cornerTool", + "slideAnchor", + "sharedEdge", + "smartPen", + enclosing, + contour, + box3d + ] ); for advanced in [false, true] { if advanced { @@ -546,7 +560,9 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); - for tool in ["extendPath", "smartPen", enclosing] { + assert_eq!(listed(contour), Some(("Contour", vec![contour]))); + assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); + for tool in ["extendPath", "smartPen", enclosing, contour, box3d] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 7324520e27..e73d787364 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -448,7 +448,7 @@ mod tests { assert_eq!(fonts(&mut app)[0]["family"], "Missing Family"); assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); app.run("object.unlockAll", json!({})).unwrap(); - assert_eq!(app.ui.status, "some text is hidden or locked, so its font wasn't replaced"); + assert_eq!(app.ui.status, "", "unlocking the skipped text clears the warning"); let r = change(&mut app, &d, &from, true).unwrap(); assert_eq!(r["runs"], 1, "{r}"); assert!(r.get("warning").is_none(), "{r}"); @@ -459,6 +459,258 @@ mod tests { assert_eq!(app.ui.status, "Saved another document"); } + #[test] + fn replacement_keeps_only_font_warnings_that_still_apply() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Bye", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "Other", "font": "Inter"})).unwrap(); + + let replace = |app: &mut VectorcraftApp, from: &str, from_style: Option<&str>, style: &str| { + app.run("text.replaceFont", json!({"from": {"family": from, "style": from_style}, "to": {"family": "Source Sans 3", "style": style}})) + .unwrap() + }; + let first = replace(&mut app, "Missing Family", Some("Regular"), "Black Wide"); + assert_eq!(first["runs"], 1, "{first}"); + assert_eq!(first["skipped"], 1, "{first}"); + let style_warning = first["warning"].as_str().unwrap().split_once("; ").unwrap().1.to_string(); + assert!(style_warning.contains("Source Sans 3 Black Wide is drawn in Source Sans 3"), "{style_warning}"); + + let unrelated = replace(&mut app, "Inter", None, "Regular"); + assert_eq!(unrelated["runs"], 1, "{unrelated}"); + assert!(unrelated.get("warning").is_none(), "{unrelated}"); + assert_eq!(app.ui.status, first["warning"].as_str().unwrap()); + + app.run("object.unlockAll", json!({})).unwrap(); + let second = replace(&mut app, "Missing Family", None, "Regular"); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, style_warning); + + let third = replace(&mut app, "Source Sans 3", Some("Black Wide"), "Regular"); + assert_eq!(third["runs"], 1, "{third}"); + assert!(third.get("warning").is_none(), "{third}"); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn a_style_specific_retry_clears_a_family_wide_skipped_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Bye", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Regular"}})) + .unwrap(); + assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(1), Some(1))); + app.run("object.unlockAll", json!({})).unwrap(); + let second = app + .run( + "text.replaceFont", + json!({"from": {"family": "Missing Family", "style": "Regular"}, "to": {"family": "Source Sans 3", "style": "Regular"}}), + ) + .unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn new_text_in_the_source_font_does_not_keep_an_old_skip_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let replace = |app: &mut VectorcraftApp, from: &str, style: &str| { + app.run("text.replaceFont", json!({"from": {"family": from}, "to": {"family": "Source Sans 3", "style": style}})).unwrap() + }; + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Editable", "font": "Missing Family"})).unwrap(); + let skipped = app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = replace(&mut app, "Missing Family", "Regular"); + assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(1), Some(1))); + app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "New", "font": "Missing Family"})).unwrap(); + app.run("object.unlockAll", json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped)]; + let second = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + assert!(fonts(&mut app).iter().any(|font| font["family"] == "Missing Family")); + } + + #[test] + fn unlocking_skipped_text_clears_its_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Other", "font": "Inter"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(first["skipped"], 1); + app.run("object.unlockAll", json!({})).unwrap(); + assert_eq!(app.ui.status, ""); + let unrelated = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(unrelated["runs"], 1); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn a_document_revision_refreshes_the_skip_warning_on_tick() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Locked", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(first["skipped"], 1); + assert!(!app.ui.status.is_empty()); + + app.session.execute("object.unlockAll", &json!({})).unwrap(); + let ctx = egui::Context::default(); + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn a_selection_only_retry_ignores_unselected_text_in_the_same_font() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Outside", "font": "Missing Family"})).unwrap(); + let selected = app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Selected", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)]; + let params = json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}); + let first = app.run("text.replaceFont", params.clone()).unwrap(); + assert_eq!((first["runs"].as_u64(), first["skipped"].as_u64()), (Some(0), Some(1))); + app.run("object.unlockAll", json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)]; + let second = app.run("text.replaceFont", params).unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + assert!(app.session.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().any(|font| font["family"] == "Missing Family")); + } + + #[test] + fn a_changed_selection_keeps_the_original_warning_scope() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 30, "text": "Outside", "font": "Missing Family"})).unwrap(); + let added = app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Added", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + let skipped = app.session.execute("text.create", &json!({"x": 10, "y": 90, "text": "Locked", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped)]; + let params = json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true}); + let first = app.run("text.replaceFont", params.clone()).unwrap(); + assert_eq!(first["skipped"], 1, "{first}"); + app.run("object.unlockAll", json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(skipped), vectorcraft_doc::NodeId(added)]; + let second = app.run("text.replaceFont", params).unwrap(); + assert_eq!(second["runs"], 2, "{second}"); + assert!(second.get("warning").is_none(), "{second}"); + assert_eq!(app.ui.status, ""); + assert!(app.session.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().any(|font| font["family"] == "Missing Family")); + } + + #[test] + fn changing_selection_does_not_clear_a_skipped_font_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let selected = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Locked", "font": "Missing Family"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.active_mut().unwrap().selection.objects = vec![vectorcraft_doc::NodeId(selected)]; + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})) + .unwrap(); + assert_eq!(first["skipped"], 1, "{first}"); + let warning = app.ui.status.clone(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap(); + let unrelated = + app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}, "selectionOnly": true})).unwrap(); + assert_eq!(unrelated["runs"], 1, "{unrelated}"); + assert!(unrelated.get("warning").is_none(), "{unrelated}"); + assert_eq!(app.ui.status, warning); + app.run("object.unlockAll", json!({})).unwrap(); + let retry = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(retry["runs"], 1, "{retry}"); + assert!(retry.get("warning").is_none(), "{retry}"); + assert_eq!(app.ui.status, ""); + } + + #[test] + fn replacing_a_font_in_another_document_keeps_the_original_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Locked", "font": "Missing Family"})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + let first = app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(first["skipped"], 1, "{first}"); + let warning = app.ui.status.clone(); + let original_uid = app.session.active().unwrap().uid; + + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Other", "font": "Inter"})).unwrap(); + let second = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3"}})).unwrap(); + assert_eq!(second["runs"], 1, "{second}"); + assert_eq!(app.ui.status, warning); + app.session.set_active(0); + assert_eq!(app.session.active().unwrap().uid, original_uid); + assert_eq!(app.ui.status, warning); + } + + #[test] + fn a_comma_in_a_substituted_style_keeps_its_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap(); + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Black, Wide"}})) + .unwrap(); + let warning = first["warning"].as_str().unwrap().to_string(); + assert!(warning.contains("Black, Wide"), "{warning}"); + let unrelated = app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Serif 4"}})).unwrap(); + assert_eq!(unrelated["runs"], 1, "{unrelated}"); + assert!(unrelated.get("warning").is_none(), "{unrelated}"); + assert_eq!(app.ui.status, warning); + } + + #[test] + fn an_unrelated_substituted_style_does_not_keep_a_resolved_warning() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 70, "text": "Other", "font": "Inter"})).unwrap(); + app.run("text.replaceFont", json!({"from": {"family": "Inter"}, "to": {"family": "Source Sans 3", "style": "Narrow"}})).unwrap(); + let first = app + .run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Source Sans 3", "style": "Black, Wide"}})) + .unwrap(); + assert!(first["warning"].as_str().is_some_and(|warning| warning.contains("Black, Wide")), "{first}"); + let resolved = app + .run( + "text.replaceFont", + json!({"from": {"family": "Source Sans 3", "style": "Black, Wide"}, "to": {"family": "Inter", "style": "Regular"}}), + ) + .unwrap(); + assert!(resolved.get("warning").is_none(), "{resolved}"); + assert_eq!(app.ui.status, ""); + } + #[test] fn find_in_folder_puts_the_missing_fonts_dialog_in_find_fonts_place() { let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder")).unwrap(); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 5fbca5a2e9..39dd49bfc6 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -13,7 +13,7 @@ //! selected text, one undo step per notch. The menu's order at the first turn stays fixed until the //! pointer leaves the field or the text selection changes; steps stop at its first and last family. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use egui::{Color32, Sense, Ui, vec2}; @@ -363,12 +363,17 @@ pub fn font_menu( // These turns preceded the opener. The popup cancels back to the newly // applied family, and any preview drawn this pass has not been applied. st.current.clone_from(&own); + st.highlight = st.rows.iter().position(|row| matches!(row, Row::Family(f) if f.eq_ignore_ascii_case(&own))); st.previewed = None; } out = Some(FontPick::Wheel(steps)); } } - if drawn || !field.contains_pointer() { + let queued = ui.data(|d| { + d.get_temp::(wheel_fields_id(ui.ctx().viewport_id())) + .is_some_and(|fields| fields.queued.iter().any(|event| event.field == field.id)) + }); + if drawn || (!field.contains_pointer() && !queued) { st.wheel_order = None; ui.data_mut(|d| d.remove::(field.id.with("wheel"))); } @@ -436,6 +441,26 @@ struct WheelField { layer: egui::LayerId, } +#[derive(Clone)] +struct QueuedWheel { + frame: u64, + field: egui::Id, + menu: egui::Id, + position: egui::Pos2, + rect: egui::Rect, + event: egui::Event, + amount: f32, + reset_after: bool, + positions_after: Vec, +} + +#[derive(Clone)] +struct ReplayWheel { + target: egui::LayerId, + position: egui::Pos2, + event: egui::Event, +} + #[derive(Clone, Default)] struct WheelFields { pass: u64, @@ -445,6 +470,8 @@ struct WheelFields { pointer: Option, fields: Vec, pending: HashMap>, + queued: Vec, + replay: Vec, } #[cfg(not(target_arch = "wasm32"))] @@ -461,6 +488,58 @@ impl egui::Plugin for WheelLayerSnapshot { "font wheel viewport layers" } + fn on_begin_pass(&mut self, ui: &mut Ui) { + let ctx = ui.ctx(); + let viewport = ctx.viewport_id(); + if viewport == egui::ViewportId::ROOT { + return; + } + let key = wheel_fields_id(viewport); + let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; + let frame = ctx.cumulative_frame_nr_for(viewport); + let mut ready = Vec::new(); + fields.queued.retain(|event| { + if event.frame < frame { + ready.push(event.clone()); + false + } else { + true + } + }); + let replayed = fields.replay.len(); + for event in ready { + let current = fields.fields.iter().find(|field| field.id == event.field); + let layer = current.map(|field| field.layer); + let opened_after_wheel = current.is_none() + && ctx.data(|d| d.get_temp::(event.menu)).is_some_and(|menu| menu.opened > 0 && menu.opened == fields.pass); + let active = opened_after_wheel + || current.is_some_and(|field| field.rect.contains(event.position) && ctx.layer_id_at(event.position) == Some(field.layer)); + let left = !active || event.reset_after || event.positions_after.iter().any(|position| ctx.layer_id_at(*position) != layer); + let id = event.field.with("wheel"); + if !active { + ctx.data_mut(|d| d.remove::(id)); + if let Some(target) = ctx.layer_id_at(event.position) { + fields.replay.push(ReplayWheel { target, position: event.position, event: event.event }); + } + } else { + let notches = ctx.data(|d| d.get_temp::(id)).unwrap_or(0.0) + event.amount; + let whole = notches.trunc(); + ctx.data_mut(|d| d.insert_temp(id, notches - whole)); + if whole != 0.0 { + fields.pending.entry(event.field).or_default().push(WheelInput::Notches(whole as i32)); + } + } + if left { + ctx.data_mut(|d| d.remove::(id)); + fields.pending.entry(event.field).or_default().push(WheelInput::Leave); + } + } + if fields.replay.len() > replayed { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(key, fields)); + } + fn on_end_pass(&mut self, ui: &mut Ui) { let ctx = ui.ctx(); let viewport = ctx.viewport_id(); @@ -502,6 +581,36 @@ fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { egui::Id::unique("font-wheel-fields").with(viewport) } +fn mark_queued_wheel_leaves(fields: &mut WheelFields, point: Option) { + let mut marked = HashSet::new(); + for event in fields.queued.iter_mut().rev() { + if marked.insert(event.field) { + match point { + Some(position) if event.rect.contains(position) => event.positions_after.push(position), + _ => event.reset_after = true, + } + } + } +} + +#[cfg(test)] +pub(crate) fn wheel_field_layer_for_test(ctx: &egui::Context, viewport: egui::ViewportId, point: egui::Pos2) -> Option { + ctx.data(|data| data.get_temp::(wheel_fields_id(viewport))) + .and_then(|fields| fields.fields.iter().find(|field| field.rect.contains(point)).map(|field| field.layer)) +} + +#[cfg(test)] +pub(crate) fn offset_wheel_fields_for_test(ctx: &egui::Context, viewport: egui::ViewportId, offset: egui::Vec2) { + let key = wheel_fields_id(viewport); + ctx.data_mut(|data| { + let mut fields = data.get_temp::(key).expect("registered wheel fields"); + for field in &mut fields.fields { + field.rect = field.rect.translate(offset); + } + data.insert_temp(key, fields); + }); +} + #[derive(Clone, PartialEq)] struct WheelTarget { input: crate::state::InputGeneration, @@ -653,8 +762,12 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } match event { egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => { + mark_queued_wheel_leaves(&mut fields, Some(*p)); for field in &fields.fields { - if over(field, pointer) && !over(field, Some(*p)) { + if pointer.is_some_and(|point| field.rect.contains(point)) + && !field.rect.contains(*p) + && !fields.queued.iter().any(|event| event.field == field.id) + { ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); fields.pending.entry(field.id).or_default().push(WheelInput::Leave); } @@ -663,23 +776,42 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } egui::Event::PointerGone => { pointer = None; + mark_queued_wheel_leaves(&mut fields, None); for field in &fields.fields { - ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); - fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + if !fields.queued.iter().any(|event| event.field == field.id) { + ctx.data_mut(|d| d.remove::(field.id.with("wheel"))); + fields.pending.entry(field.id).or_default().push(WheelInput::Leave); + } } } egui::Event::MouseWheel { unit, delta, modifiers, .. } if modifiers.is_none() && delta.y != 0.0 => { if let Some(field) = fields.fields.iter().rev().find(|f| !fields.activating.contains(&f.id) && over(f, pointer)).copied() { - let id = field.id.with("wheel"); - let mut notches: f32 = ctx.data(|d| d.get_temp(id)).unwrap_or(0.0); - notches -= match unit { + let amount = -match unit { egui::MouseWheelUnit::Point => delta.y / line, egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => delta.y, }; - let whole = notches.trunc(); - ctx.data_mut(|d| d.insert_temp(id, notches - whole)); - if whole != 0.0 { - fields.pending.entry(field.id).or_default().push(WheelInput::Notches(whole as i32)); + if cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() != raw.viewport_id { + if let Some(position) = pointer { + fields.queued.push(QueuedWheel { + frame, + field: field.id, + menu: field.menu, + position, + rect: field.rect, + event: event.clone(), + amount, + reset_after: false, + positions_after: Vec::new(), + }); + } + } else { + let id = field.id.with("wheel"); + let notches = ctx.data(|d| d.get_temp::(id)).unwrap_or(0.0) + amount; + let whole = notches.trunc(); + ctx.data_mut(|d| d.insert_temp(id, notches - whole)); + if whole != 0.0 { + fields.pending.entry(field.id).or_default().push(WheelInput::Notches(whole as i32)); + } } captured = true; return false; @@ -689,6 +821,23 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { } true }); + if !fields.replay.is_empty() { + let mut replay = Vec::new(); + for wheel in std::mem::take(&mut fields.replay) { + #[cfg(not(target_arch = "wasm32"))] + let target_still_visible = native_layers.as_ref().is_some_and(|layers| (layers.0)(wheel.position) == Some(wheel.target)); + #[cfg(target_arch = "wasm32")] + let target_still_visible = false; + if target_still_visible { + replay.push(egui::Event::PointerMoved(wheel.position)); + replay.push(wheel.event); + } + } + if !replay.is_empty() { + replay.push(pointer.map_or(egui::Event::PointerGone, egui::Event::PointerMoved)); + raw.events.splice(0..0, replay); + } + } fields.pointer = pointer; ctx.data_mut(|d| d.insert_temp(key, fields)); if captured { diff --git a/crates/ui-egui/src/graphics.rs b/crates/ui-egui/src/graphics.rs index db85972d2a..11f03f5c5e 100644 --- a/crates/ui-egui/src/graphics.rs +++ b/crates/ui-egui/src/graphics.rs @@ -195,6 +195,7 @@ mod tests { #[test] fn the_app_uploads_everything_again_in_a_new_context() { let mut app = app(); + app.canvas.worker_started = true; // render on this thread let old = egui::Context::default(); // Fonts, then the canvas. for _ in 0..3 { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 689eb2015f..251dc585e2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -66,7 +66,7 @@ fn plural_czech(n: u64) -> usize { } } -/// French: 0 and 1 are `one` (« 0 calque »), everything else `other`. +/// French and Hindi integer counts: 0 and 1 are `one`, everything else `other`. fn plural_french(n: u64) -> usize { usize::from(n > 1) } @@ -97,8 +97,18 @@ fn plural_polish(n: u64) -> usize { } /// The registry. English first: it is the fallback and the source language. -pub static LANGUAGES: [LangInfo; 27] = [ +pub static LANGUAGES: [LangInfo; 28] = [ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() }, + // Hindi shares the integer zero/one rule with French. Desktop UI fonts are loaded lazily + // from installed faces by ui_fonts; the web needs a Devanagari font in its font set. + LangInfo { + code: "hi", + name: "हिन्दी", + source: include_str!("i18n/hi.tsv"), + plural: plural_french, + complete_menus: true, + catalog: OnceLock::new(), + }, // Greek: the whole interface and the status and error messages, keeping the same names in // English as Spanish; every `el-*` locale (including `el-GR` and `el-CY`) resolves here. LangInfo { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 284e70e095..e60b76cefa 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3207,7 +3207,9 @@ digits Malayalam Малаялам Patterns Мостри Stroke Options Опции на щриха Character: Знак: + Paragraph: Абзац: Character options Опции на знака + Paragraph options Опции за абзац Stroke options Опции на щриха Transform options Опции за трансформации Stroke Weight Дебелина на щриха @@ -4194,6 +4196,8 @@ axis Both И двете @msg no such saved selection няма такава запазена селекция @msg no such segment няма такъв сегмент @msg no such spine point няма такава точка от оста +@msg `with` must be a list of at most 10000 spine point indexes `with` трябва да е списък с най-много 10000 индекса на точки от оста +@msg `with` moves points, not a handle `with` мести точки, не дръжка @msg no such spine segment няма такъв сегмент от оста @msg no such subpath няма такъв подпът @msg no such user library няма такава потребителска библиотека @@ -4524,6 +4528,9 @@ axis Both И двете @msg an image VectorCraft can't read was left out изображение, което VectorCraft не може да разчете, беше пропуснато @msg an image whose data is cut short was left out изображение с непълни данни беше пропуснато @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel свързаните картини показват записания във файла предварителен преглед с ниска резолюция, докато файловете им бъдат намерени: презакачете ги в панела „Връзки“ +@msg linked type areas past VectorCraft's limits were left out свързаните текстови области извън ограниченията на VectorCraft бяха пропуснати +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, използван като маска в свързани области, обтичащ текст или съставен път, не изрязва +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel свързаните картини без предварителен преглед във файла показват заместител, докато файловете им бъдат намерени: презакачете ги в панела „Връзки“ @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise текстовите рамки за област в редове, твърде къси за шрифта, в който се показват, получиха по-високи рамки ({_1}): текстът им иначе нямаше да се види @msg its editing data doesn't say where its art is данните му за редактиране не посочват къде се намира неговата графика @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) този файл е записан без съвместимост с PDF и данните му за редактиране не могат да бъдат прочетени ({why}) @@ -5949,6 +5956,9 @@ anchor Points: Точки: Find Nearest Swatch… Намиране на най-близкия образец… Find Nearest Swatch Намиране на най-близкия образец Apply Nearest Swatch Прилагане на най-близкия образец +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Прилагане на запълването към щриха + Apply Stroke to Fill Прилагане на щриха към запълването Select objects to find the swatches nearest their colors. Изберете обекти, за да намерите най-близките до цветовете им образци. @msg select objects or give `color` изберете обекти или задайте `color` @msg `color` is not a colour `color` не е цвят @@ -6186,6 +6196,10 @@ breakText Glyphs Глифи Bow Дъга Spike Връх Skip Spaces Пропускане на интервалите + Release Type on a Path… Освобождаване на текст по пътя… + Release Type on a Path Освобождаване на текст по пътя + Text and Path Текст и път + Path Only Само път @msg The art is too large to copy as a picture: other apps get no PNG of it Графиката е твърде голяма, за да се копира като изображение: другите приложения не получават PNG от нея # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6197,3 +6211,43 @@ breakText Glyphs Глифи Fully Outside Изцяло извън No artboards match. Няма съвпадащи работни области. Chosen: {n} of {total} Избрани: {n} от {total} + +# Contour add-on + Contour Очертание + Contour Tool Инструмент „Очертание“ + Sharp Заостряне + Bake Разшири + Turn the Contour into plain paths Превръща очертанието в обикновени пътища + Set Corners… Задаване на ъгли… + All Anchors Всички опорни точки + Odd-Numbered Anchors Нечетни опорни точки + Even-Numbered Anchors Четни опорни точки + Minimum angle Минимален ъгъл + Maximum angle Максимален ъгъл + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Избиране на свързаните + Select Embedded Избиране на вградените + Select Missing Избиране на липсващите + Select Modified Избиране на модифицираните + Select by Link Status Избиране по състояние на връзката + Select by Link Status… Избиране по състояние на връзката… + Search images Търсене на изображения + No images match. Няма съвпадащи изображения. +@msgplural Selected {n} linked image|Selected {n} linked images Избрано е {n} свързано изображение|Избрани са {n} свързани изображения +@msgplural Selected {n} embedded image|Selected {n} embedded images Избрано е {n} вградено изображение|Избрани са {n} вградени изображения +@msgplural Selected {n} missing image|Selected {n} missing images Избрано е {n} липсващо изображение|Избрани са {n} липсващи изображения +@msgplural Selected {n} modified image|Selected {n} modified images Избрано е {n} модифицирано изображение|Избрани са {n} модифицирани изображения +@msgplural Selected {n} image|Selected {n} images Избрано е {n} изображение|Избрани са {n} изображения +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; още {n} е скрито или заключено|{selected}; още {n} са скрити или заключени +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; още {n} е в шаблонен слой|{selected}; още {n} са в шаблонни слоеве +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; още {n} е извън изолираната група|{selected}; още {n} са извън изолираната група +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; още {n} не може да бъде избрано сега|{selected}; още {n} не могат да бъдат избрани сега + +# Compound Shapes add-on + Compound Shapes Съставни фигури + Shape Mode Buttons Make Compound Shapes Бутоните за режими на фигури създават съставни фигури + +# 3D Box add-on + 3D Box 3D кутия + 3D Box Tool Инструмент за 3D кутия diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d6e1bdb8ef..0d95e80181 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1469,7 +1469,9 @@ digits Malayalam Malajalam Standard Vertical Roman Alignment Standardno okomito latinično poravnanje Strikethrough Precrtano Character: Znak: + Paragraph: Pasus: Character options Opcije znakova + Paragraph options Opcije pasusa Subscript Indeks Subscript (on the roadmap) Indeks (u planu) Superscript Eksponent @@ -4589,6 +4591,8 @@ imageTrace Outline Obris @msg no such saved selection nema takvog sačuvanog odabira @msg no such segment nema takvog segmenta @msg no such spine point nema takve tačke kičme +@msg `with` must be a list of at most 10000 spine point indexes `with` mora biti lista od najviše 10000 indeksa tačaka kičme +@msg `with` moves points, not a handle `with` pomjera tačke, ne ručicu @msg no such spine segment nema takvog segmenta kičme @msg no such subpath nema takve podputanje @msg no such user library nema takve korisničke biblioteke @@ -4923,6 +4927,9 @@ imageTrace Outline Obris @msg an image VectorCraft can't read was left out izostavljena je slika koju VectorCraft ne može pročitati @msg an image whose data is cut short was left out izostavljena je slika čiji su podaci skraćeni @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel povezane slike prikazuju pregled niske rezolucije sačuvan u datoteci dok se njihove datoteke ne pronađu: ponovo ih povežite u panelu Veze +@msg linked type areas past VectorCraft's limits were left out povezana područja teksta izvan ograničenja programa VectorCraft su izostavljena +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst korišten kao maska u povezanim područjima, omotanom tekstu ili složenoj putanji ne odsijeca +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel povezane slike bez pregleda u datoteci prikazuju čuvar mjesta dok se njihove datoteke ne pronađu: ponovo ih povežite u panelu Veze @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise tekst u području u okvirima prekratkim za red fonta u kojem se prikazuje dobio je više okvire ({_1}): inače se tekst ne bi prikazao @msg its editing data doesn't say where its art is njeni podaci za uređivanje ne govore gdje joj je crtež @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ova datoteka je sačuvana bez PDF kompatibilnosti, a njeni podaci za uređivanje se ne mogu pročitati ({why}) @@ -6075,6 +6082,9 @@ shape Open Otvoren Find Nearest Swatch… Pronađi najbliži uzorak boje… Find Nearest Swatch Pronađi najbliži uzorak boje Apply Nearest Swatch Primijeni najbliži uzorak boje +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Primijeni ispunu na potez + Apply Stroke to Fill Primijeni potez na ispunu Select objects to find the swatches nearest their colors. Odaberite objekte da pronađete uzorke boja najbliže njihovim bojama. @msg select objects or give `color` odaberite objekte ili navedite `color` @msg `color` is not a colour `color` nije boja @@ -6220,6 +6230,11 @@ shape Open Otvoren Bow Luk Spike Šiljak Skip Spaces Preskoči razmake + Release Type on a Path… Oslobodi tekst na putanji… + Release Type on a Path Oslobodi tekst na putanji + Text and Path Tekst i putanja + Path Only Samo putanja + Text Only Samo tekst @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika je prevelika da bi se kopirala kao slika: druge aplikacije ne dobijaju njen PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6231,3 +6246,43 @@ shape Open Otvoren Fully Outside Potpuno vani No artboards match. Nijedna radna ploča ne odgovara. Chosen: {n} of {total} Odabrano: {n} od {total} + +# Contour add-on + Contour Kontura + Contour Tool Alat kontura + Sharp Oštro + Bake Proširi + Turn the Contour into plain paths Pretvori konturu u obične putanje + Set Corners… Postavi uglove… + All Anchors Sva sidra + Odd-Numbered Anchors Neparna sidra + Even-Numbered Anchors Parna sidra + Minimum angle Najmanji ugao + Maximum angle Najveći ugao + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Odaberi povezane + Select Embedded Odaberi ugrađene + Select Missing Odaberi nedostajuće + Select Modified Odaberi izmijenjene + Select by Link Status Odabir po statusu veze + Select by Link Status… Odabir po statusu veze… + Search images Pretraži slike + No images match. Nijedna slika ne odgovara. +@msgplural Selected {n} linked image|Selected {n} linked images Odabrana je {n} povezana slika|Odabrane su {n} povezane slike|Odabrano je {n} povezanih slika +@msgplural Selected {n} embedded image|Selected {n} embedded images Odabrana je {n} ugrađena slika|Odabrane su {n} ugrađene slike|Odabrano je {n} ugrađenih slika +@msgplural Selected {n} missing image|Selected {n} missing images Odabrana je {n} nedostajuća slika|Odabrane su {n} nedostajuće slike|Odabrano je {n} nedostajućih slika +@msgplural Selected {n} modified image|Selected {n} modified images Odabrana je {n} izmijenjena slika|Odabrane su {n} izmijenjene slike|Odabrano je {n} izmijenjenih slika +@msgplural Selected {n} image|Selected {n} images Odabrana je {n} slika|Odabrane su {n} slike|Odabrano je {n} slika +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; još {n} je skrivena ili zaključana|{selected}; još {n} su skrivene ili zaključane|{selected}; još {n} je skriveno ili zaključano +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; još {n} je na sloju predloška|{selected}; još {n} su na slojevima predloška|{selected}; još {n} je na slojevima predloška +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; još {n} je izvan izolirane grupe|{selected}; još {n} su izvan izolirane grupe|{selected}; još {n} je izvan izolirane grupe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; još {n} se sada ne može odabrati|{selected}; još {n} se sada ne mogu odabrati|{selected}; još {n} se sada ne može odabrati + +# Compound Shapes add-on + Compound Shapes Složeni oblici + Shape Mode Buttons Make Compound Shapes Tasteri načina oblika prave složene oblike + +# 3D Box add-on + 3D Box 3D kutija + 3D Box Tool Alat za 3D kutiju diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 75b6b4ca3a..a3cb5b42aa 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -615,12 +615,14 @@ Character Alignment Alineació de caràcters Character Direction Direcció de caràcters Character options Opcions de caràcter + Paragraph options Opcions de paràgraf Character Rotation Rotació de caràcters Character Set: Joc de caràcters: Character Style Estil de caràcter Character Style Options Opcions de l’estil de caràcter Character Styles Estils de caràcter Character: Caràcter: + Paragraph: Paràgraf: Charcoal Carbó Charcoal… Carbó… Check an artboard to save. Marca un tauler per desar. @@ -5055,6 +5057,7 @@ digits Malayalam Malaiàlam @msg damaged malmès @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La recuperació de dades no té cap lloc on guardar còpies: configureu Preferències → Gestió de fitxers → Recuperació de dades → Carpeta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} La recuperació de dades no pot guardar còpies a {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} No es poden carregar complements des de {path}: {e} @msg data the program reads is damaged or cut short, or the program asks for a position in a file that has none les dades que llegeix el programa estan malmeses o tallades, o el programa demana una posició en un fitxer que no en té @msg decimals must be {_1}–{_2} (got {_3}) els decimals han de ser {_1}–{_2} (rebut {_3}) @msg Dimension point is outside the canvas El punt de dimensió és fora del llenç @@ -5180,6 +5183,9 @@ digits Malayalam Malaiàlam @msg library panel `{given}` isn't missing its library al panell de biblioteca `{given}` no li falta la biblioteca @msg library panel `{given}` isn't open el panell de biblioteca `{given}` no està obert @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les imatges enllaçades mostren la previsualització de baixa resolució desada al fitxer fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços +@msg linked type areas past VectorCraft's limits were left out s’han omès les àrees de text enllaçades que superen els límits de VectorCraft +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip el text usat com a màscara en àrees enllaçades, en text ajustat o en un traçat compost no retalla +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel les imatges enllaçades sense previsualització al fitxer mostren un marcador de posició fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços @msg Live Paint Merge: select a Live Paint group and the paths to add Fusió de pintura interactiva: seleccioneu un grup de pintura interactiva i els traçats que voleu afegir @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first La pintura interactiva accepta traçats i traçats compostos: convertiu abans el text, les imatges i altres objectes a traçats @msg Live Paint: select paths or compound paths Pintura interactiva: seleccioneu traçats o traçats compostos @@ -5322,6 +5328,8 @@ digits Malayalam Malaiàlam @msg no such saved selection no existeix aquesta selecció desada @msg no such segment no existeix aquest segment @msg no such spine point no existeix aquest punt de l’espina +@msg `with` must be a list of at most 10000 spine point indexes `with` ha de ser una llista d’un màxim de 10000 índexs de punts de l’espina +@msg `with` moves points, not a handle `with` mou punts, no una nansa @msg no such spine segment no existeix aquest segment de l’espina @msg no such subpath no existeix aquest subtraçat @msg no such user library no existeix aquesta biblioteca d’usuari @@ -6083,6 +6091,9 @@ anchor Points: Punts: Find Nearest Swatch… Cerca la mostra més propera… Find Nearest Swatch Cerca la mostra més propera Apply Nearest Swatch Aplica la mostra més propera +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Aplica el farciment al traç + Apply Stroke to Fill Aplica el traç al farciment Select objects to find the swatches nearest their colors. Seleccioneu objectes per trobar les mostres més properes als seus colors. @msg select objects or give `color` seleccioneu objectes o indiqueu `color` @msg `color` is not a colour `color` no és un color @@ -6321,6 +6332,10 @@ breakText Glyphs Glifs Bow Arc Spike Pic Skip Spaces Omet els espais + Release Type on a Path… Allibera el text sobre un traçat… + Release Type on a Path Allibera el text sobre un traçat + Text and Path Text i traçat + Path Only Només traçat @msg The art is too large to copy as a picture: other apps get no PNG of it La il·lustració és massa gran per copiar-la com a imatge: les altres aplicacions no en reben cap PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6332,3 +6347,43 @@ breakText Glyphs Glifs Fully Outside Totalment fora No artboards match. Cap tauler no coincideix. Chosen: {n} of {total} Triats: {n} de {total} + +# Contour add-on + Contour Contorn + Contour Tool Eina de contorn + Sharp Punxegut + Bake Expandeix + Turn the Contour into plain paths Converteix el contorn en traçats simples + Set Corners… Defineix les cantonades… + All Anchors Tots els ancoratges + Odd-Numbered Anchors Ancoratges senars + Even-Numbered Anchors Ancoratges parells + Minimum angle Angle mínim + Maximum angle Angle màxim + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecciona les enllaçades + Select Embedded Selecciona les incrustades + Select Missing Selecciona les que falten + Select Modified Selecciona les modificades + Select by Link Status Selecciona per estat de l’enllaç + Select by Link Status… Selecciona per estat de l’enllaç… + Search images Cerca imatges + No images match. Cap imatge no coincideix. +@msgplural Selected {n} linked image|Selected {n} linked images S’ha seleccionat {n} imatge enllaçada|S’han seleccionat {n} imatges enllaçades +@msgplural Selected {n} embedded image|Selected {n} embedded images S’ha seleccionat {n} imatge incrustada|S’han seleccionat {n} imatges incrustades +@msgplural Selected {n} missing image|Selected {n} missing images S’ha seleccionat {n} imatge que falta|S’han seleccionat {n} imatges que falten +@msgplural Selected {n} modified image|Selected {n} modified images S’ha seleccionat {n} imatge modificada|S’han seleccionat {n} imatges modificades +@msgplural Selected {n} image|Selected {n} images S’ha seleccionat {n} imatge|S’han seleccionat {n} imatges +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} més està oculta o bloquejada|{selected}; {n} més estan ocultes o bloquejades +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} més és en una capa de plantilla|{selected}; {n} més són en capes de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} més és fora del grup aïllat|{selected}; {n} més són fora del grup aïllat +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} més no es pot seleccionar ara|{selected}; {n} més no es poden seleccionar ara + +# Compound Shapes add-on + Compound Shapes Formes compostes + Shape Mode Buttons Make Compound Shapes Els botons de mode de forma creen formes compostes + +# 3D Box add-on + 3D Box Caixa 3D + 3D Box Tool Eina Caixa 3D diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4cb2257256..063ddd591d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1493,7 +1493,9 @@ digits Malayalam Malajálamské Standard Vertical Roman Alignment Standardní svislé zarovnání latinky Strikethrough Přeškrtnutí Character: Znak: + Paragraph: Odstavec: Character options Možnosti znaků + Paragraph options Možnosti odstavce Subscript Dolní index Subscript (on the roadmap) Dolní index (v plánu) Superscript Horní index @@ -4292,6 +4294,7 @@ imageTrace Outline Obrys @msg Create from Selection: the selection has no area Vytvořit z výběru: výběr nemá žádnou plochu @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Obnovení dat nemá kam ukládat kopie: nastavte Předvolby → Práce se soubory → Obnovení dat → Složka (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Obnovení dat nemůže ukládat kopie do {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Zásuvné moduly nelze načíst z {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) nástrojem Přímý výběr vyberte kotevní body, kde se má cesta rozdělit (ne koncové body otevřených cest) @msg Divide Objects Below: select a path Rozdělit objekty pod: vyberte cestu @msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu @@ -4636,6 +4639,8 @@ imageTrace Outline Obrys @msg no such saved selection takový uložený výběr neexistuje @msg no such segment takový segment neexistuje @msg no such spine point takový bod páteře neexistuje +@msg `with` must be a list of at most 10000 spine point indexes `with` musí být seznam nejvýše 10000 indexů bodů páteře +@msg `with` moves points, not a handle `with` posouvá body, ne táhlo @msg no such spine segment takový segment páteře neexistuje @msg no such subpath taková dílčí cesta neexistuje @msg no such user library taková uživatelská knihovna neexistuje @@ -4980,6 +4985,9 @@ imageTrace Outline Obrys @msg graphs come in as plain art, without their data or settings grafy se načtou jako obyčejná grafika, bez svých dat a nastavení @msg an image whose data is cut short was left out obrázek s useknutými daty byl vynechán @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel propojené obrázky se zobrazují jako náhled v nízkém rozlišení uložený v souboru, dokud se nenajdou jejich soubory: znovu je propojte v panelu Propojení +@msg linked type areas past VectorCraft's limits were left out propojené textové oblasti nad limity aplikace VectorCraft byly vynechány +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip text použitý jako maska v propojených oblastech, obtékaném textu nebo složené cestě neořezává +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel propojené obrázky bez náhledu v souboru se zobrazují jako zástupný symbol, dokud se nenajdou jejich soubory: znovu je propojte v panelu Propojení @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise text v oblasti v rámcích příliš nízkých pro řádek písma, ve kterém se zde zobrazuje, dostal vyšší rámce ({_1}): jinak by nebyl vidět @msg its editing data doesn't say where its art is z jeho dat pro úpravy není zřejmé, kde je kresba @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) tento soubor byl uložen bez kompatibility s PDF a jeho data pro úpravy nelze přečíst ({why}) @@ -6099,6 +6107,9 @@ anchor Points: Body: Find Nearest Swatch… Najít nejbližší položku vzorníku… Find Nearest Swatch Najít nejbližší položku vzorníku Apply Nearest Swatch Použít nejbližší položku vzorníku +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Použít výplň na tah + Apply Stroke to Fill Použít tah na výplň Select objects to find the swatches nearest their colors. Vyberte objekty, k jejichž barvám chcete najít nejbližší položky vzorníku. @msg select objects or give `color` vyberte objekty nebo zadejte `color` @msg `color` is not a colour `color` není barva @@ -6335,6 +6346,10 @@ breakText Glyphs Glyfy Bow Oblouk Spike Špička Skip Spaces Přeskočit mezery + Release Type on a Path… Uvolnit text na cestě… + Release Type on a Path Uvolnit text na cestě + Text and Path Text a cesta + Path Only Pouze cesta @msg The art is too large to copy as a picture: other apps get no PNG of it Kresba je příliš velká na zkopírování jako obrázek: ostatní aplikace z ní nedostanou PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6346,3 +6361,43 @@ breakText Glyphs Glyfy Fully Outside Zcela vně No artboards match. Žádná pracovní plocha neodpovídá. Chosen: {n} of {total} Zvoleno: {n} z {total} + +# Contour add-on + Contour Obrys + Contour Tool Nástroj Obrys + Sharp Ostrý + Bake Rozložit + Turn the Contour into plain paths Převést obrys na běžné cesty + Set Corners… Nastavit rohy… + All Anchors Všechny kotevní body + Odd-Numbered Anchors Liché kotevní body + Even-Numbered Anchors Sudé kotevní body + Minimum angle Minimální úhel + Maximum angle Maximální úhel + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Vybrat propojené + Select Embedded Vybrat vložené + Select Missing Vybrat chybějící + Select Modified Vybrat upravené + Select by Link Status Vybrat podle stavu propojení + Select by Link Status… Vybrat podle stavu propojení… + Search images Hledat obrazy + No images match. Žádný obraz neodpovídá. +@msgplural Selected {n} linked image|Selected {n} linked images Vybrán {n} propojený obraz|Vybrány {n} propojené obrazy|Vybráno {n} propojených obrazů +@msgplural Selected {n} embedded image|Selected {n} embedded images Vybrán {n} vložený obraz|Vybrány {n} vložené obrazy|Vybráno {n} vložených obrazů +@msgplural Selected {n} missing image|Selected {n} missing images Vybrán {n} chybějící obraz|Vybrány {n} chybějící obrazy|Vybráno {n} chybějících obrazů +@msgplural Selected {n} modified image|Selected {n} modified images Vybrán {n} upravený obraz|Vybrány {n} upravené obrazy|Vybráno {n} upravených obrazů +@msgplural Selected {n} image|Selected {n} images Vybrán {n} obraz|Vybrány {n} obrazy|Vybráno {n} obrazů +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; další {n} je skrytý nebo zamčený|{selected}; další {n} jsou skryté nebo zamčené|{selected}; dalších {n} je skrytých nebo zamčených +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; další {n} je na vrstvě šablony|{selected}; další {n} jsou na vrstvách šablony|{selected}; dalších {n} je na vrstvách šablony +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; další {n} je mimo izolovanou skupinu|{selected}; další {n} jsou mimo izolovanou skupinu|{selected}; dalších {n} je mimo izolovanou skupinu +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; další {n} teď nelze vybrat|{selected}; další {n} teď nelze vybrat|{selected}; dalších {n} teď nelze vybrat + +# Compound Shapes add-on + Compound Shapes Složené tvary + Shape Mode Buttons Make Compound Shapes Tlačítka režimů tvarů vytvářejí složené tvary + +# 3D Box add-on + 3D Box 3D kvádr + 3D Box Tool Nástroj 3D kvádr diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3388daba92..9db09ea0f8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1403,7 +1403,9 @@ digits Malayalam Malayalam Standard Vertical Roman Alignment Standard lodret romersk justering Strikethrough Gennemstreget Character: Tegn: + Paragraph: Afsnit: Character options Tegnindstillinger + Paragraph options Afsnitsindstillinger Subscript Sænket skrift Subscript (on the roadmap) Sænket skrift (på vejkortet) Superscript Hævet skrift @@ -4611,6 +4613,9 @@ imageTrace Outline Kontur @msg an image VectorCraft can't read was left out et billede, som VectorCraft ikke kan læse, blev udeladt @msg an image whose data is cut short was left out et billede, hvis data er afkortet, blev udeladt @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel linkede billeder viser den gemte forhåndsvisning i lav opløsning, indtil deres filer findes: link dem igen i Links-panelet +@msg linked type areas past VectorCraft's limits were left out sammenkædede tekstområder ud over VectorCrafts grænser blev udeladt +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst brugt som maske i sammenkædede områder, ombrudt tekst eller en sammensat kurve beskærer ikke +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel linkede billeder uden forhåndsvisning i filen viser en pladsholder, indtil deres filer findes: link dem igen i Links-panelet @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise rammetekst i rammer, der er for lave til en tekstlinje i den skrifttype, den viser i, fik højere rammer ({_1}): teksten ville ellers ikke blive vist @msg its editing data doesn't say where its art is dens redigeringsdata siger ikke, hvor dens grafik er @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) denne fil blev gemt uden PDF-kompatibilitet, og dens redigeringsdata kan ikke læses ({why}) @@ -5966,6 +5971,9 @@ anchor Points: Punkter: Find Nearest Swatch… Find nærmeste farveprøve… Find Nearest Swatch Find nærmeste farveprøve Apply Nearest Swatch Anvend nærmeste farveprøve +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Anvend udfyldning på kontur + Apply Stroke to Fill Anvend kontur på udfyldning Select objects to find the swatches nearest their colors. Markér objekter for at finde de farveprøver, der ligger tættest på deres farver. @msg select objects or give `color` markér objekter, eller angiv `color` @msg `color` is not a colour `color` er ikke en farve @@ -6202,6 +6210,10 @@ breakText Glyphs Glyffer Bow Bue Spike Spids Skip Spaces Spring mellemrum over + Release Type on a Path… Frigør tekst på kurve… + Release Type on a Path Frigør tekst på kurve + Text and Path Tekst og kurve + Path Only Kun kurve @msg The art is too large to copy as a picture: other apps get no PNG of it Grafikken er for stor til at blive kopieret som et billede: andre programmer får ingen PNG af den # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6213,3 +6225,43 @@ breakText Glyphs Glyffer Fully Outside Helt udenfor No artboards match. Ingen tegneflader passer. Chosen: {n} of {total} Valgt: {n} af {total} + +# Contour add-on + Contour Kontur + Contour Tool Kontur-værktøj + Sharp Spids + Bake Udvid + Turn the Contour into plain paths Gør konturen til almindelige stier + Set Corners… Angiv hjørner… + All Anchors Alle ankre + Odd-Numbered Anchors Ulige ankre + Even-Numbered Anchors Lige ankre + Minimum angle Mindste vinkel + Maximum angle Største vinkel + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markér linkede + Select Embedded Markér integrerede + Select Missing Markér manglende + Select Modified Markér ændrede + Select by Link Status Markér efter linkstatus + Select by Link Status… Markér efter linkstatus… + Search images Søg i billeder + No images match. Ingen billeder passer. +@msgplural Selected {n} linked image|Selected {n} linked images Markerede {n} linket billede|Markerede {n} linkede billeder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerede {n} integreret billede|Markerede {n} integrerede billeder +@msgplural Selected {n} missing image|Selected {n} missing images Markerede {n} manglende billede|Markerede {n} manglende billeder +@msgplural Selected {n} modified image|Selected {n} modified images Markerede {n} ændret billede|Markerede {n} ændrede billeder +@msgplural Selected {n} image|Selected {n} images Markerede {n} billede|Markerede {n} billeder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} mere er skjult eller låst|{selected}; {n} mere er skjult eller låst +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} mere er på et skabelonlag|{selected}; {n} mere er på skabelonlag +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} mere er uden for den isolerede gruppe|{selected}; {n} mere er uden for den isolerede gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} mere kan ikke markeres nu|{selected}; {n} mere kan ikke markeres nu + +# Compound Shapes add-on + Compound Shapes Sammensatte figurer + Shape Mode Buttons Make Compound Shapes Knapper til formtilstande opretter sammensatte figurer + +# 3D Box add-on + 3D Box 3D-boks + 3D Box Tool 3D-boksværktøj diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8010726abf..d28aa09df7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3252,7 +3252,9 @@ effect Points Punkte Patterns Muster Stroke Options Konturoptionen Character: Zeichen: + Paragraph: Absatz: Character options Zeichenoptionen + Paragraph options Absatzoptionen Stroke options Konturoptionen Transform options Transformationsoptionen Stroke Weight Konturstärke @@ -3899,6 +3901,7 @@ theme Appearance Erscheinungsbild @msg Create from Selection: the selection has no area Aus Auswahl erstellen: Die Auswahl hat keine Fläche @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Die Datenwiederherstellung hat keinen Ort für ihre Kopien: Legen Sie Voreinstellungen → Dateihandhabung → Datenwiederherstellung → Ordner (recoveryFolder) fest @msg Data Recovery can't keep copies in {path}: {e} Die Datenwiederherstellung kann keine Kopien in {path} ablegen: {e} +@msg Plug-ins can't be loaded from {path}: {e} Aus {path} können keine Plug-ins geladen werden: {e} @msg direct-select anchor points to cut at (not the end points of open paths) wählen Sie mit der Direktauswahl die Ankerpunkte aus, an denen geschnitten werden soll (nicht die Endpunkte offener Pfade) @msg Divide Objects Below: select a path Darunterliegende Objekte aufteilen: Wählen Sie einen Pfad aus @msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus @@ -4245,6 +4248,8 @@ theme Appearance Erscheinungsbild @msg no such saved selection keine solche gespeicherte Auswahl @msg no such segment kein solches Segment @msg no such spine point kein solcher Achsenpunkt +@msg `with` must be a list of at most 10000 spine point indexes `with` muss eine Liste von höchstens 10000 Achsenpunkt-Indizes sein +@msg `with` moves points, not a handle `with` verschiebt Punkte, keinen Griff @msg no such spine segment kein solches Achsensegment @msg no such subpath kein solcher Teilpfad @msg no such user library keine solche Benutzerbibliothek @@ -4590,6 +4595,9 @@ theme Appearance Erscheinungsbild @msg graphs come in as plain art, without their data or settings Diagramme werden als einfache Grafik übernommen, ohne ihre Daten und Einstellungen @msg an image whose data is cut short was left out ein Bild mit abgeschnittenen Daten wurde ausgelassen @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel verknüpfte Bilder zeigen die in der Datei gespeicherte Vorschau in niedriger Auflösung, bis ihre Dateien gefunden werden: Verknüpfen Sie sie im Bedienfeld „Verknüpfungen“ neu +@msg linked type areas past VectorCraft's limits were left out verkettete Textbereiche jenseits der Grenzen von VectorCraft wurden ausgelassen +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip als Maske verwendeter Text in verketteten Bereichen, umfließendem Text oder einem zusammengesetzten Pfad beschneidet nicht +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel verknüpfte Bilder ohne Vorschau in der Datei zeigen einen Platzhalter, bis ihre Dateien gefunden werden: Verknüpfen Sie sie im Bedienfeld „Verknüpfungen“ neu @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise Flächentext in Rahmen, die für eine Zeile der Schrift, in der er hier erscheint, zu niedrig sind, hat höhere Rahmen bekommen ({_1}): Sonst wäre der Text nicht zu sehen @msg its editing data doesn't say where its art is seine Bearbeitungsdaten geben nicht an, wo seine Grafik liegt @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) diese Datei wurde ohne PDF-Kompatibilität gespeichert, und ihre Bearbeitungsdaten können nicht gelesen werden ({why}) @@ -5684,6 +5692,9 @@ anchor Points: Punkte: Find Nearest Swatch… Ähnlichstes Farbfeld suchen… Find Nearest Swatch Ähnlichstes Farbfeld suchen Apply Nearest Swatch Ähnlichstes Farbfeld anwenden +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Fläche auf Kontur anwenden + Apply Stroke to Fill Kontur auf Fläche anwenden Select objects to find the swatches nearest their colors. Wählen Sie Objekte aus, um die Farbfelder zu finden, die ihren Farben am nächsten kommen. @msg select objects or give `color` wählen Sie Objekte aus oder geben Sie `color` an @msg `color` is not a colour `color` ist keine Farbe @@ -5921,6 +5932,10 @@ breakText Glyphs Glyphen Bow Bogen Spike Spitze Skip Spaces Leerzeichen überspringen + Release Type on a Path… Pfadtext zurückwandeln… + Release Type on a Path Pfadtext zurückwandeln + Text and Path Text und Pfad + Path Only Nur Pfad @msg The art is too large to copy as a picture: other apps get no PNG of it Das Bildmaterial ist zu groß, um es als Bild zu kopieren: Andere Apps erhalten kein PNG davon # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5932,3 +5947,43 @@ breakText Glyphs Glyphen Fully Outside Vollständig außen No artboards match. Keine Zeichenfläche passt. Chosen: {n} of {total} Gewählt: {n} von {total} + +# Contour add-on + Contour Umriss + Contour Tool Umriss-Werkzeug + Sharp Spitz + Bake Umwandeln + Turn the Contour into plain paths Wandelt den Umriss in einfache Pfade um + Set Corners… Ecken festlegen… + All Anchors Alle Ankerpunkte + Odd-Numbered Anchors Ungerade Ankerpunkte + Even-Numbered Anchors Gerade Ankerpunkte + Minimum angle Minimaler Winkel + Maximum angle Maximaler Winkel + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Verknüpfte auswählen + Select Embedded Eingebettete auswählen + Select Missing Fehlende auswählen + Select Modified Geänderte auswählen + Select by Link Status Nach Verknüpfungsstatus auswählen + Select by Link Status… Nach Verknüpfungsstatus auswählen… + Search images Bilder suchen + No images match. Kein Bild passt. +@msgplural Selected {n} linked image|Selected {n} linked images {n} verknüpftes Bild ausgewählt|{n} verknüpfte Bilder ausgewählt +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} eingebettetes Bild ausgewählt|{n} eingebettete Bilder ausgewählt +@msgplural Selected {n} missing image|Selected {n} missing images {n} fehlendes Bild ausgewählt|{n} fehlende Bilder ausgewählt +@msgplural Selected {n} modified image|Selected {n} modified images {n} geändertes Bild ausgewählt|{n} geänderte Bilder ausgewählt +@msgplural Selected {n} image|Selected {n} images {n} Bild ausgewählt|{n} Bilder ausgewählt +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} weiteres ist ausgeblendet oder gesperrt|{selected}; {n} weitere sind ausgeblendet oder gesperrt +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} weiteres liegt auf einer Vorlagenebene|{selected}; {n} weitere liegen auf Vorlagenebenen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} weiteres liegt außerhalb der isolierten Gruppe|{selected}; {n} weitere liegen außerhalb der isolierten Gruppe +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} weiteres kann gerade nicht ausgewählt werden|{selected}; {n} weitere können gerade nicht ausgewählt werden + +# Compound Shapes add-on + Compound Shapes Zusammengesetzte Formen + Shape Mode Buttons Make Compound Shapes Formmodus-Schaltflächen erstellen zusammengesetzte Formen + +# 3D Box add-on + 3D Box 3D-Quader + 3D Box Tool 3D-Quader-Werkzeug diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 17f383fb8c..16f80c7309 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1991,6 +1991,7 @@ font-technology Variable Μεταβλητές Patterns Μοτίβα Stroke Options Επιλογές περιγράμματος Character: Χαρακτήρας: + Paragraph: Παράγραφος: Stroke: Περίγραμμα: Style Στυλ Style: Στυλ: @@ -2184,6 +2185,7 @@ axis Both Και τα δύο @msg Create from Selection: the selection has no area Δημιουργία από επιλογή: η επιλογή δεν έχει επιφάνεια @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Η ανάκτηση δεδομένων δεν διαθέτει θέση αποθήκευσης αντιγράφων: ορίστε Προτιμήσεις → Χειρισμός αρχείων → Ανάκτηση δεδομένων → Φάκελος (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Η ανάκτηση δεδομένων δεν μπορεί να αποθηκεύσει αντίγραφα στο {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Δεν είναι δυνατή η φόρτωση πρόσθετων από το {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) Επιλέξτε άμεσα τα σημεία αγκύρωσης όπου θα γίνει η αποκοπή (όχι τα τελικά σημεία ανοιχτών διαδρομών) @msg Divide Objects Below: select a path Διαίρεση αντικειμένων από κάτω: επιλέξτε μια διαδρομή @msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή @@ -3654,6 +3656,7 @@ digits Malayalam Μαλαγιάλαμ Stray Points Μεμονωμένα σημεία Stroke (X), double-click for the Color Picker Περίγραμμα (X), διπλό κλικ για επιλογέα χρώματος Character options Επιλογές χαρακτήρων + Paragraph options Επιλογές παραγράφου Stroke options Επιλογές περιγράμματος Transform options Επιλογές μετασχηματισμού Stroke Weight Πάχος περιγράμματος @@ -4284,6 +4287,8 @@ digits Malayalam Μαλαγιάλαμ @msg no such saved selection δεν υπάρχει τέτοια αποθηκευμένη επιλογή @msg no such segment δεν υπάρχει τέτοιο τμήμα @msg no such spine point δεν υπάρχει τέτοιο σημείο κεντρικής καμπύλης +@msg `with` must be a list of at most 10000 spine point indexes το `with` πρέπει να είναι λίστα με έως 10000 δείκτες σημείων κεντρικής καμπύλης +@msg `with` moves points, not a handle το `with` μετακινεί σημεία, όχι λαβή @msg no such spine segment δεν υπάρχει τέτοιο τμήμα κεντρικής καμπύλης @msg no such subpath δεν υπάρχει τέτοια υποδιαδρομή @msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη @@ -4623,6 +4628,9 @@ digits Malayalam Μαλαγιάλαμ @msg graphs come in as plain art, without their data or settings τα γραφήματα εισάγονται ως απλή γραφική, χωρίς τα δεδομένα και τις ρυθμίσεις τους @msg an image whose data is cut short was left out παραλείφθηκε εικόνα με περικομμένα δεδομένα @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel οι συνδεδεμένες εικόνες εμφανίζουν την προεπισκόπηση χαμηλής ανάλυσης που έχει αποθηκευτεί, μέχρι να βρεθούν τα αρχεία τους: επανασυνδέστε τις στον πίνακα Σύνδεσμοι +@msg linked type areas past VectorCraft's limits were left out οι συνδεδεμένες περιοχές κειμένου πέρα από τα όρια του VectorCraft παραλείφθηκαν +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip το κείμενο που χρησιμοποιείται ως μάσκα σε συνδεδεμένες περιοχές, σε κείμενο με αναδίπλωση ή σε σύνθετη διαδρομή δεν αποκόπτει +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel οι συνδεδεμένες εικόνες χωρίς προεπισκόπηση στο αρχείο εμφανίζουν ένα σύμβολο κράτησης θέσης, μέχρι να βρεθούν τα αρχεία τους: επανασυνδέστε τις στον πίνακα Σύνδεσμοι @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise οι περιοχές κειμένου με πλαίσια πολύ μικρά για μία γραμμή της γραμματοσειράς τους απέκτησαν μεγαλύτερο ύψος ({_1}), διαφορετικά το κείμενο δεν θα εμφανιζόταν @msg its editing data doesn't say where its art is τα δεδομένα επεξεργασίας του δεν προσδιορίζουν τη θέση του σχεδίου @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) το αρχείο αποθηκεύτηκε χωρίς συμβατότητα PDF και τα δεδομένα επεξεργασίας του δεν μπορούν να διαβαστούν ({why}) @@ -6050,6 +6058,9 @@ anchor Points: Σημεία: Find Nearest Swatch… Εύρεση πλησιέστερου δείγματος χρώματος… Find Nearest Swatch Εύρεση πλησιέστερου δείγματος χρώματος Apply Nearest Swatch Εφαρμογή πλησιέστερου δείγματος χρώματος +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Εφαρμογή γεμίσματος στο περίγραμμα + Apply Stroke to Fill Εφαρμογή περιγράμματος στο γέμισμα Select objects to find the swatches nearest their colors. Επιλέξτε αντικείμενα για να βρείτε τα δείγματα χρωμάτων που πλησιάζουν περισσότερο τα χρώματά τους. @msg select objects or give `color` επιλέξτε αντικείμενα ή δώστε `color` @msg `color` is not a colour το `color` δεν είναι χρώμα @@ -6287,6 +6298,10 @@ breakText Glyphs Γλύφοι Bow Τόξο Spike Αιχμή Skip Spaces Παράλειψη κενών + Release Type on a Path… Αποδέσμευση κειμένου σε διαδρομή… + Release Type on a Path Αποδέσμευση κειμένου σε διαδρομή + Text and Path Κείμενο και διαδρομή + Path Only Μόνο διαδρομή @msg The art is too large to copy as a picture: other apps get no PNG of it Το γραφικό είναι πολύ μεγάλο για αντιγραφή ως εικόνα: οι άλλες εφαρμογές δεν λαμβάνουν PNG του # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6298,3 +6313,43 @@ breakText Glyphs Γλύφοι Fully Outside Πλήρως εκτός No artboards match. Κανένας πίνακας σχεδίασης δεν ταιριάζει. Chosen: {n} of {total} Επιλεγμένοι: {n} από {total} + +# Contour add-on + Contour Παράλληλο περίγραμμα + Contour Tool Εργαλείο παράλληλου περιγράμματος + Sharp Οξεία + Bake Επέκταση + Turn the Contour into plain paths Μετατρέπει το παράλληλο περίγραμμα σε απλές διαδρομές + Set Corners… Ορισμός γωνιών… + All Anchors Όλα τα σημεία αγκύρωσης + Odd-Numbered Anchors Μονά σημεία αγκύρωσης + Even-Numbered Anchors Ζυγά σημεία αγκύρωσης + Minimum angle Ελάχιστη γωνία + Maximum angle Μέγιστη γωνία + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Επιλογή συνδεδεμένων + Select Embedded Επιλογή ενσωματωμένων + Select Missing Επιλογή όσων λείπουν + Select Modified Επιλογή τροποποιημένων + Select by Link Status Επιλογή κατά κατάσταση σύνδεσης + Select by Link Status… Επιλογή κατά κατάσταση σύνδεσης… + Search images Αναζήτηση εικόνων + No images match. Καμία εικόνα δεν ταιριάζει. +@msgplural Selected {n} linked image|Selected {n} linked images Επιλέχθηκε {n} συνδεδεμένη εικόνα|Επιλέχθηκαν {n} συνδεδεμένες εικόνες +@msgplural Selected {n} embedded image|Selected {n} embedded images Επιλέχθηκε {n} ενσωματωμένη εικόνα|Επιλέχθηκαν {n} ενσωματωμένες εικόνες +@msgplural Selected {n} missing image|Selected {n} missing images Επιλέχθηκε {n} εικόνα που λείπει|Επιλέχθηκαν {n} εικόνες που λείπουν +@msgplural Selected {n} modified image|Selected {n} modified images Επιλέχθηκε {n} τροποποιημένη εικόνα|Επιλέχθηκαν {n} τροποποιημένες εικόνες +@msgplural Selected {n} image|Selected {n} images Επιλέχθηκε {n} εικόνα|Επιλέχθηκαν {n} εικόνες +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}· {n} ακόμη είναι κρυφή ή κλειδωμένη|{selected}· {n} ακόμη είναι κρυφές ή κλειδωμένες +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}· {n} ακόμη είναι σε επίπεδο προτύπου|{selected}· {n} ακόμη είναι σε επίπεδα προτύπου +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας|{selected}· {n} ακόμη είναι εκτός της απομονωμένης ομάδας +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}· {n} ακόμη δεν μπορεί να επιλεγεί τώρα|{selected}· {n} ακόμη δεν μπορούν να επιλεγούν τώρα + +# Compound Shapes add-on + Compound Shapes Σύνθετα σχήματα + Shape Mode Buttons Make Compound Shapes Τα κουμπιά λειτουργιών σχημάτων δημιουργούν σύνθετα σχήματα + +# 3D Box add-on + 3D Box Κουτί 3D + 3D Box Tool Εργαλείο κουτιού 3D diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 29c0d06621..fafd0122e9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3291,7 +3291,9 @@ digits Malayalam Malayálam Patterns Motivos Stroke Options Opciones de trazo Character: Carácter: + Paragraph: Párrafo: Character options Opciones de carácter + Paragraph options Opciones de párrafo Stroke options Opciones de trazo Transform options Opciones de transformación Stroke Weight Grosor de trazo @@ -3984,6 +3986,7 @@ axis Both Ambos @msg Create from Selection: the selection has no area Crear a partir de la selección: la selección no tiene área @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Recuperación de datos no tiene dónde guardar copias: configura Preferencias → Manejo de archivos → Recuperación de datos → Carpeta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Recuperación de datos no puede guardar copias en {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} No se pueden cargar plugins desde {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) selecciona con Selección directa los puntos de ancla en los que cortar (no los puntos finales de trazados abiertos) @msg Divide Objects Below: select a path Dividir objetos inferiores: selecciona un trazado @msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado @@ -4329,6 +4332,8 @@ axis Both Ambos @msg no such saved selection no existe esa selección guardada @msg no such segment no existe ese segmento @msg no such spine point no existe ese punto del eje +@msg `with` must be a list of at most 10000 spine point indexes `with` debe ser una lista de como máximo 10000 índices de puntos del eje +@msg `with` moves points, not a handle `with` mueve puntos, no un manejador @msg no such spine segment no existe ese segmento del eje @msg no such subpath no existe ese subtrazado @msg no such user library no existe esa biblioteca de usuario @@ -4674,6 +4679,9 @@ axis Both Ambos @msg graphs come in as plain art, without their data or settings los gráficos se importan como ilustración normal, sin sus datos ni sus ajustes @msg an image whose data is cut short was left out se omitió una imagen con datos incompletos @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel las imágenes vinculadas muestran la vista previa de baja resolución guardada en el archivo hasta que se encuentren sus archivos: vuelva a vincularlas en el panel Vínculos +@msg linked type areas past VectorCraft's limits were left out se omitieron las áreas de texto enlazadas que superan los límites de VectorCraft +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip el texto usado como máscara en áreas enlazadas, texto ceñido o un trazado compuesto no recorta +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel las imágenes vinculadas sin vista previa en el archivo muestran un marcador de posición hasta que se encuentren sus archivos: vuelva a vincularlas en el panel Vínculos @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise el texto de área en marcos demasiado bajos para una línea de la fuente en que se muestra recibió marcos más altos ({_1}): de otro modo no se vería @msg its editing data doesn't say where its art is sus datos de edición no dicen dónde está su ilustración @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) este archivo se guardó sin compatibilidad con PDF y sus datos de edición no se pueden leer ({why}) @@ -6041,6 +6049,9 @@ anchor Points: Puntos: Find Nearest Swatch… Buscar muestra más cercana… Find Nearest Swatch Buscar muestra más cercana Apply Nearest Swatch Aplicar muestra más cercana +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Aplicar relleno al trazo + Apply Stroke to Fill Aplicar trazo al relleno Select objects to find the swatches nearest their colors. Seleccione objetos para buscar las muestras más cercanas a sus colores. @msg select objects or give `color` seleccione objetos o indique `color` @msg `color` is not a colour `color` no es un color @@ -6277,6 +6288,10 @@ breakText Glyphs Glifos Bow Arco Spike Pico Skip Spaces Omitir espacios + Release Type on a Path… Soltar texto en trazado… + Release Type on a Path Soltar texto en trazado + Text and Path Texto y trazado + Path Only Solo trazado @msg The art is too large to copy as a picture: other apps get no PNG of it La ilustración es demasiado grande para copiarla como imagen: las demás aplicaciones no reciben un PNG de ella # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6288,3 +6303,43 @@ breakText Glyphs Glifos Fully Outside Totalmente fuera No artboards match. Ninguna mesa de trabajo coincide. Chosen: {n} of {total} Elegidas: {n} de {total} + +# Contour add-on + Contour Contorno + Contour Tool Herramienta Contorno + Sharp Puntiaguda + Bake Expandir + Turn the Contour into plain paths Convierte el contorno en trazados simples + Set Corners… Definir esquinas… + All Anchors Todas las anclas + Odd-Numbered Anchors Anclas impares + Even-Numbered Anchors Anclas pares + Minimum angle Ángulo mínimo + Maximum angle Ángulo máximo + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleccionar vinculadas + Select Embedded Seleccionar incrustadas + Select Missing Seleccionar ausentes + Select Modified Seleccionar modificadas + Select by Link Status Seleccionar por estado de vínculo + Select by Link Status… Seleccionar por estado de vínculo… + Search images Buscar imágenes + No images match. Ninguna imagen coincide. +@msgplural Selected {n} linked image|Selected {n} linked images Se seleccionó {n} imagen vinculada|Se seleccionaron {n} imágenes vinculadas +@msgplural Selected {n} embedded image|Selected {n} embedded images Se seleccionó {n} imagen incrustada|Se seleccionaron {n} imágenes incrustadas +@msgplural Selected {n} missing image|Selected {n} missing images Se seleccionó {n} imagen ausente|Se seleccionaron {n} imágenes ausentes +@msgplural Selected {n} modified image|Selected {n} modified images Se seleccionó {n} imagen modificada|Se seleccionaron {n} imágenes modificadas +@msgplural Selected {n} image|Selected {n} images Se seleccionó {n} imagen|Se seleccionaron {n} imágenes +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} más está oculta o bloqueada|{selected}; {n} más están ocultas o bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} más está en una capa de plantilla|{selected}; {n} más están en capas de plantilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} más está fuera del grupo aislado|{selected}; {n} más están fuera del grupo aislado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} más no se puede seleccionar ahora|{selected}; {n} más no se pueden seleccionar ahora + +# Compound Shapes add-on + Compound Shapes Formas compuestas + Shape Mode Buttons Make Compound Shapes Los botones de modo de forma crean formas compuestas + +# 3D Box add-on + 3D Box Caja 3D + 3D Box Tool Herramienta Caja 3D diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 65f97fab17..9c0d61be2b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1466,7 +1466,9 @@ digits Malayalam Malajalam Standard Vertical Roman Alignment Tavallinen pystysuuntainen latinalainen tasaus Strikethrough Yliviivaus Character: Merkki: + Paragraph: Kappale: Character options Merkkiasetukset + Paragraph options Kappaleasetukset Subscript Alaindeksi Subscript (on the roadmap) Alaindeksi (suunnitteilla) Superscript Yläindeksi @@ -4206,6 +4208,7 @@ imageTrace Outline Ääriviiva @msg Create from Selection: the selection has no area Luo valinnasta: valinnalla ei ole pinta-alaa @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Tietojen palautuksella ei ole paikkaa kopioille: määritä Asetukset → Tiedostojen käsittely → Tietojen palautus → Kansio (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Tietojen palautus ei voi tallentaa kopioita kansioon {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Laajennuksia ei voi ladata kansiosta {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) valitse suoravalinnalla ankkuripisteet, joista leikataan (ei avoimien polkujen päätepisteitä) @msg Divide Objects Below: select a path Jaa alla olevat objektit: valitse polku @msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku @@ -4544,6 +4547,8 @@ imageTrace Outline Ääriviiva @msg no such saved selection tallennettua valintaa ei ole @msg no such segment segmenttiä ei ole @msg no such spine point selkärangan pistettä ei ole +@msg `with` must be a list of at most 10000 spine point indexes `with`-arvon on oltava luettelo, jossa on enintään 10000 selkärangan pisteen indeksiä +@msg `with` moves points, not a handle `with` siirtää pisteitä, ei kahvaa @msg no such spine segment selkärangan segmenttiä ei ole @msg no such subpath alipolkua ei ole @msg no such user library käyttäjäkirjastoa ei ole @@ -4882,6 +4887,9 @@ imageTrace Outline Ääriviiva @msg graphs come in as plain art, without their data or settings kaaviot tuodaan tavallisena grafiikkana ilman niiden tietoja ja asetuksia @msg an image whose data is cut short was left out kuva, jonka data on katkennut, jätettiin pois @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel linkitetyt kuvat näyttävät tiedostoon tallennetun matalan tarkkuuden esikatselun, kunnes niiden tiedostot löytyvät: linkitä ne uudelleen Linkit-paneelissa +@msg linked type areas past VectorCraft's limits were left out VectorCraftin rajat ylittävät linkitetyt tekstialueet jätettiin pois +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip maskina käytetty teksti linkitetyissä alueissa, rivitetyssä tekstissä tai yhdistelmäpolussa ei rajaa +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel linkitetyt kuvat, joilla ei ole esikatselua tiedostossa, näkyvät paikkamerkkinä, kunnes niiden tiedostot löytyvät: linkitä ne uudelleen Linkit-paneelissa @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise aluetekstin kehykset, jotka olivat liian matalia yhdelle riville niiden fontilla, korotettiin ({_1}): muuten niiden teksti ei näkyisi @msg its editing data doesn't say where its art is sen muokkaustiedoista ei selviä kuvituksen sijainti @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) tämä tiedosto tallennettiin ilman PDF-yhteensopivuutta, eikä sen muokkaustietoja voi lukea ({why}) @@ -6129,6 +6137,9 @@ anchor Points: Pisteet: Find Nearest Swatch… Etsi lähin värimalli… Find Nearest Swatch Etsi lähin värimalli Apply Nearest Swatch Käytä lähintä värimallia +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Käytä täyttöä viivaan + Apply Stroke to Fill Käytä viivaa täyttöön Select objects to find the swatches nearest their colors. Valitse objektit, joiden väreille haluat etsiä lähimmät värimallit. @msg select objects or give `color` valitse objekteja tai anna `color` @msg `color` is not a colour `color` ei ole väri @@ -6365,6 +6376,10 @@ breakText Glyphs Merkit Bow Kaari Spike Piikki Skip Spaces Ohita välilyönnit + Release Type on a Path… Vapauta teksti polulta… + Release Type on a Path Vapauta teksti polulta + Text and Path Teksti ja polku + Path Only Vain polku @msg The art is too large to copy as a picture: other apps get no PNG of it Grafiikka on liian suuri kopioitavaksi kuvana: muut sovellukset eivät saa siitä PNG-kuvaa Check for Updates… Tarkista päivitykset… VectorCraft Updates VectorCraft-päivitykset @@ -6381,3 +6396,43 @@ breakText Glyphs Merkit Fully Outside Kokonaan ulkona No artboards match. Mikään piirtoalusta ei vastaa hakua. Chosen: {n} of {total} Valittu: {n}/{total} + +# Contour add-on + Contour Ääriviiva + Contour Tool Ääriviivatyökalu + Sharp Terävä + Bake Laajenna + Turn the Contour into plain paths Muuntaa ääriviivan tavallisiksi poluiksi + Set Corners… Aseta kulmat… + All Anchors Kaikki ankkurit + Odd-Numbered Anchors Parittomat ankkurit + Even-Numbered Anchors Parilliset ankkurit + Minimum angle Pienin kulma + Maximum angle Suurin kulma + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Valitse linkitetyt + Select Embedded Valitse upotetut + Select Missing Valitse puuttuvat + Select Modified Valitse muokatut + Select by Link Status Valitse linkin tilan mukaan + Select by Link Status… Valitse linkin tilan mukaan… + Search images Hae kuvia + No images match. Mikään kuva ei vastaa hakua. +@msgplural Selected {n} linked image|Selected {n} linked images Valittiin {n} linkitetty kuva|Valittiin {n} linkitettyä kuvaa +@msgplural Selected {n} embedded image|Selected {n} embedded images Valittiin {n} upotettu kuva|Valittiin {n} upotettua kuvaa +@msgplural Selected {n} missing image|Selected {n} missing images Valittiin {n} puuttuva kuva|Valittiin {n} puuttuvaa kuvaa +@msgplural Selected {n} modified image|Selected {n} modified images Valittiin {n} muokattu kuva|Valittiin {n} muokattua kuvaa +@msgplural Selected {n} image|Selected {n} images Valittiin {n} kuva|Valittiin {n} kuvaa +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} muu on piilotettu tai lukittu|{selected}; {n} muuta on piilotettu tai lukittu +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} muu on mallitasolla|{selected}; {n} muuta on mallitasoilla +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} muu on eristetyn ryhmän ulkopuolella|{selected}; {n} muuta on eristetyn ryhmän ulkopuolella +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} muuta ei voi valita nyt|{selected}; {n} muuta ei voi valita nyt + +# Compound Shapes add-on + Compound Shapes Yhdistelmämuodot + Shape Mode Buttons Make Compound Shapes Muototilapainikkeet luovat yhdistelmämuotoja + +# 3D Box add-on + 3D Box 3D-laatikko + 3D Box Tool 3D-laatikkotyökalu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6734fd75ab..2da80b01cf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3283,7 +3283,9 @@ digits Malayalam Malayalam Patterns Motifs Stroke Options Options de contour Character: Caractère : + Paragraph: Paragraphe : Character options Options de caractère + Paragraph options Options de paragraphe Stroke options Options de contour Transform options Options de transformation Stroke Weight Épaisseur du contour @@ -3974,6 +3976,7 @@ axis Both Les deux @msg Create from Selection: the selection has no area Créer d’après la sélection : la sélection n’a pas de surface @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) La récupération des données n’a aucun emplacement où conserver les copies : définissez Préférences → Gestion des fichiers → Récupération des données → Dossier (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} La récupération des données ne peut pas conserver de copies dans {path} ({e}) +@msg Plug-ins can't be loaded from {path}: {e} Impossible de charger les plug-ins depuis {path} ({e}) @msg direct-select anchor points to cut at (not the end points of open paths) sélectionnez avec l’outil Sélection directe les points d’ancrage où couper (pas les extrémités des tracés ouverts) @msg Divide Objects Below: select a path Diviser les objets inférieurs : sélectionnez un tracé @msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé @@ -4319,6 +4322,8 @@ axis Both Les deux @msg no such saved selection sélection enregistrée inexistante @msg no such segment segment inexistant @msg no such spine point point de la dorsale inexistant +@msg `with` must be a list of at most 10000 spine point indexes `with` doit être une liste d’au plus 10000 indices de points de la dorsale +@msg `with` moves points, not a handle `with` déplace des points, pas une poignée @msg no such spine segment segment de la dorsale inexistant @msg no such subpath sous-tracé inexistant @msg no such user library bibliothèque utilisateur inexistante @@ -4662,6 +4667,9 @@ axis Both Les deux @msg graphs come in as plain art, without their data or settings les graphes sont importés comme illustration ordinaire, sans leurs données ni leurs réglages @msg an image whose data is cut short was left out une image aux données tronquées a été ignorée @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les images liées affichent l’aperçu basse résolution enregistré dans le fichier tant que leurs fichiers ne sont pas trouvés : liez-les à nouveau dans le panneau Liens +@msg linked type areas past VectorCraft's limits were left out les zones de texte liées au-delà des limites de VectorCraft ont été omises +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip le texte utilisé comme masque dans des zones liées, un habillage de texte ou un tracé transparent ne découpe pas +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel les images liées sans aperçu dans le fichier affichent un espace réservé tant que leurs fichiers ne sont pas trouvés : liez-les à nouveau dans le panneau Liens @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise le texte captif dans des cadres trop bas pour une ligne de la police dans laquelle il s’affiche a reçu des cadres plus hauts ({_1}) : il ne s’afficherait pas autrement @msg its editing data doesn't say where its art is ses données d’édition ne disent pas où se trouve son illustration @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ce fichier a été enregistré sans compatibilité PDF et ses données d’édition sont illisibles ({why}) @@ -6094,6 +6102,9 @@ anchor Points: Points : Find Nearest Swatch… Rechercher la nuance la plus proche… Find Nearest Swatch Rechercher la nuance la plus proche Apply Nearest Swatch Appliquer la nuance la plus proche +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Appliquer le fond au contour + Apply Stroke to Fill Appliquer le contour au fond Select objects to find the swatches nearest their colors. Sélectionnez des objets pour trouver les nuances les plus proches de leurs couleurs. @msg select objects or give `color` sélectionnez des objets ou indiquez `color` @msg `color` is not a colour `color` n’est pas une couleur @@ -6330,6 +6341,10 @@ breakText Glyphs Glyphes Bow Arc Spike Pointe Skip Spaces Ignorer les espaces + Release Type on a Path… Libérer le texte curviligne… + Release Type on a Path Libérer le texte curviligne + Text and Path Texte et tracé + Path Only Tracé uniquement @msg The art is too large to copy as a picture: other apps get no PNG of it L’illustration est trop grande pour être copiée en tant qu’image : les autres applications n’en reçoivent pas de PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6341,3 +6356,43 @@ breakText Glyphs Glyphes Fully Outside Entièrement à l’extérieur No artboards match. Aucun plan de travail ne correspond. Chosen: {n} of {total} Choisis : {n} sur {total} + +# Contour add-on + Contour Pourtour + Contour Tool Outil Pourtour + Sharp Pointu + Bake Décomposer + Turn the Contour into plain paths Transforme le pourtour en tracés simples + Set Corners… Définir les angles… + All Anchors Tous les points d’ancrage + Odd-Numbered Anchors Points d’ancrage impairs + Even-Numbered Anchors Points d’ancrage pairs + Minimum angle Angle minimal + Maximum angle Angle maximal + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Sélectionner les images liées + Select Embedded Sélectionner les images incorporées + Select Missing Sélectionner les images manquantes + Select Modified Sélectionner les images modifiées + Select by Link Status Sélectionner par état de lien + Select by Link Status… Sélectionner par état de lien… + Search images Rechercher des images + No images match. Aucune image ne correspond. +@msgplural Selected {n} linked image|Selected {n} linked images {n} image liée sélectionnée|{n} images liées sélectionnées +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} image incorporée sélectionnée|{n} images incorporées sélectionnées +@msgplural Selected {n} missing image|Selected {n} missing images {n} image manquante sélectionnée|{n} images manquantes sélectionnées +@msgplural Selected {n} modified image|Selected {n} modified images {n} image modifiée sélectionnée|{n} images modifiées sélectionnées +@msgplural Selected {n} image|Selected {n} images {n} image sélectionnée|{n} images sélectionnées +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected} ; {n} autre est masquée ou verrouillée|{selected} ; {n} autres sont masquées ou verrouillées +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected} ; {n} autre est sur un calque modèle|{selected} ; {n} autres sont sur des calques modèles +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected} ; {n} autre est hors du groupe isolé|{selected} ; {n} autres sont hors du groupe isolé +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected} ; {n} autre ne peut pas être sélectionnée pour l’instant|{selected} ; {n} autres ne peuvent pas être sélectionnées pour l’instant + +# Compound Shapes add-on + Compound Shapes Formes composées + Shape Mode Buttons Make Compound Shapes Les boutons de mode de forme créent des formes composées + +# 3D Box add-on + 3D Box Boîte 3D + 3D Box Tool Outil Boîte 3D diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv new file mode 100644 index 0000000000..d7235790f8 --- /dev/null +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -0,0 +1,7886 @@ +# Hindi (hi). context English source Hindi translation. +# Drafted from VectorCraft's English labels; shared terms reuse PhotoCraft's clean-room Hindi catalog. +# Remaining drafts used the local Argos English-Hindi 1.1 model with agent terminology corrections. +# No proprietary localization resources were consulted. Native-speaker review is pending. +# Product names, file extensions, keyboard keys, units and placeholders stay unchanged. +# Hindi integer plurals: 0 and 1 use one, 2+ use other (plural_french in i18n.rs). +# @plural and @msgplural translations have two forms separated by |. +# See docs/localization-hi.md for terminology, provenance and verification. + + — {n} characters from another font — दूसरे फ़ॉन्ट से {n} अक्षर + — missing — अनुपलब्ध + — substituted by {style} — {style} से बदला गया + a pin to warp | मोड़ने के लिए पिन | + a point to edit it | एडिट करने के लिए पॉइंट | + a stroke to add a width point | चौड़ाई पॉइंट जोड़ने के लिए स्ट्रोक | + across a selected object to set the gradient direction ग्रेडिएंट की दिशा सेट करने के लिए सिलेक्टेड ऑब्जेक्ट पर + across paths to push them along | पाथ को धकेलने के लिए उन पर | + an anchor or path segment to select it | सिलेक्ट करने के लिए एंकर या पाथ सेगमेंट पर | + an object to copy its attributes | गुण कॉपी करने के लिए ऑब्जेक्ट पर | + an object, then another to blend them | ब्लेंड करने के लिए पहले एक ऑब्जेक्ट पर, फिर दूसरे पर | + cancels | Double-click the tool for options रद्द करता है | ऑप्शन्स के लिए टूल पर डबल-क्लिक करें + for exact size सटीक साइज़ के लिए + for exact values सटीक मानों के लिए + from center | केंद्र से | + keeps its proportions) उसका अनुपात बनाए रखता है) + near a selected pin to rotate | घुमाने के लिए सिलेक्टेड पिन के पास | + on the canvas to create one बनाने के लिए कैनवास पर + on the canvas to create one ( बनाने के लिए कैनवास पर ( + out from a highlighted edge to place its dimension | माप रखने के लिए हाइलाइट किए किनारे से बाहर की ओर | + over paths to roughen their outlines | आउटलाइन खुरदरी करने के लिए पाथ पर | + over paths, and hold still to keep going | पाथ पर, और जारी रखने के लिए स्थिर रखें | + right or left to zoom in or out | ज़ूम इन या आउट करने के लिए दाएँ या बाएँ | + selects several, or draws one inside an artboard) कई का सिलेक्शन करता है या आर्टबोर्ड के भीतर बनाता है) + the art to add a pin | पिन जोड़ने के लिए आर्टवर्क पर | + the object to duplicate डुप्लीकेट करने के लिए ऑब्जेक्ट + the object to select | सिलेक्ट करने के लिए ऑब्जेक्ट | + to add जोड़ने के लिए + to add a corner point | कॉर्नर पॉइंट जोड़ने के लिए | + to add a smooth point | स्मूद पॉइंट जोड़ने के लिए | + to add smooth points | स्मूद पॉइंट जोड़ने के लिए | + to apply the selection's to it | सिलेक्शन के गुण उस पर लागू करने के लिए | + to blend from it | उससे ब्लेंड करने के लिए | + to change one side | एक तरफ़ बदलने के लिए | + to close | बंद करने के लिए | + to constrain proportions | अनुपात बनाए रखने के लिए | + to copy | कॉपी करने के लिए | + to create area type | एरिया टाइप बनाने के लिए | + to create point type | पॉइंट टाइप बनाने के लिए | + to draw | बनाने के लिए | + to exit editing एडिटिंग से बाहर निकलने के लिए + to finish पूरा करने के लिए + to keep zooming ज़ूम जारी रखने के लिए + to move | खिसकाने के लिए | + to move in perspective | पर्सपेक्टिव में खिसकाने के लिए | + to pan the view दृश्य पैन करने के लिए + to remove pins पिन हटाने के लिए + to remove points पॉइंट हटाने के लिए + to sample a color रंग का सैंपल लेने के लिए + to scale in perspective पर्सपेक्टिव में स्केल करने के लिए + to search every command सभी कमांड खोजने के लिए + to select an artboard | आर्टबोर्ड का सिलेक्ट करने के लिए | + to select more pins | और पिन का सिलेक्ट करने के लिए | + to select more points | और पॉइंट का सिलेक्ट करने के लिए | + to select multiple objects | कई ऑब्जेक्ट का सिलेक्ट करने के लिए | + to set spacing and orientation स्पेसिंग और ओरिएंटेशन सेट करने के लिए + to set the reference point | रेफ़रेंस पॉइंट सेट करने के लिए | + to size the brush ( ब्रश का साइज़ बदलने के लिए ( + to toggle corner | कॉर्नर चालू/बंद करने के लिए | + to transform | रूपांतरित करने के लिए | + to zoom in | ज़ूम इन करने के लिए | + to zoom into an area किसी क्षेत्र में ज़ूम करने के लिए + to zoom out | ज़ूम आउट करने के लिए | + while dragging to move perpendicular to the plane | प्लेन के लंबवत खिसकाने के लिए ड्रैग करते समय | + : : + “{file}” is protected by a password. “{file}” पासवर्ड से सुरक्षित है। + “{name}” already exists. Replace it? “{name}” पहले से मौजूद है। क्या आप इसे बदलना चाहते हैं? + "In" Control Points “इन” कंट्रोल पॉइंट्स + "Out" Control Points “आउट” कंट्रोल पॉइंट्स + (closest) (निकटतम) + [Custom] [कस्टम] + [Default] [डिफ़ॉल्ट] + [Default] is protected: New… starts an editable copy. [डिफ़ॉल्ट] सुरक्षित है: नया… एडिट करने योग्य प्रति बनाता है। + [High Quality Print] [उच्च गुणवत्ता प्रिंट] + [High Resolution] [उच्च रिज़ॉल्यूशन] + [Low Resolution] [कम रिज़ॉल्यूशन] + [Medium Resolution] [मध्यम रिज़ॉल्यूशन] + [Normal Character Style] [सामान्य कैरेक्टर स्टाइल] + [Normal Paragraph Style] [सामान्य पैराग्राफ़ स्टाइल] + [PDF/X-1a:2001] [PDF/X-1a:2001] + [PDF/X-3:2002] [PDF/X-3:2002] + [PDF/X-4:2010] [PDF/X-4:2010] + [Press Quality] [प्रेस गुणवत्ता] + [Smallest File Size] [सबसे छोटा फ़ाइल साइज़] + [Unnamed] [बिना नाम] + [VectorCraft Default] [VectorCraft डिफ़ॉल्ट] + {count} of {total} artboards {total} में से {count} आर्टबोर्ड + {effect} is already applied {effect} पहले से लागू है + {file}, line {line} {file}, पंक्ति {line} + {folders} and {files} searched {folders} और {files} में खोज की गई + {format} Options {format} ऑप्शन्स + {kind} Gradient {kind} ग्रेडिएंट + {kind} Style Options… {kind} स्टाइल ऑप्शन्स… + {kind}, {model} {kind}, {model} + {n} objects selected {n} ऑब्जेक्ट सिलेक्टेड + {name} (spot) {name} (स्पॉट) + {page} of {count} {count} में से {page} + {pages} in all, {count} per copy कुल {pages}, प्रति कॉपी {count} + {people} contributors · {commits} commits {people} योगदानकर्ता · {commits} कमिट + {percent}% opacity {percent}% ओपेसिटी + {ready} of {total} ready {total} में से {ready} तैयार + {secs} sec {secs} सेकंड + {shortcut} with the tool sizes the brush टूल के साथ {shortcut} ब्रश का साइज़ बदलता है + {title} (selection) {title} (सिलेक्शन) + {tool} Options {tool} ऑप्शन्स + {tool} Tool Options {tool} टूल ऑप्शन्स + {w} × {h} pt {w} × {h} pt + {warning}: click to correct to the closest color ({hex}) {warning}: निकटतम रंग ({hex}) में सुधारने के लिए क्लिक करें + @{login}: {prs}, {commits}, +{added} / −{deleted} lines (Δ {delta}), +{binary_added} / −{binary_deleted} binary assets, {first} – {last} @{login}: {prs}, {commits}, +{added} / −{deleted} पंक्तियाँ (Δ {delta}), +{binary_added} / −{binary_deleted} बाइनरी एसेट्स, {first} – {last} + % of all commits सभी कमिट्स का % + + Add Scale + स्केल जोड़ें + < 1 sec < 1 सेकंड + <ओपेसिटी मास्क> + ▾ Default Actions ▾ डिफ़ॉल्ट एक्शन्स + ● Recording ● रिकॉर्डिंग + ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} पहले से {names} में उपयोग था — वहाँ से हटा दिया गया है। + 0.2 (quality) to 100 (speed) 0.2 (गुणवत्ता) से 100 (गति) + 1 {unit} on the artboard stands for {real} {unit} in the scene. आर्टबोर्ड पर 1 {unit} दृश्य में {real} {unit} दर्शाता है। + 1 bit 1 बिट + 1 Color Job 1 रंग जॉब + 1 Color Job… 1 रंग जॉब… + 1 Layer 1 लेयर + 16 bit 16 बिट + 16 bits/pixel 16 बिट/पिक्सेल + 16 Colors 16 रंग + 2 Color Job 2 रंग जॉब + 2 Color Job… 2 रंग जॉब… + 2-Up 2 दृश्य + 24 bit 24 बिट + 24 bits/pixel 24 बिट्स/पिक्सेल + 256 Colors 256 रंग + 2K Cinema 2K सिनेमा + 2up 2 दृश्य + 3 Color Job 3 रंग जॉब + 3 Color Job… 3 रंग जॉब… + 3 Colors 3 रंग + 3 x 3 Average 3 x 3 औसत + 30° Angles 30° कोण + 32 bit 32 बिट + 32 bits/pixel 32 बिट्स/पिक्सेल + 3D and Materials 3D और मटीरियल्स + 3D Box 3D बॉक्स + 3D Box Tool 3D बॉक्स टूल + 3D Lighting Preset 3D लाइटिंग प्रीसेट + 3D Ribbon 3D रिबन + 4 bit 4 बिट + 4-Up 4 दृश्य + 45° Angles 45° कोण + 4K Cinema 4K सिनेमा + 4K UHD 4K UHD + 4up 4 दृश्य + 5 x 5 Average 5 x 5 औसत + 6 Colors 6 रंग + 60° Angles 60° कोण + 8 bit 8 बिट + 8 Colors 8 रंग + 8K UHD 8K UHD + 90° & 45° & 30° Angles 90° और 45° और 30° कोण + 90° & 45° Angles 90° और 45° कोण + 90° Angles 90° कोण + A file dialog is open: choose there first फ़ाइल डायलॉग खुला है: पहले वहाँ चुनें + A File per Object प्रति ऑब्जेक्ट एक फ़ाइल + A File… एक फ़ाइल… + A later row takes this shortcut बाद वाली पंक्ति यह शॉर्टकट लेती है + A legacy .ai file holds one artboard: each artboard you check is saved as a separate file. पुरानी .ai फ़ाइल में एक आर्टबोर्ड रहता है: हर चुना हुआ आर्टबोर्ड अलग फ़ाइल में सेव किया जाता है। + A lower value follows the stroke closely; a higher one gives fewer points and smoother curves. कम मान स्ट्रोक का बारीकी से अनुसरण करता है; अधिक मान से कम पॉइंट और अधिक स्मूद कर्व मिलते हैं। + A new preset starting from the selected one सिलेक्टेड प्रीसेट से नया प्रीसेट + A saved copy of the selected preset सिलेक्टेड प्रीसेट की सेव की हुई प्रति + A3 A3 + A4 A4 + A5 A5 + A6 A6 + About परिचय + About VectorCraft VectorCraft के बारे में + above ऊपर + Above Text टेक्स्ट के ऊपर + Absolute निरपेक्ष + Absolute Colorimetric निरपेक्ष कलरिमेट्रिक + Absolute Position निरपेक्ष स्थिति + Abutting सटे हुए + Accelerated त्वरित + Accent Color एक्सेंट रंग + Accented Edges उभारे गए किनारे + Accented Edges… उभारे गए किनारे… + Accurate सटीक + Action {n} एक्शन {n} + Action Options एक्शन ऑप्शन्स + Action Options… एक्शन ऑप्शन्स… + Action Set: एक्शन सेट: + Actions एक्शन्स + Activate Document डॉक्यूमेंट सक्रिय करें + Activate Panel पैनल सक्रिय करें + Active Perspective Plane सक्रिय पर्सपेक्टिव प्लेन + Actual Size वास्तविक साइज़ + Adaptive अनुकूली + Add जोड़ें + Add Anchor (Pen) एंकर जोड़ें (पेन) + Add Anchor Point एंकर पॉइंट जोड़ें + Add Anchor Point Tool ऐड एंकर पॉइंट टूल + Add Anchor Points एंकर पॉइंट जोड़ें + Add Anchors एंकर जोड़ें + Add Anchors… एंकर जोड़ें… + Add as Effect इफ़ेक्ट के रूप में जोड़ें + Add Content सामग्री जोड़ें + Add Effect इफ़ेक्ट जोड़ें + Add Event इवेंट जोड़ें + Add filters from the list above ऊपर की सूची से फ़िल्टर जोड़ें + Add Font Files फ़ॉन्ट फ़ाइलें जोड़ें + Add Fonts फ़ॉन्ट जोड़ें + Add Freeform Line फ्रीफॉर्म लाइन जोड़ें + Add Freeform Point फ्रीफॉर्म पॉइंट जोड़ें + Add Guide गाइड जोड़ें + Add Guides गाइड्स जोड़ें + Add JavaScript File जावास्क्रिप्ट फ़ाइल जोड़ें + Add Light लाइट जोड़ें + Add Mesh Line मेश लाइन जोड़ें + Add New नया जोड़ें + Add New Effect नया इफ़ेक्ट जोड़ें + Add New Fill नया फ़िल जोड़ें + Add New Stroke नया स्ट्रोक जोड़ें + Add Points पॉइंट जोड़ें + Add Points at Crossings क्रॉसिंग पर पॉइंट जोड़ें + Add Points to Segments सेगमेंट पर पॉइंट जोड़ें + Add Points to Segments… सेगमेंट पर पॉइंट जोड़ें… + Add Selected Artwork (Alt: as one asset) सिलेक्टेड आर्टवर्क जोड़ें (Alt: एक एसेट के रूप में) + Add Selected Artwork as Multiple Assets सिलेक्टेड आर्टवर्क कई एसेट्स के रूप में जोड़ें + Add Selected Artwork as One Asset सिलेक्टेड आर्टवर्क एक एसेट के रूप में जोड़ें + Add space to fit फ़िट करने के लिए जगह जोड़ें + Add Spine Point स्पाइन पॉइंट जोड़ें + Add Swatches स्वॉचेस जोड़ें + Add to Brushes ब्रश में जोड़ें + Add to Graphic Styles ग्राफ़िक स्टाइल्स में जोड़ें + Add to Library लाइब्रेरी में जोड़ें + Add to Profiles प्रोफ़ाइल में जोड़ें + Add to Profiles… प्रोफ़ाइल में जोड़ें… + Add to Selection सिलेक्शन में जोड़ें + Add to Stack स्टैक में जोड़ें + Add to Swatches स्वॉचेस में जोड़ें + Add to Symbols सिंबल्स में जोड़ें + Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें + Add Used Colors उपयोग किए रंग जोड़ें + Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर + Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर + Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें + Adjust Color Balance… कलर बैलेंस समायोजित करें… + Adjust Colors रंग समायोजित करें + Adjust Options: समायोजन ऑप्शन्स: + Adjustment समायोजन + Advanced उन्नत + Advanced Character Formats उन्नत कैरेक्टर फ़ॉर्मैट + Advanced Options उन्नत ऑप्शन्स + After First: शुरू के बाद: + Align संरेखित करें + Align Bottom नीचे संरेखित करें + Align center केंद्र में संरेखित करें + Align Center केंद्र में संरेखित करें + Align left बाएँ संरेखित करें + Align Objects: ऑब्जेक्ट संरेखित करें: + Align On: इस पर संरेखित करें: + Align right दाएँ संरेखित करें + Align Stroke to Center स्ट्रोक केंद्र में संरेखित करें + Align Stroke to Inside स्ट्रोक भीतर संरेखित करें + Align Stroke to Outside स्ट्रोक बाहर संरेखित करें + Align Stroke: स्ट्रोक संरेखित करें: + Align to Artboard आर्टबोर्ड पर संरेखित करें + Align to Corners and Ends कोनों और सिरों पर संरेखित करें + Align to Glyph Bounds ग्लिफ़ की सीमाओं पर संरेखित करें + Align to Key Object मुख्य ऑब्जेक्ट पर संरेखित करें + Align to Page पेज पर संरेखित करें + Align to Path पाथ पर संरेखित करें + Align to Selection सिलेक्शन पर संरेखित करें + Align To: इससे संरेखित करें: + Align Top ऊपर संरेखित करें + Align: संरेखित करें: + Alignment Guides संरेखण गाइड्स + Alignment: संरेखण: + All सभी + All Affected Objects सभी प्रभावित ऑब्जेक्ट + All Anchors सभी एंकर + All Artboards सभी आर्टबोर्ड + All Artwork Above ऊपर का सारा आर्टवर्क + All Caps सभी कैपिटल + All Categories सभी श्रेणियाँ + All in One Folder सभी एक फ़ोल्डर में + All Layers सभी लेयर्स + All on Active Artboard सक्रिय आर्टबोर्ड पर सभी + All on Same Layers समान लेयर्स पर सभी + All printer's marks सभी प्रिंटर मार्क्स + All Rasterized Regions सभी रास्टराइज़ किए क्षेत्र + All Scripts सभी लिपियाँ + All shortcuts reset to defaults. सभी शॉर्टकट डिफ़ॉल्ट पर रीसेट किए गए। + All Slices सभी स्लाइस + All Text Objects सभी टेक्स्ट ऑब्जेक्ट + All the art सारा आर्टवर्क + All Tools सभी टूल्स + Alt Alt + Alt key toggles to Smooth Tool Alt कुंजी से स्मूद टूल पर जाएँ + Alt-click: reset the horizontal scale too Alt-click: क्षैतिज पैमाने को भी रीसेट करें + Alt: Alt: + Alt+Click Alt+Click + Alt+Drag Alt+Drag + Alter Paths for Appearance उपस्थिति के लिए वैकल्पिक पाथ + Alternates for Current Selection वर्तमान सिलेक्शन के लिए ऑप्शन + Amber एम्बर + Ambient Light परिवेश प्रकाश + Amount मात्रा + Amount: मात्रा: + Analogous अनुरूप + Analogous 2 अनुरूप 2 + Anchor Eraser Brush एंकर इरेज़र ब्रश + Anchor Inspector एंकर इंस्पेक्टर + Anchor Point एंकर पॉइंट + Anchor Point Tool एंकर पॉइंट टूल + Anchor Points एंकर पॉइंट्स + Anchor Points, Handle, and Bounding Box Display एंकर पॉइंट्स, हैंडल और बाउंडिंग बॉक्स का प्रदर्शन + Anchor/Path Labels एंकर/पाथ लेबल + Anchors एंकर + Anchors selected: {count} सिलेक्टेड एंकर: {count} + Anchors: एंकर: + Angle कोण + Angle: एंगल: + Angled Strokes तिरछे स्ट्रोक + Angled Strokes… तिरछे स्ट्रोक… + Angles कोण + Angular कोणीय + Angular Guides कोणीय गाइड्स + Animated Zoom एनिमेटेड ज़ूम + Anti-alias एंटी-एलियास + Anti-Alias एंटी-एलियास + Anti-alias Rasters रास्टर एंटी-एलियास करें + Anti-aliased Artwork एंटी-एलियास किया आर्टवर्क + Anti-aliasing: एंटी-एलियासिंग: + Any except extracting pages पेज निकालने के अलावा सभी + Any Kind किसी भी प्रकार का + Appearance अपीयरेंस + Appearance Attribute अपीयरेंस गुण + Appearance Item अपीयरेंस आइटम + Appearance of Black काले रंग का प्रदर्शन + Appearance panel अपीयरेंस पैनल + Appearance Panel अपीयरेंस पैनल + Applied Filters लागू फ़िल्टर + Applies the next time VectorCraft starts. अगली बार VectorCraft शुरू होने पर लागू होगा। + Applies when the linked file is relinked or updated. लिंक्ड फ़ाइल दोबारा लिंक या अपडेट होने पर लागू होगा। + Apply लागू करें + Apply {name} {name} लागू करें + Apply as Filter फ़िल्टर के रूप में लागू करें + Apply Brush ब्रश लागू करें + Apply Bullets बुलेट लागू करें + Apply Character Style कैरेक्टर स्टाइल लागू करें + Apply Data Set डेटा सेट लागू करें + Apply Effect इफ़ेक्ट लागू करें + Apply Fill to Stroke स्ट्रोक पर फ़िल लागू करें + Apply Gradient Preset ग्रेडिएंट प्रीसेट अप्लाई करें + Apply Graphic Style ग्राफ़िक स्टाइल लागू करें + Apply Last Color पिछला रंग लागू करें + Apply Last Effect पिछला इफ़ेक्ट लागू करें + Apply Last Gradient पिछला ग्रेडिएंट लागू करें + Apply Nearest Swatch निकटतम स्वॉच लागू करें + Apply Numbers क्रमांकन लागू करें + Apply Paragraph Style पैराग्राफ़ स्टाइल लागू करें + Apply Stroke to Fill फ़िल पर स्ट्रोक लागू करें + Apply SVG Filter… SVG फ़िल्टर लागू करें… + Apply to All सभी पर लागू करें + Apply to Selected Anchors सिलेक्टेड एंकर पर लागू करें + Apply To: इस पर लागू करें: + Approximate path अनुमानित पाथ + Arabic अरबी + Arc आर्क + Arc Lower… निचला आर्क… + Arc Segment Tool Options आर्क सेगमेंट टूल ऑप्शन्स + Arc Tool आर्क टूल + Arc Upper… ऊपरी आर्क… + Arc… आर्क… + Arch… मेहराब… + Area क्षेत्र + Area / Path Type एरिया / पाथ टाइप + Area Graph Tool एरिया ग्राफ़ टूल + Area Text एरिया टेक्स्ट + Area Text Objects एरिया टेक्स्ट ऑब्जेक्ट + Area Type एरिया टाइप + Area Type Options एरिया टाइप ऑप्शन्स + Area Type Options… एरिया टाइप ऑप्शन्स… + Area Type Tool एरिया टाइप टूल + Around Object ऑब्जेक्ट के चारों ओर + Arrange व्यवस्थित करें + Arrange by Column कॉलम के अनुसार व्यवस्थित करें + Arrange by Row पंक्ति के अनुसार व्यवस्थित करें + Arrange in Grid ग्रिड में व्यवस्थित करें + Arrange in Grid… ग्रिड में व्यवस्थित करें… + Arrange Intertwine Area इंटरट्वाइन क्षेत्र व्यवस्थित करें + Arrange Tools व्यवस्था टूल्स + Arrange: Bring to Front व्यवस्थित करें: सबसे आगे लाएँ + Arrow तीर + Arrow (open) तीर (खुला) + Arrow Scale: तीर का स्केल: + Arrow Style: तीर की स्टाइल: + Arrowheads: एरोहेड्स: + Art आर्टवर्क + Art & Illustration कला और चित्रण + Art and Bright Colors आर्टवर्क और चमकीले रंग + Art Brush आर्ट ब्रश + Art Brush Options आर्ट ब्रश ऑप्शन्स + Art Optimized आर्टवर्क के लिए अनुकूलित + Art Ribbons आर्ट रिबन + Art using a deleted global swatch keeps its colour. हटाए गए ग्लोबल स्वॉच वाला आर्टवर्क अपना रंग बनाए रखता है। + Artboard आर्टबोर्ड + Artboard {n} of {total} {total} में से आर्टबोर्ड {n} + Artboard {number} आर्टबोर्ड {number} + Artboard Options आर्टबोर्ड ऑप्शन्स + Artboard Options: edit with the Artboard tool आर्टबोर्ड ऑप्शन्स: आर्टबोर्ड टूल से एडिट करें + Artboard Options… आर्टबोर्ड ऑप्शन्स… + Artboard or Item Name आर्टबोर्ड या आइटम का नाम + Artboard Tool आर्टबोर्ड टूल + Artboard: आर्टबोर्ड: + Artboards आर्टबोर्ड्स + Artboards: {n} आर्टबोर्ड: {n} + ArtCraft website ArtCraft वेबसाइट + ArtCraft Website ArtCraft वेबसाइट + Artistic कलात्मक + Artwork आर्टवर्क + Artwork Cleanup आर्टवर्क की सफ़ाई + Artwork Colors आर्टवर्क के रंग + As Multiple Assets कई एसेट्स के रूप में + As Single Asset एक एसेट के रूप में + Ascender असेंडर + Ascent असेंट + Ask When Modified बदलाव होने पर पूछें + Aspect Ratio पहलू अनुपात + Asset Export एसेट एक्सपोर्ट + Asset Export Settings एसेट एक्सपोर्ट सेटिंग्स + Assets एसेट्स + Assign असाइन करें + Assign Profile प्रोफ़ाइल असाइन करें + Assign Profile… प्रोफ़ाइल असाइन करें… + Assign: असाइन करें: + Attach जोड़ें + Attach Objects on Path पाथ पर ऑब्जेक्ट जोड़ें + Attach to Active Plane सक्रिय प्लेन से जोड़ें + Attribute: विशेषता: + Attributes एट्रिब्यूट्स + Author Title: लेखक का पद: + Author: लेखक: + Auto स्वचालित + Auto Color ऑटो कलर + Auto Grouping ऑटो ग्रूपिंग + Auto Leading: ऑटो लीडिंग: + Auto Size ऑटो साइज़ + Auto Size New Area Type नए एरिया टाइप का ऑटो साइज़ + Auto Spell Check ऑटो वर्तनी जाँच + Auto-Between ऑटो-बिटवीन + Auto-Centered ऑटो-केंद्रित + Auto-Collapse Iconic Panels आइकन वाले पैनल अपने-आप समेटें + Auto-Overlap ऑटो ओवरलैप + Auto-Rotate (turn the paper to each artboard) ऑटो-रोटेट (हर आर्टबोर्ड के अनुसार कागज़ घुमाएँ) + Auto-Simplify अपने-आप सरल करें + Auto-Sliced ऑटो-स्लाइस्ड + Auto-Smooth अपने-आप स्मूद करें + Automate स्वचालित करें + Automatic स्वचालित + Automatic flatness स्वचालित फ़्लैटनेस + Automatically अपने-आप + Automatically Save Recovery Data रिकवरी डेटा अपने-आप सेव करें + Average औसत + Average & Join औसत करके जोड़ें + Average & Join… औसत करके जोड़ें… + Average… औसत… + Away from the Line लाइन से दूर + Axis अक्ष + Axis side अक्ष की तरफ़ + Axis: अक्ष: + B4 B4 + B5 B5 + Back वापस + Background Color: बैकग्राउंड रंग: + Background Contents बैकग्राउंड सामग्री + Background Contents: बैकग्राउंड सामग्री: + Background Level बैकग्राउंड स्तर + Background: बैकग्राउंड: + Backspace Backspace + Bake बेक करें + Balance संतुलन + Bar बार + Bar Graph Tool बार ग्राफ़ टूल + Barbed कंटीले + Bas Relief बास रिलीफ़ + Bas Relief… बास रिलीफ़… + Base Along: आधार के साथ: + Baseline बेसलाइन + Baseline (Standard) बेसलाइन (मानक) + Baseline Optimized बेसलाइन ऑप्टिमाइज़्ड + Baseline Shift बेसलाइन शिफ़्ट + Basic बुनियादी + Basic Character Formats बुनियादी कैरेक्टर फ़ॉर्मैट + Basic Latin बेसिक लैटिन + Basic Shapes बुनियादी शेप्स + Batch बैच + Batch Trace Folder फ़ोल्डर बैच ट्रेस करें + Batch… बैच… + Bearing दिशा + Before Last: अंत के पहले: + Begin Recording रिकॉर्डिंग शुरू करें + Begin Undo Group पूर्ववत समूह शुरू करें + Bend: मोड़: + Bengali बंगाली + Best सर्वोत्तम + Between Line and Object रेखा और ऑब्जेक्ट के बीच + Bevel बेवल + Bevel both sides दोनों तरफ़ बेवल + Bevel Inside अंदर बेवल + Bevel Join बेवल जॉइन + Bevel Shape बेवल शेप + Bicubic बाइक्यूबिक + Binary assets added बाइनरी एसेट्स जोड़े गए + Binary assets removed बाइनरी एसेट्स हटाए गए + Bind Variable वेरिएबल बाँधें + Bitmap बिटमैप + Black काला + Black & White ब्लैक एंड व्हाइट + Black and White काला और सफ़ेद + Black and White Logo काला और सफ़ेद लोगो + Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. काला और सफ़ेद वैसे ही रहते हैं। गहरे रंग स्ट्रोक के रंग के शेड्स बनते हैं और हल्के रंग उसके टिंट्स बनते हैं। + Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. काला स्ट्रोक का रंग बनता है और सफ़ेद वैसा ही रहता है। बाकी रंग अपनी ब्राइटनेस के अनुसार स्ट्रोक के रंग के टिंट्स बनते हैं। + Black Intensity काले की तीव्रता + Black Outline काली आउटलाइन + BLANK DOCUMENT PRESETS खाली डॉक्यूमेंट प्रीसेट्स + Bleed ब्लीड + Bleed: ब्लीड: + Bleeds ब्लीड्स + Blend ब्लेंड + Blend Front to Back आगे से पीछे ब्लेंड करें + Blend Horizontally क्षैतिज ब्लेंड करें + Blend Info ब्लेंड जानकारी + Blend Options ब्लेंड ऑप्शन्स + Blend Options… ब्लेंड ऑप्शन्स… + Blend Tool ब्लेंड टूल + Blend Vertically लंबवत ब्लेंड करें + Blending Mode ब्लेंडिंग मोड + Blends and Transparency ब्लेंड्स और पारदर्शिता + Bloat फुलाएँ + Bloat Tool ब्लोट टूल + Blob Brush ब्लॉब ब्रश + Blob Brush Tool ब्लॉब ब्रश टूल + Blocks ब्लॉक्स + Blue नीला + Blur ब्लर + Blur Mode ब्लर मोड + Bold बोल्ड + Border Thickness बॉर्डर की मोटाई + Both दोनों + Both sides दोनों तरफ़ + Bottom नीचे + Bottom in Front नीचे वाला आगे + Bottom Left नीचे बाएँ + Bottom Left: नीचे बाएँ: + Bottom Right नीचे दाएँ + Bottom Right: नीचे दाएँ: + Bottom to Top नीचे से ऊपर + Bottom-Justified Tab नीचे संरेखित टैब + Bottom-to-Bottom Leading नीचे से नीचे लीडिंग + Bottom: नीचे: + Bounding Box बाउंडिंग बॉक्स + Bounds सीमाएँ + Bounds (Fill Proportionally) सीमाएँ (अनुपात बनाए रखते हुए भरें) + Bounds (Fit Proportionally) सीमाएँ (अनुपात बनाए रखते हुए फ़िट करें) + Bow बो + Bracket ब्रैकेट + Bracket never closed ब्रैकेट बंद नहीं हुआ + Branding ब्रांडिंग + Break Link लिंक तोड़ें + Break Link to Graphic Style ग्राफ़िक स्टाइल से लिंक तोड़ें + Break Link to Symbol सिंबल से लिंक तोड़ें + Break Text टेक्स्ट बाँटें + Break Text into Glyphs टेक्स्ट ग्लिफ़ में बाँटें + Break Text into Lines टेक्स्ट पंक्तियों में बाँटें + Break Text into Paragraphs टेक्स्ट पैराग्राफ़ में बाँटें + Break Text into Words टेक्स्ट शब्दों में बाँटें + Break Text into: टेक्स्ट इसमें बाँटें: + Break Thread थ्रेड तोड़ें + Brick ईंट + Brick by Column कॉलम के अनुसार ईंटें + Brick by Row पंक्ति के अनुसार ईंटें + Brick Offset: ईंटों का ऑफ़सेट: + Brightness ब्राइटनेस + Brightness: ब्राइटनेस: + Brightness/Contrast चमक/कंट्रास्ट + Brightness/Contrast… चमक/कंट्रास्ट… + Brights चमकीले + Bring All to Front सभी सबसे आगे लाएँ + Bring Forward आगे लाएँ + Bring to Front सबसे आगे लाएँ + Bristle ब्रिसल + Bristle Brush ब्रिसल ब्रश + Bristle Brush Options ब्रिसल ब्रश ऑप्शन्स + Bristle Brush Strokes ब्रिसल ब्रश स्ट्रोक्स + Bristle Density: ब्रिसल घनत्व: + Bristle Length: ब्रिसल लंबाई: + Bristle Thickness: ब्रिसल मोटाई: + Brown भूरा + Browser ब्राउज़र + Brush Affects: ब्रश का प्रभाव: + Brush Art ब्रश आर्टवर्क + Brush Definition ब्रश परिभाषा + Brush Detail ब्रश डिटेल + Brush Libraries ब्रश लाइब्रेरीज़ + Brush Libraries Menu ब्रश लाइब्रेरीज़ मेनू + Brush Library ब्रश लाइब्रेरी + Brush Options ब्रश ऑप्शन्स + Brush Options… ब्रश ऑप्शन्स… + Brush Scale Options ब्रश स्केल ऑप्शन्स + Brush Size ब्रश साइज़ + Brush Strokes ब्रश स्ट्रोक्स + Brushes ब्रश + Built-in Libraries अंतर्निहित लाइब्रेरीज़ + Built-in presets are read-only: New… starts an editable copy. अंतर्निहित प्रीसेट केवल पढ़ने के लिए हैं: नया… एडिट करने योग्य प्रति बनाता है। + Built-in presets don't change: New makes a copy you can edit. अंतर्निहित प्रीसेट बदलते नहीं हैं: नया एडिट करने योग्य प्रति बनाता है। + Built-in presets don't change: New… starts an editable copy. अंतर्निहित प्रीसेट बदलते नहीं हैं: नया… एडिट करने योग्य प्रति बनाता है। + Bulge… उभार… + Bullet बुलेट + Bullets बुलेट्स + Bullets and Numbering बुलेट्स और क्रमांकन + Burasagari बुरासागरी + Burlap टाट + Business Card 3.5 × 2 in बिज़नेस कार्ड 3.5 × 2 in + Business Card 85 × 55 mm बिज़नेस कार्ड 85 × 55 mm + Business Card 91 × 55 mm बिज़नेस कार्ड 91 × 55 mm + Butt Cap बट कैप + By Artboard or Item आर्टबोर्ड या आइटम के अनुसार + By Columns कॉलम के अनुसार + By Count संख्या के अनुसार + By Distance दूरी के अनुसार + By Format फ़ॉर्मैट द्वारा + By Item, Then Format आइटम द्वारा, फिर फ़ॉर्मैट + By Layer लेयर द्वारा + By Object ऑब्जेक्ट द्वारा + By Rows पंक्तियाँ + By Size or Row आकार या पंक्ति द्वारा + Byte Order: बाइट ऑर्डर: + Calligraphic कैलिग्राफिक + Calligraphic Brush कैलिग्राफिक ब्रश + Calligraphic Brush Options कैलिग्राफिक ब्रश ऑप्शन्स + Calligraphic Nibs कैलिग्राफिक निब्स + Can't export “{name}”. "{name}" निर्यात नहीं कर सकते। + Can't open “{name}”. "{name}" नहीं खोल सकते हैं। + Can't print these settings: see the Summary इन सेटिंग्स को मुद्रित नहीं कर सकते: सारांश देखें + Can't save “{name}”. "{name}" सेव नहीं कर सकते। + Cancel रद्द करें + Cancel Export निर्यात रद्द करना + Cancel Image Trace इमेज ट्रेस रद्द करना + Cancel Key Object कुंजी ऑब्जेक्ट रद्द करें + Cancel Pattern Editing रद्द करना पैटर्न संपादन + Cancel Plug-in Run प्लग-इन रन रद्द करें + Canvas कैनवास + Canvas Color कैनवास का रंग + Cap कैप + Cap Height कैप हाइट + Cap: कैप: + Caps Lock Cursor State कैप्स लॉक कर्सर स्टेट + Capture Data Set कैप्चर डेटा सेट + Cascade कैस्केड + Case केस + Catalan कैटलन + Categories श्रेणियाँ + Cell Size सेल साइज़ + Center केंद्र + Center Artwork सेंटर आर्टवर्क + Center on Artboard आर्टबोर्ड पर केंद्र + Center-Justified Tab केंद्र-संरेखित टैब + Centimeters सेंटीमीटर + Chalk & Charcoal चॉक और चारकोल + Chalk & Charcoal… चॉक और चारकोल… + Chamfer चम्फर + Change बदलें + Change All सभी बदलें + Change Case प्रकरण बदलें + Change Panel Layout पैनल लेआउट बदलें + Change Screen Mode (F) स्क्रीन मोड बदलें (F) + Change to Artboard Rulers आर्टबोर्ड शासकों में परिवर्तन + Change to Global Rulers वैश्विक शासकों में परिवर्तन + Change to Left-to-Right Layout लेफ्ट-टू-राइट लेआउट में परिवर्तन + Change to Right-to-Left Layout राइट-टू-लेफ्ट लेआउट में परिवर्तन + Changed since the last check. आखिरी चेक के बाद से बदल गया। + Changed since the last Refresh. आखिरी रिफ्रेश के बाद से बदल गया। + Changes allowed: परिवर्तन की अनुमति: + Changes made since it was last saved will be lost. क्योंकि यह पिछले बचाया गया था परिवर्तन खो दिया जाएगा। + Changes the reference app's preferences संदर्भ ऐप की वरीयताओं को बदलता है + Changing these settings changes how raster effects look when exported, flattened or expanded. ये सेटिंग्स बदलने से एक्सपोर्ट, फ़्लैटन या एक्सपैंड किए गए रास्टर इफ़ेक्ट्स का रूप बदलता है। + Channel चैनल + Channel 1 चैनल 1 + Channel 2 चैनल 2 + Channel 3 चैनल 3 + Channel 4 चैनल 4 + Character कैरेक्टर + Character / Paragraph कैरेक्टर / पैराग्राफ + Character Alignment चरित्र संरेखण + Character Color चरित्र रंग + Character Direction चरित्र निर्देशन + Character options चरित्र ऑप्शन्स + Character Rotation चरित्र रोटेशन + Character Set: चरित्र सेट: + Character Style कैरेक्टर स्टाइल + Character Style Options कैरेक्टर स्टाइल ऑप्शन्स + Character Styles कैरेक्टर स्टाइल्स + Character: कैरेक्टर: + Charcoal चारकोल + Charcoal… चारकोल… + Check an artboard to save. बचाने के लिए एक आर्टबोर्ड की जाँच करें। + Check Document डॉक्यूमेंट की जाँच करें + Check for Updates… अपडेट जाँचें… + Check Links चेक लिंक + Check Script स्क्रिप्ट की जाँच करें + Check Script… स्क्रिप्ट… + Check Selection सिलेक्शन जाँच करें + Check Spelling… वर्तनी जाँचें… + Checked चेक + Chevron शेवरॉन + Chinese चीनी + Choose a filter एक फिल्टर चुनें + Choose a folder एक फ़ोल्डर चुनें + Choose the file to relink each linked file to. Files with the size and contents saved with the link come first. हर लिंक्ड फ़ाइल को दोबारा लिंक करने के लिए फ़ाइल चुनें। जिन फ़ाइलों का साइज़ और डेटा सेव किए गए लिंक से मेल खाता है, वे पहले दिखती हैं। + Choose… चुनें… + Chop Design चोपड़ा डिजाइन + Chosen: {n} of {total} चुने गए: {total} में से {n} + Chrome क्रोम + Chrome… क्रोम… + Circle वृत्त + Circle (open) सर्किल (ओपन) + Classic क्लासिक + Classic Defaults क्लासिक डिफ़ॉल्ट + Clean Up क्लीन अप + Clean Up… सफाई… + Clear साफ़ करें + Clear All सभी साफ़ करें + Clear All Tabs सभी टैब साफ़ करें + Clear Amount पारदर्शिता मात्रा + Clear Appearance स्पष्ट उपस्थिति + Clear Events घटनाओं को साफ़ करें + Clear Guides गाइड्स हटाएँ + Clear History हिस्ट्री साफ़ करें + Clear Overrides साफ़ ओवरराइड्स + Clear Recent Files हाल की फ़ाइलें साफ़ करें + Clear Selection सिलेक्शन साफ़ करें + Click क्लिक करें + Click an anchor point एक एंकर पॉइंट पर क्लिक करें + Click or drag क्लिक करें या खींचें + Click the art with the Gradient tool to add or select points. पॉइंट जोड़ने या सिलेक्ट करने के लिए ग्रेडिएंट टूल से आर्टवर्क पर क्लिक करें। + Click the first point पहले बिंदु पर क्लिक करें + Click the ramp or a type button to apply a gradient. एक ग्रेडिएंट लगाने के लिए रैंप या एक प्रकार का बटन पर क्लिक करें। + Click to add a tab stop, drag to move it, drag it off the ruler to delete it टैब स्टॉप जोड़ने के लिए क्लिक करें, खिसकाने के लिए ड्रैग करें, हटाने के लिए रूलर से बाहर ड्रैग करें + Click to apply to the selected type सिलेक्टेड प्रकार पर लागू करने के लिए क्लिक करें + Click to choose a swatch, Shift-click to mix a colour स्वॉच चुनने के लिए क्लिक करें, रंग मिलाने के लिए Shift-क्लिक करें + Click to edit संपादित करने के लिए क्लिक करें + Click to edit the mask; Alt-click to view only the mask; Shift-click to disable or enable it मास्क एडिट करने के लिए क्लिक करें; केवल मास्क देखने के लिए Alt-क्लिक करें; उसे अक्षम या सक्षम करने के लिए Shift-क्लिक करें + Click to place each file at 100%, or drag to size it; arrow keys switch files, Esc skips one. हर फ़ाइल को 100% साइज़ पर प्लेस करने के लिए क्लिक करें या साइज़ तय करने के लिए ड्रैग करें। एरो कुंजियों से फ़ाइल बदलें; Esc से एक फ़ाइल छोड़ें। + Click to select, double-click to edit सिलेक्ट करने के लिए क्लिक करें, संपादित करने के लिए डबल क्लिक करें + Click to toggle visibility दिखाने या छिपाने के लिए क्लिक करें + Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit ज़ूम इन के लिए क्लिक करें, ज़ूम आउट के लिए Alt-क्लिक करें, पैन करने के लिए ड्रैग करें, फ़िट करने के लिए डबल-क्लिक करें + Click, then press the key this code stands for (Esc cancels) क्लिक करें, फिर इस कोड वाली कुंजी दबाएँ (Esc से कैंसल करें) + Click, then press the new shortcut (Esc cancels) क्लिक करें, फिर नए शॉर्टकट दबाएँ (Esc रद्द) + Client-side (.html) क्लाइंट-साइड (.html) + Clip क्लिप + Clip Complex Regions क्लिप कॉम्प्लेक्स क्षेत्र + Clip Group क्लिप समूह + Clip to Art कला के लिए क्लिप + Clip to Artboard क्लिप टू आर्टबोर्ड + Clip to Bounding Box क्लिप टू बाउंडिंग बॉक्स + Clipboard as PDF PDF के रूप में क्लिपबोर्ड + Clipboard as PNG PNG के रूप में क्लिपबोर्ड + Clipboard as SVG SVG के रूप में क्लिपबोर्ड + Clipboard as Text टेक्स्ट के रूप में क्लिपबोर्ड + Clipboard Formats क्लिपबोर्ड फ़ॉर्मैट + Clipboard Handling क्लिपबोर्ड हैंडलिंग + Clipping Mask क्लिपिंग मास्क + Clipping Masks क्लिपिंग मास्क + Clockwise क्लॉकवार + Close बंद करें + Close All सभी बंद करें + Close Gaps With Paths पाथ के साथ अंतराल बंद करें + Close Library लाइब्रेरी + Close or Join बंद करें या शामिल हों + Close Panel पैनल बंद करें + Close Path बंद पाथ + Close Path: बंद पाथ: + Close Path… बंद पाथ… + Close paths when ends are within: जब समाप्त होता है तो बंद पाथ भीतर होते हैं: + Close the circular ends of open profiles. Partial sweeps keep their cut sides open. खुली प्रोफ़ाइल के गोल सिरे बंद करें। आंशिक स्वीप की कटी हुई साइड खुली रहती हैं। + Closed बंद + Closing bracket with no opening one कोई ओपन करने के साथ समापन ब्रैकेट + Clumped गुच्छेदार + Cmd Cmd + CMYK CMYK + CMYK Color CMYK रंग + CMYK colours print with their own values; off, they go through the colour settings too. ऑन होने पर CMYK रंग अपने मानों के साथ प्रिंट होते हैं; ऑफ़ होने पर उन पर भी कलर सेटिंग्स लागू होती हैं। + CMYK Equivalents CMYK समकक्ष + CMYK Images CMYK इमेज + CMYK profile in effect इफ़ेक्ट में CMYK प्रोफ़ाइल + CMYK: CMYK: + Coarse Dots मोटे बिंदु + Coincidence: संयोग: + Collapse Panel Group पैनल समूह संक्षिप्त करें + Collapse Panels to Icons सिकोड़ें करने के लिए पैनल + Collapse to Icons प्रतीक के लिए पतन + Collate कोलेट + Collect for Export एक्सपोर्ट के लिए कलेक्ट करें + Collect in New Layer नई लेयर में इकट्ठा + Collect Links in a Separate Folder एक अलग फ़ोल्डर में लिंक इकट्ठा करें + Collinear Anchors कोलिनियर एंकर + Color रंग + Color (, or Shift+,) रंग (, या Shift+) + Color Adjustments रंग समायोजन + Color bars रंग सलाखों + Color blindness – Deuteranopia-type कलर ब्लाइंडनेस – ड्यूटेरानोपिया प्रकार + Color blindness – Protanopia-type रंग अंधापन - प्रोटानोपिया प्रकार + Color blindness – Tritanopia-type कलर ब्लाइंडनेस – ट्राइटेनोपिया प्रकार + Color Burn कलर बर्न + Color conversion: रंग रूपांतरण: + Color Dodge कलर डॉज + Color Effects रंग इफ़ेक्ट + Color Effects Panel रंग इफ़ेक्ट पैनल + Color Group रंग समूह + Color Group: रंग समूह: + Color Group: {name} रंग समूह: {name} + Color Guide रंग गाइड + Color Guide Options रंग गाइड ऑप्शन्स + Color Guide Options… रंग गाइड ऑप्शन्स… + Color Halftone कलर हाफ़टोन + Color Halftone… कलर हाफ़टोन… + Color images रंग इमेज + Color Library रंग लाइब्रेरी + Color Library… रंग लाइब्रेरी… + Color Management रंग प्रबंधन + Color Mixer (Shift-click the chip) कलर मिक्सर (रंग चिप पर Shift-क्लिक करें) + Color Mode रंग मोड + Color Mode: रंग मोड: + Color Model: रंग मॉडल: + Color Models रंग मॉडल + Color Panel Options रंग पैनल ऑप्शन्स + Color Picker कलर पिकर + Color Picker… कलर पिकर… + Color Reduction: रंग में कमी: + Color Scheme रंग योजना + Color Settings रंग सेटिंग्स + Color Settings… रंग सेटिंग्स… + Color Space कलर स्पेस + Color Swatches रंग स्वॉचेस + Color Table रंग तालिका + Color Table ({n} color) रंग तालिका ({n} रंग) + Color Table ({n} colors) रंग तालिका ({n} रंग) + Color Table (4 colors) रंग तालिका (4 रंग) + Color Theme रंग थीम + Color Themes रंग थीम्स + Color Type: रंग का प्रकार: + Color wheel कलर व्हील + Color: रंग: + Colored Pencil रंगीन पेंसिल + Colored Pencil… रंगीन पेंसिल… + Coloring Controls रंग नियंत्रण + Colorization रंगांकन + Colorization Tips रंगीकरण युक्तियाँ + Colorize रंगीन करें + Colors रंग + Colors: रंग: + Column Graph Tool कॉलम ग्राफ टूल + Column Type: स्तंभ प्रकार: + Column Width: कॉलम चौड़ाई: + Column… स्तंभ… + Columns: कॉलम: + Combine Point Text पॉइंट टेक्स्ट को मिलाएं + Combine Slices संयोजन स्लाइस + Coming soon — tracked in the parity plan जल्द ही आ रहा है - समानता योजना में ट्रैक किया गया + Command कमांड + Command Click to Select Objects Behind कमांड पीछे ऑब्जेक्ट्स का सिलेक्ट करने के लिए क्लिक करें + Command Dialog कमान डायलॉग + Comment not closed टिप्पणी बंद नहीं + Commenting, filling in form fields and signing टिप्पणी करना, फॉर्म फ़ील्ड में भरना और हस्ताक्षर करना + Commits कमिट्स + Community समुदाय + Company कंपनी + Compatibility: संगतता: + Compatible Gradient and Gradient Mesh Printing कंपैटिबल ग्रेडिएंट और ग्रेडिएंट मेश प्रिंटिंग + Compiled or not text संकलित या टेक्स्ट नहीं + Compiled script: ask its author for the .jsx file कंपाइल की हुई स्क्रिप्ट: इसके लेखक से .jsx फ़ाइल माँगें + Complement संगम + Complementary पूरक + Complementary 2 पूरक 2 + Complete पूरा करना + Complexity: जटिलता: + Composite समग्र + Composite colours are converted to it; separations separate with it when it is a CMYK profile. कंपोज़िट रंग इस प्रोफ़ाइल में कन्वर्ट होते हैं; CMYK प्रोफ़ाइल होने पर सेपरेशन्स भी इसी से बनते हैं। + Compound कम्पाउंड + Compound 2 कम्पाउंड 2 + Compound Path कंपाउंड पाथ + Compound Shape कंपाउंड शेप + Compound Shapes मिश्रित आकार + Compress (RLE) संपीड़न (RLE) + Compress text and line art टेक्स्ट और लाइन कला को संपीड़ित करें + Compression संपीड़न + Compression › Color › Above Ppi संपीड़न › रंग › पीपीआई के ऊपर + Compression: संपीड़न: + Concave अवतरण + Concentric Dividers: सांद्रिक विभाजक: + Condition identifier: शर्त पहचानकर्ता: + Configure Shape आकार को कॉन्फ़िगर करें + Conflict {n} of {count} {count} में से विरोध {n} + Connect कनेक्ट + Connect Selected End Points कनेक्ट सिलेक्टेड अंत अंक + Consider Open Filled Paths as Closed बंद के रूप में ओपन भरा पाथ पर विचार करें + Consolidate All Windows सभी विंडो एक साथ लाएँ + Constrain कंस्ट्रक्शन + Constrain Angle कंस्ट्रक्शन एंगल + Constrain Width and Height Proportions कंस्ट्रक्शन चौड़ाई और ऊंचाई के अनुपात + Construction Guides निर्माण गाइड + Conté Crayon कॉन्टे क्रेयॉन + Conté Crayon… कॉन्टे क्रेयॉन… + Contextual Alternates प्रासंगिक ऑप्शन + Contextual Task Bar प्रासंगिक टास्क बार + Continue in Background पृष्ठभूमि में जारी + Contour कंटूर + Contour Tool कंटूर टूल + Contrast कंट्रास्ट + Contrasty अधिक कंट्रास्ट + Contributors योगदानकर्ता + Control नियंत्रण + Convert कन्वर्ट करें + Convert All Spot Colors to Process सभी स्पॉट कलर्स को प्रोसेस में कनवर्ट करें + Convert All Strokes to Outlines सभी स्ट्रोक को आउटलाइन में कनवर्ट करें + Convert All Text to Outlines सभी टेक्स्ट को आउटलाइन में कनवर्ट करें + Convert Anchor Point एंकर पॉइंट कनवर्ट करें + Convert Anchor Points एंकर पॉइंट कन्वर्ट करें + Convert Color रंग बदलें + Convert Document Color Mode डॉक्यूमेंट का कलर मोड कन्वर्ट करें + Convert Layers to Symbols लेयर्स को सिंबल्स में कन्वर्ट करें + Convert Process to Global प्रोसेस रंग को ग्लोबल में कन्वर्ट करें + Convert Selected Anchor Points to Corner सिलेक्टेड एंकर पॉइंट को कॉर्नर पॉइंट में कन्वर्ट करें + Convert Selected Anchor Points to Smooth सिलेक्टेड एंकर पॉइंट को स्मूद पॉइंट में कन्वर्ट करें + Convert text to outlines टेक्स्ट को आउटलाइन में कन्वर्ट करें + Convert To Area Type एरिया टाइप में कनवर्ट करें + Convert to Artboards आर्टबोर्ड में कनवर्ट करें + Convert to CMYK CMYK में कनवर्ट करें + Convert to destination गंतव्य में कनवर्ट करें + Convert to destination (preserve numbers) गंतव्य में कनवर्ट करें (संख्या संरक्षित करें) + Convert to Global ग्लोबल में कनवर्ट करें + Convert to Grayscale ग्रेस्केल में बदलें + Convert To Outlines कन्वर्ट करने के लिए रूपरेखा + Convert to Parametric Shape पैरामीट्रिक शेप में कन्वर्ट करें + Convert To Point Type पॉइंट टाइप में कनवर्ट करें + Convert to RGB RGB में कनवर्ट करें + Convert to Shape शेप में बदलें + Convert to sRGB sRGB में बदलें + Convert to Straight Lines सीधी लाइन में कन्वर्ट करें + Convert to Text टेक्स्ट में कनवर्ट करें + Convert: कन्वर्ट करें: + Convex उत्तल + Cool ठंडा + Copies: प्रतियाँ: + Copy कॉपी करें + Copy (make a transformed copy) प्रतिलिपि (एक परिवर्तित प्रतिलिपि बनाना) + Copy All Objects सभी ऑब्जेक्ट्स कॉपी करें + Copy All Styles सभी स्टाइल्स की प्रतिलिपि बनाएँ + Copy Appearance उपस्थिति कॉपी करें + Copy Artboard कॉपी आर्टबोर्ड + Copy Color Value (Hex) कॉपी कलर वैल्यू (Hex) + Copy Fonts Used in the Document डॉक्यूमेंट में प्रयुक्त फ़ॉन्ट कॉपी करें + Copy Guide कॉपी गाइड + Copy in Perspective पर्सपेक्टिव में प्रतिलिपि + Copy into the document's folder डॉक्यूमेंट के फ़ोल्डर में कॉपी करें + Copy Links कॉपी लिंक + Copy only fonts you own or are licensed to install. केवल उन फ़ॉन्टों को कॉपी करें जिन्हें आप स्वयं करते हैं या इंस्टॉल करने के लिए लाइसेंस प्राप्त हैं। + Copy Report रिपोर्ट कॉपी करें + Copy Selected Style सिलेक्टेड स्टाइल को कॉपी करें + Copy to User Defined उपयोगकर्ता परिभाषित करने के लिए कॉपी करें + Copy Width Point कॉपी चौड़ाई पॉइंट + Copyright कॉपीराइट + Copyright and Contact Info कॉपीराइट और संपर्क जानकारी + Copyright Info URL: कॉपीराइट जानकारी URL: + Copyright Notice: कॉपीराइट सूचना: + Copyright Status: कॉपीराइट स्थिति: + Copyright Symbol कॉपीराइट सिंबल + Copyrighted कॉपीराइट युक्त + Coral कोरल + Corner कोना + Corner Point Angle Threshold: कॉर्नर पॉइंट एंगल थ्रेसहोल्ड: + Corner Radius कोने की त्रिज्या + Corner Radius: कोने की त्रिज्या: + Corner Tool कॉर्नर टूल + Corner: कोना: + Corners कोने + Corners selected: {count} कॉर्नर्स का सिलेक्शन: {count} + Corners… कोने… + Couldn't {} {name}: {e} {name} को {} नहीं किया जा सका: {e} + Couldn't copy to the system clipboard: {e} सिस्टम क्लिपबोर्ड को कॉपी नहीं कर सका: {e} + Couldn't paste from the clipboard: {e} क्लिपबोर्ड से पेस्ट नहीं कर सका: {e} + Couldn't save recovery data: {e} वसूली डेटा नहीं बचा सकता: {e} + Count गिनती + Count: गिनती: + Cove कोव + Crack Brightness दरार ब्राइटनेस + Crack Depth दरार गहराई + Crack Spacing दरार स्पेसिंग + Craquelure क्रैक्लूर + Craquelure… क्रैक्लूर… + Create बनाएँ + Create Clipping Mask क्लिपिंग मास्क बनाएँ + Create Compound Path From Ellipses एलिप्स से कंपाउंड पाथ बनाएँ + Create Dimension आयाम बनाएँ + Create Document डॉक्यूमेंट बनाएं + Create from Guides गाइड से बनाएँ + Create from Selection सिलेक्शन से बनाएँ + Create From: से बनाएँ: + Create Gradient Mesh ग्रेडिएंट मेश बनाएँ + Create Gradient Mesh… ग्रेडिएंट मेश बनाएँ… + Create Graph ग्राफ़ बनाएँ + Create New {kind} Style नई {kind} स्टाइल बनाएँ + Create New Action नया एक्शन बनाएँ + Create New Fields by द्वारा नए फील्ड्स का निर्माण + Create New Layer नई लेयर बनाएँ + Create New Library नई लाइब्रेरी बनाएँ + Create New Library… नई लाइब्रेरी बनाएं… + Create New Set नया सेट बनाएँ + Create New Sublayer न्यू सबलेयर बनाएं + Create New Swatch… नया स्वॉच बनाएँ… + Create Object Mosaic ऑब्जेक्ट मोज़ेक बनाएँ + Create Object Mosaic… ऑब्जेक्ट मोज़ेक बनाएँ… + Create Outlines आउटलाइन बनाएँ + Create Path पाथ बनाएँ + Create PDF layers from layers and sublayers लेयर्स और सबलेयरों से PDF लेयरें बनाएं + Create PDF layers from top-level layers शीर्ष स्तर की लेयर्स से PDF लेयरें बनाएं + Create PDF-Compatible File PDF-संगत फ़ाइल बनाएँ + Create Report रिपोर्ट बनाएं + Create Slice स्लाइस बनाएं + Create Slice from Selection सिलेक्शन से स्लाइस बनाएं + Create Slices from Guides गाइड से स्लाइस बनाएं + Create Sub-folders सब-फ़ोल्डर्स बनाएं + Create Swatch Legend स्वॉच विवरण बनाएँ + Create Swatch Legend… स्वॉच विवरण बनाएँ… + Create Text टेक्स्ट बनाना + Create Trim Marks ट्रिम मार्क्स बनाएं + Create: बनाएँ: + Created बनाना + Created: बनाया गया: + CRLF (Windows) CRLF (Windows) + Croatian क्रोएशियाई + Crop क्रॉप करें + Crop Image फसल की इमेज + Crop Marks क्रॉप मार्क + Crop To करने के लिए फसल + Cross क्रॉस + Crosshatch क्रॉसहैच + Crosshatch… क्रॉसहैच… + Crystallize क्रिस्टलाइज़ करें + Crystallize Tool क्रिस्टलीकरण टूल + Crystallize… क्रिस्टलाइज़ करें… + CSS Properties सीएसएस प्रॉपर्टीज़ + Ctrl Ctrl + Currency & Symbols मुद्रा और सिंबल + Current Brush वर्तमान ब्रश + Current Colors वर्तमान रंग + Current Colors ({total}) वर्तमान रंग ({total}) + Current Colors (0) वर्तमान रंग (0) + Current Symbol वर्तमान सिंबल + Cursor Swatch Preview कर्सर स्वॉच प्रीव्यू + Curvature वक्रता + Curvature Tool वक्रता टूल + Curve कर्व + Curved घुमावदार + Curves… कर्व्स… + Custom कस्टम + Custom Scale कस्टम स्केल + Customize… अनुकूलित करें… + Cut काटें + Cut Artboard कट आर्टबोर्ड + Cut Path कट पाथ + Cut Path at Selected Anchor Points सिलेक्टेड एंकर अंक पर पाथ काटें + Cutout कटआउट + Cutout… कटआउट… + Cyan सियान + Czech चेक + Danish डैनिश + Dark डार्क + Dark Gray गहरा ग्रे + Dark Intensity डार्क तीव्रता + Dark Rough डार्क रफ़ + Dark Strokes डार्क स्ट्रोक्स + Dark Strokes… डार्क स्ट्रोक्स… + Darken डार्कन + Darkness गहरापन + dash डैश + Dash डैश + Dash 1 डैश 1 + Dash 2 डैश 2 + Dash 3 डैश 3 + Dash 4 डैश 4 + Dash 5 डैश 5 + Dash Pattern डैश पैटर्न + Dash: डैश: + Dashed डैश्ड + Dashed Line डैश्ड लाइन + Dashes to Geometry डैश को ज्यामिति में बदलें + Dashes to Geometry… डैश को ज्यामिति में बदलें… + Data Recovery डेटा रिकवरी + Data Set डेटा सेट + Data Set Name डेटा सेट नाम + Data Sets डेटा सेट्स + Data… डेटा… + Date (YYYY-MM-DD) तारीख (YYYYYY-MM-DD) + Date (YYYYMMDD) तारीख (YYYYMMDD) + Dates तारीख + De-Interlace डी-इंटरलेस + De-Interlace… डी-इंटरलेस… + Decimal-Justified Tab दशमलव-संरेखित टैब + Decimal: दशमलव: + Decorative सजावटी + Decrease Font Size फ़ॉन्ट साइज घटाना + Decrease Font Size by Five Steps पांच चरणों द्वारा फ़ॉन्ट आकार घटाना + Deep Ungroup सभी अंदरूनी ग्रुप अनग्रुप करें + Deep Ungroup… सभी अंदरूनी ग्रुप अनग्रुप करें… + Default डिफ़ॉल्ट + Default Actions डिफ़ॉल्ट कार्रवाई + Default Figure डिफ़ॉल्ट चित्र + Default Fill and Stroke डिफ़ॉल्ट भरें और स्ट्रोक + Default Fill and Stroke (D) डिफ़ॉल्ट भरें और स्ट्रोक (D) + Default Graphic Style डिफ़ॉल्ट ग्राफिक स्टाइल + Default Language डिफ़ॉल्ट भाषा + Default Position डिफ़ॉल्ट स्थिति + Default Printer डिफ़ॉल्ट प्रिंटर + Default Swatches डिफ़ॉल्ट स्वॉचेस + Define a variable first पहले एक चर को परिभाषित करें + Define Grid… ग्रिड परिभाषित… + Define Perspective Grid पर्सपेक्टिव ग्रिड डिफ़ाइन करें + Define Perspective Grid… पर्सपेक्टिव ग्रिड डिफ़ाइन करें… + Definition परिभाषा + Delete हटाएँ + Delete “{name}”? "{name}" को हटाएं? + Delete {kind} Style Delete {kind} Style + Delete Action Sets एक्शन सेट हटाएं + Delete All सभी हटाएँ + Delete All Slices सभी स्लाइस हटाएँ + Delete Anchor Point एंकर पॉइंट हटाएँ + Delete Anchor Point Tool डिलीट एंकर पॉइंट टूल + Delete Anchor Points एंकर पॉइंट्स हटाएँ + Delete Artboard आर्टबोर्ड हटाएँ + Delete Artboards आर्टबोर्ड्स हटाएँ + Delete Brush ब्रश हटाएँ + Delete Character Style कैरेक्टर स्टाइल हटाएँ + Delete Data Set डेटा सेट हटाएँ + Delete Data Sets डेटा सेट्स हटाएँ + Delete Design डिलीट डिजाइन + Delete Empty Artboards खाली आर्टबोर्ड हटाएँ + Delete Export Preset प्रीसेट एक्सपोर्ट करें हटाएँ + Delete Freeform Point फ्रीफॉर्म पॉइंट हटाएं + Delete Gradient Preset ग्रेडिएंट प्रीसेट हटाएँ + Delete Graphic Style ग्राफ़िक स्टाइल हटाएँ + Delete Graphic Style (Alt-click: without asking) ग्राफ़िक स्टाइल हटाएँ (Alt-क्लिक: बिना पूछे) + Delete Graphic Styles ग्राफ़िक स्टाइल्स हटाएँ + Delete Group समूह हटाएँ + Delete Guide गाइड हटाएँ + Delete Guides गाइड्स हटाएँ + Delete Image Trace Preset डिलीट इमेज ट्रेस प्रीसेट + Delete Instances इंस्टेंस हटाएँ + Delete Layer लेयर हटाएँ + Delete Library लाइब्रेरी हटाएँ + Delete Library Group लाइब्रेरी समूह + Delete Library Item लाइब्रेरी आइटम हटाएं + Delete Light लाइट हटाएँ + Delete Mesh Point मेश पॉइंट हटाएँ + Delete Paragraph Style पैराग्राफ़ स्टाइल हटाएँ + Delete Pattern पैटर्न हटाएँ + Delete PDF Preset PDF प्रीसेट हटाएँ + Delete Perspective Grid Preset पर्सपेक्टिव ग्रिड पूर्व निर्धारित हटाएँ + Delete Point पॉइंट हटाएँ + Delete Preset प्रीसेट हटाएँ + Delete Print Preset प्रिंट प्रीसेट हटाएँ + Delete Profile प्रोफ़ाइल हटाएँ + Delete Save for Web Preset वेब के लिए सेव करें प्रीसेट हटाएँ + Delete Selected Item सिलेक्टेड आइटम हटाएं + Delete Selection सिलेक्शन हटाएँ + Delete Slice स्लाइस हटाएँ + Delete Slices स्लाइस हटाएँ + Delete Spine Point स्पिन पॉइंट को हटाएं + Delete Stop रोकें हटाएँ + Delete Style स्टाइल हटाएँ + Delete Styles स्टाइल्स हटाएं + Delete Swatch स्वॉच हटाएँ + Delete Symbol सिंबल हटाएँ + Delete Symbols सिंबल्स हटाएँ + Delete Tab टैब हटाएं + Delete the action set “{name}” and its actions? एक्शन सेट "{name}" और इसके कार्यों को हटाएं? + Delete the graphic style “{name}”? ग्राफिक स्टाइल "{name}" को हटा दें? + Delete the library “{name}”? लाइब्रेरी "{name}" को हटा दें? + Delete the selected action sets and their actions? सिलेक्टेड कार्रवाई सेट और उनके कार्यों को हटा दें? + Delete the selected brushes? सिलेक्टेड ब्रश को हटा दें? + Delete the selected symbol? सिलेक्टेड सिंबल हटाएँ? + Delete the selected symbols? सिलेक्टेड सिंबल्स हटाएँ? + Delete theme थीम हटाएं + Delete Theme थीम हटाएं + Delete these {n} graphic styles? इन {n} ग्राफिक स्टाइल्स को हटाएं? + Delete this {n} graphic style? इस {n} ग्राफिक स्टाइल को हटाएं? + Delete this saved preset इस सेव किए गए प्रीसेट को हटा दें + Delete Toolbar टूलबार हटाएं + Delete Transparency Flattener Preset पारदर्शिता फ़्लैटनर प्रीसेट हटाएँ + Delete Variable चर हटाएँ + Delete Variables वेरिएबल्स हटाएँ + Delete View व्यू हटाएँ + Delete Width Point चौड़ाई बिंदु हटाएँ + Delete Workspace वर्कस्पेस हटाएँ + Denominator हर + Depth गहराई + Depth: गहराई: + Desaturate डीसैचुरेट करें + Descender डिसेंडर + Description विवरण + Description: विवरण: + Deselect डीसिलेक्ट करें + Design… डिजाइन… + Desired देसी + Destination Folder: गंतव्य फ़ोल्डर: + Destination: गंतव्य: + Detail डिटेल + Detail: डिटेल: + Devices उपकरण + Dialog डायलॉग + Diameter: व्यास: + Diamond डायमंड + Diamond (open) हीरा (ओपन) + Difference डिफ़रेंस + Differences from [Default]: [Default] से अंतर: + Differences from {preset}: {preset} से अंतर: + Differences from VectorCraft Default: वेक्टर क्रेफ्ट डिफ़ॉल्ट से मतभेद: + Diffuse डिफ़्यूज़ + Diffuse Glow डिफ़्यूज़ ग्लो + Diffuse Glow… डिफ़्यूज़ ग्लो… + Diffusion डिफ़्यूज़न + Digits अंक + Dim Copies to: प्रतियाँ इतनी मंद करें: + Dim Images to: करने के लिए इमेज: + Dimension आयाम + Dimension Lines आयाम लाइन + Dimension Text आयाम टेक्स्ट + Dimension Tool आयाम टूल + Dimension Tool Options आयाम टूल ऑप्शन्स + Dimensions आयाम + Direct Selection प्रत्यक्ष सिलेक्शन + Direct Selection Tool डायरेक्ट सिलेक्शन टूल + Direct-select anchor points to edit them. उन्हें संपादित करने के लिए डायरेक्ट-सिलेक्शन एंकर अंक। + Direction Balance दिशा संतुलन + Direction Handles निर्देशन हैंडल + Direction: दिशा: + Directives निर्देश + Disable Auto Add/Delete ऑटो जोड़ना/हटाना अक्षम करें + Disable Opacity Mask ओपेसिटी मास्क अक्षम करें + Discard डिस्कर्ड + Discard Empty Type डिस्कर्ड खाली प्रकार + Discard Recovered Documents रिकवर किए डॉक्यूमेंट डिस्कार्ड करें + Discard White Overprint in Output आउटपुट में अलार्म व्हाइट ओवरप्रिंट + Discord Discord + Discretionary Hyphen विवेकाधीन हाइफेन + Discretionary Ligatures वैकल्पिक लिगेचर + Display डिस्प्ले + Display All Blacks Accurately सभी ब्लैक्स को सटीक रूप से प्रदर्शित करें + Display All Blacks as Rich Black सभी ब्लैक्स को रिच ब्लैक के रूप में प्रदर्शित करें + Display Bitmaps as Anti-aliased Images in Pixel Preview पिक्सेल प्रीव्यू में एंटी-अलाइस्ड इमेज के रूप में बिटमैप प्रदर्शित करें + Display name प्रदर्शित नाम + Display Options प्रदर्शन ऑप्शन्स + Display Print Size at 100% Zoom 100% ज़ूम पर प्रिंट आकार प्रदर्शित करें + Distance दूरी + Distance: दूरी: + Distort विरूपित करें + Distort & Transform डिस्टॉर्ट और रूपांतरण + Distort Appearance विरूपण + Distort Linear Gradients लीनियर ग्रेडिएंट डिस्टॉर्ट करें + Distort Pattern Fills पैटर्न फ़िल डिस्टॉर्ट करें + Distortion विरूपण + Distribute वितरित करें + Distribute Evenly समान रूप से वितरित करें + Distribute Objects: ऑब्जेक्ट वितरित करें: + Distribute Spacing स्पेसिंग वितरित करें + Distribute Spacing: स्पेसिंग वितरित करें: + Dither डिथर + Dither: डिथर: + Divide विभाजित करें + Divide and Outline Will Remove Unpainted Artwork डिवाइड और आउटलाइन अनपेंटेड आर्टवर्क को हटा देगा + Divide Horizontally Into क्षैतिज रूप से विभाजित करें + Divide into Dashes डैश में बाँटें + Divide into Dashes… डैश में बाँटें… + Divide Objects Below नीचे के ऑब्जेक्ट विभाजित करें + Divide Slices डिवाइड स्लाइस + Divide Slices… डिवाइड स्लाइस… + Divide Vertically Into खड़ी करने के लिए + Do Not Move मत करो + Do Not Scale स्केल न करें + Do you want to save the changes you made to “{name}”? क्या आप "{name}" में किए गए परिवर्तनों को सेव करना चाहते हैं? + Dock Panel पैनल डॉक करें + Document डॉक्यूमेंट + Document Color Mode डॉक्यूमेंट रंग मोड + Document Health Check डॉक्यूमेंट स्वास्थ्य जांच + Document Info डॉक्यूमेंट की जानकारी + Document Ink Options डॉक्यूमेंट स्याही ऑप्शन्स + Document JSON डॉक्यूमेंट JSON + Document Library डॉक्यूमेंट लाइब्रेरी + Document model डॉक्यूमेंट मॉडल + Document Name डॉक्यूमेंट का नाम + Document open password डॉक्यूमेंट खुला पासवर्ड + Document profile डॉक्यूमेंट प्रोफ़ाइल + Document Raster Effects Settings डॉक्यूमेंट रास्टर इफ़ेक्ट्स सेटिंग्स + Document Raster Effects Settings Dialog डॉक्यूमेंट रास्टर इफ़ेक्ट्स सेटिंग्स डायलॉग + Document Raster Effects Settings… डॉक्यूमेंट रास्टर इफ़ेक्ट्स सेटिंग्स… + Document Setup डॉक्यूमेंट सेटअप + Document Setup… डॉक्यूमेंट सेटअप… + Document Swatches डॉक्यूमेंट Swatch + Document Title: डॉक्यूमेंट शीर्षक: + Document Tools डॉक्यूमेंट टूल + Documents you create appear here. डॉक्यूमेंट जो आप यहाँ दिखाई देते हैं। + Don't include profiles प्रोफ़ाइल शामिल नहीं है + Don't Relink दोबारा लिंक न करें + Don't Save सेव करें नहीं + Don't Show Center नहीं दिखाएँ केंद्र + Done संपन्न + Done Editing Pattern डोन संपादन पैटर्न + Dot बिंदु + Dot Color from Art कला से डॉट कलर + Dot Gain 15% डॉट लाभ 15% + Dot on Bar बार पर डॉट + Dots बिंदु + Double Arrow डबल तीर + Double Bar डबल बार + Double Click To Isolate अलग करने के लिए डबल-क्लिक करें + Double Column डबल कॉलम + Double Left Quotation Marks डबल वाम कोटेशन मार्क + Double Quotes: डबल उद्धरण: + Double Right Quotation Marks डबल राइट कोटेशन मार्क्स + Double Slash डबल स्लैश + Double-click डबल क्लिक + Double-click to edit संपादित करने के लिए डबल क्लिक करें + Double-click to edit the characters' paint वर्णों के रंग को संपादित करने के लिए डबल क्लिक करें + Double-click to insert सम्मिलित करने के लिए डबल क्लिक करें + Double-click to rename नाम बदलने के लिए डबल क्लिक करें + Double-click to replace प्रतिस्थापित करने के लिए डबल क्लिक करें + Double-click to target the contents सामग्री को लक्षित करने के लिए डबल क्लिक करें + Down (right reading) नीचे (दाएं पढ़ने) + Download डाउनलोड + Download: डाउनलोड: + Downloaded {what} {what} डाउनलोड किया गया + Draft ड्राफ़्ट + Drag खींचें + Drag a handle एक हैंडल खींचें + Drag an item here, or right-click one, to put it in this group. इस ग्रुप में जोड़ने के लिए आइटम यहाँ ड्रैग करें या उस पर राइट-क्लिक करें। + Drag art here, or select it and click +. Hold Alt for one asset of several objects. आर्टवर्क यहाँ ड्रैग करें या उसे सिलेक्ट करके + क्लिक करें। कई ऑब्जेक्ट का एक एसेट बनाने के लिए Alt दबाए रखें। + Drag art or swatches here, or use + to add the selection's colors and text styles. आर्टवर्क या स्वॉचेस यहाँ ड्रैग करें या सिलेक्शन के रंग और टेक्स्ट स्टाइल्स जोड़ने के लिए + उपयोग करें। + Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. यहाँ कला, रंग और टेक्स्ट स्टाइल्स को खींचें ताकि उन्हें डॉक्यूमेंट्स में पुनः उपयोग किया जा सके। लाइब्रेरी इस मशीन पर संग्रहीत हैं - कोई खाता आवश्यक नहीं है। + Drag onto art to apply this appearance इस उपस्थिति को लागू करने के लिए कला पर खींचें + Drag out from a circle or arc for its radius, inwards for its diameter. अपनी त्रिज्या के लिए एक सर्कल या चाप से बाहर निकलें, इसके व्यास के लिए आगे। + Drag out from a corner, or click two straight lines, then click to place. एक कोने से बाहर खींचें, या दो सीधी रेखाओं पर क्लिक करें, फिर जगह पर क्लिक करें। + Drag out from a segment, or click two points, then click to place. एक खंड से बाहर खींचें, या दो बिंदुओं पर क्लिक करें, फिर जगह पर क्लिक करें। + Drag rings to rotate. Shift snaps to 15°. घुमाने के लिए रिंग ड्रैग करें। Shift से 15° पर स्नैप होता है। + Drag the art to move it on the paper इसे कागज पर स्थानांतरित करने के लिए कला को खींचें + Drag the light, or its rings. Shift snaps to 15°. लाइट या उसकी रिंग ड्रैग करें। Shift से 15° पर स्नैप होता है। + Drag to float as a toolbar एक टूलबार के रूप में तैरने के लिए खींचें + Drag to float the toolbar टूलबार को तैरने के लिए खींचें + Drag to move आगे बढ़ने के लिए + Drag to the window's left edge to dock खिड़की के बाएं किनारे पर डॉक करने के लिए खींचें + Drag values or labels. Double-click a value to type. मूल्यों या लेबल खींचें। टाइप करने के लिए एक मान को डबल क्लिक करें। + Draw ड्रा + Draw Behind पीछे खींचना + Draw Dashed Lines as Solid Lines सॉलिड लाइन्स के रूप में डैश लाइन्स को ड्रॉ करें + Draw in Perspective पर्सपेक्टिव में ड्रॉ + Draw Inside अंदर खींचो + Draw Mode Controls मोड नियंत्रण खींचें + Draw Normal सामान्य + Draw: ड्रा: + Drawer menu दराज मेनू + Drawing : real size — 1:10 labels 1 unit on the page as 10. ड्रॉइंग : वास्तविक साइज़ — 1:10 में पेज पर 1 यूनिट का लेबल 10 होता है। + Drawing Mode ड्राइंग मोड + Drop ड्रॉप + Drop Artwork ड्रॉप आर्टवर्क + Drop here to take it out of its group इसे अपने समूह से बाहर निकालने के लिए यहां ड्रॉप करें + Drop Shadow ड्रॉप शैडो + Drop Shadow… ड्रॉप शैडो… + Dry Brush ड्राई ब्रश + Dry Brush… ड्राई ब्रश… + Duotone डुओटोन + Duotone Gradients डुओटोन ग्रेडिएंट्स + Duotone… डुओटोन… + Duplicate डुप्लीकेट करें + Duplicate {kind} Style डुप्लिकेट {kind} स्टाइल + Duplicate Action or Action Set डुप्लिकेट एक्शन या एक्शन सेट + Duplicate Anchors एंकर की प्रति बनाएँ + Duplicate and Offset 10 pt डुप्लिकेट और ऑफ़सेट 10 pt + Duplicate Artboard आर्टबोर्ड की प्रति बनाएँ + Duplicate Artboards आर्टबोर्ड्स की प्रति बनाएँ + Duplicate Brush डुप्लिकेट ब्रश + Duplicate Character Style कैरेक्टर स्टाइल की प्रति बनाएँ + Duplicate Effect इफ़ेक्ट की प्रति बनाएँ + Duplicate Effects इफ़ेक्ट्स की प्रति बनाएँ + Duplicate Graphic Style ग्राफ़िक स्टाइल की प्रति बनाएँ + Duplicate Item डुप्लिकेट आइटम + Duplicate Layer लेयर डुप्लीकेट करें + Duplicate Objects ऑब्जेक्ट्स की प्रति बनाएँ + Duplicate Paragraph Style पैराग्राफ़ स्टाइल की प्रति बनाएँ + Duplicate Rows पंक्तियाँ की प्रति बनाएँ + Duplicate Selected Item डुप्लिकेट सिलेक्शन आइटम + Duplicate Selection सिलेक्शन की प्रति बनाएँ + Duplicate Slice स्लाइस की प्रति बनाएँ + Duplicate Swatch स्वॉच की प्रति बनाएँ + Duplicate Symbol सिंबल की प्रति बनाएँ + Duplicate Toolbar डुप्लिकेट टूलबार + Duplication डुप्लीकेशन + Dutch डच + DWG (use DXF) DWG (DXF का उपयोग करें) + DXF Import Options DXF आयात ऑप्शन्स + DXF Info DXF जानकारी + DXF Options DXF ऑप्शन्स + DXF Options Dialog DXF ऑप्शन्स डायलॉग + Dynamic Symbol डायनामिक सिंबल + e.g. 1-3, 5 उदाहरण के लिए 1-3, 5 + Each Design Represents: प्रत्येक डिजाइन का प्रतिनिधित्व करता है: + Each entry of the file is matched to a VectorCraft tool, command or panel. Check the matches and answer what is left. फ़ाइल का प्रत्येक प्रविष्टि एक वेक्टर क्रेफ्ट टूल, कमांड या पैनल से मेल खाती है। मैचों की जाँच करें और जवाब दें कि क्या छोड़ दिया गया है। + Each page prints as one image, at the document's raster effects resolution. हर पेज डॉक्यूमेंट के रास्टर इफ़ेक्ट्स रिज़ॉल्यूशन पर एक इमेज के रूप में प्रिंट होता है। + Each run may take up to {minutes} minutes and do {times} times the work other plug-ins may. It runs in the background, and you can cancel it. हर रन में {minutes} मिनट तक लग सकते हैं और अन्य प्लग-इन से {times} गुना काम हो सकता है। यह बैकग्राउंड में चलता है और आप इसे रद्द कर सकते हैं। + Earth Tones पृथ्वी टोन + Ease In ईज़ इन + Ease In Out बाहर में आसानी + Ease Out ईज़ आउट + Ease Out In ईज़ आउट इन + East Asian Type पूर्वी एशियाई प्रकार + Edge किनारा + Edge Brightness किनारे की ब्राइटनेस + Edge Fidelity किनारे की सटीकता + Edge Intensity किनारे की तीव्रता + Edge Only केवल किनारा + Edge Simplicity किनारे की सरलता + Edge Thickness किनारे की मोटाई + Edge Width किनारे की चौड़ाई + Edit एडिट + Edit Artboards आर्टबोर्ड्स एडिट करें + Edit Character Style कैरेक्टर स्टाइल एडिट करें + Edit Clipping Path क्लिपिंग पाथ एडिट करें + Edit Color Group रंग समूह एडिट करें + Edit Colors रंग एडिट करें + Edit Contents सामग्री संपादित करें + Edit Custom Dictionary… कस्टम शब्दकोश संपादित करें… + Edit Data Set डेटा सेट एडिट करें + Edit Data Set… डेटा सेट एडिट करें… + Edit Envelope एन्वेलप एडिट करें + Edit Freeform Point फ्रीफॉर्म पॉइंट संपादित करें + Edit Gradient ग्रेडिएंट एडिट करें + Edit Opacity Mask ओपेसिटी मास्क एडिट करें + Edit or Apply Color Group रंग समूह संपादित करें या लागू करें + Edit or Apply Color Group… रंग समूह संपादित करें या लागू करें… + Edit or Apply Colors रंग संपादित करें या लागू करें + Edit Original मूल एडिट करें + Edit Parametric Shape पैरामीट्रिक आकार एडिट करें + Edit Path पाथ एडिट करें + Edit Pattern पैटर्न एडिट करें + Edit PDF Preset PDF प्रीसेट एडिट करें + Edit Perspective Grid पर्सपेक्टिव ग्रिड एडिट करें + Edit Print Preset प्रिंट प्रीसेट एडिट करें + Edit selected paths within: भीतर सिलेक्टेड पाथ संपादित करें: + Edit Selection सिलेक्शन एडिट करें + Edit Selection… सिलेक्शन एडिट करें… + Edit Symbol सिंबल एडिट करें + Edit Text टेक्स्ट एडिट करें + Edit the applied effect, or add another one? लागू इफ़ेक्ट संपादित करें, या एक दूसरे को जोड़ें? + Edit the point बिन्दु संपादित करें + Edit the stop स्टॉप संपादित करें + Edit theme थीम संपादित करें + Edit Theme थीम संपादित करें + Edit Toolbar टूलबार संपादित करें + Edit Views दृश्य एडिट करें + Edit Views… दृश्य एडिट करें… + Edit… संपादित करें… + Editable संपादन योग्य + Effect इफ़ेक्ट + Effect Gallery इफ़ेक्ट गैलरी + Effect Gallery Dialog इफ़ेक्ट गैलरी + Effect Gallery… इफ़ेक्ट गैलरी… + Effect Options इफ़ेक्ट ऑप्शन्स + Effect… इफ़ेक्ट… + Effective PPI प्रभावी पीपीआई + Effects इफ़ेक्ट्स + Eliminate हटाएँ + Ellipse एलिप्स + Ellipse Properties: एलिप्स प्रॉपर्टीज़: + Ellipse Tool एलिप्स टूल + Ellipse… एलिप्स… + Ellipsis दीर्घविराम + Em Box एम बॉक्स + Em Box Bottom/Left एम बॉक्स नीचे/बाएँ + Em Box Center एम बॉक्स सेंटर + Em Box Top/Right एम बॉक्स ऊपर/दाएँ + Em Dash एम डैश + Em Space एम स्पेस + Embed एम्बेड करें + Embed Fonts (for other applications) एम्बेड फ़ॉन्ट (अन्य अनुप्रयोगों के लिए) + Embed Fonts (Glyphs Used) फ़ॉन्ट एम्बेड करें (उपयोग किए ग्लिफ़) + Embed ICC Profile ICC प्रोफ़ाइल एम्बेड करें + Embed ICC Profiles ICC प्रोफ़ाइल एम्बेड करें + Embed Image एम्बेड इमेज + Embed Image(s) एम्बेड इमेज(s) + Embed page thumbnails एम्बेड पृष्ठ थंबनेल + Embedded एम्बेडेड + Embedded Image एम्बेडेड इमेज + Empty Artboards खाली आर्टबोर्ड + Empty Text खाली टेक्स्ट + Emulsion: इमल्शन: + En Dash एन डैश + En Space एन स्पेस + Enable Background Export पृष्ठभूमि निर्यात सक्षम करें + Enable Background Save पृष्ठभूमि सेव करें सक्षम करें + Enable Contextual Task Bar प्रासंगिक टास्क बार सक्षम करें + Enable copying of text, images and other content टेक्स्ट, इमेज और अन्य सामग्री की प्रतिलिपि बनाने में सक्षम करें + Enable Guides for 9-Slice Scaling 9 स्लाइस स्केलिंग के लिए गाइड सक्षम करें + Enable in-menu font previews इन-मेनू फ़ॉन्ट प्रीव्यू सक्षम करें + Enable Missing Glyph Protection मिसिंग ग्लाइफ संरक्षण सक्षम करें + Enable Opacity Mask ओपेसिटी मास्क सक्षम करें + Enable plaintext metadata सादाटेक्स्ट मेटाडाटा सक्षम करें + Enable Rubber Band for के लिए रबर बैंड सक्षम करें + Enable text access for screen readers स्क्रीन रीडर के लिए टेक्स्ट एक्सेस सक्षम करें + Enable Touch Gestures टच जेस्चर ऑन करें + Enable Touch Workspace टच वर्कस्पेस सक्षम करें + Enclosing Lasso लासो संलग्न करना + Enclosing Lasso Tool लासो टूल संलग्न करना + Encoding एन्कोडिंग + Encoding and writing the file… फ़ाइल को एन्कोडिंग और लेखन… + Encoding: एन्कोडिंग: + Encryption: {name} (set by Compatibility) एन्क्रिप्शन: {name} ( संगतता द्वारा सेट) + End arrowhead अंत का एरोहेड + End Length अंत की लंबाई + End Percent अंत प्रतिशत + End Shape अंत आकार + End Tile अंत टाइल + End Undo Group एंड अनडो ग्रुप + End: अंत: + English English + English: UK अंग्रेज़ी: UK + English: USA अंग्रेज़ी: USA + Enhanced बढ़ी + Enlarged बड़ा किया गया + Enter Enter + Enter Isolation Mode आइसोलेशन मोड में जाएँ + Entire Font पूरा फ़ॉन्ट + Envelope एन्वेलप + Envelope #10 लिफाफाफा #10 + Envelope Distort एन्वेलप डिस्टॉर्ट + Envelope DL लिफ़ाफ़ा DL + Envelope Info लिफाफे की जानकारी + Envelope Mesh एन्वेलप मेश + Envelope Options एन्वेलप ऑप्शन्स + Envelope Options… एन्वेलप ऑप्शन्स… + EPS Options ईपीएस ऑप्शन्स + EPS Options Dialog ईपीएस ऑप्शन्स डायलॉग + Equalize Handles हैंडल बराबर करें + Eraser इरेज़र + Eraser Tool इरेज़र टूल + Error त्रुटि + Esc Esc + Even शाम + Even Fields सम फ़ील्ड्स + Even-Numbered Anchors यहां तक कि संख्या वाले एंकर + Event: कार्यक्रम: + Every (minutes) हर (मिनट) + Every option is at its default. प्रत्येक ऑप्शन इसके डिफ़ॉल्ट रूप से होता है। + Every option matches {base}. प्रत्येक ऑप्शन {base} से मेल खाता है। + Every-line Composer हर लाइन संगीतकार + Exact सटीक + Exact dash lengths सटीक डैश लंबाई + Example: {name} उदाहरण: {name} + Exceptions (comma separated) अपवाद (कोमा अलग) + Exclude बाहर रखें + Exclude from playback प्लेबैक से निकलें + Exclude Pure Black शुद्ध काला छोड़ें + Exclusion एक्सक्लूज़न + Exit बाहर निकलें + Exit Isolation Mode आइसोलेशन मोड से बाहर निकलें + Exit Symbol Editing Mode सिंबल एडिटिंग मोड से बाहर निकलें + Expand एक्सपैंड करें + Expand 1 Selected 1 सिलेक्टेड विस्तार + Expand Appearance अपीयरेंस एक्सपैंड करें + Expand Appearance first (Object › Expand Appearance) पहले अपीयरेंस एक्सपैंड करें (ऑब्जेक्ट › अपीयरेंस एक्सपैंड करें) + Expand Blend ब्लेंड एक्सपैंड करें + Expand Brush Strokes ब्रश स्ट्रोक्स एक्सपैंड करें + Expand Compound Shape कंपाउंड शेप एक्सपैंड करें + Expand Dashes into Paths डैश को पाथ में एक्सपैंड करें + Expand Envelope एन्वेलप एक्सपैंड करें + Expand Gradient Mesh ग्रेडिएंट मेश एक्सपैंड करें + Expand Gradient To ग्रेडिएंट इसमें एक्सपैंड करें + Expand Image Trace इमेज ट्रेस एक्सपैंड करें + Expand Instances इंस्टेंस एक्सपैंड करें + Expand Layers Panel Rows लेयर्स पैनल की रो एक्सपैंड करें + Expand Live Paint लाइव पेंट एक्सपैंड करें + Expand Object ऑब्जेक्ट का विस्तार + Expand Objects on Path पाथ पर ऑब्जेक्ट्स एक्सपैंड करें + Expand Options ऑप्शन्स एक्सपैंड करें + Expand Panels पैनलों का विस्तार + Expand Repeat रिपीट एक्सपैंड करें + Expand Shape शेप एक्सपैंड करें + Expand Shaper Group शेपर ग्रुप एक्सपैंड करें + Expand: एक्सपैंड करें: + Expand… एक्सपैंड करें… + Expanded Patterns विस्तारित पैटर्न + Export एक्सपोर्ट करें + Export {count} Selected निर्यात {count} सिलेक्टेड + Export All Open Documents सभी डॉक्यूमेंट्स का निर्यात करें + Export All Open Documents as PDF PDF के रूप में सभी ओपन डॉक्यूमेंट्स को निर्यात करें + Export All Open Documents as SVG SVG के रूप में सभी ओपन डॉक्यूमेंट्स का निर्यात करें + Export All… सभी को निर्यात करें… + Export and Clipboard Transparency Flattener Settings एक्सपोर्ट और क्लिपबोर्ड ट्रांसपेरेंसी फ़्लैटनर सेटिंग्स + Export Artboard आर्टबोर्ड निर्यात करें + Export As इस रूप में एक्सपोर्ट करें + Export As PNG… PNG के रूप में निर्यात करें… + Export As SVG… SVG के रूप में निर्यात करें… + Export As… इस रूप में एक्सपोर्ट करें… + Export Asset संपत्ति निर्यात करें + Export Assets निर्यात परिसंपत्तियां + Export CSS CSS निर्यात करें + Export CSS… CSS निर्यात करें… + Export Data Sets… डेटा सेट निर्यात करें… + Export Document डॉक्यूमेंट निर्यात करें + Export DXF DXF निर्यात करें + Export EPS ईपीएस निर्यात करें + Export Export Presets निर्यात प्रीसेट + Export for Screens स्क्रीन के लिए निर्यात + Export for Screens Settings स्क्रीन सेटिंग के लिए निर्यात + Export for Screens… स्क्रीन के लिए निर्यात… + Export Keyboard Shortcuts… कीबोर्ड शॉर्टकट निर्यात करें… + Export Layer निर्यात लेयर + Export Library लाइब्रेरी + Export Library… लाइब्रेरी निर्यात करें… + Export Option निर्यात ऑप्शन + Export PDF PDF निर्यात करें + Export PDF Presets PDF प्रीसेट्स एक्सपोर्ट करें + Export PDFs As: PDF निर्यात करें: + Export Perspective Grid Presets निर्यात पर्सपेक्टिव ग्रिड प्रीसेट + Export Preset: प्रीसेट एक्सपोर्ट करें: + Export Preset… प्रीसेट एक्सपोर्ट करें… + Export Presets प्रीसेट्स एक्सपोर्ट करें + Export Print Presets निर्यात प्रिंट प्रीसेट + Export Selected Art Only केवल सिलेक्टेड कला का निर्यात करें + Export Selected CSS… चुनिंदा सीएसएस निर्यात करें… + Export Selection निर्यात सिलेक्शन + Export Selection… निर्यात सिलेक्शन… + Export Settings सेटिंग्स एक्सपोर्ट करें + Export the selected assets (else all of them) सिलेक्टेड परिसंपत्तियों को निर्यात करें (उनमें से सभी को छोड़ दें) + Export to: इसमें एक्सपोर्ट करें: + Export Transparency Flattener Presets पारदर्शिता फ़्लैटनर प्रीसेट एक्सपोर्ट करें + Export Type: निर्यात प्रकार: + Export: एक्सपोर्ट करें: + Export… एक्सपोर्ट करें… + Exported {path} {path} एक्सपोर्ट किया गया + Exported {what} निर्यात किया गया {what} + Exporting {} निर्यात {} + Exposure एक्सपोज़र + Exposure… एक्सपोज़र… + Extend Path पाथ का विस्तार + Extend Path Tool पाथ टूल का विस्तार + Extend Path… पाथ का विस्तार करें… + Extension Lines एक्सटेंशन लाइन + Extension: विस्तार: + Extrude & Bevel… एक्सट्रूडेड और बेवेल… + Eyedropper आईड्रॉपर + Eyedropper Applies: आईड्रॉपपर लागू होता है: + Eyedropper Options आईड्रॉपर ऑप्शन्स + Eyedropper Picks Up: आईड्रॉपर पिक्स अप: + Eyedropper Tool आईड्रॉपर टूल + Eyedropper: click the art to sample the key color आईड्रॉपर: मुख्य रंग का सैंपल लेने के लिए आर्टवर्क पर क्लिक करें + Eyedropper: click the art to sample the stop's colour आईड्रॉपर: स्टॉप के रंग का नमूना लेने के लिए कला पर क्लिक करें + Farsi फारसी + Favorites पसंदीदा + Feather फ़ेदर + Feather… फ़ेदर… + Feet पैर + Feet & Inches पैर & इंच + Fewer Elements कम एलिमेंट + Fidelity: सटीकता: + Figure Space अंक-स्पेस + Figure: आकृति: + File फ़ाइल + File › Place… brings in an image, linked or embedded. फ़ाइल> प्लेस... एक इमेज, लिंक्ड या एम्बेडेड में लाता है। + File {n} of {total} {total} की फ़ाइल {n} + File + Data Set Name फ़ाइल + डेटा सेट नाम + File + Number फ़ाइल + संख्या + File Dimensions फ़ाइल आयाम + File Format: फ़ाइल फ़ॉर्मेट: + File Formats फ़ाइल फ़ॉर्मैट + File Handling फ़ाइल हैंडलिंग + File Info फ़ाइल जानकारी + File Info Dialog फ़ाइल की जानकारी डायलॉग + File Info… फ़ाइल जानकारी… + File Name: फ़ाइल नाम: + File or URL: फ़ाइल या यूआरएल: + Files फ़ाइलें + Files of a PDF standard can't be password-protected. एक PDF मानक की फ़ाइलें पासवर्ड की रक्षा नहीं की जा सकती है। + Files of this standard tag their colours with ICC profiles. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं। + Fill फ़िल + Fill (X), double-click for the Color Picker रंग पिकर के लिए डबल क्लिक करें + Fill & Stroke भरें और स्ट्रोक करें + Fill and Stroke भरें और स्ट्रोक करें + Fill and Stroke Controls भरण और स्ट्रोक नियंत्रण + Fill Arc आर्क भरें + Fill Color फ़िल रंग + Fill Gradient ग्रेडिएंट भरें + Fill Grid ग्रिड भरें + Fill Line लाइन भरें + Fill new strokes नए स्ट्रोक भरें + Fill New Type Objects With Placeholder Text प्लेसहोल्डर टेक्स्ट के साथ नए प्रकार के ऑब्जेक्ट भरें + Fill Pattern पैटर्न भरें + Fill Rule नियम भरें + Fill with Placeholder Text प्लेसहोल्डर टेक्स्ट से भरें + Fill: फ़िल: + Fill: click for swatches, Shift-click for the color mixer फ़िल: स्वॉचेस के लिए क्लिक करें, कलर मिक्सर के लिए Shift-क्लिक करें + Filled Dot भरा डॉट + Filled Open Paths भरा खुला पाथ + Filled Square भरा वर्ग + Filling in form fields and signing फॉर्म फ़ील्ड में भरना और साइन करना + Fills भरता + Film & Video फ़िल्म और वीडियो + Film Grain… फ़िल्म ग्रेन… + Filter फ़िल्टर + Filter Layers Panel Rows फ़िल्टर लेयरें पैनल पंक्तियाँ + Filters फिल्टर + Find खोजें + Find and Replace… खोजें और बदलें… + Find Font फ़ॉन्ट खोजें + Find Font Files फ़ॉन्ट फ़ाइल का पता लगाएं + Find Font… फ़ॉन्ट खोजें… + Find Fonts फाइंड फ़ॉन्ट + Find Fonts in Folder… फ़ोल्डर में फ़ॉन्ट खोजें… + Find in Folder… फ़ोल्डर में खोजें… + Find Linked Files लिंक्ड फ़ाइलें खोजें + Find Linked Files in Folder… फ़ोल्डर में लिंक्ड फ़ाइलें खोजें… + Find Nearest Swatch निकटतम स्वॉच खोजें + Find Nearest Swatch… निकटतम स्वॉच खोजें… + Find Next अगला खोजें + Find Objects ऑब्जेक्ट्स खोजें + Fine Dots बारीक बिंदु + Fine noise hides banding in the gradient fill ठीक शोर ग्रेडिएंट भरने में बैंडिंग छिपाता है + Finnish फिनिश + First पहला + First Artboard प्रथम आर्टबोर्ड + First Baseline फर्स्ट बेसलाइन + First commit पहला कमिट + First Page पहला पन्ना + First-line Left Indent फर्स्ट-लाइन लेफ्ट इंडेंट + Fish… मछली… + Fisheye… फ़िशआई… + Fit फ़िट करें + Fit All सभी फिट + Fit All in Window विंडो में सभी फिट + Fit Artboard in Window विंडो में फिट आर्टबोर्ड + Fit dashes to corners and ends कोनों और सिरों के लिए फिट डैश + Fit Headline फिट हेडलाइन + Fit in View दृश्य में फ़िट करें + Fit in Window विंडो में फिट + Fit on Screen स्क्रीन पर फ़िट करें + Fit to Artwork Bounds आर्टवर्क बाउंड्स के लिए फिट + Fit to Corners and Ends कॉर्नर और एंड्स के लिए फिट + Fit to Page पेज पर फिट + Fit to Selected Art सिलेक्टेड कला के लिए फिट + Fix All सभी को ठीक करें + Fix All Issues सभी मुद्दों को ठीक करें + Fix Issues मुद्दों को ठीक करें + Fix Selected निर्धारित करना + Fixed निश्चित + Flag… झंडा… + Flare फ्लेयर + Flare Tool फ्लेयर टूल + Flare Tool Options फ़्लेयर टूल ऑप्शन्स + Flat Angle फ्लैट कोण + Flat Blunt फ्लैट ब्लंट + Flat Curve फ्लैट वक्र + Flat Fan फ्लैट फैन + Flat Image फ्लैट इमेज + Flat Logo Flat लोगो + Flat Point फ्लैट पॉइंट + Flatness: समतलता: + Flatten चपटा + Flatten Artwork आर्टवर्क फ़्लैट करें + Flatten Transparency पारदर्शिता फ़्लैट करें + Flatten Transparency… पारदर्शिता फ़्लैट करें… + Flattener preset: फ़्लैटनर प्रीसेट: + Flattener presets फ़्लैटनर प्रीसेट्स + Flattener Preview फ़्लैटनर प्रीव्यू + Flip पलटें + Flip Across आड़ी दिशा में पलटें + Flip Along साथ में फ्लिप + Flip Along Horizontal Axis क्षैतिज अक्ष के साथ फ्लिप + Flip Along Vertical Axis वर्टिकल एक्सिस के साथ फ्लिप + Flip Horizontal क्षैतिज पलटें + Flip Row Order फ्लिप पंक्ति ऑर्डर + Flip Vertical लंबवत पलटें + Flip: पलटें: + Float All in Windows सभी को विंडो में फ़्लोट करें + Float in Window विंडो में फ़्लोट करें + Float Panel पैनल फ़्लोट करें + Float Tool Group फ्लोट टूल ग्रुप + Focal Fill फोकल फिल + Focal Stroke फोकल स्ट्रोक + Folder फ़ोल्डर + Folder Name: फ़ोल्डर का नाम: + Folders: फ़ोल्डर: + Font फ़ॉन्ट + Font Family फ़ॉन्ट परिवार + Font Family & Style फ़ॉन्ट परिवार और स्टाइल + Font Family, Style & Size फ़ॉन्ट परिवार, स्टाइल और आकार + Font Family: फ़ॉन्ट परिवार: + Font List फ़ॉन्ट सूची + Font Preview Size फ़ॉन्ट प्रीव्यू साइज़ + Font Size फ़ॉन्ट साइज़ + Font Size: फ़ॉन्ट साइज़: + Font Style: फ़ॉन्ट स्टाइल: + Font Technology फ़ॉन्ट प्रौद्योगिकी + Font: फ़ॉन्ट: + Fonts फ़ॉन्ट + Fonts in Document डॉक्यूमेंट में फ़ॉन्ट + Fonts in Document: {count} डॉक्यूमेंट में फ़ॉन्ट: {count} + fonts not copied: {fonts} फ़ॉन्ट कॉपी नहीं हुए: {fonts} + Fonts whose licence doesn't allow embedding are not copied. जिन फ़ॉन्ट का लाइसेंस एम्बेडिंग की अनुमति नहीं देता है, उन्हें कॉपी नहीं किया जाता है। + For Fractions: फ्रैक्शन के लिए: + Force सेना + Forced Line Break जबरन लाइन ब्रेक + Foreground Level फ़ोरग्राउंड स्तर + Forget Import Matches फॉरगेट आयात मैच + Fork फोर्क + Format फ़ॉर्मेट + Format Options फ़ॉर्मेट ऑप्शन्स + Format Presets फ़ॉर्मैट प्रीसेट + Format Settings फ़ॉर्मैट सेटिंग + Format: फ़ॉर्मेट: + Formats: फ़ॉर्मैट: + Fractional Widths आंशिक चौड़ाई + Fractions भिन्न + Free मुक्त + Free Distort फ़्री डिस्टॉर्ट + Free Distort… फ़्री डिस्टॉर्ट… + Free Transform मुक्त रूपांतरण + Free Transform Tool फ्री ट्रांसफॉर्म टूल + Freeform फ्रीफॉर्म + Freeform Gradient फ़्रीफ़ॉर्म ग्रेडिएंट + French फ्रेंच + Frequencies and angles are the output device's to apply. फ़्रीक्वेंसी और एंगल आउटपुट डिवाइस लागू करता है। + Frequency आवृत्ति + Fresco फ़्रेस्को + Fresco… फ़्रेस्को… + from the format's public description फ़ॉर्मैट के सार्वजनिक विवरण से + from your earlier imports अपने पहले आयात से + From: से: + Front सामने + Frosted फ़्रॉस्टेड + Full Document पूरा डॉक्यूमेंट + Full Justify फुल जस्टिफ़ाई + Full Screen Mode फ़ुल स्क्रीन मोड + Full Screen Mode with Menu Bar मेनू बार के साथ फ़ुल स्क्रीन मोड + Full Tone पूर्ण टोन + Full Width पूर्ण चौड़ाई + Fully Inside पूरी तरह से अंदर + Fully Outside पूरी तरह बाहर + Function Key: समारोह कुंजी: + Fuzziness: फ़ज़ीनेस: + Gamma गामा + Gamut Check गैमट जाँच + Gamut Warning गैमट चेतावनी + gap गैप + Gap गैप + Gap 1 अंतर 1 + Gap 2 अंतर 2 + Gap 3 अंतराल 3 + Gap 4 अंतराल 4 + Gap 5 दूरी 5 + Gap Detection गैप डिटेक्शन + Gap Length: अंतराल की लंबाई: + Gap Options गैप ऑप्शन्स + Gap Options… गैप ऑप्शन्स… + Gap Preview Color: गैप प्रीव्यू रंग: + Gap: गैप: + Gaussian Blur गॉसियन ब्लर + Gaussian Blur… गॉसियन ब्लर… + Gear गियर + General सामान्य + General › Placement › X सामान्य › प्लेसमेंट › एक्स + General › Thumbnails सामान्य › थंबनेल + Generate CSS सीएसएस उत्पन्न करना + Generate CSS: the whole document's CSS while nothing is selected CSS जनरेट करें: कुछ सिलेक्ट न होने पर पूरे डॉक्यूमेंट का CSS बनता है + Geometric Guides ज्यामितीय गाइड + Geometric Patterns ज्यामितीय पैटर्न + German जर्मन + German: Swiss जर्मन: स्विस + Get Preferences प्राथमिकता प्राप्त करें + Get Text Range टेक्स्ट रेंज प्राप्त करें + GIF, 128 colours GIF, 128 रंग + Glass ग्लास + Glass… ग्लास… + Global ग्लोबल + Global Adjust वैश्विक समायोजन + Global Brush Dimensions ग्लोबल ब्रश आयाम + Global Edit Options ग्लोबल एडिट ऑप्शन्स + Global Process Color ग्लोबल प्रोसेस कलर + Global Process Color, CMYK ग्लोबल प्रोसेस कलर, CMYK + Glow Amount ग्लो मात्रा + Glow Brightness ग्लो ब्राइटनेस + Glow Size ग्लो साइज़ + Glowing Edges चमकते किनारे + Glowing Edges… चमकते किनारे… + glyph {id} ग्लिफ़ {id} + Glyph Bounds ग्लिफ़ की सीमाएँ + Glyph Scaling: ग्लिफ़ स्केलिंग: + Glyphs ग्लिफ़्स + Go to Artboard आर्टबोर्ड पर जाएं + Go to Conflict विरोध पर जाएँ + Go To Link लिंक पर जाएं + Good अच्छा + GPL palettes keep solid colours only, as RGB. जीपीएल पैलेट केवल RGB के रूप में ठोस रंग रखते हैं। + GPU Performance GPU प्रदर्शन + Grab bag विविध + Gradient ग्रेडिएंट + Gradient (. or Shift+.) ग्रेडिएंट (। या Shift+)। + Gradient across stroke पूरे स्ट्रोक में ग्रेडिएंट + Gradient along stroke स्ट्रोक के साथ ग्रेडिएंट + Gradient and Mesh Resolution: ग्रेडिएंट और मेश रिज़ॉल्यूशन: + Gradient Fill: click to apply, drag onto art ग्रेडिएंट फिल: लागू करने के लिए क्लिक करें, कला पर खींचें + Gradient Finishes ग्रेडिएंट फिनिश + Gradient Mesh ग्रेडिएंट मेश + Gradient Presets ग्रेडिएंट प्रीसेट्स + Gradient swatches ग्रेडिएंट स्वॉचेस + Gradient Tool ग्रेडिएंट टूल + Gradient Vector ग्रेडिएंट वेक्टर + Gradient within stroke स्ट्रोक के भीतर ग्रेडिएंट + Gradients ग्रेडिएंट्स + Grain ग्रेन + Grain Type ग्रेन प्रकार + Grain… ग्रेन… + Graininess ग्रेनीनेस + Grainy Dots दानेदार बिंदु + Graph ग्राफ़ + Graph Column ग्राफ़ कॉलम + Graph Data ग्राफ़ डेटा + Graph Design ग्राफ़ डिजाइन + Graph Marker ग्राफ़ मार्कर + Graph Type ग्राफ़ टाइप + Graphic ग्राफिक + Graphic Pen ग्राफ़िक पेन + Graphic Pen… ग्राफ़िक पेन… + Graphic Style ग्राफ़िक स्टाइल + Graphic Style Libraries ग्राफिक स्टाइल लाइब्रेरी + Graphic Style Libraries Menu ग्राफ़िक स्टाइल लाइब्रेरी मेनू + Graphic Style Library ग्राफ़िक स्टाइल लाइब्रेरी + Graphic Style Options ग्राफिक स्टाइल ऑप्शन्स + Graphic Style Options… ग्राफिक स्टाइल ऑप्शन्स… + Graphic Styles ग्राफ़िक स्टाइल्स + Graphic Styles (4) ग्राफिक स्टाइल्स (4) + Graphic Styles Options ग्राफ़िक स्टाइल ऑप्शन्स + Graphics ग्राफ़िक्स + Graphics Processor ग्राफिक्स प्रोसेसर + Graphics: {adapter} ग्राफिक्स: {adapter} + Gravity ग्रेविटी + Gray ग्रे + Gray Gamma 2.2 ग्रे गामा 2.2 + Grays ग्रे + Grays and Neutrals ग्रे और तटस्थ + Grayscale ग्रेस्केल + Grayscale images ग्रेस्केल इमेज + Grayscale Images ग्रे स्केल इमेज + Greek & Cyrillic ग्रीक & Cyrillic + Green हरा + Greeting Card ग्रीटिंग कार्ड + Grey ग्रे + Grid ग्रिड + Grid by Column कॉलम द्वारा ग्रिड + Grid by Row रॉ द्वारा ग्रिड + Grid Color & Opacity ग्रिड रंग और ओपेसिटी + Grid Colors: ग्रिड रंग: + Grid Repeat ग्रिड दोहराएँ + Grid Size: ग्रिड साइज़: + Grid View ग्रिड व्यू + Gridline every ग्रिडलाइन हर + Gridline every: ग्रिडलाइन हर: + Grids In Back ग्रिड में वापस + Group समूह + Group Overlapping Objects समूह ओवरलैपिंग ऑब्जेक्ट + Group Selection समूह सिलेक्शन + Group Selection Tool समूह सिलेक्शन टूल + Group with इसके साथ समूह बनाएँ + Groups समूह + Grout Width ग्राउट चौड़ाई + Growth: विकास: + Guide गाइड + Guides गाइड्स + Guides & Grid गाइड और ग्रिड + Gujarati गुजराती + Gutter गटर + Gutter: गटर: + H Spacing: एच स्पेसिंग: + H: H: + Ha हाउ + Hair Space हेयर स्पेस + Half Arrow (left) आधा तीर (बाएं) + Half Arrow (right) आधा तीर (दाएं) + Half Circle आधा सर्कल + Halftone Pattern हाफ़टोन पैटर्न + Halftone Pattern… हाफ़टोन पैटर्न… + Halo हलो + Hand हैंड + Hand Tool हैंड टूल + Hand-Drawn हाथ-ड्रन + Handles हैंडल्स + Hard कठोर + Hard Light हार्ड लाइट + Hard Mix हार्ड मिक्स + Harmony Rules हार्मनी नियम + Harmony Rules: सद्भाव नियम: + Harmony Sets हार्मोनी सेट + HDTV 1080p HDTV 1080p + HDTV 720p HDTV 720p + Head: सिर: + Health Check स्वास्थ्य जांच + Heart दिल + Heavy Ink भारी स्याही + Height ऊँचाई + Height: ऊंचाई: + Height/Width ऊंचाई / चौड़ाई + Help सहायता + Help › Search Commands… मदद › खोज कमांड… + HEX HEX + Hex by Column कॉलम द्वारा हेक्स + Hex by Row पंक्ति द्वारा हेक्स + Hexagon षट्भुज + Hexagon (open) हेक्सागोन (ओपन) + Hidden छिपा हुआ + Hidden Layer छिपी हुई लेयर + Hidden Objects: छुपे ऑब्जेक्ट्स: + Hide छिपाएँ + Hide Artboards आर्टबोर्ड्स छिपाएँ + Hide Bar बार छिपाएँ + Hide Bounding Box बाउंडिंग बॉक्स छिपाएँ + Hide Code कोड छुपाएं + Hide Corner Widget हिडन कॉर्नर विजेट + Hide Corner Widget for angles greater than से अधिक कोणों के लिए छुपा कॉर्नर विजेट + Hide Edges हाइड एज + Hide Extension Lines एक्सटेंशन लाइन छिपाएँ + Hide Font Height Options फ़ॉन्ट हाइट ऑप्शन्स छिपाएँ + Hide Gradient Annotator ग्रेडिएंट एनोटेटर छिपाएँ + Hide Grid ग्रिड छिपाएँ + Hide Guides गाइड्स छिपाएँ + Hide Hidden Characters छिपे हुए चरित्र छुपाएं + Hide Live Paint Gaps छुपा लाइव पेंट गैप + Hide Note नोट छिपाएँ + Hide Options ऑप्शन्स छिपाएँ + Hide Others अन्य छिपाएँ + Hide Presets प्रीसेट्स छिपाएँ + Hide Print Tiling प्रिंट टाइलिंग छिपाएँ + Hide Rulers रूलर्स छिपाएँ + Hide Slices स्लाइस छिपाएँ + Hide Snap to Glyph Options ग्लिफ़ पर स्नैप ऑप्शन्स छिपाएँ + Hide Template टेम्पलेट छिपाएँ + Hide Text Threads टेक्स्ट थ्रेड छुपाएं + Hide Thumbnail थंबनेल छिपाएँ + Hide Thumbnails हिंदुस्तान + Hide Transparency Grid पारदर्शिता ग्रिड छिपाएँ + Hide Units इकाइयाँ छिपाएँ + Hide VectorCraft VectorCraft छिपाएँ + Hide Video Rulers वीडियो शासक + High उच्च + High (300 ppi) उच्च (300 ppi) + High Contrast उच्च न्यायालय + High Contrast 2 उच्च न्यायालय 2 + High Contrast 3 उच्च न्यायालय 3 + High Fidelity Photo उच्च निष्ठा फोटो + High Performance (discrete) उच्च निष्पादन (डिस्क्रीट) + High Quality Print उच्च गुणवत्ता वाले प्रिंट + High resolution उच्च संकल्प + High Resolution उच्च संकल्प + Highlight हाइलाइट + Highlight Alternate Glyphs हाइलाइट अल्टरनेटर ग्लिफ़ + Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर + Highlight Area हाइलाइट क्षेत्र + Highlight Font Name हाइलाइट फ़ॉन्ट नाम + Highlight Kerning हाइलाइट कर्निंग + Highlight Rows हाइलाइट पंक्तियाँ + Highlight Substituted Fonts हाईलाइट सबस्टिट्यूटेड फ़ॉन्ट + Highlight Substituted Glyphs बदले हुए ग्लिफ़ हाइलाइट करें + Highlight Tracking हाइलाइट ट्रैकिंग + Highlight Variable उच्च प्रकाश परिवर्तनीय + Highlight: हाइलाइट: + Hindi हिन्दी + History हिस्ट्री + History Options… हिस्ट्री ऑप्शन्स… + History States हिस्ट्री स्थितियाँ + Hold होल्ड + Hollow खोखले + Hollow Circle खोखले सर्कल + Home होम + Horizon Height: क्षितिज ऊंचाई: + Horizontal क्षैतिज + Horizontal & Vertical Align Center क्षैतिज और ऊर्ध्वाधर संरेखित केंद्र + Horizontal % क्षैतिज % + Horizontal Align Center क्षैतिज संरेखित केंद्र + Horizontal Align Left क्षैतिज दिशा में बाएँ अलाइन करें + Horizontal Align Right क्षैतिज दिशा में दाएँ अलाइन करें + Horizontal Distribute Center क्षैतिज वितरण केंद्र + Horizontal Distribute Left बाएँ किनारों के अनुसार क्षैतिज दिशा में डिस्ट्रिब्यूट करें + Horizontal Distribute Right दाएँ किनारों के अनुसार क्षैतिज दिशा में डिस्ट्रिब्यूट करें + Horizontal Distribute Space क्षैतिज स्पेस वितरित करें + Horizontal Dividers: क्षैतिज विभाजक: + Horizontal Grid: क्षैतिज ग्रिड: + Horizontal Guide क्षैतिज गाइड + Horizontal Plane क्षैतिज प्लेन + Horizontal Scale क्षैतिज स्केल + Horizontal Scale % क्षैतिज स्केल % + Horizontal: क्षैतिज: + How colours outside the press's gamut are separated. प्रेस के बाहर के रंग कैसे अलग हो जाते हैं। + HTML and Images एचटीएमएल और इमेज + Hue ह्यू + Hue Shift ह्यू शिफ़्ट + Hue/Saturation ह्यू/सैचुरेशन + Hue/Saturation… ह्यू/सैचुरेशन… + Hyphen Limit: हाइफेन सीमा: + Hyphenate हाइफ़नेशन + Hyphenate Capitalized Words हाइफेनेट कैपिटलाइज़्ड शब्द + Hyphenation हाइफ़नेशन + Hyphenation Zone: हाइफेनेशन ज़ोन: + Hyphenation… हाइफ़नेशन… + hyphens हाइफेन्स + ICC Profile ICC प्रोफ़ाइल + ICF Bottom/Left ICF बॉटम/लेफ्ट + ICF Box ICF बॉक्स + ICF Top/Right ICF ऊपर/दाएँ + Identify Objects By ऑब्जेक्ट्स की पहचान करके + If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. अगर ड्रॉइंग टैबलेट के पेन से ड्रॉ नहीं हो रहा, तो X11 (XWayland) ऑप्शन चुनें। + Ignore अनदेखा करें + Ignore Artboards (all the art as one page) आर्टबोर्ड्स नज़रअंदाज़ करें (सारा आर्टवर्क एक पेज पर) + Ignore Color Ignore रंग + Ignore White Ignore व्हाइट + Image इमेज + Image Info इमेज जानकारी + Image Map: इमेज मानचित्र: + Image Size इमेज साइज़ + Image Trace इमेज ट्रेस + Image Trace (Make and Expand) इमेज ट्रेस (बनाएँ और एक्सपैंड करें) + Image Trace Presets इमेज ट्रेस प्रीसेट्स + Image Trace Preview इमेज ट्रेस प्रीव्यू + Image Trace View इमेज ट्रेस दृश्य + Image Tracing इमेज ट्रेसिंग + Image: इमेज: + Images चित्र + Images Only केवल इमेज + Images: इमेज: + Images: link to the file instead of only embedding it. इमेज: केवल इसे एम्बेड करने के बजाय फ़ाइल को लिंक करें। + Import Data Sets… डेटा सेट आयात करें… + Import Data… आयात डेटा… + Import Export Presets आयात निर्यात प्रीसेट + Import Keyboard Shortcuts… कीबोर्ड शॉर्टकट आयात करें… + Import Library आयात लाइब्रेरी + Import Library… आयात लाइब्रेरी… + Import Matches आयात मैच + Import PDF PDF आयात करें + Import PDF Presets PDF प्रीसेट्स इम्पोर्ट करें + Import Perspective Grid Presets आयात पर्सपेक्टिव ग्रिड प्रीसेट + Import Preset… प्रीसेट इम्पोर्ट करें… + Import Print Presets आयात प्रिंट प्रीसेट + Import Shortcut Set आयात शॉर्टकट सेट + Import Shortcut Set… आयात शॉर्टकट सेट… + Import Transparency Flattener Presets पारदर्शिता फ़्लैटनर प्रीसेट इम्पोर्ट करें + Import… इम्पोर्ट करें… + Imported {what}: {} आयात {what}: {} + Imported. Press OK to keep the imported set. आयात किया गया। आयातित सेट को रखने के लिए ठीक दबाएं। + In Merge Mode, Clicking Stroke Splits the Path मर्ज मोड में, क्लिकिंग स्ट्रोक पाथ को विभाजित करता है + In Tangent Handles टैंगेंट हैंडल में + In the File फ़ाइल में + In the selected objects सिलेक्टेड ऑब्जेक्ट्स में + In VectorCraft वेक्टर क्रेफ्ट में + In: इनपुट: + Inches इंच + Include Action Steps एक्शन चरण शामिल करें + Include all profiles सभी प्रोफ़ाइल शामिल करें + Include All Subdirectories सभी उपनिर्देशों को शामिल करें + Include Artboard Fill आर्टबोर्ड भरना शामिल है + Include Blacks with CMY: सीएमवाई के साथ ब्लैक शामिल करें: + Include Bleed ब्लीड शामिल करें + Include Clip Groups क्लिप समूह को शामिल करें + Include Cmy Blacks Cmy Blacks शामिल + Include CMYK PostScript in RGB Files RGB फ़ाइलों में CMYK PostScript को शामिल करें + Include destination profile गंतव्य प्रोफ़ाइल को शामिल करें + Include Document Thumbnails डॉक्यूमेंट थंबनेल शामिल करें + Include Editing Data for Other Apps अन्य ऐप्स के लिए संपादन डेटा शामिल करें + Include Hidden Layers छिपी हुई लेयर शामिल करें + Include in playback प्लेबैक में शामिल करें + Include Linked Files लिंक्ड फ़ाइलें शामिल करें + Include Metadata मेटाडाटा शामिल + Include non-printing layers गैर-प्रिंटिंग लेयर्स को शामिल करें + Include Objects On Canvas कैनवास पर ऑब्जेक्ट्स शामिल करें + Include SVG Code SVG कोड शामिल करें + Include Swatches for Tints टिंट्स के लिए स्वॉचेस शामिल करें + Include tagged source profiles टैग किए गए स्रोत प्रोफ़ाइल शामिल करें + Includes शामिल + Includes itself खुद को शामिल करना + Increase Font Size फ़ॉन्ट आकार बढ़ाएं + Increase Font Size by Five Steps पांच चरणों से फ़ॉन्ट आकार बढ़ाएं + Inflate… फुलाएँ… + Info जानकारी + Ink स्याही + Ink Limit स्याही की सीमा + Ink Outlines इंक आउटलाइन्स + Ink Outlines… इंक आउटलाइन्स… + Inks स्याही + Inner Corner Tile इनर कॉर्नर टाइल + Inner Glow… इनर ग्लो… + Inner Radius: इनर त्रिज्या: + Input Black इनपुट ब्लैक + Input White इनपुट व्हाइट + Insert सम्मिलित करें + Insert Break Character ब्रेक कैरेक्टर डालें + Insert Character वर्ण सम्मिलित करें + Insert Inline Symbol इनलाइन सिंबल डालें + Insert Kashidas कशीदा जोड़ें + Insert Special Character विशेष वर्ण सम्मिलित करें + Insert Whitespace Character व्हाइटस्पेस कैरेक्टर डालें + Inserting, deleting and rotating pages सम्मिलित करना, हटाने और घूर्णन पृष्ठों + Inside अंदर + Inspect Document निरीक्षण डॉक्यूमेंट + Inspect Object ऑब्जेक्ट का निरीक्षण करना + Inspect Plug-in प्लग-इन की जानकारी देखें + Install “{name}”, which asks for a heavy budget? "{name}" स्थापित करें, जो एक भारी बजट के लिए पूछता है? + Install Plug-in प्लग-इन इंस्टॉल करें + Install Plug-in… प्लग-इन इंस्टॉल करें… + Installed plug-in {} स्थापित प्लग-इन {} + Intensity तीव्रता + Intensity: तीव्रता: + Intent: इंटेंट: + Interface Language इंटरफ़ेस भाषा + Interlaced इंटरलेस्ड + Internal CSS आंतरिक सीएसएस + Internet Standard RGB (sRGB) इंटरनेट स्टैंडर्ड RGB (sRGB) + Interpolation इंटरपोलेशन + Intersect इंटरसेक्ट करें + Intertwine इंटरट्वाइन + Invalid panel layout; restored the default dock अमान्य पैनल लेआउट; डिफ़ॉल्ट डॉक पुनर्स्थापित किया गया + Inverse उल्टा करें + Invert इन्वर्ट + Invert Colors उलटा रंग + Invert Mask मास्क इन्वर्ट करें + Invert Pie पाई उलटें + Inverted Round उल्टे दौर + Invoke Distance Guides दूरी गाइड्स दिखाएँ + Isolate पृथक + Isolate Blending ब्लेंडिंग अलग करें + Isolate Group अलग समूह + Isolate Selected Group सिलेक्टेड समूह अलग करें + Isolate Selected Object सिलेक्टेड ऑब्जेक्ट को अलग करें + Isometric Bottom आइसोमेट्रिक बॉटम + Isometric Left आइसोमेट्रिक लेफ्ट + Isometric Right आइसोमेट्रिक राइट + Isometric Top आइसोमेट्रिक टॉप + Issues fixed: {count} निश्चित मुद्दे: {count} + It may take minutes, so it runs in the background, where you can cancel it. इसमें कुछ मिनट लग सकते हैं, इसलिए यह बैकग्राउंड में चलता है। आप इसे कैंसल कर सकते हैं। + Italian इतालवी + Italic इटैलिक + Its graphics, colors and text styles are deleted from this machine. इसके ग्राफ़िक्स, रंग और टेक्स्ट स्टाइल्स इस कंप्यूटर से हट जाएँगे। + Japanese जापानी + Japanese Double Postcard जापानी डबल पोस्टकार्ड + Japanese Envelope #3 जापानी लिफाफाफा #3 + Japanese Envelope #4 जापानी लिफाफा #4 + Japanese Postcard जापानी पोस्टकार्ड + JavaScript Files जावास्क्रिप्ट फ़ाइलें + JavaScript: जावास्क्रिप्ट: + Join जोड़ें + Join our Discord हमारे डिसकॉर्ड में शामिल हों + Join Our Discord हमारे डिसकॉर्ड में शामिल हों + Join Point Text पॉइंट टेक्स्ट में शामिल हों + Join the ArtCraft community on Discord (discord.gg/artcraft) Discord (discord.gg/artcraft) पर ArtCraft समुदाय में शामिल हों + Join the lines of each paragraph प्रत्येक पैराग्राफ की लाइनों में शामिल हों + Join Tool जॉइन टूल + Joins जुड़ना + Joins: जुड़ना: + Justification जस्टिफ़िकेशन + Justification… जस्टिफ़िकेशन… + Justify जस्टिफ़ाई करें + Justify all lines सभी लाइनों को जस्ट करें + Justify Vertically वर्टिकल दिशा में जस्टिफ़ाई करें + Justify with last line aligned center अंतिम पंक्ति संरेखित केंद्र के साथ Justify + Justify with last line aligned left आखिरी लाइन बाएँ अलाइन करके जस्टिफ़ाई करें + Justify with last line aligned right अंतिम पंक्ति के साथ Justify सही गठबंधन + Kaku #2 काकू #2 + Kaku #3 काकू #3 + Kannada कन्नड़ + Kashidas कशीदा + Keep a link to an image file instead of only embedding it इमेज फ़ाइल को केवल एम्बेड करने के बजाय उसका लिंक रखें + Keep both sides the same width दोनों पक्षों को समान चौड़ाई रखें + Keep Formatting स्वरूपण रखना + Keep graphics, colors and text styles here to use them in any document. Libraries are stored on this machine — no account required. ग्राफ़िक्स, रंग और टेक्स्ट स्टाइल्स यहाँ रखें ताकि किसी भी डॉक्यूमेंट में उपयोग कर सकें। लाइब्रेरीज़ इसी कंप्यूटर पर रहती हैं — अकाउंट की ज़रूरत नहीं है। + Keep Handles हैंडल रखें + Keep Original मूल रखें + Keep Plain Text प्लेन टेक्स्ट रखें + Keep selected सिलेक्ट करें + Keep Shared Points Together साझा अंक एक साथ रखें + Keep the pasted color as a new swatch with a numbered name. पेस्ट किए गए रंग को एक नए swatch के रूप में रखें। + Keep this row's colors (exclude) इस पंक्ति के रंग (बाहर) रखें + Keep visible surfaces only when expanding विस्तार करते समय केवल दृश्यमान सतहों को रखें + Keep: ध्यान रखें: + Keeps the document editable: VectorCraft reopens the PDF with nothing lost. For files you'll edit again. डॉक्यूमेंट को संपादित करने में सक्षम रखता है: VectorCraft PDF को कुछ भी नहीं खो सकता है। फ़ाइलों के लिए आप फिर से संपादित करेंगे। + Kerning कर्निंग + Key Color: कुंजी रंग: + Keyboard Increment कीबोर्ड इंक्रीमेंट + Keyboard Shortcut Conflicts कीबोर्ड शॉर्टकट के कॉन्फ़्लिक्ट + Keyboard Shortcut Set कीबोर्ड शॉर्टकट सेट + Keyboard Shortcuts कीबोर्ड शॉर्टकट + Keyboard Shortcuts… कीबोर्ड शॉर्टकट… + Keys कुंजी + Keywords: कीवर्ड: + Kind प्रकार + Kinsoku Set किनसोकू सेट + Kite पतंग + Knife चाकू + Knockout Group नॉकआउट समूह + Lab Lab + Lab Spot Colors लैब स्पॉट रंग + Lab Spot Colors: लैब स्पॉट रंग: + Lab Values लैब मूल्य + Landscape लैंडस्केप + Landscape (flipped) लैंडस्केप (फ्लिप) + Language भाषा + Language Level 2 भाषा स्तर 2 + Language Level 3 भाषा स्तर 3 + Language Options भाषा ऑप्शन्स + Language: भाषा: + Large बड़ा + Large Gaps बड़े अंतराल + Large List View बड़ी सूची देखें + Large Tabs बड़े टैब + Large Thumbnail View बड़े थंबनेल देखें + Large Thumbnails बड़े थंबनेल + Large to Small छोटा + Largest: सबसे बड़ा: + Lasso लैस्सो + Lasso Tool लैस्सो टूल + Last अंतिम + Last Artboard अंतिम आर्टबोर्ड + Last commit अंतिम कमिट + Last Effect: {} अंतिम इफ़ेक्ट: {} + Last Effect: {name} अंतिम इफ़ेक्ट: {name} + Last Effect… अंतिम इफ़ेक्ट… + Last Page अंतिम पृष्ठ + Latin लैटिन + Latin Extended लैटिन विस्तारित + Latin-1 Supplement लैटिन-1 अनुपूरक + Layer लेयर + Layer Names लेयर का नाम + Layer Options लेयर ऑप्शन्स + Layer Options… लेयर ऑप्शन्स… + Layers लेयर्स + Layers Panel Options लेयर्स पैनल ऑप्शन्स + Layout Order: लेआउट आदेश: + Layout: लेआउट: + Leader: नेता: + Leading लीडिंग + Leaf पत्ता + Leave Out of Global Edit ग्लोबल एडिट से बाहर निकलना + Left बाएँ + Left Complement लेफ्ट कम्प्लीमेंट + Left Diagonal बायाँ विकर्ण + Left Grid: बाएं ग्रिड: + Left in Front सामने में छोड़ दिया + Left Indent बाएं इंडेंट + Left Plane लेफ्ट प्लेन + Left to Right बाएं से दाएं + Left-Justified Tab बाएँ-संरेखित टैब + Left-to-Right Paragraph Direction बाएँ-से-दाएँ पैराग्राफ़ दिशा + Left: बाएँ: + Left/Right: बाएं / दाएं: + Legacy .ai Options पुराने .ai फ़ॉर्मैट के ऑप्शन्स + Legacy (version 7) पुराना फ़ॉर्मैट (संस्करण 7) + Legacy Macintosh RGB (Gamma 1.8) पुराना Macintosh RGB (गामा 1.8) + Legacy vector clipboard विरासत वेक्टर क्लिपबोर्ड + Legacy vector clipboard (no transparency) विरासत वेक्टर क्लिपबोर्ड (कोई पारदर्शिता नहीं) + Legal लीगल + Legends in Wedges वेज में किंवदंतियों + Length लंबाई + Length X-Axis: लंबाई X-Axi: + Length Y-Axis: Y-अक्ष की लंबाई: + Length: लंबाई: + Less कम + Letter लेटर + Letter Spacing: अक्षर अंतराल: + Letterhead A4 लेटरहेड A4 + Letterhead Letter लेटरहेड पत्र + letters पत्र + Levels स्तर + Levels… स्तर… + LF (macOS, Linux) LF (macOS, Linux) + Libraries लाइब्रेरीज़ + Library लाइब्रेरी + Library Panel Options लाइब्रेरी पैनल ऑप्शन्स + Library: लाइब्रेरी: + Ligatures are off while the text is tracked. टेक्स्ट पर ट्रैकिंग लागू होने पर लिगेचर ऑफ़ रहते हैं। + Light लाइट + Light behind the object ऑब्जेक्ट के पीछे प्रकाश + Light Blue हल्का नीला + Light Direction लाइट की दिशा + Light Gray हल्का ग्रे + Light Intensity लाइट तीव्रता + Light Red हल्का लाल + Light Rough हल्का खुरदरा + Light/Dark Balance लाइट / डार्क बैलेंस + Lighten लाइटन + Lighten Grout ग्राउट हल्का करें + Lighting लाइटिंग + Lightness लाइटनेस + Lights लाइट्स + Limit Color Guide to Library लाइब्रेरी के लिए कलर गाइड को सीमित करें + Limit colors to swatch library रंगों को स्वॉच लाइब्रेरी तक सीमित करें + Limit colors to swatch library: {name} रंगों को इस स्वॉच लाइब्रेरी तक सीमित करें: {name} + Limit to Library: इस लाइब्रेरी तक सीमित करें: + Limit: सीमा: + Limited लिमिटेड + Line लाइन + line {line} लाइन {line} + Line {line} लाइन {line} + Line {line}: {name}: {status} लाइन {line}: {name}: {status} + Line Art लाइन आर्ट + Line Art and Text Resolution: लाइन आर्ट एंड टेक्स्ट रिज़ॉल्यूशन: + Line Breaks लाइन ब्रेक + Line Color लाइन रंग + Line Cut लाइन कट + Line Cut Tool लाइन कट टूल + Line delta पंक्तियों का अंतर + Line Endings: लाइन समापन: + Line Graph Tool लाइन ग्राफ़ टूल + Line Segment लाइन सेगमेंट + Line Segment Tool लाइन सेगमेंट टूल + Line Segment Tool Options लाइन सेगमेंट टूल ऑप्शन्स + Line Type: लाइन प्रकार: + Line Weight: लाइन वजन: + Line-end Punctuation Half Width लाइन के अंत में विराम-चिह्न की आधी चौड़ाई + Linear लीनियर + Linear Gradient लीनियर ग्रेडिएंट + Lines रेखाएँ + lines {lines} पंक्तियाँ {lines} + Lines +/− पंक्तियाँ +/− + Lines added जोड़ी गई पंक्तियाँ + Lines deleted हटाई गई पंक्तियाँ + Lines: clicks add points joined by a line लाइन्स: क्लिक्स ऐड पॉइंट्स एक लाइन से जुड़ गए + Link लिंक करें + Link Block Series लिंक ब्लॉक श्रृंखला + Link harmony colors लिंक सद्भाव रंग + Link Info लिंक जानकारी + Link JavaScript Files… जावास्क्रिप्ट फ़ाइलों को लिंक करें… + Link Opacity Mask लिंक अपारदर्शिता मास्क + Link start and end arrowhead scales लिंक स्टार्ट एंड एंड एंड तीरहेड स्केल + Link the mask मास्क लिंक करें + Linked लिंक्ड + Linked File लिंक्ड फ़ाइल + Linked File Not Found लिंक्ड फ़ाइल नहीं मिला + Linked Files लिंक्ड फ़ाइलें + Links लिंक + Linux Display Server Linux डिस्प्ले सर्वर + Liquify लिक्विफ़ाई + List Data Sets सूची डेटा सेट + List Folder सूची फ़ोल्डर + List Graphic Styles सूची ग्राफिक स्टाइल्स + List Keyboard Shortcuts सूची कीबोर्ड शॉर्टकट + List Patterns सूची पैटर्न + List Plug-ins सूची प्लग इन + List Preferences सूची प्राथमिकताएं + List Slices सूची स्लाइस + List Toolbars सूची टूलबार + List Variables सूची चर + List View सूची दृश्य + List Workspaces सूची वर्कस्पेस + Live curve fitting लाइव वक्र फिटिंग + Live Paint लाइव पेंट + Live Paint Bucket लाइव पेंट बकेट + Live Paint Bucket (Stroke) लाइव पेंट बाल्टी (स्ट्रोक) + Live Paint Info लाइव पेंट जानकारी + Live Paint Selection Tool लाइव पेंट सिलेक्शन टूल + Live preview लाइव प्रीव्यू + Live Shape लाइव आकार + Live Shape Properties लाइव शेप प्रॉपर्टीज़ + Load Actions… एक्शन्स लोड करें… + Load Color Profile… लोड कलर प्रोफ़ाइल… + Load EPS into Clipboard ईपीएस को क्लिपबोर्ड में लोड करें + Load Image into Clipboard क्लिपबोर्ड में इमेज लोड करें + Load Metafile into Clipboard फ़ाइल को क्लिपबोर्ड में लोड करें + Load PDF into Clipboard PDF को क्लिपबोर्ड में लोड करें + Load Place Cursor लोड प्लेस कर्सर + Load Profile… लोड प्रोफ़ाइल… + Load SVG into Clipboard SVG को क्लिपबोर्ड में लोड करें + Load Text into Clipboard क्लिपबोर्ड में टेक्स्ट लोड करें + Load Texture… लोड बनावट… + Load Variable Library लोड परिवर्तनीय लाइब्रेरी + Load Variable Library… लोड परिवर्तनीय लाइब्रेरी… + Loaded Texture भारित बनावट + Loads native code मूल कोड लोड करता है + Local Libraries स्थानीय लाइब्रेरी + Locate Library… लाइब्रेरी… + Locate Object ऑब्जेक्ट का पता लगाएं + Locate Selected Objects सिलेक्टेड ऑब्जेक्ट्स का पता लगाएँ + Location स्थान + Location: स्थान: + Lock लॉक करें + Lock (⌘2) लॉक करें (⌘2) + Lock All सभी लॉक करें + Lock All Except Selected सभी को छोड़कर सिलेक्टेड ताला + Lock Artboards लॉक आर्टबोर्ड + Lock Grid लॉक ग्रिड + Lock Guides गाइड्स लॉक करें + Lock Others लॉक अन्य + Lock Selected लॉक सिलेक्टेड + Lock Slices स्लाइस लॉक करें + Lock Station Point लॉक स्टेशन पॉइंट + Lock Variables लॉक चर + Locked लॉक्ड + Logo 1000×1000 लोगो 1000 × 1000 + Long लंबा + Long Lines लंबी रेखाएँ + Long Strokes लंबे स्ट्रोक + Longest: सबसे लंबे: + Lossless (lossy WebP isn't available yet) लॉसलेस (लॉसी WebP अभी उपलब्ध नहीं है) + Lossy: हानि: + Low निम्न + Low Fidelity Photo लो फिडेलिटी फोटो + Low Resolution कम संकल्प + Low resolution (150 ppi) कम संकल्प (150 ppi) + lowercase लोअरकेस + Luminosity ल्यूमिनोसिटी + LZW Compression LZW संपीड़न + Mac मैक + Magenta मैजेंटा + Magic Wand जादू की छड़ी + Magic Wand Options जादू की छड़ी ऑप्शन्स + Magic Wand Settings जादू की छड़ी सेटिंग्स + Magic Wand Tool मैजिक वैंड टूल + Maintain Envelope Shape लिफाफे आकार को बनाए रखें + Make बनाएँ + Make a theme on Create and save it. Create पर थीम बनाकर सेव करें। + Make all bleed settings the same सभी ब्लीड सेटिंग्स एक जैसी करें + Make and Expand बनाएँ और एक्सपैंड करें + Make Blend ब्लेंड बनाएँ + Make Clipping Mask क्लिपिंग मास्क बनाएँ + Make Compound Path कंपाउंड पाथ बनाएँ + Make Compound Shape कंपाउंड शेप बनाएँ + Make Corner कॉर्नर पॉइंट बनाएँ + Make Dynamic डायनामिक बनाएँ + Make Envelope एन्वेलप बनाएँ + Make Graph Dynamic ग्राफ़ डायनामिक बनाएँ + Make Guides गाइड्स बनाएँ + Make Image Dynamic इमेज डायनामिक बनाएँ + Make Intertwine इंटरट्वाइन बनाएँ + Make Live Paint लाइव पेंट बनाएँ + Make Mask मास्क बनाएँ + Make Opacity Mask ओपेसिटी मास्क बनाएँ + Make Pattern पैटर्न बनाएँ + Make Pixel Perfect पिक्सेल परफ़ेक्ट बनाएँ + Make Sides Equal साइड बराबर करें + Make Slice स्लाइस बनाएँ + Make Smooth स्मूद करें + Make Text Dynamic टेक्स्ट डायनामिक बनाएँ + Make Text Wrap टेक्स्ट रैप बनाएँ + Make the bleed values differ ब्लीड के मान अलग-अलग करें + Make Visibility Dynamic विज़िबिलिटी डायनामिक बनाएँ + Make Visible दिखाएँ + Make with Mesh… मेश से बनाएँ… + Make with Top Object सबसे ऊपर के ऑब्जेक्ट से बनाएँ + Make with Warp… वार्प से बनाएँ… + Make/Release Clipping Mask क्लिपिंग मास्क बनाएँ/रिलीज़ करें + Malayalam मालायम + Manage Presets प्रीसेट प्रबंधित करें + Manage Toolbars टूलबार प्रबंधित करें + Manage Toolbars… टूलबार प्रबंधित करें… + Manage Workspaces वर्कस्पेस प्रबंधित करें + Manage Workspaces… वर्कस्पेस प्रबंधित करें… + Manually मैन्युअल + Marathi मराठी + Mark as trapped निशानेबाज़ी + Mark Older Files as [Converted] When Opened पुरानी फ़ाइलें ओपन करने पर उन्हें [Converted] चिह्नित करें + Marker… मार्कर… + Marks मार्क्स + Marks and Bleed मार्क्स एंड ब्लीड + Marks and Bleeds मार्क्स एंड ब्लीड्स + Mask मास्क + Match मैच + Match User Interface Brightness उपयोगकर्ता इंटरफ़ेस चमक मैच + Materials… सामग्री… + Matte मैट + Matte: मैट: + Max Count मैक्सिको + Max. Radius मैक्स। त्रिज्या + Maximize अधिकतम करें + Maximize Editability अनुकूलन क्षमता + Maximum अधिकतम + Maximum angle अधिकतम कोण + Maximum Editability अधिकतम संपादन + Maximum: अधिकतम: + Measure मापें + Measure & Inspect उपाय और निरीक्षण + Measure & Inspect Tool माप और निरीक्षण टूल + Measure Tool माप टूल + Measurement Labels मापन लेबल + Media मीडिया + Medium मध्यम + Medium (150 ppi) मध्यम (150 ppi) + Medium Dark मध्यम डार्क + Medium Dots मध्यम बिंदु + Medium Gaps मध्यम अंतराल + Medium Gray मध्यम ग्रे + Medium Light मध्यम प्रकाश + Medium Lines मध्यम रेखाएँ + Medium Resolution मध्यम संकल्प + Medium Strokes मध्यम स्ट्रोक + Medium Thumbnail View मध्यम थंबनेल + Medium Thumbnails मध्यम थंबनेल + Menu commands मेनू आदेश + Menu Commands मेन्यू कमान + Menu Dialog मेन्यू डायलॉग + Merge मर्ज करें + Merge colors into one row रंगों को एक पंक्ति में मिलाएं + Merge Graphic Styles मर्ज ग्राफिक स्टाइल्स + Merge Graphic Styles… मर्ज ग्राफिक स्टाइल्स… + Merge Layers लेयर्स मर्ज करें + Merge Live Paint मर्ज लाइव पेंट + Merge only with selection केवल सिलेक्शन के साथ विलय करें + Merge Selected मर्ज सिलेक्टेड + Merge Shared Edge मर्ज साझा एज + Merge Swatches स्वॉचेस मर्ज करें + Merged PRs मर्ज किए गए PR + Mesh मेश + Mesh Point Color मेश पॉइंट का रंग + Mesh Tool मेश टूल + Message: संदेश: + Metadata: मेटाडेटा: + Metallic Gradients धातुई ग्रेडिएंट + Meters मीटर + Method विधि + Method: विधि: + Mezzotint मेज़ोटिंट + Mezzotint… मेज़ोटिंट… + Millimeters मिलीमीटर + Minify मिनिफ़ाई करें + Minimal मिनिमल + Minimize छोटा करें + Minimum न्यूनतम + Minimum angle न्यूनतम कोण + Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम से अधिक नहीं होना चाहिए, न ही अधिकतम होना चाहिए। + Minimum: न्यूनतम: + Minus Back पीछे वाला घटाएँ + Minus Front सामने वाला घटाएँ + Mirror मिरर + Mirror & Cut मिरर और कट + Mirror & Cut Tool मिरर और कट टूल + Mirror Repeat मिरर दोहराएँ + Missing मिसिंग + Missing Fonts मिसिंग फ़ॉन्ट + Missing Fonts Dialog मिसिंग फ़ॉन्ट डायलॉग + Missing: {path} मिसिंग: {path} + Miter माइटर + Miter Join मिटर जॉइन + Miter Limit माइटर सीमा + Miter Limit: माइटर सीमा: + Mixed मिश्रित + Mixed Appearances मिश्रित उपस्थिति + Mixed line endings मिश्रित लाइन अंत + Mixed Objects मिश्रित ऑब्जेक्ट्स + Mobile मोबाइल + Mode मोड + Mode: मोड: + Model मॉडल + Models मॉडल्स + Modern आधुनिक + Modified संशोधित + Modified since it was read: {path} इसके बाद से इसे पढ़ा गया: {path} + Modified: संशोधित: + Modify संशोधित करें + Mojikumi मोजियाकुमी + Mojikumi Set मोजिकुमी सेट + Monitor RGB मॉनिटर RGB + Mono मोनो + Monochromatic मोनोक्रोमैटिक + Monochrome मोनोक्रोम + Monochrome images मोनोक्रोम इमेज + Monospaced मोनोस्पेस्ड + More और + More Align options अधिक संरेखित ऑप्शन्स + More Options अधिक ऑप्शन्स + More Paragraph options अधिक पैराग्राफ ऑप्शन्स + More Pathfinder options अधिक पाथफाइंडर ऑप्शन्स + More Settings अधिक सेटिंग्स + Mosaic Tiles मोज़ेक टाइल्स + Mosaic Tiles… मोज़ेक टाइल्स… + Move मूव करें + Move All Objects सभी ऑब्जेक्ट ले जाएँ + Move Anchor Point एंकर पॉइंट मूव करें + Move Anchors एंकर मूव करें + Move Appearance अपीयरेंस मूव करें + Move Artboard आर्टबोर्ड मूव करें + Move Artboard Up/Down आर्टबोर्ड ऊपर/नीचे मूव करें + Move Artwork with Artboard आर्टबोर्ड के साथ आर्टवर्क मूव करें + Move Brush ब्रश मूव करें + Move Direction Handle डायरेक्शन हैंडल मूव करें + Move Document डॉक्यूमेंट मूव करें + Move Down नीचे मूव करें + Move Effect इफ़ेक्ट मूव करें + Move Envelope Mesh Point एन्वेलप मेश पॉइंट खिसकाएँ + Move Envelope Point एन्वेलप पॉइंट खिसकाएँ + Move Graphic Style ग्राफ़िक स्टाइल मूव करें + Move Guide गाइड मूव करें + Move Guide to Layer गाइड को लेयर में मूव करें + Move in Perspective पर्सपेक्टिव में मूव करें + Move Library Group लाइब्रेरी ग्रुप मूव करें + Move Library Item to Group लाइब्रेरी आइटम को ग्रुप में मूव करें + Move Locked and Hidden Artwork with Artboard आर्टबोर्ड के साथ लॉक्ड और छिपा हुआ आर्टवर्क मूव करें + Move Mesh Point मेश पॉइंट मूव करें + Move Mesh Points मेश पॉइंट मूव करें + Move Panel पैनल मूव करें + Move Plane प्लेन मूव करें + Move Plane and Copy Objects प्लेन मूव करें और ऑब्जेक्ट कॉपी करें + Move Plane and Objects प्लेन और ऑब्जेक्ट मूव करें + Move Plane to Match Object ऑब्जेक्ट से मेल खाने के लिए प्लेन मूव करें + Move Rows रो मूव करें + Move Slice स्लाइस मूव करें + Move Slices स्लाइस मूव करें + Move Spine Point स्पाइन पॉइंट मूव करें + Move Swatch स्वॉच खिसकाएँ + Move to Group ग्रुप में मूव करें + Move Type on a Path पाथ पर टाइप मूव करें + Move Up ऊपर मूव करें + Move… मूव करें… + Movie Clip फिल्म क्लिप + Multiple Files एकाधिक फ़ाइलें + Multiple objects एकाधिक ऑब्जेक्टएं + Multiply मल्टिप्लाई + Muted मुट्ठी + My Themes मेरी थीम + N pt per प्रति pt + N slices …, evenly spaced N स्लाइस ..., समान रूप से स्पेस किया गया + Name नाम + Name (A–Z) नाम (A–Z) + Name 40% नाम 40% + Name: नाम: + Name* @ 66.67 % (RGB/Preview) नाम* 66.67 % (RGB/Preview) + Name* @ 66.67% (RGB/Preview) नाम* @ 66.67% (RGB/Preview) + Names the script builds as it runs: {count} स्क्रिप्ट के नाम के रूप में यह चलाता है: {count} + Navigate नेविगेट करें + Navigator नेविगेटर + Navigator Panel Options नेविगेटर पैनल ऑप्शन्स + Nearly Closed Paths लगभग बंद पाथ + Nearly Coincident Anchors लगभग Coincident एंकर + Needless Clipping Groups अनावश्यक क्लिपिंग समूह + Needless Compound Paths अनावश्यक यौगिक पाथ + Needless Groups अनावश्यक समूह + Needs a choice एक ऑप्शन की आवश्यकता है + Needs a key एक कुंजी की आवश्यकता है + Needs Attention Only केवल ध्यान देने की जरूरत + Needs dialogs संवाद की आवश्यकता + Needs features only the reference app has केवल संदर्भ ऐप की आवश्यकता है + Needs files फ़ाइलों की आवश्यकता + Needs menu commands आवश्यकता मेनू आदेश + Needs nothing beyond plain JavaScript सादे जावास्क्रिप्ट से परे कुछ भी नहीं होना चाहिए + Needs the desktop app डेस्कटॉप ऐप की आवश्यकता है + Needs the document model डॉक्यूमेंट मॉडल की आवश्यकता है + Needs the script language's own objects or directives स्क्रिप्ट भाषा की अपनी ऑब्जेक्ट्स या निर्देशों की आवश्यकता है + Negative नकारात्मक + Neon Glow नियॉन ग्लो + Neon Glow… नियॉन ग्लो… + Nesting too deep to follow का पालन करने के लिए बहुत गहरी + Neutral Gradients न्यूट्रल ग्रेडिएंट्स + New नया + New {kind} Style… नया {kind} Style… + New Action नया एक्शन + New Action… नया एक्शन… + New Art Appearance नई कला उपस्थिति + New Art Brush from Selection सिलेक्शन से नई कला ब्रश + New Art Has Basic Appearance नई कला मूलभूत उपस्थिति है + New Artboard नया आर्टबोर्ड + New Artboard Options… न्यू आर्टबोर्ड ऑप्शन्स… + New Bristle Brush न्यू ब्रिस्टल ब्रश + New Brush नया ब्रश + New Brush… नया ब्रश… + New Calligraphic Brush नई कैलिग्राफिक ब्रश + New Character Style नई कैरेक्टर स्टाइल + New Character Style… नई कैरेक्टर स्टाइल… + New Color Group न्यू कलर ग्रुप + New Color Group… न्यू कलर ग्रुप… + New Data Set नया डेटा सेट + New Data Set… नया डेटा सेट… + New Design नई डिजाइन + New Document Presets नया डॉक्यूमेंट प्रीसेट + New file नई फ़ाइल + New from Template टेम्पलेट से नया + New from Template… टेम्पलेट से नया… + New Graphic Style नई ग्राफिक स्टाइल + New Graphic Style (Alt-click to name it) नया ग्राफ़िक स्टाइल (नाम देने के लिए Alt-क्लिक करें) + New Graphic Style… नई ग्राफिक स्टाइल… + New Group नया समूह + New Group… नया समूह… + New Guide नई गाइड + New Layer नई लेयर + New Layer Options… न्यू लेयर ऑप्शन्स… + New Layer… नई लेयर… + New Library Group न्यू लाइब्रेरी ग्रुप + New Name नया नाम + New Opacity Masks Are Clipping नई अपारदर्शिता मास्क क्लिपिंग कर रहे हैं + New Opacity Masks Are Inverted नई अपारदर्शिता मास्क उल्टे हैं + New Paragraph Style न्यू पैराग्राफ स्टाइल + New Paragraph Style… नया अनुच्छेद स्टाइल… + New Pattern Brush from Selection सिलेक्शन से नए पैटर्न ब्रश + New PDF Preset नया PDF प्रीसेट + New Print Preset न्यू प्रिंट प्रीसेट + New Scatter Brush from Selection सिलेक्शन से नए स्कैटर ब्रश + New Set नया सेट + New Set… नया सेट… + New Sublayer न्यू सबलायर + New Sublayer… न्यू सबलेयर… + New Swatch नया स्वॉच + New Swatch… नया स्वॉच… + New Symbol नया सिंबल + New Symbol… नया सिंबल… + New Symbols from Layers लेयर्स से नए सिंबल बनाएँ + New theme from the current color वर्तमान रंग से नया विषय + New Toolbar नया टूलबार + New Toolbar… नया टूलबार… + New Variable नया परिवर्तनीय + New Variable… नई परिवर्तनीय… + New View नया दृश्य + New View… नया दृश्य… + New Window नई विंडो + New Without Dialog बिना डायलॉग के + New Workspace नया वर्कस्पेस + New Workspace… नया वर्कस्पेस… + New… नया… + Next अगला + Next Artboard आगामी आर्टबोर्ड + Next Data Set आगामी डेटा सेट + Next Document अगला डॉक्यूमेंट + Next Library अगला लाइब्रेरी + Next Object Above अगला ऑब्जेक्ट ऊपर + Next Object Below नीचे दिए गए ऑब्जेक्ट + Next page अगला पृष्ठ + Next Page अगला पृष्ठ + Next Segment अगला खंड + No नहीं + No actions. Press ● to record. कोई कार्रवाई नहीं। प्रेस ● रिकॉर्ड करने के लिए। + No alternates for the selected character. सिलेक्टेड चरित्र के लिए कोई ऑप्शन नहीं। + No artboards match. कोई आर्टबोर्ड मैच नहीं। + No assets कोई संपत्ति नहीं + No assets yet. Collect art with Object › Collect for Export, or drag it into the Asset Export panel. अभी कोई एसेट नहीं है। ऑब्जेक्ट › एक्सपोर्ट के लिए कलेक्ट करें से आर्टवर्क जोड़ें या उसे एसेट एक्सपोर्ट पैनल में ड्रैग करें। + No Break कोई ब्रेक नहीं + No brushes ब्रश नहीं + No colors to recolor (preserved colors are left out). फिर से रंगने के लिए कोई रंग नहीं ( संरक्षित रंग बाहर छोड़ दिए गए हैं)। + No contributor data was built into this copy. इस प्रति में योगदानकर्ता डेटा शामिल नहीं है। + No conversion कोई रूपांतरण + No CSS सीएसएस नहीं + no data set to edit संपादित करने के लिए कोई डेटा सेट नहीं + no data set to rename नाम बदलने के लिए कोई डेटा सेट नहीं + No Dither कोई डिथर नहीं + no document कोई डॉक्यूमेंट नहीं + No document कोई डॉक्यूमेंट नहीं + No Document कोई डॉक्यूमेंट नहीं + No document open कोई डॉक्यूमेंट खुला नहीं है + No document open. कोई डॉक्यूमेंट खुला नहीं है. + No downsampling कोई downsampling + No equivalent समतुल्य नहीं + No filter plug-ins installed कोई फिल्टर प्लग-इन स्थापित नहीं है + No fonts are available. कोई फ़ॉन्ट उपलब्ध नहीं हैं। + No gradient swatches कोई ग्रेडिएंट स्वॉच नहीं + No graphic styles कोई ग्राफिक स्टाइल नहीं + No Group कोई समूह नहीं + No images कोई इमेज नहीं + No images match. कोई इमेज मैच नहीं। + No issues found. कोई समस्या नहीं मिली। + No items in this library match “{query}”. इस लाइब्रेरी में कोई आइटम "{query}" नहीं है। + No Legend नो लीजेंड + No matches. कोई मैच नहीं। + No matching fonts कोई मेल खाता फ़ॉन्ट नहीं + No model credits were built into this copy. इस प्रति में मॉडल क्रेडिट शामिल नहीं हैं। + No options कोई ऑप्शन्स + No printer settings to open here यहाँ ओपन करने के लिए कोई प्रिंटर सेटिंग नहीं + No results कोई परिणाम नहीं + No saved themes कोई बचाया विषयों + No saved views (View → New View…) कोई बचाया दृष्टिकोण (देखें → नया दृश्य) + No selection कोई सिलेक्शन नहीं + No Selection कोई सिलेक्शन नहीं + No Slices कोई स्लाइस नहीं + No symbols in this document इस डॉक्यूमेंट में कोई सिंबल नहीं + No text selected कोई टेक्स्ट नहीं चुना गया + No Thumbnails कोई थंबनेल नहीं + No unused symbols अप्रयुक्त सिंबल + no variable to rename नाम बदलने के लिए कोई चर नहीं + Noise नॉइज़ + Nonbreaking Hyphen न टूटने वाला हाइफ़न + Nonbreaking Space न टूटने वाला स्पेस + None कोई नहीं + None (/) कोई नहीं (/) + None (Color Preview) कोई नहीं (रंग प्रीव्यू) + None (keep transparency) कोई भी नहीं (कीप पारदर्शिता) + None. कोई नहीं. + Normal सामान्य + Normal Screen Mode सामान्य स्क्रीन मोड + Norwegian नॉर्वेजियन + Not a script for the reference app संदर्भ ऐप के लिए कोई स्क्रिप्ट नहीं + Not followed: outside the script's folder इसके बाद नहीं: स्क्रिप्ट के फ़ोल्डर के बाहर + Not found नहीं पाया + not known yet अभी तक ज्ञात नहीं है + Not read नहीं पढ़े + Not read: a limit was reached पढ़ना नहीं: एक सीमा तक पहुंच गई थी + Not valid UTF-8: unreadable bytes were replaced मान्य नहीं UTF-8: अप्राप्य बाइट को प्रतिस्थापित किया गया था + Note Paper नोट पेपर + Note Paper… नोट पेपर… + Note: ध्यान दें: + Nothing is selected. Select the art to export, then open this tab again. कुछ भी नहीं चुना गया है। निर्यात करने के लिए कला सिलेक्ट करें, फिर इस टैब को फिर से ओपन करें। + Nothing matches the Show filter. कुछ भी नहीं शो फिल्टर से मेल खाता है। + Nothing to print प्रिंट करने के लिए कुछ भी नहीं + NTSC Colors NTSC रंग + Nudge न्याय + Nudge in Perspective पर्सपेक्टिव में न्याय + Number (####) संख्या (#####) + Number of Artboards: आर्टबोर्ड की संख्या: + Number of Colors: रंगों की संख्या: + Number of Decimals: दशमलव की संख्या: + Number of Recent Files to Display हाल ही में प्रदर्शित करने के लिए फ़ाइलों की संख्या + Number of Recent Fonts हाल ही में फ़ॉन्ट की संख्या + Number: संख्या: + Numbered List क्रमांकित सूची + Numbers Without Units Are Points यूनिट्स के बिना नंबर अंक हैं + Numerator न्यूमेरेटर + Object ऑब्जेक्ट + Object Highlighting ऑब्जेक्ट हाइलाइटिंग + Object IDs: ऑब्जेक्ट ID: + Object Name ऑब्जेक्ट का नाम + Object Properties ऑब्जेक्ट प्रॉपर्टीज़ + Object Selection by Path Only केवल पाथ द्वारा ऑब्जेक्ट सिलेक्शन + Object types: {names} ऑब्जेक्ट प्रकार: {names} + Objects ऑब्जेक्ट्स + Objects on Path पाथ पर ऑब्जेक्टएं + Objects on Path Options पाथ ऑप्शन्स पर ऑब्जेक्ट्स + Objects on Path Tool पाथ टूल पर ऑब्जेक्टएं + Objects using them keep their look but are no longer linked. उन्हें उपयोग करने वाले ऑब्जेक्ट पहले जैसे दिखते रहेंगे, लेकिन लिंक हट जाएगा। + Objects with Color Effects रंग इफ़ेक्ट के साथ ऑब्जेक्ट + Objects with Spot Colors स्पॉट कलर्स के साथ ऑब्जेक्ट्स + Ocean Ripple ओशन रिपल + Ocean Ripple… ओशन रिपल… + Odd Fields विषम फ़ील्ड्स + Odd-Numbered Anchors Odd-Numbered एंकर + Odia ओडिया + of of + of {count} {count} + of characters used वर्णों का इस्तेमाल किया + Off बंद + Off-Artboard Art ऑफ आर्टबोर्ड आर्ट + Off-Axis Back ऑफ-एक्सिस बैक + Off-Axis Bottom ऑफ-एक्सिस बॉटम + Off-Axis Front ऑफ-एक्सिस फ्रंट + Off-Axis Left ऑफ-एक्सिस लेफ्ट + Off-Axis Right ऑफ-एक्सिस राइट + Off-Axis Top ऑफ-एक्सिस टॉप + Off: an editable copy of its art, embedded in this document. ऑफ़: इस डॉक्यूमेंट में एम्बेड की गई, एडिट करने योग्य आर्टवर्क की कॉपी। + Offset ऑफ़सेट + Offset Path पाथ ऑफ़सेट करें + Offset Path… पाथ ऑफ़सेट करें… + Offset X ऑफसेट एक्स + Offset: ऑफ़सेट: + Ogee ओगे + OK ठीक है + Omit ओमित + On चालू + On Artboards आर्टबोर्ड पर + On Both Sides दोनों तरफ + On Copy कॉपी पर + On Left Side बाईं ओर + On Paste पेस्ट पर + On Right Side दाईं ओर + On Screen स्क्रीन पर + On: one locked object showing the document, updated when it changes. ऑन: डॉक्यूमेंट दिखाने वाला एक लॉक्ड ऑब्जेक्ट, जो डॉक्यूमेंट बदलने पर अपडेट होता है। + One File of the Selection सिलेक्शन की एक फ़ाइल + One file per artboard: -.{ext} प्रति आर्टबोर्ड एक फ़ाइल: -.{ext} + One or more of the symbols are in use and cannot be deleted until their instances are expanded or deleted. एक या अधिक सिंबल उपयोग में हैं। उन्हें हटाने से पहले उनके इंस्टेंस एक्सपैंड करें या हटाएँ। + One page per artboard. प्रति आर्टबोर्ड एक पृष्ठ। + One Point एक बिंदु + One Point Perspective एक बिंदु पर्सपेक्टिव + One Point Perspective Preset 1 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 1 + One Point Perspective Preset 2 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 2 + One Point Perspective Preset 3 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 3 + One Point Perspective Preset 4 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 4 + One Point Perspective Preset 5 एक बिंदु पर्सपेक्टिव पूर्व निर्धारित 5 + Only Web Colors केवल वेब रंग + Opacity ओपेसिटी + Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप + Opacity Mask ओपेसिटी मास्क + Opacity Mask Info ओपेसिटी मास्क की जानकारी + Opacity Mask Options ओपेसिटी मास्क ऑप्शन्स + Opacity: ओपेसिटी: + Opacity: {value} ओपेसिटी: {value} + Opacity: 50% Multiply ओपेसिटी: 50% मल्टिप्लाई + Opacity: Default Opacity: डिफ़ॉल्ट + Opaque अपारदर्शी + Open ओपन + Open a document to check it for issues. इसे मुद्दों के लिए जांच करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to draw parametric shapes. पैरामीट्रिक आकृतियों को आकर्षित करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to draw with the Smart Pen. स्मार्ट पेन के साथ आकर्षित करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to edit its anchor points. अपने एंकर बिन्दुओं को संपादित करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to edit its patterns. अपने पैटर्न को संपादित करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to navigate it. इसे नेविगेट करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to preview its flattening. अपने चपटापन का प्रीव्यू करने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to preview its pages अपने पृष्ठों का प्रीव्यू करने के लिए एक डॉक्यूमेंट ओपन करें + Open a document to see its artboards. अपने आर्टबोर्ड को देखने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to see its graphic styles. अपनी ग्राफिक स्टाइल्स को देखने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to see its history. अपने इतिहास को देखने के लिए एक डॉक्यूमेंट ओपन करें। + Open a document to see its swatches. स्वॉचेस देखने के लिए कोई डॉक्यूमेंट ओपन करें। + Open Brush Library ओपन ब्रश लाइब्रेरी + Open Document डॉक्यूमेंट ओपन करें + Open Documents As Tabs डॉक्यूमेंट टैब के रूप में ओपन करें + Open Graphic Style Library ओपन ग्राफिक स्टाइल लाइब्रेरी + Open Location after Export निर्यात के बाद खुला स्थान + Open password: पासवर्ड ओपन करें: + Open Paths ओपन पाथ + Open Recent File 1 हाल ही में फ़ाइल ओपन करें 1 + Open Recent File 10 ओपन हाल ही में फ़ाइल 10 + Open Recent File 11 हाल ही में फ़ाइल ओपन करें 11 + Open Recent File 12 हाल ही में फ़ाइल ओपन करें 12 + Open Recent File 13 हाल ही में फ़ाइल ओपन करें 13 + Open Recent File 14 हाल ही में फ़ाइल ओपन करें 14 + Open Recent File 15 हाल ही में फ़ाइल ओपन करें 15 + Open Recent File 16 हाल ही में फ़ाइल ओपन करें 16 + Open Recent File 17 ओपन हाल ही में फ़ाइल 17 + Open Recent File 18 हाल ही में फ़ाइल ओपन करें 18 + Open Recent File 19 हाल ही में फ़ाइल ओपन करें 19 + Open Recent File 2 ओपन हाल ही में फ़ाइल 2 + Open Recent File 20 हाल ही में फ़ाइल ओपन करें 20 + Open Recent File 21 हाल ही में फ़ाइल ओपन करें 21 + Open Recent File 22 हाल ही में फ़ाइल ओपन करें 22 + Open Recent File 23 हाल ही में फ़ाइल ओपन करें 23 + Open Recent File 24 हाल ही में फ़ाइल ओपन करें 24 + Open Recent File 25 हाल ही में फ़ाइल ओपन करें 25 + Open Recent File 26 ओपन हाल ही में फ़ाइल 26 + Open Recent File 27 हाल ही में फ़ाइल ओपन करें 27 + Open Recent File 28 हाल ही में फ़ाइल ओपन करें 28 + Open Recent File 29 ओपन हाल ही में फ़ाइल 29 + Open Recent File 3 ओपन हाल ही में फ़ाइल 3 + Open Recent File 30 हाल ही में फ़ाइल ओपन करें 30 + Open Recent File 4 हाल ही में फ़ाइल ओपन करें 4 + Open Recent File 5 ओपन हाल ही में फ़ाइल 5 + Open Recent File 6 ओपन हाल ही में फ़ाइल 6 + Open Recent File 7 हाल ही में फ़ाइल ओपन करें 7 + Open Recent File 8 ओपन हाल ही में फ़ाइल 8 + Open Recent File 9 ओपन हाल ही में फ़ाइल 9 + Open Recent Files रीसेंट फ़ाइल्स + Open Swatch Library स्वॉच लाइब्रेरी ओपन करें + Open Symbol Library ओपन सिंबल लाइब्रेरी + Open the URL in the web browser यूआरएल को वेब ब्राउज़र में ओपन करें + Open this dialog with these settings next time अगली बार इन सेटिंग्स के साथ इस संवाद को ओपन करें + Open this setting's help page इस सेटिंग की मदद पृष्ठ को ओपन करें + Open… ओपन… + Opening it left out what VectorCraft can't read yet ({what}), so replacing it loses that for good. Save under another name to keep it. ओपन करते समय वे हिस्से छूट गए जिन्हें VectorCraft अभी पढ़ नहीं सकता ({what})। फ़ाइल रिप्लेस करने पर वे हमेशा के लिए खो जाएँगे। मूल फ़ाइल रखने के लिए दूसरे नाम से सेव करें। + Opens files in other apps अन्य ऐप्स में फ़ाइलों को ओपन करें + Opens network connections नेटवर्क कनेक्शन ओपन करें + OpenType Features ओपन टाइप सुविधाएँ + Optical ऑप्टिकल + Optical Margin Alignment ऑप्टिकल मार्जिन संरेखण + Optimize for fast web view तेजी से वेब दृश्य के लिए ऑप्टिमाइज़ + Optimized ऑप्टिमाइज़्ड + Options ऑप्शन्स + Options for Selection… सिलेक्शन के लिए ऑप्शन्स… + Options: ऑप्शन्स: + Options… ऑप्शन्स… + or more spaces with a tab या एक टैब के साथ अधिक रिक्त स्थान + Orange नारंगी + Order: आदेश: + Ordinals क्रमसूचक + Orientation ओरिएंटेशन + Orientation: ओरिएंटेशन: + Original मूल + Original: click to restore मूल: पुनर्स्थापित करने के लिए क्लिक करें + Other अन्य + Other Layers अन्य लेयरें + Other Libraries अन्य लाइब्रेरी + Other Library… अन्य लाइब्रेरी… + Other Script… अन्य स्क्रिप्ट… + Out of Gamut Warning गैमट से बाहर होने की चेतावनी + Out of Web Color Warning वेब कलर चेतावनी से बाहर + Out Tangent Handles आउट टैंगेंट हैंडल + Out: आउटपुट: + Outer Corner Tile बाहरी कॉर्नर टाइल + Outer Glow… बाहरी ग्लो… + Outline रूपरेखा + Outline Object रूपरेखा ऑब्जेक्ट + Outline Others अन्य लोग + Outline Stroke स्ट्रोक को आउटलाइन में बदलें + Outline Text टेक्स्ट को आउटलाइन में बदलें + Outlined Strokes रेखांकित स्ट्रोक + Outlined Text रेखांकित टेक्स्ट + Outlines रूपरेखा + Outlines and Rules रूपरेखा और नियम + Outlines with Source Image स्रोत इमेज के साथ रूपरेखा + Output आउटपुट + Output › Mode आउटपुट › मोड + Output All Blacks Accurately सटीक रूप से सभी ब्लैक्स को आउटपुट करें + Output All Blacks as Rich Black सभी ब्लैक्स को रिच ब्लैक के रूप में आउटपुट करें + Output Black आउटपुट ब्लैक + Output condition: उत्पादन की स्थिति: + Output Intent सम्पर्क करने का विवरण + Output intent profile: आउटपुट इंटेंट प्रोफ़ाइल: + Output White आउटपुट व्हाइट + Output: आउटपुट: + Outside बाहर + Outside the document डॉक्यूमेंट के बाहर + Oval अंडाकार + Overlap ओवरलैप + Overlap: ओवरलैप: + Overlapping ओवरलैपिंग + Overlay ओवरले + Overlay Edge ओवरले किनारा + Overprint ओवरप्रिंट + Overprint and Transparency Flattener ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर + Overprint and Transparency Flattener Options ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + Overprint Black ओवरप्रिंट ब्लैक + Overprint Black… ओवरप्रिंट ब्लैक… + Overprint Fill फ़िल ओवरप्रिंट करें + Overprint Preview ओवरप्रिंट प्रीव्यू + Overprint Preview (separations) ओवरप्रिंट प्रीव्यू (अलगाव) + Overprint Stroke स्ट्रोक ओवरप्रिंट करें + Overprint: ओवरप्रिंट: + Overprints: ओवरप्रिंट: + Override Action "Export" Commands ओवरराइड एक्शन "एक्सपोर्ट" कमांड + Override Action "Open" Commands ओवरराइड एक्शन "ओपन" कमांड + Override Action "Save" Commands एक्शन के "सेव करें" कमांड ओवरराइड करें + Override Character Color ओवरराइड कैरेक्टर कलर + Overrides ओवरराइड्स + Package पैकेज करें + Package collects a saved document with its linked files and fonts. पैकेज सेव किए गए डॉक्यूमेंट, उसकी लिंक्ड फ़ाइलों और फ़ॉन्ट को एक साथ कलेक्ट करता है। + Package created पैकेज बनाया गया + Package… पैकेज करें… + Page पृष्ठ + Page Cover 1640×624 पेज कवर 1640 × 624 + Page information पृष्ठ की जानकारी + Page Isolated Blending पृष्ठ पृथक सम्मिश्रण + Page Knockout Group पेज नॉकआउट ग्रुप + Pages पृष्ठ + Paint Daubs पेंट डॉब्स + Paint Daubs… पेंट डॉब्स… + Paint Fills पेंट भरता + Paint Opacity: पेंट ओपेसिटी: + Paint Stops At: पेंट स्टॉप: + Paint Strokes पेंट स्ट्रोक + Paintbrush पेंटब्रश + Paintbrush Tool पेंटब्रश टूल + Palette Knife पैलेट नाइफ़ + Palette Knife… पैलेट नाइफ़… + Palette: पैलेट: + Panel menu पैनल मेनू + Panel Options… पैनल ऑप्शन्स… + Panels पैनल्स + Panels Except Tools and Control पैनलों को छोड़कर टूल और नियंत्रण + Paragraph पैराग्राफ़ + Paragraph options पैराग्राफ़ ऑप्शन्स + Paragraph Style पैराग्राफ़ स्टाइल + Paragraph Style Options पैराग्राफ़ स्टाइल ऑप्शन्स + Paragraph Styles पैराग्राफ़ स्टाइल्स + Paragraph Symbol पैराग्राफ सिंबल + Paragraph: पैराग्राफ़: + Parametric Shape पैरामीट्रिक आकार + Parametric Shape Tool पैरामीट्रिक आकार टूल + Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono (OFL). Icons: Lucide (ISC) + VectorCraft. ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono (OFL). प्रतीक: Lucide (ISC) + VectorCraft. + Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. ArtCraft का हिस्सा। MIT OR Apache-2.0। फ़ॉन्ट: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL)। आइकन: Lucide (ISC) + VectorCraft। + Password पासवर्ड + Paste पेस्ट करें + Paste Design पेस्ट डिजाइन + Paste in Back बैक में पेस्ट करें + Paste in Front फ्रंट में पेस्ट करें + Paste in Place स्थान पर पेस्ट करें + Paste Offset पेस्ट ऑफ़सेट + Paste on All Artboards सभी आर्टबोर्ड पर पेस्ट करें + Paste Remembers Layers चिपकाएँ यादें लेयर + Paste without Formatting स्वरूपण के बिना पेस्ट करें + Pasted चिपकाना + Pastels पेस्टल + Patchwork पैचवर्क + Patchwork… पैचवर्क… + Path पाथ + Path Effects पाथ इफ़ेक्ट + Path Eraser पाथ इरेज़र + Path Eraser Tool पाथ इरेज़र टूल + Path Length पाथ की लंबाई + Path Only केवल पाथ + Path Precision Tools पाथ परिशुद्धता टूल + Path: पाथ: + Pathfinder पाथफ़ाइंडर + Pathfinder Options पाथफाइंडर ऑप्शन्स + Pathfinder Options… पाथफाइंडर ऑप्शन्स… + Pathfinders: पाथफाइंडर: + Paths पाथ्स + Paths: {paths} Anchors: {anchors} Colors: {colors} पाथ: {paths} एंकर: {anchors} रंग: {colors} + Pattern पैटर्न + Pattern Borders पैटर्न सीमा + Pattern Brush पैटर्न ब्रश + Pattern Brush Options पैटर्न ब्रश ऑप्शन्स + Pattern Editing पैटर्न संपादन + Pattern Options पैटर्न ऑप्शन्स + Pattern options are available in pattern editing mode. पैटर्न ऑप्शन्स पैटर्न संपादन मोड में उपलब्ध हैं। + Pattern Swatches पैटर्न Swatches + Pattern Type पैटर्न प्रकार + Patterns पैटर्न्स + Pause For इतने समय रुकें + PDF PDF + PDF 1.3 files have no transparency: the preset flattens it. PDF 1.3 फ़ाइलों में कोई पारदर्शिता नहीं है: प्रीसेट इसे फ्लैट करता है। + PDF 1.7 PDF 1.7 + PDF File PDF फ़ाइल + PDF Info PDF की जानकारी + PDF Preset PDF प्रीसेट + PDF Preset: PDF प्रीसेट: + PDF Presets PDF प्रीसेट्स + PDF Presets… PDF प्रीसेट्स… + PDF Print PDF प्रिंट + PDF Settings PDF सेटिंग + PDF-compatible PDF संगत + PDF/A files carry their own output intent. PDF/A फ़ाइलें अपने आउटपुट इरादे को ले जाती हैं। + PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged. PDF/X-1a फ़ाइलें CMYK होती हैं: हर रंग को डेस्टिनेशन प्रोफ़ाइल में बिना टैग कन्वर्ट किया जाता है (खाली होने पर आउटपुट इंटेंट की CMYK प्रोफ़ाइल)। + PDF/X-1a:2001 PDF/X-1a:2001 + PDF/X-3:2002 PDF/X-3:2002 + PDF/X-4:2010 PDF/X-4:2010 + Pen पेन + Pen Tool पेन टूल + Pencil पेंसिल + Pencil Tool पेंसिल टूल + Pentagram पेंटाग्राम + per slice प्रति स्लाइस + Percent: प्रतिशत: + Perceptual परसेप्चुअल + Perceptual Scales अवधारणात्मक स्केल + Performance प्रदर्शन + Permissions अनुमतियां + Permissions password: अनुमति पासवर्ड: + Persistent पर्सिएंट + Perspective पर्सपेक्टिव + Perspective Distort पर्सपेक्टिव + Perspective Grid पर्सपेक्टिव ग्रिड + Perspective Grid Options पर्सपेक्टिव ग्रिड ऑप्शन्स + Perspective Grid Preset पर्सपेक्टिव ग्रिड पूर्व निर्धारित + Perspective grid presets पर्सपेक्टिव ग्रिड प्रीसेट्स + Perspective Grid Presets पर्सपेक्टिव ग्रिड प्रीसेट्स + Perspective Grid Presets… पर्सपेक्टिव ग्रिड प्रीसेट्स… + Perspective Grid Settings पर्सपेक्टिव ग्रिड सेटिंग्स + Perspective Grid Tool पर्सपेक्टिव ग्रिड टूल + Perspective Plane Options… पर्सपेक्टिव प्लेन ऑप्शन्स… + Perspective Selection Tool पर्सपेक्टिव सिलेक्शन टूल + Phone 360×800 फ़ोन 360×800 + Phone 375×667 फ़ोन 375 × 667 + Phone 375×812 फ़ोन 375 × 812 + Phone 390×844 फ़ोन 390 × 844 + Phone 393×852 फ़ोन 393×852 + Phone 412×915 फोन 412 × 915 + Phone 430×932 फोन 430 × 932 + Photo Low Fidelity फोटो लो फिडेलिटी + Photocopy फ़ोटोकॉपी + Photocopy… फ़ोटोकॉपी… + Picas पाइका + Pick Color From: से रंग चुनें: + Pie End Angle: पाई एंड एंगल: + Pie Graph Tool पाई ग्राफ़ टूल + Pie Start Angle: पाई स्टार्ट एंगल: + Pin Bar Position पिन बार स्थिति + Pink गुलाबी + Pivot: पिवोट: + Pixel पिक्सेल + Pixel Preview पिक्सेल प्रीव्यू + Pixelate पिक्सेलेट + Pixels पिक्सेल + Place प्लेस करें + Place DXF DXF रखें + Place from Library लाइब्रेरी + Place onto a new locked, dimmed template layer below the current layer वर्तमान लेयर के नीचे एक नए बंद, dimmed टेम्पलेट लेयर पर रखें + Place PDF PDF रखें + Place Symbol Instance सिंबल इंस्टेंस प्लेस करें + Place the pages with the placement again पृष्ठों को फिर से प्लेसमेंट के साथ रखें + Place… प्लेस… + Placed Document प्लेस्ड डॉक्यूमेंट + Placed File Info रखी हुई फ़ाइल की जानकारी + Placement Options प्लेसमेंट ऑप्शन्स + Placement Options… प्लेसमेंट ऑप्शन्स… + Placement: प्लेसमेंट: + Plaster प्लास्टर + Plaster… प्लास्टर… + Plastic Wrap प्लास्टिक रैप + Plastic Wrap… प्लास्टिक रैप… + Plates प्लेट + Platform: मंच: + Play Action खेल कार्रवाई + Play Current Selection वर्तमान सिलेक्शन + Play: चलाएँ: + Playback Options प्लेबैक ऑप्शन्स + Playback Options… प्लेबैक ऑप्शन्स… + Plug-in Info प्लगइन जानकारी + Plug-in… प्लग-इन… + Plug-ins प्लग-इन्स + Plug-ins & Scratch Disks प्लग-इन और स्क्रैच डिस्क + Plus प्लस + Point Sample पॉइंट सैंपल + Point Text पॉइंट टेक्स्ट + Point Text Objects पॉइंट टेक्स्ट ऑब्जेक्ट्स + Point: पॉइंट: + Pointillize पॉइंटिलाइज़ + Pointillize… पॉइंटिलाइज़… + Points पॉइंट्स + Points per segment प्रति खंड अंक + Points: पॉइंट्स: + Points: clicks add free points अंक: क्लिक मुफ्त अंक जोड़ते हैं + Polar Grid ध्रुवीय ग्रिड + Polar Grid Tool ध्रुवीय ग्रिड टूल + Polar Grid Tool Options ध्रुवीय ग्रिड टूल ऑप्शन्स + Polish पोलिश + Polygon बहुभुज + Polygon Properties: बहुभुज प्रॉपर्टीज़: + Polygon Tool पॉलीगोन टूल + Portrait पोर्ट्रेट + Portrait (flipped) पोर्ट्रेट (फ्लिप) + Portuguese पुर्तगाली + Position स्थिति + Position Panel Above Text स्थिति पैनल ऊपर टेक्स्ट + Position: स्थिति: + Positive सकारात्मक + Postcard पोस्टकार्ड + Poster 18 × 24 in पोस्टर 18 × 24 in + Poster 24 × 36 in पोस्टर 24 × 36 in + Poster Edges पोस्टर एजेस + Poster Edges… पोस्टर एजेस… + Posterization पोस्टराइज़ेशन + PostScript: पोस्टस्क्रिप्ट: + Power Saving (integrated) पावर सेविंग (एकीकृत) + PPI पीपीआई + Precise Cursors सटीक कर्सर + Precision प्रेसिजन + Precision: परिशुद्धता: + Preferences प्रेफ़रेंसेज़ + Preferences… प्रेफ़रेंसेज़… + Prefix: उपसर्ग: + Preparing the image… इमेज तैयार करना… + Presentation Attributes प्रस्तुति योगदान + Presentation Mode प्रस्तुति मोड + Preserve बनाए रखें + Preserve Alpha Transparency अल्फा पारदर्शिता संरक्षित करें + Preserve Appearance उपस्थिति संरक्षित करें + Preserve Appearance and Overprints उपस्थिति और ओवरप्रिंट को संरक्षित करें + Preserve CMYK Numbers CMYK नंबर संरक्षित करें + Preserve editing capabilities संपादन क्षमताओं को संरक्षित करना + Preserve Editing Capabilities संपादन क्षमताओं को संरक्षित करना + Preserve Lightness प्रकाश संरक्षण + Preserve Overprints and Spot Colors ओवरप्रिंट और स्पॉट कलर्स को संरक्षित करें + Preserve Paths संरक्षित पाथ + Preserve Shape Using: संरक्षित आकार का उपयोग: + Preserve Spot Colors स्पॉट कलर्स को संरक्षित करें + Preserve Text Appearance टेक्स्ट उपस्थिति को संरक्षित करें + Preserve Text Editability टेक्स्ट संपादन क्षमता को संरक्षित करना + Preserve Tints टिंट्स बनाए रखें + Preserve: बनाए रखें: + Preset {} Preset {} + Preset {number} Preset {number} + PRESET DETAILS प्रीसेट विवरण + Preset Name प्रीसेट का नाम + Preset name: प्रीसेट का नाम: + Preset: प्रीसेट: + Presets प्रीसेट्स + Presets you save with the Save Preset button appear here. प्रीसेट सेव करें बटन से सेव किए गए प्रीसेट यहाँ दिखते हैं। + Presets: प्रीसेट्स: + Press प्रेस + Press a key… एक कुंजी दबाना… + Press and hold to view the source image स्रोत इमेज देखने के लिए प्रेस और पकड़ो + Press keys… कुंजियाँ दबाएँ… + Press Quality प्रेस गुणवत्ता + Pressure दबाव + Preview प्रीव्यू + Preview (1 inch on the page) प्रीव्यू (1 इंच पृष्ठ पर) + Preview All Layers सभी लेयर्स का प्रीव्यू करें + Preview in Browser ब्राउज़र में प्रीव्यू + Preview in Browser needs the desktop app (the web downloads files instead) ब्राउज़र में प्रीव्यू डेस्कटॉप ऐप (वेब डाउनलोड फ़ाइलों के बजाय) की जरूरत है + Preview Mode प्रीव्यू मोड + Preview the document as it is now डॉक्यूमेंट का प्रीव्यू करें क्योंकि यह अब है + Previous पिछला + Previous Artboard पिछला आर्टबोर्ड + Previous Data Set पिछला डेटा सेट + Previous Document पिछला डॉक्यूमेंट + Previous Library पिछला लाइब्रेरी + Previous page पिछला पृष्ठ + Previous Page पिछला पृष्ठ + Primary प्राथमिक + Print प्रिंट करें + Print & Proof प्रिंट और सबूत + Print as Bitmap बिटमैप के रूप में प्रिंट करें + Print Ink Fixes प्रिंट इंक फिक्स + Print Ink Fixes… प्रिंट इंक फिक्स… + Print Layers: प्रिंट लेयरें: + Print Preset प्रिंट प्रीसेट + Print Preset: प्रिंट प्रीसेट: + Print presets प्रिंट प्रीसेट्स + Print Presets प्रिंट प्रीसेट्स + Print Presets… प्रिंट प्रीसेट्स… + Print Preview प्रिंट प्रीव्यू + Print Setup प्रिंट सेटअप + Print Tiling प्रिंट टाइलिंग + Print Tiling Pages प्रिंट टाइलिंग पेज + Print Tiling Tool प्रिंट टाइलिंग टूल + Print… प्रिंट करें… + Printer प्रिंटर + Printer mark type: प्रिंटर चिह्न प्रकार: + Printer profile: प्रिंटर प्रोफ़ाइल: + Printer Setup… प्रिंटर सेटअप… + Printer: प्रिंटर: + Printers प्रिंटर + Printing / Exporting मुद्रण / निर्यात + Printing & Proofing मुद्रण और प्रूफिंग + Printing allowed: मुद्रण की अनुमति है: + Problems समस्याएं + Process Color प्रोसेस रंग + Profile Cover 1500×500 प्रोफ़ाइल कवर 1500 × 500 + Profile inclusion: प्रोफ़ाइल समावेश: + Profile: प्रोफ़ाइल: + Progressive प्रोग्रेसिव + Projecting Cap प्रोजेक्टिंग कैप + Proof Colors प्रूफ़ रंग + Proof Setup प्रूफ़ सेटअप + Properties प्रॉपर्टीज़ + Proportional Lining आनुपातिक लाइनिंग + Proportional Metrics आनुपातिक मीट्रिक + Proportional Oldstyle आनुपातिक ओल्डस्टाइल + Protect Corners कॉर्नर को सुरक्षित रखें + Proximity Guides निकटता गाइड + PRs पीआर + Public Domain पब्लिक डोमेन + Pucker सिकोड़ें + Pucker & Bloat… पकर और ब्लोट… + Pucker Tool कच्छा टूल + Punctuation विराम चिह्न + Punctuation Space विराम-चिह्न स्पेस + Punjabi पंजाबी + Puppet Warp पपेट वार्प + Puppet Warp Pins कठपुतली वार्प पिन + Puppet Warp Tool कठपुतली वार्प टूल + Purple बैंगनी + Put back in the toolbar टूलबार में वापस रखो + Q Q + Quality गुणवत्ता + Quality {quality} गुणवत्ता {quality} + Quality: गुणवत्ता: + Quarter Space क्वार्टर स्पेस + Quick Actions क्विक एक्शन्स + Quickly start a new file जल्दी से एक नई फ़ाइल शुरू करें + Quit VectorCraft VectorCraft बंद करें + Radar Graph Tool रडार ग्राफ टूल + Radial रेडियल + Radial Blur रेडियल ब्लर + Radial Blur… रेडियल ब्लर… + Radial Dividers: रेडियल विभाजक: + Radial Glows रेडियल चमक + Radial Gradient रेडियल ग्रेडिएंट + Radial Repeat रेडियल दोहराव + Radius त्रिज्या + Radius 1 त्रिज्या 1 + Radius 2 त्रिज्या 2 + Radius: त्रिज्या: + Radius1 त्रिज्या1 + Radius2 त्रिज्या2 + Rainbow इंद्रधनुष + Ramp: रैम्प: + Random यादृच्छिक + Randomize Colors यादृच्छिक रंग + Randomize Opacity ओपेसिटी यादृच्छिक करें + Randomize Opacity… ओपेसिटी यादृच्छिक करें… + Randomly change color order यादृच्छिक रूप से रंग क्रम बदलने + Randomly change saturation and brightness रैंडम रूप से संतृप्ति और चमक को बदल देता है + Range: रेंज: + Raster Effects रीस्टर इफ़ेक्ट + Raster File Format: रास्टर फ़ाइल फ़ॉर्मैट: + Raster Sample Size: रास्टर सैंपल साइज़: + Raster/Vector Balance: रास्टर/वेक्टर बैलेंस: + Rasterize रास्टराइज़ करें + Rasterize Unsupported Art असमर्थित आर्टवर्क रास्टराइज़ करें + Rasterize… रास्टराइज़ करें… + Rasterized Complex Regions Rasterized कॉम्प्लेक्स क्षेत्र + Rasters रास्टर + Rating: रेटिंग: + Ratio अनुपात + Rays रे + Read Shortcut Set File शॉर्टकट सेट फ़ाइल पढ़ें + Reads or sets environment variables पर्यावरण चर पढ़ता है या सेट करता है + Ready तैयार + Real name वास्तविक नाम + Real World: रियल वर्ल्ड: + Real-time Drawing and Editing रियल टाइम ड्राइंग और संपादन + Rearrange All सभी को फिर से व्यवस्थित करें + Rearrange All Artboards सभी आर्टबोर्ड को फिर से व्यवस्थित करें + Rearrange All Artboards… सभी आर्टबोर्ड को पुनर्व्यवस्थित करें… + Rearrange Artboards रीरेंज आर्टबोर्ड + Recall Selection सिलेक्शन वापस लाएँ + Recent हाल के + RECENT हाल के + RECENT (1) रेकेंट (1) + Recent Colors हाल के रंग + Recent File हाल ही में फ़ाइल + Recent Files हाल की फ़ाइलें + Recent Font हाल ही में फ़ॉन्ट + Recent Font 1 हाल ही में फ़ॉन्ट 1 + Recent Font 10 हाल ही में फ़ॉन्ट 10 + Recent Font 11 हाल ही में फ़ॉन्ट 11 + Recent Font 12 हाल ही में फ़ॉन्ट 12 + Recent Font 13 हाल ही में फ़ॉन्ट 13 + Recent Font 14 हाल ही में फ़ॉन्ट 14 + Recent Font 15 हाल के फ़ॉन्ट 15 + Recent Font 2 हाल ही में फ़ॉन्ट 2 + Recent Font 3 हाल ही में फ़ॉन्ट 3 + Recent Font 4 हाल के फ़ॉन्ट 4 + Recent Font 5 हाल के फ़ॉन्ट 5 + Recent Font 6 हाल ही में फ़ॉन्ट 6 + Recent Font 7 हाल के फ़ॉन्ट 7 + Recent Font 8 हाल ही में फ़ॉन्ट 8 + Recent Font 9 हाल ही में फ़ॉन्ट 9 + Recent Fonts हाल के फ़ॉन्ट्स + Recent URLs हाल के URL + Recolor रंग बदलें + Recolor Artwork आर्टवर्क के रंग बदलें + Recolor Artwork… आर्टवर्क के रंग बदलें… + Recolor this row इस पंक्ति को फिर से व्यवस्थित करें + Recolor with Preset प्रीसेट से रंग बदलें + Record रिकॉर्ड + Recover Documents डॉक्यूमेंट पुनर्प्राप्त करें + Recovery Data रिकवरी डेटा + Rectangle आयत + Rectangle Cut आयतन कट + Rectangle Cut Tool आयत कट टूल + Rectangle Properties: आयत प्रॉपर्टीज़: + Rectangle Tool रेक्टेंगल टूल + Rectangle: Sunshine आयत: सनशाइन + Rectangle… आयत… + Rectangular Grid आयताकार ग्रिड + Rectangular Grid Tool आयताकार ग्रिड टूल + Rectangular Grid Tool Options आयताकार ग्रिड टूल ऑप्शन्स + Red लाल + Redefine {kind} Style Redefine {kind} स्टाइल + Redefine {name} {name} फिर से डिफ़ाइन करें + Redefine Character Style रेडफाइन कैरेक्टर स्टाइल + Redefine Graphic Style ग्राफ़िक स्टाइल फिर से डिफ़ाइन करें + Redefine Graphic Style “{name}” ग्राफ़िक स्टाइल “{name}” फिर से डिफ़ाइन करें + Redefine Paragraph Style पैराग्राफ़ स्टाइल फिर से डिफ़ाइन करें + Redefine Symbol सिंबल फिर से डिफ़ाइन करें + Redo फिर से करें + Redo {} {} फिर से करें + Redo {name} {name} फिर से करें + Reduce Colors रंग कम करें + Reduce to Basic Appearance बुनियादी उपस्थिति को कम करना + Reduction: कमी: + Reference Point संदर्भ बिंदु + Reflect परावर्तित करें + Reflect Horizontal क्षैतिज परिलक्षित + Reflect Tool परावर्तन टूल + Reflect X एक्स को प्रतिबिंबित करें + Reflect Y Y को प्रतिबिंबित + Reflect… परावर्तित करें… + Refresh रिफ्रेश + Refresh Font List रिफ्रेश फ़ॉन्ट सूची + Registered Trademark Symbol पंजीकृत ट्रेडमार्क सिंबल + Registration marks रजिस्ट्रेशन मार्क्स + Registration: पंजीकरण: + Registry name: रजिस्ट्री नाम: + Regular सामान्य + Regular expression not closed नियमित अभिव्यक्ति बंद नहीं + Rejoin Path Pieces पाथ के हिस्से फिर से जोड़ें + Rejoin Path Pieces… पाथ के हिस्से फिर से जोड़ें… + Relative सापेक्ष + Relative Colorimetric सापेक्ष कलरिमेट्रिक + Release रिलीज़ करें + Release Blend ब्लेंड रिलीज़ करें + Release Clipping Mask क्लिपिंग मास्क रिलीज़ करें + Release Compound Path कंपाउंड पाथ रिलीज़ करें + Release Compound Shape कंपाउंड शेप रिलीज़ करें + Release Envelope एन्वेलप रिलीज़ करें + Release Guides गाइड्स रिलीज़ करें + Release Image Trace इमेज ट्रेस रिलीज़ करें + Release Intertwine इंटरट्वाइन रिलीज़ करें + Release Live Paint लाइव पेंट रिलीज़ करें + Release Opacity Mask ओपेसिटी मास्क रिलीज़ करें + Release Repeat रिपीट रिलीज़ करें + Release Selection सिलेक्शन रिलीज़ करें + Release Shaper Group शेपर ग्रुप रिलीज़ करें + Release Slice स्लाइस रिलीज़ करें + Release Text Wrap टेक्स्ट रैप रिलीज़ करें + Release Threaded Text थ्रेडेड टेक्स्ट रिलीज़ करें + Release to Layers (Build) लेयर्स में रिलीज़ करें (बिल्ड) + Release to Layers (Sequence) लेयर्स में रिलीज़ करें (क्रम में) + Release Type on a Path पाथ पर टाइप रिलीज़ करें + Release Type on a Path… पाथ पर टाइप रिलीज़ करें… + Release with Perspective पर्सपेक्टिव के साथ रिलीज़ करें + Relief रिलीफ़ + Relink दोबारा लिंक करें + Relink Linked Files to the Document लिंक्ड फ़ाइलें डॉक्यूमेंट से दोबारा लिंक करें + Relink to Folder… फ़ोल्डर से दोबारा लिंक करें… + Relink… दोबारा लिंक करें… + Reload Plug-ins प्लग-इन फिर से लोड करें + Remember Import Matches याद रखें आयात मैच + Remember My Choices मेरी पसंद याद रखें + Remove हटाएँ + Remove “{keyword}” "{keyword}" निकालें + Remove Anchor Points एंकर पॉइंट्स हटाएँ + Remove Asset एसेट निकालें + Remove blank lines between paragraphs पैराग्राफ के बीच रिक्त रेखाएं निकालें + Remove Breaks ब्रेक निकालें + Remove Brush Stroke ब्रश स्ट्रोक निकालें + Remove Color Profile… रंग प्रोफ़ाइल निकालें… + Remove Corners कोने हटाएँ + Remove Effect इफ़ेक्ट हटाएँ + Remove Effects इफ़ेक्ट्स हटाएँ + Remove from Shaper Group शेपर ग्रुप से निकालें + Remove Gaps गैप निकालें + Remove Guide गाइड हटाएँ + Remove Item आइटम निकालें + Remove JavaScript File जावास्क्रिप्ट फ़ाइल निकालें + Remove Line Breaks लाइन ब्रेक हटाएँ + Remove Paragraph Breaks पैराग्राफ ब्रेक निकालें + Remove Plug-in प्लग-इन निकालें + Remove Points, Keep Shape अंक निकालें, आकार रखें + Remove Redundant Points गैरज़रूरी पॉइंट हटाएँ + Remove Selected Assets सिलेक्टेड परिसंपत्तियों को हटा दें + Remove Selected Entry सिलेक्टेड प्रविष्टि निकालें + Remove Strokes स्ट्रोक हटाएँ + Remove the shortcut शॉर्टकट निकालें + Remove Threading थ्रेडिंग निकालें + Remove White Overprint व्हाइट ओवरप्रिंट निकालें + Rename नाम बदलें + Rename Action कार्रवाई का नाम बदलें + Rename Asset परिसंपत्ति का नाम बदलें + Rename Character Style कैरेक्टर स्टाइल का नाम बदलें + Rename Data Set डेटा सेट का नाम बदलें + Rename Data Set… डेटा सेट का नाम बदलें… + Rename Design डिजाइन का नाम बदलें + Rename Graphic Style ग्राफ़िक स्टाइल का नाम बदलें + Rename Group… समूह का नाम बदलें… + Rename Library लाइब्रेरी का नाम बदलें + Rename Library Group लाइब्रेरी समूह का नाम बदलें + Rename Library… लाइब्रेरी का नाम बदलें… + Rename Paragraph Style पैराग्राफ़ स्टाइल का नाम बदलें + Rename Preset प्रीसेट का नाम बदलें + Rename Style स्टाइल का नाम बदलें + Rename Toolbar टूलबार नाम दें + Rename Variable चर का नाम बदलें + Rename View व्यू का नाम बदलें + Rename Workspace वर्कस्पेस का नाम बदलें + Rename… नाम बदलें… + Render Threads (-1 = Automatic) रेंडर थ्रेड्स (-1 = ऑटोमैटिक) + Rendering intent: प्रतिपादन इरादे: + Reorder आदेश + Reorder Appearance अपीयरेंस का क्रम बदलें + Reorder Appearance Item अपीयरेंस आइटम का क्रम बदलें + Reorder Artboards आर्टबोर्ड्स का क्रम बदलें + Repeat दोहराएँ + Repeat {name} दोहराएँ {name} + Repeat Objects ऑब्जेक्ट दोहराएं + Repeat Options दोहरा ऑप्शन्स + Repeat Pathfinder पाथफाइंडर दोहराएं + Repeat Tab टैब दोहराएँ + Repeating दोहराना + Replace रिप्लेस करें + Replace “{name}”, the file this document was opened from? “{name}” को रिप्लेस करें? यह वही फ़ाइल है जिससे यह डॉक्यूमेंट ओपन हुआ था। + Replace Font फ़ॉन्ट रिप्लेस करें + Replace it with another file, or ignore it: its images keep showing the preview saved with the document. दूसरी फ़ाइल से रिप्लेस करें या इसे छोड़ दें: इसकी इमेज डॉक्यूमेंट के साथ सेव किया गया प्रीव्यू दिखाती रहेंगी। + Replace Missing Fonts अनुपलब्ध फ़ॉन्ट रिप्लेस करें + Replace Missing Fonts… अनुपलब्ध फ़ॉन्ट रिप्लेस करें… + Replace Spine स्पाइन रिप्लेस करें + Replace Symbol सिंबल रिप्लेस करें + Replace With Font इस फ़ॉन्ट से रिप्लेस करें + Replace With Font From इस स्रोत के फ़ॉन्ट से रिप्लेस करें + Replace with Top Object सबसे ऊपर के ऑब्जेक्ट से रिप्लेस करें + Replace with Top Object… सबसे ऊपर के ऑब्जेक्ट से रिप्लेस करें… + Replace: रिप्लेस करें: + Replace… रिप्लेस करें… + Replaces the saved preset of that name. उसी नाम से सेव किए गए प्रीसेट को रिप्लेस करता है। + Report copied रिपोर्ट करना + Require a password to open the document डॉक्यूमेंट ओपन करने के लिए एक पासवर्ड की आवश्यकता है + Reselect पुनः सिलेक्ट करें + Reset रीसेट करें + Reset {} {} रीसेट करें + Reset {name} रीसेट करें {name} + Reset all सभी रीसेट करें + Reset all 3D settings to their defaults. सभी 3D सेटिंग्स को उनके डिफ़ॉल्ट रूप से रीसेट करें। + Reset all Revolve settings to their defaults. सभी रिवॉल्व सेटिंग्स डिफ़ॉल्ट पर रीसेट करें। + Reset Automation स्वचालन रीसेट करें + Reset Bar Position बार स्थिति रीसेट करें + Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें + Reset Envelope Mesh एन्वेलप मेश रीसेट करें + Reset Envelope Shape एन्वेलप शेप रीसेट करें + Reset Essentials एसेंशियल्स रीसेट करें + Reset Essentials Classic आवश्यक क्लासिक रीसेट करें + Reset Horizontal Scale क्षैतिज स्केल रीसेट करें + Reset Keyboard Shortcuts कीबोर्ड शॉर्टकट रीसेट करें + Reset Layout लेआउट रीसेट करें + Reset OpenType Features ओपन टाइप सुविधाएँ रीसेट करें + Reset Painting पेंटिंग रीसेट करें + Reset Panel पैनल रीसेट करें + Reset Preferences प्रेफ़रेंसेज़ रीसेट करें + Reset Printing and Proofing मुद्रण और प्रूफिंग रीसेट करें + Reset Profiles प्रोफ़ाइल रीसेट करें + Reset Rotate View व्यू घुमाएँ रीसेट करें + Reset Ruler Origin शासकीय उत्पत्ति रीसेट करें + Reset Symbol Instance सिंबल इंस्टेंस रीसेट करें + Reset Text Transform टेक्स्ट ट्रांसफॉर्मर को रीसेट करें + Reset Text Transform and Scale टेक्स्ट ट्रांसफॉर्म और स्केल को रीसेट करें + Reset the rows to the artwork's colors आर्टवर्क के रंग के लिए पंक्तियों को रीसेट करें + Reset to default डिफ़ॉल्ट पर रीसेट करें + Reset to Default डिफ़ॉल्ट पर रीसेट करें + Reset to Defaults डिफ़ॉल्ट पर रीसेट करें + Reset to Inverse इनवर्स को रीसेट करें + Reset to Linear रैखिक के लिए रीसेट करें + Reset to White, Black व्हाइट, ब्लैक में रीसेट करें + Reset Tracing सम्पर्क करने का विवरण + Reset Tracking and Kerning ट्रैकिंग और कर्निंग रीसेट करें + Reset Transform रूपांतरण रीसेट करें + Reset Typography Typography रीसेट करें + Reset Web वेब रीसेट करें + Reset with Mesh मेश से रीसेट करें + Reset with Mesh… मेश से रीसेट करें… + Reset with Warp वार्प से रीसेट करें + Reset with Warp… वार्प से रीसेट करें… + Reshape आकार बदलें + Reshape Segment सेगमेंट को आकार देना + Reshape Spine स्पाइन का आकार बदलें + Reshape Spine Segment स्पिन सेगमेंट को फिर से आकार दें + Reshape Tool रीशेप टूल + Reshape Type Area रीशैप टाइप एरिया + Reshape Type Path टाइप पाथ रीशेप करें + Resize आकार + Resize Artboard आर्टबोर्ड का आकार बदलें + Resize panel window पैनल विंडो का साइज़ बदलें + Resize panels पैनलों का साइज़ बदलें + Resize Slice स्लाइस का आकार + Resize Type Area प्रकार क्षेत्र का आकार + Resolution: रिज़ॉल्यूशन: + Responsive उत्तरदायी + Restore पुनर्स्थापित करें + Restore every preference to its default (applied on OK) प्रत्येक वरीयता को उसके डिफ़ॉल्ट में पुनर्स्थापित करें ( OK पर लागू) + Restore Recovered Documents पुनर्स्थापना डॉक्यूमेंट + Restored documents open unsaved: save them to keep them. रिकवर किए डॉक्यूमेंट बिना सेव किए ओपन होते हैं। रखने के लिए उन्हें सेव करें। + Restrict printing, editing and other tasks प्रिंटिंग, एडिटिंग और बाकी कामों पर पाबंदी लगाएँ + Restricted Colors प्रतिबंधित रंग + Reticulation रेटिकुलेशन + Reticulation… रेटिकुलेशन… + Retract Handles रिट्रैक्ट हैंडल + Retract Handles… वापस लेने के हैंडल… + Reverse Direction रिवर्स दिशा + Reverse Front to Back आगे-पीछे का क्रम उलटें + Reverse Gradient रिवर्स ग्रेडिएंट + Reverse Order रिवर्स ऑर्डर + Reverse Path Direction रिवर्स पाथ दिशा + Reverse Path Direction Off रिवर्स पाथ दिशा बंद + Reverse Path Direction On रिवर्स पाथ दिशा पर + Reverse Spine रिवर्स स्पाइन + Reverse the order क्रम उलटें + Reverse Traps रिवर्स ट्रैप + Reverse Triangle रिवर्स त्रिभुज + Revert मूल स्थिति में लाएँ + Revert to the saved version of “{name}”? "{name}" के सेव किए गए संस्करण को उलट दें? + Revolve angle कोण घूमना + Revolve… रिवॉल्व… + RGB RGB + RGB Color RGB रंग + RGB Images RGB इमेज + RGB: RGB: + Ridges per segment: प्रति खंड रिज: + Right दाएँ + Right Complement सही पूरक + Right Diagonal दायाँ विकर्ण + Right Grid: राइट ग्रिड: + Right in Front फ्रंट में राइट + Right Indent राइट इंडेंट + Right Plane दायाँ प्लेन + Right to Left बाएं का अधिकार + Right-click an item to move it into this group. इस समूह में इसे स्थानांतरित करने के लिए किसी आइटम को राइट-क्लिक करें। + Right-Justified Tab दाएँ-संरेखित टैब + Right-to-Left Paragraph Direction दाएँ से बाएँ पैराग्राफ़ दिशा + Right: दाएँ: + Ring रिंग + Rings रिंग्स + Ripple Magnitude रिपल परिमाण + Ripple Size रिपल साइज़ + Rise… उठान… + Roman रोमन + Roman Baseline रोमन बेसलाइन + Roman Hanging Punctuation रोमन हैंगिंग विराम चिह्न + Rotate घुमाएँ + Rotate 90° CW 90° सीडब्ल्यू + Rotate Tool रोटेट टूल + Rotate View व्यू घुमाएँ + Rotate View to Selection व्यू को सिलेक्शन के अनुसार रोटेट करें + Rotate View Tool रोटेट व्यू टूल + Rotate: घुमाव: + Rotate… घुमाव… + Rotation घुमाव + Rotation relative to: इसके सापेक्ष: + Rotation X रोटेशन X + Rotation Y रोटेशन वाई + Rotation Z रोटेशन Z + Rotation: घुमाव: + Rough Pastels रफ़ पेस्टल्स + Rough Pastels… रफ़ पेस्टल्स… + Roughen… खुरदरा करें… + Round गोल + Round Angle गोल कोण + Round Blunt राउंड ब्लंट + Round Cap राउंड कैप + Round Corners… राउंड कॉर्नर… + Round Curve गोल वक्र + Round Fan राउंड फैन + Round Join राउंड जॉइन + Round Point राउंड पॉइंट + Rounded गोल + Rounded Rectangle गोल आयत + Rounded Rectangle Tool राउंडेड रेक्टेंगल टूल + Rounded Rectangle… गोल आयत… + Roundness: राउंडनेस: + Row Size: पंक्ति का आकार: + Rows: पंक्तियाँ: + Ruby रूबी + Ruby… रूबी… + Rule: नियम: + Ruler Origin शासकीय उत्पत्ति + Rulers रूलर्स + Rulers & Grids रूलर्स और ग्रिड + Run Length रन लंबाई + Run Plug-in रन प्लग-इन + Runs code the checker can't read रन कोड चेकर को पढ़ा नहीं जा सकता + Russian रूसी + Same समीर + Same As Source स्रोत के समान + Same file एक ही फ़ाइल + Same item as a later row बाद में पंक्ति के रूप में समान आइटम + Same size समान आकार + Sample Color नमूना रंग + Sample Color from Screen स्क्रीन से नमूना रंग + Sandstone बलुआ पत्थर + Sans Serif / Gothic सैंस सेरिफ़ / गॉथिक + Saturate सैचुरेट करें + Saturate… सैचुरेट करें… + Saturation सैचुरेशन + Save सेव + Save a Copy कॉपी सेव + Save a Copy… कॉपी सेव… + Save a Timestamped Copy एक टाइम्सटाम्प्ड कॉपी सेव करें + Save Actions… एक्शन्स सेव करें… + Save and Close सेव करें और बंद करें + Save As सेव ऐज़ + Save as New Preset… नए प्रीसेट के रूप में सेव करें… + Save as PDF… PDF के रूप में सेव करें… + Save as preset: प्रीसेट के रूप में सेव करें: + Save As Preset… प्रीसेट के रूप में सेव करें… + Save as Template टेम्पलेट के रूप में सेव करें + Save as Template… टेम्पलेट के रूप में सेव करें… + Save As… सेव ऐज़… + Save Brush Library ब्रश लाइब्रेरी सेव करें + Save Brush Library… ब्रश लाइब्रेरी सेव करें… + Save Brushes… ब्रश सेव करें… + Save Changes बदलाव सेव करें + Save changes to {name} {name} में बदलाव सेव करें + Save color group to Swatch panel कलर ग्रुप को स्वॉच पैनल में सेव करें + Save Colors as Swatches रंगों को स्वॉचेस के रूप में सेव करें + Save Document डॉक्यूमेंट सेव करें + Save Document Info… डॉक्यूमेंट जानकारी सेव करें… + Save each artboard to a separate file प्रत्येक आर्टबोर्ड को एक अलग फ़ाइल में सेव करें + Save Export Preset सेविंग प्रीसेट + Save for Office Documents कार्यालय डॉक्यूमेंट्स के लिए सेव करें + Save for Office Documents… कार्यालय डॉक्यूमेंट्स के लिए सेव करें… + Save for Web वेब के लिए सेव करें + Save for Web (Legacy)… वेब के लिए सेव करें (लेगेसी)… + Save for Web Presets वेब प्रीसेट के लिए सेव करें + Save for Web Preview वेब प्रीव्यू के लिए सेव करें + Save for Web Settings वेब सेटिंग्स के लिए सेव करें + Save Gradient Preset ग्रेडिएंट प्रीसेट सेव करें + Save Gradient Preset… ग्रेडिएंट प्रीसेट सेव करें… + Save Graphic Style Library ग्राफिक स्टाइल लाइब्रेरी सेव करें + Save Graphic Style Library… ग्राफिक स्टाइल लाइब्रेरी सेव करें… + Save Grid as Preset ग्रिड को प्रीसेट के रूप में सेव करें + Save Grid as Preset… ग्रिड को प्रीसेट के रूप में सेव करें… + Save Image Trace Preset सेव इमेज ट्रेस प्रीसेट + Save PDF PDF सेव करें + Save PDF Dialog PDF सेव डायलॉग + Save PDF Preset PDF प्रीसेट सेव करें + Save Perspective Grid Preset सेव पर्सपेक्टिव ग्रिड प्रीसेट + Save Preset प्रीसेट सेव करें + Save Preset… प्रीसेट सेव करें… + Save Print Preset सेव करें प्रिंट प्रीसेट + Save Recovery Data रिकवरी डेटा सेव करें + Save Save for Web Preset सेव फॉर वेब प्रीसेट + Save selected colors as swatches सिलेक्टेड रंगों को स्वॉचेस के रूप में सेव करें + Save Selection सिलेक्शन सेव करें + Save Selection… सिलेक्शन सेव करें… + Save Swatch Library स्वॉच लाइब्रेरी सेव करें + Save Swatch Library… स्वॉच लाइब्रेरी सेव करें… + Save Symbol Library सिंबल लाइब्रेरी सेव करें + Save Symbol Library… सिंबल लाइब्रेरी सेव करें… + Save Symbols… सिंबल सेव करें… + Save the current layout under this name इस नाम के तहत वर्तमान लेआउट सेव करें + Save the document first? पहले डॉक्यूमेंट सेव करें? + Save the selected preset to a file सिलेक्टेड प्रीसेट को एक फ़ाइल में सेव करें + Save the settings as a preset सेटिंग्स को प्रीसेट के रूप में सेव करें + Save Theme थीम सेव करें + Save theme to My Themes मेरी थीम पर थीम सेव करें + Save these settings as a preset इन सेटिंग्स को प्रीसेट के रूप में सेव करें + Save these settings as a print preset इन सेटिंग्स को प्रिंट प्रीसेट के रूप में सेव करें + Save to Swatches स्वॉचेस में सेव करें + Save To: यहाँ सेव करें: + Save Transparency Flattener Preset ट्रांसपेरेंसी फ़्लैटनर प्रीसेट सेव करें + Save Transparency Flattener Preset… ट्रांसपेरेंसी फ़्लैटनर प्रीसेट सेव करें… + Save Variable Library… वैरिएबल लाइब्रेरी सेव करें… + Save… सेव… + Saved सेव किए गए + SAVED सेव किए गए + Saved {n} files beside {path} {path} के पास {n} फ़ाइलें सेव की गईं + Saved {path} सेव्ड {path} + Saved recovery data for {title} {title} के लिए सेव्ड रिकवरी डेटा + Saved Selection 1 सेव्ड सिलेक्शन 1 + Saved Selection 10 सेव्ड सिलेक्शन 10 + Saved Selection 11 सेव्ड सिलेक्शन 11 + Saved Selection 12 सेव्ड सिलेक्शन 12 + Saved Selection 13 सेव्ड सिलेक्शन 13 + Saved Selection 14 सेव्ड सिलेक्शन 14 + Saved Selection 15 सेव्ड सिलेक्शन 15 + Saved Selection 16 सेव्ड सिलेक्शन 16 + Saved Selection 17 सेव्ड सिलेक्शन 17 + Saved Selection 18 सेव्ड सिलेक्शन 18 + Saved Selection 19 सेव्ड सिलेक्शन 19 + Saved Selection 2 सेव किया गया सिलेक्शन 2 + Saved Selection 20 सेव्ड सिलेक्शन 20 + Saved Selection 21 सेव्ड सिलेक्शन 21 + Saved Selection 22 सेव्ड सिलेक्शन 22 + Saved Selection 23 सेव्ड सिलेक्शन 23 + Saved Selection 24 सेव्ड सिलेक्शन 24 + Saved Selection 25 सेव्ड सिलेक्शन 25 + Saved Selection 3 सेव्ड सिलेक्शन 3 + Saved Selection 4 सेव्ड सिलेक्शन 4 + Saved Selection 5 सेव्ड सिलेक्शन 5 + Saved Selection 6 सेव्ड सिलेक्शन 6 + Saved Selection 7 सेव्ड सिलेक्शन 7 + Saved Selection 8 सेव्ड सिलेक्शन 8 + Saved Selection 9 सेव्ड सिलेक्शन 9 + Saved Selections सेव किया गया सिलेक्शन + Saved to User Defined: {} उपयोगकर्ता परिभाषित करने के लिए सेव किया गया: {} + Saved View 1 सेव्ड व्यू 1 + Saved View 10 सेव्ड व्यू 10 + Saved View 11 सेव्ड व्यू 11 + Saved View 12 सेव्ड व्यू 12 + Saved View 13 सेव्ड व्यू 13 + Saved View 14 सेव किया गया देखें 14 + Saved View 15 सेव्ड व्यू 15 + Saved View 16 सेव्ड व्यू 16 + Saved View 17 सेव किया गया देखें 17 + Saved View 18 सेव्ड व्यू 18 + Saved View 19 सेव्ड व्यू 19 + Saved View 2 सेव्ड व्यू 2 + Saved View 20 सेव्ड व्यू 20 + Saved View 21 सेव्ड व्यू 21 + Saved View 22 सेव किया गया देखें 22 + Saved View 23 सेव किया गया देखें 23 + Saved View 24 सेव्ड व्यू 24 + Saved View 25 सेव्ड व्यू 25 + Saved View 3 सेव्ड व्यू 3 + Saved View 4 सेव्ड व्यू 4 + Saved View 5 सेव्ड व्यू 5 + Saved View 6 सेव्ड व्यू 6 + Saved View 7 सेव्ड व्यू 7 + Saved View 8 सेव्ड व्यू 8 + Saved View 9 सेव्ड व्यू 9 + Saved Views सेव किया गया दृश्य + Saves the current bars, toolbar and panel layout. वर्तमान बार, टूलबार और पैनल लेआउट को बचाता है। + Saving सेव किया जा रहा है + Saving {} बचत {} + Saving Poster.vectorcraft बचत Poster.vectorcraft + Saving recovery data for {} {} के लिए रिकवरी डेटा सेव करना + Scale आकार बदलें + Scale Artwork with Artboard आर्टबोर्ड के साथ स्केल आर्टवर्क + Scale Corners स्केल कॉर्नर + Scale Cursor Proportional to UI स्केल कर्सर प्रोपोरेशनल टू यूआई + Scale Design स्केल डिजाइन + Scale in Perspective पर्सपेक्टिव में स्केल + Scale Lineweights स्केल लाइनवेट + Scale Presets स्केल प्रीसेट + Scale Proportionately अनुपात बनाए रखते हुए स्केल करें + Scale Strokes & Effects स्केल स्ट्रोक & इफ़ेक्ट + Scale Text Attributes स्केल टेक्स्ट विशेषता + Scale Tints स्केल टिंट + Scale to Fit Artboard फिट आर्टबोर्ड के लिए स्केल + Scale Tool स्केल टूल + Scale X स्केल X + Scale X: स्केल X: + Scale Y स्केल Y + Scale Y: स्केल Y: + Scale: स्केल: + Scale… स्केल… + Scaling स्केलिंग + Scaling: स्केलिंग: + Scallop स्कैलप + Scallop Tool स्कैलप टूल + Scans: स्कैन: + Scatter स्कैटर + Scatter Brush स्कैटर ब्रश + Scatter Brush Options स्कैटर ब्रश ऑप्शन्स + Scatter Graph Tool स्कैटर ग्राफ़ टूल + Scatter Shapes स्कैटर शेप + Scatter: स्कैटर: + Scissors कैंची + Scissors Tool कैंची टूल + Scratch Disks स्क्रैच डिस्क + Screen स्क्रीन + Screen (72 ppi) स्क्रीन (72 ppi) + Screen Mode स्क्रीन मोड + Screen Mode Controls स्क्रीन मोड नियंत्रण + Screens स्क्रीन + Scribble… स्क्रिबल… + Script / Brush स्क्रिप्ट / ब्रश + Scripts स्क्रिप्ट्स + Scrub Numeric Fields by Dragging ड्रैगिंग द्वारा स्क्रब न्यूमेरिक फील्ड + Search खोजें + Search All सभी खोजें + Search artboards खोज आर्टबोर्ड + Search commands and tools खोज आदेश और टूल + Search commands and tools… आदेश और टूल खोजें… + Search Commands… कमांड खोजें… + Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर + Search images इमेज खोजना + Searching… खोज… + Secondary माध्यमिक + Section Symbol अनुभाग सिंबल + Security सुरक्षा + Seed: सीड: + Segmented color wheel विभाजित रंग पहिया + Segments सेगमेंट + Select सिलेक्ट + Select a character with the Type tool to see its alternates. अल्टरनेट ग्लिफ़ देखने के लिए टाइप टूल से कोई कैरेक्टर सिलेक्ट करें। + Select a parametric shape to edit it. With none selected, these set the next shape. एडिट करने के लिए पैरामीट्रिक शेप सिलेक्ट करें। कोई शेप सिलेक्ट न होने पर ये सेटिंग्स अगली शेप पर लागू होंगी। + Select a text object एक टेक्स्ट ऑब्जेक्ट चुनें + Select a text object to edit its character attributes. अपने चरित्र विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। + Select a text object to edit its paragraph attributes. अपनी पैराग्राफ विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। + Select a text object to set its tab stops. अपने टैब स्टॉप सेट करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। + Select All सभी सिलेक्ट करें + Select All Art on Layer ऑल आर्ट ऑन लेयर चुनें + Select All Assets सभी परिसंपत्तियों का सिलेक्शन + Select All Bound Objects सभी ऑब्जेक्ट्स सिलेक्ट करें + Select All Instances सभी इंस्टीट्यूशन चुनें + Select All Pins सभी पिन चुनें + Select All Unused सभी सिलेक्ट करें + Select an image to see its Link Info. अपनी लिंक जानकारी देखने के लिए एक इमेज सिलेक्ट करें। + Select an image to trace एक इमेज का पता लगाने के लिए चुनें + Select Anchors एंकर सिलेक्ट करें + Select Appearance Item अपीयरेंस आइटम सिलेक्ट करें + Select Art आर्टवर्क सिलेक्ट करें + Select art and choose Object › Pattern › Make. कला सिलेक्ट करें और ऑब्जेक्ट चुनें › पैटर्न › मेक. + Select art and click New Symbol to make one. कला सिलेक्ट करें और एक बनाने के लिए नए सिंबल पर क्लिक करें। + Select art and use New Brush to make one. कला सिलेक्ट करें और एक बनाने के लिए नए ब्रश का उपयोग करें। + Select art to make a scatter, art or pattern brush. एक बिखरे, कला या पैटर्न ब्रश बनाने के लिए कला चुनें। + Select artwork to apply effects इफ़ेक्ट लागू करने के लिए आर्टवर्क सिलेक्ट करें + Select Bound Object बाउंड ऑब्जेक्ट सिलेक्ट करें + Select by Artboards आर्टबोर्ड द्वारा चुनें + Select by Artboards… आर्टबोर्ड द्वारा सिलेक्ट करें… + Select by Color रंग द्वारा चुनें + Select by Color Kind कलर किंड द्वारा चुनें + Select by Link Status लिंक स्थिति सिलेक्ट करें + Select by Link Status… लिंक स्थिति द्वारा सिलेक्ट करें… + Select Data Set डेटा सेट सिलेक्ट करें + Select Embedded एम्बेडेड सिलेक्ट करें + Select Fills भरता सिलेक्ट करें + Select Freeform Point फ़्रीफ़ॉर्म पॉइंट सिलेक्ट करें + Select Gradient Stop ग्रेडिएंट स्टॉप चुनें + Select Guides गाइड्स सिलेक्ट करें + Select Linked लिंक्ड सिलेक्ट करें + Select Missing मिसिंग सिलेक्ट करें + Select Modified संशोधित सिलेक्ट करें + Select Objects ऑब्जेक्ट्स सिलेक्ट करें + Select objects to adjust their colors. अपने रंगों को समायोजित करने के लिए ऑब्जेक्ट्स सिलेक्ट करें। + Select objects to find the swatches nearest their colors. रंगों से सबसे अधिक मेल खाने वाले स्वॉच ढूँढने के लिए ऑब्जेक्ट सिलेक्ट करें। + Select objects to see their CSS, or Generate CSS for the whole document. CSS देखने के लिए ऑब्जेक्ट सिलेक्ट करें या पूरे डॉक्यूमेंट के लिए CSS जनरेट करें। + Select Same Tint % समान टिंट % सिलेक्ट करें + Select Segments सेगमेंट सिलेक्ट करें + Select Shaper Face शेपर फेस सिलेक्ट करें + Select Slices स्लाइस सिलेक्ट करें + Select Strokes स्ट्रोक सिलेक्ट करें + Select styled art and click New Graphic Style. स्टाइलबद्ध कला सिलेक्ट करें और नई ग्राफिक स्टाइल क्लिक करें। + Select text टेक्स्ट चुनें + Select Text by Font फ़ॉन्ट द्वारा टेक्स्ट सिलेक्ट करें + Select text or click into text with the Type tool to insert glyphs टेक्स्ट सिलेक्ट करें या glyphs डालने के लिए टाइप टूल के साथ टेक्स्ट में क्लिक करें + Select text to set its OpenType features. अपनी OpenType सुविधाओं को सेट करने के लिए टेक्स्ट सिलेक्ट करें। + Select the art (and, on top of it, the mask object) कला सिलेक्ट करें (और इसके शीर्ष पर, मास्क ऑब्जेक्ट) + Select Tool टूल सिलेक्ट करें + Select two or more objects, or a group दो या अधिक ऑब्जेक्ट चुनें, या एक समूह चुनें + Select Unused अप्रयुक्त चुनें + Select: सिलेक्ट: + Selected Artwork सिलेक्टेड आर्टवर्क + Selected Brushes Only केवल सिलेक्टेड ब्रश + Selected Slices सिलेक्टेड स्लाइस + Selected Styles Only केवल सिलेक्टेड स्टाइल्स + Selected Styles Only (0) केवल सिलेक्टेड स्टाइल्स (0) + Selected Swatches सिलेक्टेड स्वॉचेस + Selected Swatches Only केवल सिलेक्टेड स्वॉचेस + Selected Swatches Only (0) केवल सिलेक्टेड Swatches (0) + Selected Symbols Only केवल सिलेक्टेड सिंबल + Selected: {n}, Total number of files to export: {m} सिलेक्टेड: {n}, निर्यात करने के लिए फ़ाइलों की कुल संख्या: {m} + Selection सिलेक्शन + Selection & Anchor Display सिलेक्शन और एंकर प्रदर्शन + Selection Only केवल सिलेक्शन + Selection Tool सिलेक्शन टूल + Selection Tools सिलेक्शन टूल + Selection: सिलेक्शन: + Selective सिलेक्शनात्मक + Send Backward पीछे भेजें + Send to Back सबसे पीछे भेजें + Send to Current Layer वर्तमान लेयर को भेजें + Sends messages to other apps अन्य ऐप्स को संदेश भेजता है + Sentence case वाक्य का मामला + Separate colors into rows पंक्तियों में अलग रंग + Separate several keywords with commas. अल्पविराम के साथ कई कीवर्ड अलग करें। + Separations पृथक्करण + Separations list the document's inks here: one page per ink that prints. सेपरेशन्स यहाँ डॉक्यूमेंट की इंक दिखाते हैं: प्रिंट होने वाली हर इंक के लिए एक पेज। + Separations Preview सेपरेशन्स प्रीव्यू + Serbian: Cyrillic सर्बियाई: साइरिलिक + Serbian: Latin सर्बियाई: लैटिन + Serialize Document डॉक्यूमेंट को सीरियलाइज़ करें + Serif / Mincho सेरिफ / मिंचो + Server-side (.map) सर्वर-साइड (.map) + Services सेवाएँ + Set {n} सेट {n} + Set 1 सेट 1 + Set Alignment, Keep Position सेट संरेखण, स्थिति रखें + Set Alignment, Keep Position: सेट संरेखण, स्थिति रखें: + Set Anchor सेट एंकर + Set Anchors एंकर सेट करें + Set as Default डिफ़ॉल्ट के रूप में सेट करें + Set base color आधार रंग सेट करें + Set base color to the current color वर्तमान रंग के लिए आधार रंग सेट करें + Set Bounds सेट बाउंड्स + Set Corners सेट कॉर्नर + Set Corners… सेट कॉर्नर… + Set Current Layer वर्तमान लेयर सेट करें + Set Font Height Reference फ़ॉन्ट ऊंचाई संदर्भ सेट करें + Set History Limit… इतिहास लिमिट सेट करें… + Set Keyboard Shortcut कीबोर्ड शॉर्टकट सेट करें + Set Mesh Point Color मेश पॉइंट का रंग सेट करें + Set Options ऑप्शन्स सेट + Set Options… ऑप्शन्स सेट करें… + Set Preference प्राथमिकता सेट करें + Set Size of Each प्रत्येक का आकार सेट करें + Set Size of Each… प्रत्येक का आकार सेट करें… + Set Slice Rectangle सेट स्लाइस आयत + Set Tab Stops टैब स्टॉप्स सेट करें + Set Text टेक्स्ट सेट करें + Set the selected color to the current color सिलेक्टेड रंग को वर्तमान रंग में सेट करें + Set Zoom ज़ूम सेट करें + Set: सेट: + Settings सेटिंग्स + Settings… सेटिंग्स… + Setup… सेटअप… + Shades शेड + Shades of Gray ग्रे के शेड्स + Shading शेडिंग + Shadow Intensity शैडो तीव्रता + Shadows and Glows छाया और चमक + Shaft: दस्ता: + Shape शेप + Shape Builder शेप बिल्डर + Shape Builder Delete आकार बिल्डर डिलीट + Shape Builder Regions आकार बिल्डर क्षेत्र + Shape Builder Tool शेप बिल्डर टूल + Shape Effects आकार इफ़ेक्ट + Shape Mode आकार मोड + Shape Mode Buttons Make Compound Shapes आकार मोड बटन मिश्रित आकार बनाते हैं + Shape Modes: आकार मोड: + Shape Properties आकार प्रॉपर्टीज़ + Shape Properties: आकार प्रॉपर्टीज़: + Shape: शेप: + Shaper शेपर + Shaper Tool शेपर टूल + Shapes शेप्स + Shared Edge Merge Tool साझा एज मर्ज टूल + Shared Edges साझा एज + Sharp तीक्ष्ण + Sharpen शार्पन + Sharpness शार्पनेस + Shear शियर + Shear Tool शीयर टूल + Shear: शियर: + Shear… शियर… + Shell Lower… निचला शेल… + Shell Upper… ऊपरी शेल… + Shift Shift + Shift to Color… रंग बदलने के लिए… + Shift-click: break into paragraphs Shift-क्लिक: पैराग्राफ़ में बाँटें + Shift: Shift: + Shift+Click Shift+Click + Shift+Drag Shift+Drag + Shifts the tints of global and spot colors; other colors stay. ग्लोबल और स्पॉट रंगों के टिंट्स बदलता है; बाकी रंग वैसे ही रहते हैं। + Short छोटा + Short Lines छोटी रेखाएँ + Short Strokes छोटे स्ट्रोक + Shortcut शॉर्टकट + Shortcuts शॉर्टकट्स + Shorter Than Length लंबाई से कम + Show दिखाएँ + Show {kind} Brushes शो {kind} ब्रश + Show Active Plane Widget सक्रिय प्लेन विजेट दिखाएं + Show All सभी दिखाएँ + Show All Hidden Attributes सभी छिपे हुए गुण दिखाएँ + Show All Layers सभी लेयर्स दिखाएँ + Show all open documents सभी खुला डॉक्यूमेंट दिखाएं + Show all plates सभी प्लेटें दिखाएं + Show All Plates सभी प्लेटें दिखाएं + Show All Swatches सभी Swatches दिखाएँ + Show and print from the Lab definition; PDF files carry it as the ink's alternate color. लैब परिभाषा से शो और प्रिंट करें; PDF फ़ाइलें इसे स्याही के वैकल्पिक रंग के रूप में ले जाती हैं। + Show and separate through the working CMYK space, as in older documents. पुराने डॉक्यूमेंट्स के रूप में कार्य CMYK अंतरिक्ष के माध्यम से दिखाएँ और अलग करें। + Show Artboards आर्टबोर्ड्स दिखाएँ + Show axis अक्ष दिखाएँ + Show Bounding Box बाउंडिंग बॉक्स दिखाएँ + Show Brush Size ब्रश साइज़ दिखाएँ + Show Center केंद्र दिखाएँ + Show Center Mark शो सेंटर मार्क + Show Code कोड दिखाएं + Show color bars रंग सलाखों दिखाएँ + Show Color Groups रंग समूह दिखाएँ + Show Color Swatches रंग स्वॉचेस दिखाएँ + Show Corner Widget शो कॉर्नर विजेट + Show Cross Hairs क्रॉस हेयर + Show East Asian Options पूर्वी एशियाई ऑप्शन्स + Show Edges शो एज + Show Embedded एम्बेडेड दिखाएँ + Show Find Field क्षेत्र का पता लगाएं + Show Font Height Options फ़ॉन्ट ऊंचाई ऑप्शन्स दिखाएं + Show Font Names in English फ़ॉन्ट के नाम अंग्रेज़ी में दिखाएँ + Show Gradient Annotator ग्रेडिएंट एनोटेटर दिखाएँ + Show Gradient Swatches ग्रेडिएंट स्वॉचेस दिखाएँ + Show Grid ग्रिड दिखाएँ + Show Grid (⌘') ग्रिड दिखाएँ (⌘') + Show Guides गाइड्स दिखाएँ + Show handles when multiple anchors are selected जब एकाधिक एंकरों का सिलेक्शन किया जाता है तो हैंडल दिखाएं + Show Hidden Characters हिडन कैरेक्टर दिखाएं + Show Images in Outline Mode आउटलाइन मोड में इमेज दिखाएं + Show in Folder फ़ोल्डर में दिखाएँ + Show Indic Options इन्डिक ऑप्शन्स + Show Issue प्रदर्शन + Show Layers Only केवल लेयर्स दिखाएं + Show Library लाइब्रेरी दिखाएँ + Show Link Info लिंक जानकारी दिखाएँ + Show List View सूची दृश्य दिखाएँ + Show Live Paint Gaps लाइव पेंट गैप दिखाएं + Show Mesh मेश दिखाएँ + Show Missing मिसिंग दिखाएँ + Show Modified संशोधित दिखाएँ + Show Note नोट दिखाएं + Show Options ऑप्शन्स दिखाएँ + Show Original Path मूल पाथ दिखाएं + Show Package पैकेज करें दिखाएँ + Show Panel शो पैनल + Show Pattern Swatches पैटर्न Swatches दिखाएँ + Show Perspective Grid पर्सपेक्टिव ग्रिड दिखाएँ + Show Pixel Grid (Above 600% Zoom) प्रदर्शन पिक्सेल ग्रिड (600% ज़ूम ऊपर) + Show Presets प्रीसेट्स दिखाएँ + Show Print Tiling प्रिंट टाइलिंग दिखाएँ + Show Properties Panel शो प्रॉपर्टीज़ पैनल + Show Rulers रूलर्स दिखाएँ + Show Rulers (⌘R) रूलर्स दिखाएँ (⌘R) + Show segmented color wheel खंडित रंग पहिया दिखाएँ + Show Slice Numbers स्लाइस नंबर दिखाएँ + Show Slices स्लाइस दिखाएँ + Show smooth color wheel चिकनी रंग पहिया दिखाएँ + Show Snap to Glyph Options ग्लिफ़ पर स्नैप ऑप्शन्स दिखाएँ + Show Swatch Bounds स्वॉच की सीमाएँ दिखाएँ + Show Swatch Kinds स्वॉच प्रकार दिखाएँ + Show Template टेम्पलेट दिखाएँ + Show Text Threads टेक्स्ट थ्रेड्स दिखाएं + Show The Home Screen When No Documents Are Open जब कोई डॉक्यूमेंट खुला नहीं है तो होम स्क्रीन दिखाएं + Show Thumbnail थंबनेल दिखाएं + Show Thumbnail View थंबनेल देखें दिखाएँ + Show Thumbnails थंबनेल दिखाएं + Show Tile Edge टाइल एज + Show Tints/Shades शो टिंट्स / शेड्स + Show Tool Group Labels टूल ग्रुप लेबल दिखाएं + Show Tool Tips टूल युक्तियाँ दिखाएँ + Show Toolbar शो टूलबार + Show Transparency Grid पारदर्शिता ग्रिड दिखाएँ + Show Video Rulers शो वीडियो शासक + Show Video Safe Areas वीडियो सुरक्षित क्षेत्र दिखाएं + Show Vivid/Muted चमकीले/मंद दिखाएँ + Show Warm/Cool शो वार्म / कूल + Show: दिखाएँ: + Show/hide plate (Alt-click: only this plate) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट) + Shown with the optimised preview. आशावादी प्रीव्यू के साथ दिखाया गया है। + Shrink Text to Fit टेक्स्ट को फिट करने के लिए सिकोड़ें + Side 1: साइड 1: + Side 2: साइड 2: + Side Length: साइड लंबाई: + Side Tile साइड टाइल + Sides: भुजाएँ: + Silhouettes सिल्हूट + Simple सरल + Simplified Chinese सरलीकृत चीनी + Simplify सरल करें + Simplify Anchors एंकर को सरलीकृत करें + Simplify Anchors (Keep Shape) एंकर कम करें (शेप बनाए रखें) + Simplify Anchors (Keep Shape)… एंकर कम करें (शेप बनाए रखें)… + Simplify Anchors… एंकर को सरलीकृत करें… + Simplify: सरल करें: + Simplify… सरल करें… + Simulate अनुकरण + Simulate Colored Paper नकली रंग का कागज + Simulate Paper पेपर सिम्युलेट करें + Simulate prints overprints as Overprint Preview shows them; separations always keep them. A preset flattens transparency before printing (PostScript files always flatten it). ओवरप्रिंट प्रीव्यू के रूप में प्रिंट ओवरप्रिंट को अनुकरण करना उन्हें दिखाता है; जुदाई हमेशा उन्हें रखते हैं। प्रिंटिंग से पहले एक प्रीसेट सपाट पारदर्शिता (पोस्टस्क्रिप्ट फ़ाइलें हमेशा इसे सपाट करती हैं)। + Single Corner Radius सिंगल कॉर्नर त्रिज्या + Single File एकल फ़ाइल + Single Left Quotation Mark सिंगल लेफ्ट क्वोटेशन मार्क + Single Quotes: एकल उद्धरण: + Single Right Quotation Mark सिंगल राइट कोटेशन मार्क + Single Word Justification: एकल शब्द जस्टिफ़िकेशन: + Single-line Composer एकल लाइन संगीतकार + Sixth Space छठे हिस्से जितना स्पेस + Size आकार + Size Tile to Art आकार टाइल कला के लिए + Size: साइज़: + Size: {size} Tracking: {tracking} साइज़: {size} ट्रैकिंग: {tracking} + Size/Leading साइज़/लीडिंग + Sketch स्केच + Sketched Art स्केच कला + Skew तिरछा करें + Skew: तिरछा करें: + Skin Tone Ramps स्किन टोन रैमप्स + Skip Blank Artboards खाली आर्टबोर्ड छोड़ें + Skip Objects with Spot Colors स्पॉट कलर्स के साथ ऑब्जेक्ट्स छोड़ें + Skip Spaces स्पेस छोड़ें + Sky Gradients स्काई ग्रेडिएंट + Slash स्लैश + Slice स्लाइस + Slice Options स्लाइस ऑप्शन्स + Slice Options… स्लाइस ऑप्शन्स… + Slice Selection Tool स्लाइस सिलेक्शन टूल + Slice Tool स्लाइस टूल + Slice Type: स्लाइस प्रकार: + Slices स्लाइस + slices across, evenly spaced भर में स्लाइस, समान रूप से स्पेसेड + slices down, evenly spaced नीचे स्लाइस, समान रूप से स्पेस किया गया + Slices: स्लाइस: + Slide Anchor Along Path पाथ के साथ स्लाइड एंकर + Sliding स्लाइडिंग + Slope: ढलान: + Small छोटा + Small Caps स्मॉल कैप्स + Small Caps (on the roadmap) छोटे कैप्स (रोडमैप पर) + Small Caps: स्मॉल कैप्स: + Small Gaps छोटे अंतराल + Small List View लघु सूची देखें + Small Thumbnail View छोटे थंबनेल देखें + Small Thumbnails छोटे थंबनेल + Small to Large छोटे से बड़े + Smaller ↔ Larger छोटा ↔ बड़ा + Smallest File Size सबसे छोटा फ़ाइल साइज + Smart Blur स्मार्ट ब्लर + Smart Blur… स्मार्ट ब्लर… + Smart Guides स्मार्ट गाइड्स + Smart Guides (⌘U) स्मार्ट गाइड्स (⌘U) + Smart Guides (View → Smart Guides) स्मार्ट गाइड (देखें → स्मार्ट गाइड) + Smart Pen स्मार्ट पेन + Smart Pen Panel स्मार्ट पेन पैनल + Smart Pen Tool स्मार्ट पेन टूल + Smart Punctuation… स्मार्ट विराम-चिह्न… + Smooth स्मूथ + Smooth Anchors चिकना एंकर + Smooth Anchors… चिकना एंकर… + Smooth Color चिकना रंग + Smooth Tool चिकना टूल + Smooth… चिकना करें… + Smoothness चिकनापन + Smudge Stick स्मज स्टिक + Smudge Stick… स्मज स्टिक… + Snap Curves To Lines स्नैप कर्व्स टू लाइन्स + Snap Options स्नैप ऑप्शन्स + Snap to Glyph ग्लिफ़ पर स्नैप करें + Snap to Glyph Options ग्लिफ़ पर स्नैप ऑप्शन्स + Snap to Grid ग्रिड पर स्नैप करें + Snap to Perpendicular लंबवत दिशा में स्नैप करें + Snap to Pixel पिक्सेल के लिए स्नैप + Snap to Point पॉइंट पर स्नैप करें + Snap to Tangent स्नैप टू टेंगेंट + Snap to Unit स्नैप टू यूनिट + Snapping स्नैप करना + Snapping Tolerance स्नैपिंग सहिष्णुता + Social सामाजिक + Social Landscape Post 1200×630 सोशल लैंडस्केप पोस्ट 1200 × 630 + Social Portrait Post 1080×1350 सोशल पोर्ट्रेट पोस्ट 1080 × 1350 + Social Square Post 1080×1080 सोशल स्क्वायर पोस्ट 1080 × 1080 + Social Story 1080×1920 सोशल स्टोरी 1080 × 1920 + Social Tall Post 1000×1500 सामाजिक लंबा पोस्ट 1000 × 1500 + Soft सॉफ़्ट + Soft Light सॉफ़्ट लाइट + Soft Mix शीतल मिश्रण + Softness कोमलता + Solid ठोस + Some lists were cut short at their limit. कुछ सूचियों को उनकी सीमा पर कम काट दिया गया था। + Sort क्रमबद्ध करें + Sort by Hue द्वारा क्रमबद्ध Hue + Sort by Kind द्वारा क्रमबद्ध + Sort by Luminance द्वारा क्रमबद्ध Luminance + Sort by Name नाम से क्रमबद्ध करें + Sort by Popularity लोकप्रियता द्वारा क्रमबद्ध + Sort by Status स्थिति द्वारा क्रमबद्ध + Sort By: द्वारा क्रमबद्ध: + Sort Objects ऑब्जेक्ट्स को क्रमबद्ध करें + Sort Objects… ऑब्जेक्ट्स क्रमबद्ध करें… + Sort Swatches स्वॉचेस सॉर्ट करें + Source code on GitHub GitHub पर स्रोत कोड + Source Folder: स्रोत फ़ोल्डर: + Source Image स्रोत इमेज + Source Sans 3 Source Sans 3 + Space After Paragraph पैराग्राफ़ के बाद स्पेस + Space Before Paragraph पैराग्राफ़ से पहले स्पेस + Spaces स्पेस + Spacing स्पेसिंग + Spacing Guides स्पेसिंग गाइड + Spacing: स्पेसिंग: + Spanish स्पेनिश + Sparkle झिलमिल + Spatter छींटे + Spatter… छींटे… + Specified Distance निर्दिष्ट दूरी + Specified Steps निर्दिष्ट चरण + Specify: निर्दिष्ट करें: + Speckle धब्बेदार + Spectrum स्पेक्ट्रम + Spectrum Gradients स्पेक्ट्रम ग्रेडिएंट + Speech Bubble स्पीच बबल + Spelling स्पेलिंग + Spike स्पाइक + Spin स्पिन + Spiral सर्पिल + Spiral Tool सर्पिल टूल + Split at Anchors एंकर पर विभाजित + Split at Anchors… एंकर पर विभाजित… + Split at Crossings क्रॉसिंग में विभाजित + Split at Cursor कर्सर में विभाजित + Split Complementary स्प्लिट कॉम्प्लेमेंटरी + Split Freeform Line स्प्लिट फ्रीफॉर्म लाइन + Split Into Grid ग्रिड में बाँटें + Split Into Grid… ग्रिड में बाँटें… + Split Path स्प्लिट पाथ + Split Text at Cursor कर्सर में स्प्लिट टेक्स्ट + Sponge स्पंज + Sponge… स्पंज… + spot स्पॉट + Spot Color स्पॉट रंग + Spot Colors स्पॉट रंग + Spot Colors (0) स्पॉट कलर्स (0) + Spot Colors… स्पॉट कलर्स… + Spray Radius स्प्रे त्रिज्या + Sprayed Strokes स्प्रे किए गए स्ट्रोक + Sprayed Strokes… स्प्रे किए गए स्ट्रोक… + Spread: फैलाव: + Sprinkles छिड़काव + Square वर्ग + Square (open) स्क्वायर (ओपन) + Square 8 × 8 in स्क्वायर 8 × 8 इंच + Square Size वर्ग साइज़ + Squeeze… सिकोड़न… + sRGB IEC61966-2.1 sRGB IEC61966-2.1 + Stacked स्टैक्ड + Stacked Bar Graph Tool स्टैक्ड बार ग्राफ टूल + Stacked Column Graph Tool स्टैक्ड कॉलम ग्राफ टूल + Stacking Order स्टैकिंग ऑर्डर + Stained Glass रंगीन कांच + Stained Glass… रंगीन कांच… + Stair Step सीढ़ी कदम + Stamp स्टैम्प + Stamp… स्टैम्प… + Standard मानक + Standard Legend स्टैंडर्ड लीजेंड + Standard Ligatures मानक लिगेचर + Standard Vertical Roman Alignment स्टैंडर्ड वर्टिकल रोमन संरेखण + Standard: मानक: + Star तारा + Star Tool स्टार टूल + Start arrowhead आरंभिक तीरहेड + Start at: शुरू करें: + Start from VectorCraft Defaults वेक्टर क्रेफ्ट डिफ़ॉल्ट से शुरू + Start Global Edit ग्लोबल एडिट + Start Length प्रारंभ लंबाई + Start Percent शुरू करें प्रतिशत + Start Shape प्रारंभ आकार + Start Tile टाइल प्रारंभ करें + Start: प्रारंभ: + Static Symbol स्टैटिक सिंबल + Status स्थिति + Step चरण + Step Backward एक चरण पीछे + Step by Step चरण दर चरण + Step Forward एक चरण आगे + Step Type चरण प्रकार + Step up or down ऊपर या नीचे कदम + Steps: चरण: + Stiffness: कठोरता: + Stippled बिंदुकित + Stop रोकें + Stop Editing Opacity Mask बंद करो संपादन ओपेसिटी मास्क + Stop editing the opacity mask ओपेसिटी मास्क को संपादित करना बंद करें + Stop Global Edit स्टॉप ग्लोबल एडिट + Stop on Errors त्रुटि पर रोक + Stop Playing/Recording प्लेबैक/रिकॉर्डिंग रोकें + Straight सीधे + Straight Line सीधी रेखा + Straight or Curved Segment सीधे या घुमावदार खंड + Stray Points अकेले पॉइंट + Strength शक्ति + Stretch Between Guides गाइड के बीच खिंचाव + Stretch Curve स्ट्रेच कर्व + Stretch to fit फिट करने के लिए खिंचाव + Stretch to Fit Stroke Length फिट स्ट्रोक की लंबाई के लिए खिंचाव + Strikethrough स्ट्राइकथ्रू + String not closed स्ट्रिंग बंद नहीं + Stroke स्ट्रोक + Stroke (X), double-click for the Color Picker स्ट्रोक (एक्स), रंग पिकर के लिए डबल क्लिक करें + Stroke Color स्ट्रोक रंग + Stroke Direction स्ट्रोक दिशा + Stroke Gradient स्ट्रोक ग्रेडिएंट + Stroke Length स्ट्रोक लंबाई + Stroke options स्ट्रोक ऑप्शन्स + Stroke Options स्ट्रोक ऑप्शन्स + Stroke Pattern स्ट्रोक पैटर्न + Stroke Pressure स्ट्रोक प्रेशर + Stroke Weight स्ट्रोक वजन + Stroke When Editable स्ट्रोक जब संपादन योग्य + Stroke Width स्ट्रोक चौड़ाई + Stroke: स्ट्रोक: + Stroke: click for swatches, Shift-click for the color mixer स्ट्रोक: स्वॉचेस के लिए क्लिक करें, कलर मिक्सर के लिए Shift-क्लिक करें + Strokes स्ट्रोक्स + Strokes use one or more of these brushes. Take the brushes off those strokes and delete the brushes? एक या अधिक ब्रश स्ट्रोक्स पर उपयोग हो रहे हैं। उन स्ट्रोक्स से ब्रश हटाकर ये ब्रश डिलीट करें? + Style स्टाइल + Style Attributes स्टाइल गुण + Style Attributes (Entity References) स्टाइल एट्रिब्यूट्स (एन्टीटी रेफरेंस) + Style Name: स्टाइल का नाम: + Style: स्टाइल: + Styling: स्टाइल: + Stylistic स्टाइलिस्ट + Stylistic Alternates शैलीगत ऑप्शन + Stylistic Sets स्टाइलिस्टिक सेट्स + Stylize शैलीबद्ध करें + Subdivisions उप-विभाजन + Subsample सबसैंपल करें + Subscript सबस्क्रिप्ट + Subscript (on the roadmap) सबस्क्रिप्ट (रोडमैप पर) + Subscript: सबस्क्रिप्ट: + Subset सबसेट + Subset fonts below: नीचे सबसेट फ़ॉन्ट: + Subtract घटाएँ + Suffix प्रत्यय + Sumi-e सुमी-ए + Sumi-e… सुमी-ए… + Summary सारांश + Sunshine सनशाइन + Superscript सुपरस्क्रिप्ट + Superscript (on the roadmap) सुपरस्क्रिप्ट (रोडमैप पर) + Superscript: सुपरस्क्रिप्ट: + SVG 1.1 SVG 1.1 + SVG Filters SVG फिल्टर + SVG Interactivity SVG अन्तरक्रियाशीलता + SVG Options SVG ऑप्शन्स + SVG Profile: SVG प्रोफ़ाइल: + Swallowtail स्वॉलोटेल + Swap Fill and Stroke स्वैप भरें और स्ट्रोक + Swap Fill and Stroke (Shift+X) स्वैप फिल एंड स्ट्रोक (Shift+X) + Swap Objects स्वैप ऑब्जेक्ट्स + Swap Objects and Sizes स्वैप ऑब्जेक्ट्स और साइज + Swap start and end arrowheads स्वैप शुरू और अंत तीरहेड्स + Swap the selected object for the file, keeping its place and transform फ़ाइल के लिए सिलेक्टेड ऑब्जेक्ट को स्वैप करें, अपनी जगह को बनाए रखें और परिवर्तित करें + Swash स्वॉश + Swatch Conflict स्वॉच विरोध + Swatch Conflicts स्वॉच विरोध + Swatch exchange files keep solid colors only. स्वॉच एक्सचेंज फ़ाइलों में केवल सॉलिड रंग रहते हैं। + Swatch Libraries स्वॉच लाइब्रेरीज़ + Swatch Libraries Menu घड़ी लाइब्रेरीों मेनू + Swatch Library स्वॉच लाइब्रेरी + Swatch Name: स्वॉच का नाम: + Swatch Options स्वॉच ऑप्शन्स + Swatch Options… स्वॉच ऑप्शन्स… + Swatch Tiles स्वॉच टाइल्स + Swatches स्वॉचेस + Swedish स्वीडिश + Switch Units स्विच यूनिट + Switch workspace वर्कस्पेस स्विच + Switch x/y स्विच x/y + Symbol सिंबल + Symbol Instance सिंबल इंस्टेंस + Symbol Instance Appearance सिंबल इंस्टेंस अपीयरेंस + Symbol Libraries सिंबल लाइब्रेरीज़ + Symbol Libraries Menu सिंबल लाइब्रेरीों मेनू + Symbol Library सिंबल लाइब्रेरी + Symbol Options सिंबल ऑप्शन्स + Symbol Options… सिंबल ऑप्शन्स… + Symbol Screener सिंबल स्क्रीनर + Symbol Screener Tool सिंबल स्क्रीनर टूल + Symbol Scruncher सिंबल स्क्रंचर + Symbol Scruncher Tool सिंबल स्क्रंचर टूल + Symbol Set Density: सिंबल सेट डेंसिटी: + Symbol Shifter सिंबल शिफ्टर + Symbol Shifter Tool सिंबल शिफ़्टर टूल + Symbol Sizer सिंबल साइज़र + Symbol Sizer Tool सिंबल साइज़र टूल + Symbol Spinner सिंबल स्पिनर + Symbol Spinner Tool सिंबल स्पिनर टूल + Symbol Sprayer सिंबल स्प्रेयर + Symbol Sprayer Tool सिंबल स्प्रेयर टूल + Symbol Stainer सिंबल स्टेनर + Symbol Stainer Tool सिंबल स्टेनर टूल + Symbol Styler सिंबल स्टाइलर + Symbol Styler Tool सिंबल स्टाइलर टूल + Symbol Type: सिंबल टाइप: + Symbolism Tool प्रतीकवाद टूल + Symbolism Tools Options प्रतीकवाद टूल ऑप्शन्स + Symbols सिंबल्स + Syntax newer than ES3 ES3 की तुलना में सिंटैक्स नया + System सिस्टम + System Layout सिस्टम लेआउट + System Title Bar सिस्टम टाइटल बार + Tab Tab + Tab Stops टैब स्टॉप्स + Table तालिका + Tablet 1024×1366 टैबलेट 1024 × 1366 + Tablet 1024×768 टैबलेट 1024 × 768 + Tablet 768×1024 टैबलेट 768 × 1024 + Tablet 800×1280 टैबलेट 800 × 1280 + Tablet 820×1180 टैबलेट 820 × 1180 + Tablet 834×1194 टैबलेट 834 × 1194 + Tabloid टैबलॉयड + Tabs टैब + Tabular Lining टैबुलर लाइनिंग + Tabular Oldstyle टैबुलर ओल्डस्टाइल + Tag टैग + Tag (open) टैग (ओपन) + Tail: पूंछ: + Tamil तमिल + Taper टेपर + Target लक्ष्य + Target Contents लक्ष्य सामग्री + Target: लक्ष्य: + Tate-chu-yoko ताते-चू-योको + Tate-chu-yoko Settings ताते-चू-योको सेटिंग्स + Tate-chu-yoko Settings… ताते-चू-योको सेटिंग्स… + Technical Drawing तकनीकी ड्राइंग + Telugu तेलुगु + Temperature तापमान + Temperature/Tint तापमान / तापमान + Temperature/Tint… तापमान / टिंट… + Template टेम्पलेट + Template literal not closed टेम्पलेट साक्षर नहीं बंद + Templates टेम्पलेट्स + Templates Folder टेम्पलेट्स फ़ोल्डर + Templates… टेम्पलेट्स… + Tetrad टेट्राड + Tetrad 2 टेट्राड 2 + Tetrad 3 टेट्राड 3 + Text टेक्स्ट + Text and Path टेक्स्ट और पाथ + Text Displayed in Cell टेक्स्ट सेल में प्रदर्शित + Text Displayed in Cell: टेक्स्ट सेल में प्रदर्शित: + Text Export Options टेक्स्ट निर्यात ऑप्शन्स + Text Fill & Stroke Color टेक्स्ट फिल एंड स्ट्रोक कलर + Text Fill Color टेक्स्ट फिल कलर + Text Flow टेक्स्ट प्रवाह + Text Import Options टेक्स्ट आयात ऑप्शन्स + Text Only केवल टेक्स्ट + Text Orientation टेक्स्ट अभिविन्यास + Text Stroke Color टेक्स्ट स्ट्रोक कलर + Text Tweaker टेक्स्ट ट्वीकर + Text Tweaker… टेक्स्ट ट्वीकर… + Text Wrap टेक्स्ट लपेटना + Text Wrap Options टेक्स्ट रैप ऑप्शन्स + Text Wrap Options… टेक्स्ट्यचर्या ऑप्शन्स… + Text: टेक्स्ट: + Texture टेक्सचर + Texture Coverage टेक्सचर कवरेज + Texture Image बनावट इमेज + Texturizer टेक्सचराइज़र + Texturizer… टेक्सचराइज़र… + Thai थाई + The active document changed while the screen color sampler was open स्क्रीन कलर सैंपलर खुला रहने के दौरान एक्टिव डॉक्यूमेंट बदल गया + The art keeps its own colors. कला अपने स्वयं के रंग रखता है। + The bounds of the visible art. दृश्य कला की सीमा। + The cell shows the type object's text as HTML. सेल HTML के रूप में टाइप ऑब्जेक्ट के टेक्स्ट को दिखाता है। + The dialog was closed before its file dialog answered संवाद अपनी फ़ाइल से पहले बंद कर दिया गया था संवाद जवाब दिया + The document has no colour swatches. डॉक्यूमेंट में कोई कलर स्वॉच नहीं है। + The document was closed while its file dialog was open डॉक्यूमेंट बंद हो गया था जबकि इसकी फ़ाइल संवाद खुला था + The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. कागज़ का वह किनारा जहाँ प्रिंटर प्रिंट नहीं कर सकता: आर्टवर्क इस सीमा के अंदर रहता है और प्रीव्यू में सीमा डैश लाइन से दिखती है। + The file is too large to read in full, so only its first part is listed. फ़ाइल पूर्ण रूप से पढ़ने के लिए बहुत बड़ी है, इसलिए केवल इसका पहला हिस्सा सूचीबद्ध है। + The file writes keys and modifiers as codes. Check the proposed meanings and answer the codes that are not known yet. फ़ाइल कोड के रूप में कुंजी और संशोधक लिखती है। प्रस्तावित अर्थों की जाँच करें और उन कोडों का उत्तर दें जो अभी तक ज्ञात नहीं हैं। + The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. मुख्य रंग स्ट्रोक का रंग बनता है। बाकी रंगों की ह्यू भी उतनी ही बदलती है; उनकी सैचुरेशन और ब्राइटनेस बनी रहती हैं। + The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents. सेव पैनल में नाम “{typed}” था; VectorCraft ने फ़ाइल टाइप का एक्सटेंशन जोड़ दिया। फ़ाइल रिप्लेस करने पर उसका पुराना डेटा ओवरराइट होगा। + The page as it prints जैसा कि यह प्रिंट करता है, पेज + The plug-in is computing… प्लग-इन कंप्यूटिंग है… + The plug-in writes the whole document. प्लग-इन पूरे डॉक्यूमेंट को लिखते हैं। + the preset पूर्व निर्धारित + The Print Tiling tool placed the pages. प्रिंट टाइलिंग टूल ने पृष्ठों को रखा। + The samples show this brush on a blue stroke. नमूने इस ब्रश को ब्लू स्ट्रोक पर दिखाते हैं। + The search stopped at its limit: search a smaller folder. सर्च अपनी लिमिट तक पहुँच गई: छोटे फ़ोल्डर में सर्च करें। + The selected character's font is not available. सिलेक्टेड चरित्र का फ़ॉन्ट उपलब्ध नहीं है। + The selected objects have no CSS of their own (see below). सिलेक्टेड ऑब्जेक्ट का अपना CSS नहीं है (नीचे देखें)। + The system's settings of this printer इस प्रिंटर की प्रणाली की सेटिंग + These fonts aren't available. Their text shows in another font. ये फ़ॉन्ट उपलब्ध नहीं हैं। इनका टेक्स्ट दूसरे फ़ॉन्ट में दिखता है। + Thickness मोटाई + Thickness: मोटाई: + Thin Space थिन स्पेस + Third Space थर्ड स्पेस + Third Vanishing Point: तीसरा गायब बिंदु: + This document already has a swatch named “{name}” with another color. इस डॉक्यूमेंट में “{name}” नाम का स्वॉच पहले से है, लेकिन उसका रंग अलग है। + This library is empty यह लाइब्रेरी खाली है + This library is empty. यह लाइब्रेरी खाली है। + This panel is on the roadmap (see the parity plan). यह पैनल रोडमैप पर है (पारिटी प्लान देखें)। + This system has no screen color sampler इस प्रणाली में कोई स्क्रीन रंग नमूना नहीं है + Thread Text थ्रेड टेक्स्ट + Threaded Text थ्रेडेड टेक्स्ट + Threads धागा + Three Point तीन बिंदु + Three Point Perspective तीन बिंदु पर्सपेक्टिव + Three Point Perspective Preset 1 तीन बिंदु पर्सपेक्टिव पूर्व निर्धारित 1 + Three Point Perspective Preset 2 तीन बिंदु पर्सपेक्टिव पूर्व निर्धारित 2 + Three Point Perspective Preset 3 तीन बिंदु पर्सपेक्टिव पूर्व निर्धारित 3 + Three Point Perspective Preset 4 तीन बिंदु पर्सपेक्टिव पूर्व निर्धारित 4 + Three Point Perspective Preset 5 तीन बिंदु पर्सपेक्टिव पूर्व निर्धारित 5 + Threshold थ्रेशहोल्ड + Thumbnail View थंबनेल देखें + Thumbnails: थंबनेल: + TIFF (8-bit Color) TIFF (8-बिट रंग) + TIFF (Black & White) TIFF (ब्लैक एंड व्हाइट) + Tile टाइल + tile {number} टाइल {number} + Tile Edge Color टाइल एज रंग + Tile Edge Color… टाइल एज रंग… + Tile Full Pages टाइल पूर्ण पृष्ठ + Tile Imageable Areas टाइल कल्पनाशील क्षेत्र + Tile Range: टाइल रेंज: + Tile Size टाइल साइज़ + Tile Type: टाइल प्रकार: + Tiles are numbered across, then down; leave the range empty for every tile. टाइल नंबर पहले बाएँ से दाएँ, फिर नीचे चलते हैं। सभी टाइल के लिए रेंज खाली रखें। + Tilt झुकाव + Time (hhmmss) समय (hhmms) + Tint टिंट + Tint Reduction टिंट में कमी + Tints टिंट्स + Tints and Shades टिंट्स और शेड्स + Tiny Handles टिनी हैंडल + Tiny Lens छोटा लेंस + Tip extends past the end point टिप अंत बिंदु तक फैला हुआ है + Tip on the end point अंत बिंदु पर टिप + Tip: युक्ति: + Tips सुझाव + Title Case शीर्षक प्रकरण + Titling Alternates टाइटलिंग ऑप्शन + to तक + To: तक: + Toggle Fill/Stroke Focus फ़िल/स्ट्रोक फ़ोकस बदलें + Toggle Line Composer लाइन कंपोज़र बदलें + Toggle Selection सिलेक्शन टॉगल करें + Toggle single/double column सिंगल/डबल कॉलम बदलें + Tolerance टॉलरेंस + Tolerance: टॉलरेंस: + Tone 1 टोन 1 + Tone 2 टोन 2 + Tone 3 टोन 3 + Tone 4 टोन 4 + Too large to check जांच करने के लिए बहुत बड़ा + Tool टूल + Tool Option टूल ऑप्शन + Tool Options… टूल ऑप्शन्स… + Toolbar: Add Tool टूलबार: ऐड टूल + Toolbar: Advanced / Basic टूलबार: उन्नत / बुनियादी + Toolbar: Remove Tool टूलबार: टूल निकालें + Toolbar: Reset टूलबार: रीसेट करें + Toolbar: Show Controls टूलबार: शो कंट्रोल + Toolbar: Single/Double Column टूलबार: सिंगल / डबल कॉलम + Toolbars टूलबार्स + Tools टूल्स + Tools take a single key (optionally with Shift) टूल्स एक कुंजी लेते हैं (वैकल्पिक रूप से Shift के साथ) + Tooth Height: टूथ ऊंचाई: + Top ऊपर + Top in Front फ्रंट में शीर्ष + Top Left ऊपर बाएँ + Top Left: ऊपर बाएँ: + Top Right ऊपर दाएँ + Top Right: ऊपर दाएँ: + Top to Bottom नीचे की ओर + Top-Justified Tab ऊपर-संरेखित टैब + Top-to-Top Leading ऊपर से ऊपर लीडिंग + Top: ऊपर: + Torn Edges फटे किनारे + Torn Edges… फटे किनारे… + Total Width: कुल चौड़ाई: + Total: कुल: + Touch Type टच टाइप + Touch Type Tool टच टाइप टूल + Trace ट्रेस करें + Trace the image with the Default preset डिफ़ॉल्ट प्रीसेट के साथ इमेज को ट्रेस करें + Tracing Presets ट्रेसिंग प्रीसेट + Tracing Result रिक्ति परिणाम + Tracing Result with Outlines Outlines के साथ परिणाम ट्रेसिंग + Tracing the colors… रंग अनुरेखण… + Tracking ट्रैकिंग + Trackpad Gesture to Rotate View दृश्य घुमाने के लिए ट्रैकपैड जेस्चर + Trademark Symbol ट्रेडमार्क सिंबल + Transform रूपांतरण करें + Transform Again फिर से बदलना + Transform Both दोनों को बदलना + Transform Each प्रत्येक को बदलना + Transform Each… प्रत्येक ट्रांसफॉर्मर… + Transform in Perspective पर्सपेक्टिव में रूपांतरण + Transform Object Only केवल ऑब्जेक्ट को ट्रांसफॉर्म करें + Transform Objects ऑब्जेक्ट को रूपांतरित करें + Transform options ट्रांसफॉर्म ऑप्शन्स + Transform Panel ट्रांसफॉर्म पैनल + Transform Pattern Only केवल ट्रांसफॉर्म पैटर्न + Transform Pattern Tiles ट्रांसफॉर्म पैटर्न टाइलें + Transform Patterns ट्रांसफॉर्म पैटर्न + Transform Tools टूल बदलना + Transform… रूपांतरण करें… + Transforms रूपांतरण + Transparency पारदर्शिता + Transparency Flattener Presets ट्रांसपेरेंसी फ़्लैटनर प्रीसेट्स + Transparency Flattener Presets… ट्रांसपेरेंसी फ़्लैटनर प्रीसेट्स… + Transparency Grid पारदर्शिता ग्रिड + Transparency Info पारदर्शिता की जानकारी + Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour. प्रीसेट के अनुसार ट्रांसपेरेंसी फ़्लैट होती है। टाइप आउटलाइन के रूप में और ग्रेडिएंट रंगों की पट्टियों के रूप में लिखे जाते हैं। + Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth. प्रीसेट के अनुसार ट्रांसपेरेंसी फ़्लैट होती है। टाइप आउटलाइन के रूप में लिखा जाता है; ग्रेडिएंट स्मूद रहते हैं। + Transparency Options पारदर्शिता ऑप्शन्स + Transparent पारदर्शी + Transparent (Default) पारदर्शी (डिफ़ॉल्ट) + Transparent Background पारदर्शी पृष्ठभूमि + Transparent Images: पारदर्शी इमेज: + Transparent Objects पारदर्शी ऑब्जेक्टएं + Transpose ट्रांसपोज़ + Transverse (the page a quarter turn on the paper) ट्रांसवर्स (पेपर पर एक चौथाई मोड़ पृष्ठ) + Trap ट्रैप + Trap… ट्रैप… + Traps with Process Color प्रक्रिया रंग के साथ जाल + Triad त्रिदाद + Triad 2 त्रिद 2 + Triad 3 त्रिक 3 + Triangle त्रिभुज + Triangle (open) त्रिभुज (ओपन) + Triangle to Bar त्रिभुज से बार + Trim ट्रिम करें + Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. अपीयरेंस एक्सपैंड करने पर ढकी हुई ज्यामिति ट्रिम करें। लाइव प्रीव्यू पूरी सतह रखता है। ट्रांसपेरेंट पेंट और विज़िबिलिटी लिमिट से बड़ी सतहों के सभी फेस बने रहते हैं। + Trim mark weight: ट्रिम मार्क वजन: + Trim marks ट्रिम अंक + Trim View ट्रिम देखें + True Colors असली रंग + True colour needs version 2004 or later: the nearest of 256 colours is written. ट्रू कलर के लिए संस्करण 2004 या बाद का चाहिए: अभी 256 रंगों में सबसे निकट वाला रंग लिखा जाता है। + Turkish तुर्की + Turn off Data Recovery for complex documents जटिल डॉक्यूमेंट्स के लिए डेटा रिकवरी बंद करें + Turn the Contour into plain paths कंटूर को सादे रास्ते में बदल दें + Tweak… ट्वीक… + Twirl ट्वर्ल + Twirl Rate: ट्वर्ल दर: + Twirl Tool ट्वर्ल टूल + Twist मरोड़ + Twist… मरोड़… + Two Point दो बिंदु + Two Point Perspective दो बिंदु पर्सपेक्टिव + Two Point Perspective Preset 1 दो बिंदु पर्सपेक्टिव पूर्व निर्धारित 1 + Two Point Perspective Preset 2 दो बिंदु पर्सपेक्टिव पूर्व निर्धारित 2 + Two Point Perspective Preset 3 दो बिंदु पर्सपेक्टिव पूर्व निर्धारित 3 + Two Point Perspective Preset 4 दो बिंदु पर्सपेक्टिव पूर्व निर्धारित 4 + Two Point Perspective Preset 5 दो बिंदु पर्सपेक्टिव पूर्व निर्धारित 5 + Type टाइप + Type becomes outlines, and strokes a CAD line can't draw become filled shapes. टाइप आउटलाइन बनता है। जिन स्ट्रोक्स को CAD लाइन नहीं दिखा सकती, वे फ़िल की हुई शेप बनते हैं। + Type Object Selection by Path Only टाइप ऑब्जेक्ट केवल पाथ से सिलेक्ट करें + Type on a Path पाथ पर टाइप + Type on a Path Options पाथ पर टाइप ऑप्शन्स + Type on a Path Options… पाथ पर टाइप ऑप्शन्स… + Type on a Path Tool पाथ पर टाइप टूल + Type Optimized टाइप ऑप्टिमाइज़ + Type Orientation प्रकार अभिविन्यास + Type stays text, and every stroke is a line with its lineweight and dashes. टाइप टेक्स्ट बना रहता है। हर स्ट्रोक अपने लाइनवेट और डैश वाली लाइन बनता है। + Type Tool टाइप टूल + Type Tools प्रकार टूल + Type: प्रकार: + Type… टाइप… + Typing टाइपिंग + UI Brightness यूआई चमक + UI Scaling यूआई स्केलिंग + Unbind Variable वेरिएबल का बंधन हटाएँ + Underline अंडरलाइन + Underpainting अंडरपेंटिंग + Underpainting… अंडरपेंटिंग… + Undo पूर्ववत करें + Undo {} {} पूर्ववत करें + Undo {name} {name} पूर्ववत करें + Unembed एम्बेड हटाएँ + Unembed… एम्बेड हटाएँ… + Unembedded to {} Unembed to {} + Ungroup समूह तोड़ें + Ungroup Color Group रंग समूह का ग्रूपिंग हटाएँ + Unicode यूनिकोड + Unicode (UTF-16) यूनिकोड (UTF-16) + Unicode (UTF-8) यूनिकोड (UTF-8) + Uniform एकसमान + Uniformly Scaled वर्दी स्केल + Unique अनोखा + Unite मिलाएँ + Unite and Simplify एकजुट और सरलीकरण + Units इकाइयाँ + Units & Scale इकाइयों और स्केल + Units: इकाइयाँ: + Units: {units} इकाईयां: {units} + Unknown अज्ञात + Unknown directive अज्ञात निर्देश + Unlink harmony colors सामंजस्य रंगों का लिंक हटाएँ + Unlink Opacity Mask ओपेसिटी मास्क का लिंक हटाएँ + Unlink the mask मास्क को अनलिंक करें + Unlock अनलॉक करें + Unlock All सभी अनलॉक करें + Unlock All Layers सभी लेयर्स अनलॉक + Unlock Artboards अनलॉक आर्टबोर्ड + Unlock Grid अनलॉक ग्रिड + Unlock Guides अनलॉक गाइड + Unlock Selected सिलेक्टेड आइटम अनलॉक करें + Unlock Variables वेरिएबल्स अनलॉक करें + Unnamed Objects नामरहित ऑब्जेक्टएं + Unpainted Objects अनपेक्षित ऑब्जेक्टएं + Unprintable margin: अनप्रिंटेबल मार्जिन: + Unselected Artwork अनसिलेक्टेड आर्टवर्क + Unsharp Mask अनशार्प मास्क + Unsharp Mask… अनशार्प मास्क… + Unshift अनशिफ़्ट + Unsorted बिना क्रम + Untitled शीर्षकहीन + Up (right reading) ऊपर (सीधा पढ़ने योग्य) + Up/Down: ऊपर/नीचे: + Update Changed Links अद्यतन परिवर्तित लिंक + Update Data Set डेटा सेट अद्यतन करें + Update Dimensions अद्यतन आयाम + Update Link अद्यतन लिंक + Update Links अद्यतन लिंक + Update Modified Links अद्यतन संशोधित लिंक + Update Selection अद्यतन सिलेक्शन + UPPERCASE अपरकैस + Urdu उर्दू + URL: यूआरएल: + Use उपयोग + Use Artboards आर्टबोर्ड का उपयोग करें + Use Black Point Compensation ब्लैक पॉइंट मुआवजा का उपयोग करें + Use Compression संपीड़न का उपयोग करें + Use Default डिफ़ॉल्ट का उपयोग करें + Use document bleed settings डॉक्यूमेंट की ब्लीड सेटिंग्स उपयोग करें + Use Document Raster Effects Resolution डॉक्यूमेंट के रास्टर इफ़ेक्ट्स का रिज़ॉल्यूशन उपयोग करें + Use Even-Odd Fill Rule यहां तक कि-Odd भरण नियम का उपयोग करें + Use Japanese Crop Marks जापानी फसल मार्क्स का प्रयोग करें + Use Library Item लाइब्रेरी आइटम का उपयोग करें + Use Low Resolution Proxy for Linked EPS लिंक्ड ईपीएस के लिए कम रिज़ॉल्यूशन प्रॉक्सी का उपयोग करें + Use Non-Zero Winding Fill Rule गैर-ज़ीरो विंडिंग फिल नियम का उपयोग करें + Use Outside Rectangle As Frame बाहर आयत फ्रेम के रूप में उपयोग करें + Use Precise Cursors सटीक कर्सर का उपयोग करें + Use Pressure Pen दबाव पेन का प्रयोग करें + Use Preview Bounds प्रीव्यू बाउंड्स का उपयोग करें + Use Registration Point for Symbol सिंबल के लिए रजिस्ट्रेशन पॉइंट उपयोग करें + Use Square for Previews प्रीव्यू के लिए स्क्वायर का उपयोग करें + Use System Defaults for Edit Original सिस्टम डिफ़ॉल्ट का उपयोग करने के लिए संपादित करें मूल + Use Text for Previews प्रीव्यू के लिए टेक्स्ट का उपयोग करें + Use the document's swatch: pasted colors take its color. डॉक्यूमेंट की घड़ी का उपयोग करें: पेस्ट किए गए रंग अपना रंग लेते हैं। + Use the Selected Text's Font सिलेक्टेड टेक्स्ट के फ़ॉन्ट का उपयोग करें + Use Typographer's Quotes टाइपोग्राफ़िक उद्धरण चिह्न उपयोग करें + User Brush Library 1 उपयोगकर्ता ब्रश लाइब्रेरी 1 + User Brush Library 10 उपयोगकर्ता ब्रश लाइब्रेरी 10 + User Brush Library 2 उपयोगकर्ता ब्रश लाइब्रेरी 2 + User Brush Library 3 उपयोगकर्ता ब्रश लाइब्रेरी 3 + User Brush Library 4 उपयोगकर्ता ब्रश लाइब्रेरी 4 + User Brush Library 5 उपयोगकर्ता ब्रश लाइब्रेरी 5 + User Brush Library 6 उपयोगकर्ता ब्रश लाइब्रेरी 6 + User Brush Library 7 उपयोगकर्ता ब्रश लाइब्रेरी 7 + User Brush Library 8 उपयोगकर्ता ब्रश लाइब्रेरी 8 + User Brush Library 9 उपयोगकर्ता ब्रश लाइब्रेरी 9 + User Defined उपयोगकर्ता परिभाषित + User Defined Libraries उपयोगकर्ता परिभाषित लाइब्रेरी + User Graphic Style Library 1 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 1 + User Graphic Style Library 10 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 10 + User Graphic Style Library 2 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 2 + User Graphic Style Library 3 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 3 + User Graphic Style Library 4 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 4 + User Graphic Style Library 5 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 5 + User Graphic Style Library 6 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 6 + User Graphic Style Library 7 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 7 + User Graphic Style Library 8 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 8 + User Graphic Style Library 9 उपयोगकर्ता ग्राफिक स्टाइल लाइब्रेरी 9 + User Interface उपयोगकर्ता इंटरफ़ेस + User Library उपयोगकर्ता लाइब्रेरी + User Preset उपयोगकर्ता Preset + User Swatch Library 1 यूज़र स्वॉच लाइब्रेरी 1 + User Swatch Library 10 यूज़र स्वॉच लाइब्रेरी 10 + User Swatch Library 2 यूज़र स्वॉच लाइब्रेरी 2 + User Swatch Library 3 उपयोगकर्ता स्वॉच लाइब्रेरी 3 + User Swatch Library 4 यूज़र स्वॉच लाइब्रेरी 4 + User Swatch Library 5 यूज़र स्वॉच लाइब्रेरी 5 + User Swatch Library 6 यूज़र स्वॉच लाइब्रेरी 6 + User Swatch Library 7 यूज़र स्वॉच लाइब्रेरी 7 + User Swatch Library 8 यूज़र स्वॉच लाइब्रेरी 8 + User Swatch Library 9 यूज़र स्वॉच लाइब्रेरी 9 + User Symbol Library 1 यूज़र सिंबल लाइब्रेरी 1 + User Symbol Library 10 यूज़र सिंबल लाइब्रेरी 10 + User Symbol Library 2 यूज़र सिंबल लाइब्रेरी 2 + User Symbol Library 3 यूज़र सिंबल लाइब्रेरी 3 + User Symbol Library 4 यूज़र सिंबल लाइब्रेरी 4 + User Symbol Library 5 यूज़र सिंबल लाइब्रेरी 5 + User Symbol Library 6 यूज़र सिंबल लाइब्रेरी 6 + User Symbol Library 7 यूज़र सिंबल लाइब्रेरी 7 + User Symbol Library 8 यूज़र सिंबल लाइब्रेरी 8 + User Symbol Library 9 यूज़र सिंबल लाइब्रेरी 9 + Username यूज़रनेम + Uses every data set of the open document. खुला डॉक्यूमेंट के प्रत्येक डेटा सेट का उपयोग करता है। + UTF-16 (Unicode) UTF-16 (Unicode) + V Spacing: वी स्पेसिंग: + V: V: + Value Axis मूल्य एक्सिस + Variable चर + Variable Font वेरिएबल फ़ॉन्ट + Variable Options वैरिएबल ऑप्शन्स + Variable Options… परिवर्तनीय ऑप्शन्स… + Variable Width Profile वैरिएबल चौड़ाई प्रोफ़ाइल + Variables वेरिएबल्स + Variation वैरिएशन + Variation: भिन्नता: + Vector Effects वेक्टर इफ़ेक्ट + Vector Halftone वेक्टर हाफ़टोन + Vector Halftone… वेक्टर हाफ़टोन… + Vector illustration — fast, open, scriptable. वेक्टर चित्रण - तेज, खुला, स्क्रिप्टेबल। + VectorCraft {release} and later (version {n}) VectorCraft {release} और बाद के संस्करण (संस्करण {n}) + VectorCraft copies the fonts to {folder}. VectorCraft फ़ॉन्ट को {folder} में कॉपी करता है। + VectorCraft Default VectorCraft डिफ़ॉल्ट + VectorCraft Defaults VectorCraft डिफ़ॉल्ट + VectorCraft didn't quit normally last time. These documents had unsaved changes: पिछली बार VectorCraft सामान्य तरीके से बंद नहीं हुआ था। इन डॉक्यूमेंट्स में बिना सेव किए बदलाव थे: + VectorCraft documents: one locked object, updated when the file changes. VectorCraft डॉक्यूमेंट्स: एक लॉक्ड ऑब्जेक्ट, जो फ़ाइल बदलने पर अपडेट होता है। + VectorCraft Generic CMYK (SWOP-like) वेक्टर क्रेफ्ट जेनेरिक CMYK (SWOP-like) + VectorCraft Help… VectorCraft मदद… + VectorCraft on getartcraft.com getartcraft.com पर VectorCraft + VectorCraft on GitHub GitHub पर VectorCraft + VectorCraft read this script without running it. VectorCraft ने इस स्क्रिप्ट को रन किए बिना पढ़ा। + VectorCraft Swatches (.vcswatches) वेक्टर क्रेफ्ट Swatches (.vcswatches) + VectorCraft Updates वेक्टर क्रेफ्ट अपडेट + Vectors वेक्टर + Version संस्करण + Version {version} — open-source vector illustration in pure Rust. संस्करण {version} — पूरी तरह Rust में बना ओपन-सोर्स वेक्टर इलस्ट्रेशन ऐप। + Version: संस्करण: + Vertical लंबवत + Vertical % अनुलंब % + Vertical Align वर्टिकल संरेखित + Vertical Align Bottom वर्टिकल संरेखित नीचे + Vertical Align Center ऊर्ध्वाधर संरेखित केंद्र + Vertical Align Top वर्टिकल संरेखित टॉप + Vertical Area Type वर्टिकल एरिया टाइप + Vertical Area Type Tool वर्टिकल एरिया टाइप टूल + Vertical Distribute Bottom वर्टिकल डिस्ट्रिब्यूट बॉटम + Vertical Distribute Center वर्टिकल डिस्ट्रिब्यू सेंटर + Vertical Distribute Space लंबवत स्पेस वितरित करें + Vertical Distribute Top वर्टिकल डिस्ट्रिब्यूट टॉप + Vertical Dividers: ऊर्ध्वाधर विभाजक: + Vertical Guide वर्टिकल गाइड + Vertical Scale लंबवत स्केल + Vertical Scale % वर्टिकल स्केल % + Vertical Type लंबवत टाइप + Vertical Type on a Path पाथ पर वर्टिकल टाइप + Vertical Type on a Path Tool पाथ पर वर्टिकल टाइप टूल + Vertical Type Tool वर्टिकल टाइप टूल + Vertical: लंबवत: + Vertically Scaled लंबवत स्केल + Very High बहुत अधिक + Video वीडियो + Video 1920×1080 1920 × 1080 वीडियो + Video 3840×2160 वीडियो 3840 × 2160 + Video Banner 2560×1440 वीडियो बैनर 2560 × 1440 + Video Ruler Pixel Aspect Ratio: वीडियो शासक पिक्सेल दृष्टि अनुपात: + Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720 + View व्यू + View {n} {n} + View Artboard Only केवल आर्टबोर्ड देखें + View Opacity Mask ओपेसिटी मास्क देखें + View PDF after saving सेव करने के बाद PDF देखें + View: व्यू: + Viewing Angle: देखने का कोण: + Viewing Distance: देखने की दूरी: + Violet बैंगनी + Visibility दृश्यता + Visible & Printable Layers दृश्यमान और प्रिंट करने योग्य लेयरें + Visible Layers दृश्यमान लेयरें + Vivid विद + Volume आयतन + W: W: + Warm गर्म + Warnings चेतावनी + Warp मोड़ें + Warp Options वार्प ऑप्शन्स + Warp Tool वार्प टूल + Watch 184×224 घड़ी 184 × 224 + Watch 198×242 देखें 198 × 242 + Water Paper वॉटर पेपर + Water Paper… वॉटर पेपर… + Watercolor वॉटरकलर + Watercolor… वॉटरकलर… + Wave… वेव… + Web 1024×768 वेब 1024 × 768 + Web 1280×720 वेब 1280 × 720 + Web 1280×800 वेब 1280 × 800 + Web 1366×768 वेब 1366 × 768 + Web 1440×900 वेब 1440 × 900 + Web 1600×900 वेब 1600 × 900 + Web 1920×1080 वेब 1920×1080 + Web Safe 216 वेब सुरक्षित 216 + Web Safe RGB वेब सुरक्षित RGB + Web Shift वेब शिफ्ट + Web Snap: वेब स्नैप: + WebP WebP + Weight वज़न + Weight: वज़न: + Welcome to VectorCraft VectorCraft में आपका स्वागत है + When pasting text जब टेक्स्ट चिपकाना + White सफ़ेद + White Intensity सफ़ेद की तीव्रता + Wide Blurry चौड़ा धुंधला + Wide Sharp चौड़ा तीक्ष्ण + Widget Position: विजेट स्थिति: + Width चौड़ाई + Width and Height चौड़ाई और ऊँचाई + Width Point चौड़ाई बिंदु + Width Point Edit चौड़ाई पॉइंट संपादित करें + Width Point Edit… चौड़ाई पॉइंट संपादित करें… + Width Profile चौड़ाई प्रोफ़ाइल + Width Profiles चौड़ाई प्रोफ़ाइल + Width Tool चौड़ाई टूल + Width: चौड़ाई: + Window विंडो + Windows Windows + Word Spacing: शब्द स्पेसिंग: + Words Longer Than: से ज्यादा शब्द: + Working CMYK वर्किंग CMYK + Working CMYK (don't tag) कार्य CMYK (टैग नहीं) + Working RGB वर्किंग RGB + Workspace वर्कस्पेस + Workspace {i} वर्कस्पेस {i} + Wrinkle शिकन + Wrinkle Tool शिकन टूल + Write Layers लेयर लिखें + Writes, moves or deletes files फ़ाइलों को राइट्स, मूव या डिलीट करता है + x Height x ऊँचाई + X Position X स्थिति + x-height x-ऊँचाई + x-Height x-ऊँचाई + X: X: + X11 (XWayland) X11 (XWayland) + X11 (XWayland) When a Pen Is Attached पेन कनेक्ट होने पर X11 (XWayland) + XML ID XML ID + XML literal not closed XML लिटरल बंद नहीं है + Y Position वाई स्थिति + Y: Y: + Yards यार्ड + Yellow पीला + Yes हाँ + Yonroku-ban योनरोकु-बान + Your browser downloads the files (several as one .zip). आपका ब्राउज़र फ़ाइलों को डाउनलोड करता है (एक ज़िप के रूप में कई)। + Your changes will be lost if you don't save them. यदि आप उन्हें नहीं बचाते हैं तो आपका परिवर्तन खो जाएगा। + Zero-Opacity Objects शून्य-ऑपेसिटी ऑब्जेक्ट + Zig Zag… ज़िग ज़ैग… + Zoom ज़ूम + Zoom In ज़ूम इन + Zoom Out ज़ूम आउट + Zoom to Selection सिलेक्ट करने के लिए ज़ूम + Zoom Tool ज़ूम टूल + Zoom with Mouse Wheel माउस व्हील के साथ ज़ूम +@id file.close बंद करें +@id pathfinder.add मिलाएँ +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees “{_1}” अधिक संसाधन माँगता है (हर रन में {minutes} मिनट और सामान्य से {times} गुना निर्देश): उपयोगकर्ता की सहमति मिलने पर इसे `allowHeavy: true` से इंस्टॉल करें +@msg "{0}" is not a colour: write it as #rrggbb "{0}" एक रंग नहीं है: इसे #rrggbb के रूप में लिखें +@msg “{name}” is not a file "{name}" एक फ़ाइल नहीं है +@msg ({note}) ({more}) ({note}) ({more}) +@msg (fonts not copied: {fonts}) (फ़ॉन्ट कॉपी नहीं हुए: {fonts}) +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} पिक्सेल {_3} के लिए बहुत बड़ा है (अधिकांश {max} पिक्सेल एक तरफ): पैमाने को कम करें +@msg {_1} bytes of RGBA data for a {width} × {height} image {_1} एक {width} × {height} इमेज के लिए RGBA डेटा के बाइट्स +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1} पढ़ा नहीं जा सकता है, या तब से बदल सकता है क्योंकि यह पढ़ा गया था: इसे फिर से लिंक करें या अपडेट करें +@msg {_1} can't go into {into} {_1} {into} में नहीं जा सकता है +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1} कम रिज़ॉल्यूशन के लिए प्रिंटिंग को सीमित नहीं कर सकते: PDF 1.4 या बाद में चुनें, या उच्च-रिज़ॉल्यूशन प्रिंटिंग की अनुमति दें +@msg {_1} cannot be used on Windows {_1} का उपयोग विंडोज पर नहीं किया जा सकता है +@msg {_1} failed: {e} {_1} विफल: {e} +@msg {_1} files {_1} फ़ाइलें +@msg {_1} files are written by file.saveAsTemplate {_1} फ़ाइलें file.saveAsTemplate से लिखी जाती हैं +@msg {_1} files can be opened but not written (see document.formats) {_1} फ़ाइलें ओपन हो सकती हैं, लेकिन लिखी नहीं जा सकतीं (document.formats देखें) +@msg {_1} files can't be {_2} {_1} फ़ाइलें {_2} नहीं हो सकती हैं +@msg {_1} files can't be opened yet {_1} फ़ाइलों को अभी तक ओपन किया नहीं जा सकता है +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1} फ़ाइलों को पासवर्ड से सुरक्षित नहीं किया जा सकता है: पासवर्ड को हटा दें या कोई मानक नहीं चुनें +@msg {_1} files can't carry editing data: turn off preserveEditing {_1} फ़ाइलों में एडिटिंग डेटा नहीं रह सकता: preserveEditing बंद करें +@msg {_1} files can't have PDF layers: turn off createLayers {_1} फ़ाइलों में PDF लेयर्स नहीं रह सकतीं: createLayers बंद करें +@msg {_1} files need a creation date, and this platform has no clock to give one {_1} फ़ाइलों को सृजन की तारीख की आवश्यकता होती है, और इस प्लेटफॉर्म को एक देने के लिए कोई घड़ी नहीं है। +@msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} समाप्त हो गया, लेकिन डॉक्यूमेंट या प्लग-इन इस बीच बदल गया: इसे फिर से चलाएं +@msg {_1} font families available {_1} फ़ॉन्ट परिवारों उपलब्ध +@msg {_1} has no {_2} style {_1} में कोई {_2} स्टाइल नहीं है +@msg {_1} is {_2} bytes (limit {_3}) {_1} {_2} बाइट्स (limit {_3}) है। +@msg {_1} is a live effect (Effect › Plug-ins) {_1} एक लाइव इफ़ेक्ट (इफ़ेक्टी> प्लग-इन) है। +@msg {_1} is already used by {_2} {_1} का उपयोग पहले से ही {_2} द्वारा किया जाता है +@msg {_1} is an exporter (File › Export › Export As…) {_1} एक निर्यातक (फ़ाइल> निर्यात › निर्यात As...) है। +@msg {_1} is not a file {_1} एक फ़ाइल नहीं है +@msg {_1} is reserved by the system {_1} सिस्टम द्वारा आरक्षित है +@msg {_1} isn't a path {_1} एक पाथ नहीं है +@msg {_1} MB of document, at most {_2} MB {_1} MB of document, at most {_2} MB +@msg {_1} MB of images, at most {_2} MB {_1} MB of images, at most {_2} MB +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} ऑब्जेक्ट्स (limit {MAX_OBJECTS}) +@msg {_1} options: {e} {_1} ऑप्शन्स: {e} +@msg {_1} paints nothing to rasterize {_1} कुछ भी नहीं पेंट करता है +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1} पासवर्ड के पास {MAX_LEGACY_PASSWORD} ASCII वर्ण (PDF 1.7) और बाद में कोई लेना) हो सकता है। +@msg {_1} with linked images or an image map writes several files: use document.export {_1} जुड़े इमेज या एक इमेज मानचित्र के साथ कई फ़ाइलें लिखते हैं: document.export का उपयोग करें +@msg {_1} writes one file per artboard here: use document.export, or name one artboard {_1} प्रति आर्टबोर्ड एक फ़ाइल लिखता है: document.export का उपयोग करें, या एक आर्टबोर्ड नाम दें +@msg {_1}: belongs to another account {_1}: किसी अन्य खाते से संबंधित है +@msg {_1}: not a folder of its own {_1}: अपने खुद के फ़ोल्डर नहीं +@msg {_1}: not a plain file {_1}: एक सादे फ़ाइल नहीं +@msg {_1}: not saved, so not closed {_1}: बचाया नहीं गया, इसलिए बंद नहीं हुआ +@msg {_1}: they came in as the page's art {_1}: वे पृष्ठ की कला के रूप में आए +@msg {at}: {msg} {at}: {msg} +@msg {bpp}-bit bitmaps can't be read {bpp}-bit bitmaps पढ़ा नहीं जा सकता +@msg {C}: no effect at index {from} {C}: इंडेक्स {from} पर कोई इफ़ेक्ट नहीं +@msg {C}: no effect at index {list} {C}: इंडेक्स {list} पर कोई इफ़ेक्ट नहीं +@msg {command} didn't create an object {command} ने एक ऑब्जेक्ट नहीं बनाई थी +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} संरक्षित है और रहता है +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} संरक्षित है: किसी अन्य नाम के तहत सेटिंग्स को सेव करना +@msg {depth}-bit PSD files in this colour mode can't be read इस रंग मोड में {depth}-bit PSD फ़ाइलों को पढ़ा नहीं जा सकता है +@msg {dest}: {e} {dest}: {e} +@msg {doc} has no folder {doc} में कोई फ़ोल्डर नहीं है +@msg {file} isn't linked {file} लिंक्ड नहीं है +@msg {folder} is not a package folder {folder} एक पैकेज फ़ोल्डर नहीं है +@msg {folder}: {e} {folder}: {e} +@msg {folder}: more than {max} files and folders {folder}: {max} फ़ाइलों और फ़ोल्डरों से अधिक +@msg {g} is not a Live Paint group {g} एक लाइव पेंट समूह नहीं है +@msg {id} is no top-level layer {id} कोई शीर्ष स्तर की लेयर नहीं है +@msg {id} is not a slice {id} एक स्लाइस नहीं है +@msg {id} opens another app: only the person at the keyboard can run it {id} एक अन्य ऐप खोलता है: केवल कीबोर्ड पर व्यक्ति इसे चला सकता है +@msg {k} `{v}` is not one of the choices {k} `{v}` ऑप्शन में से एक नहीं है +@msg {k} has control characters{_1} {k} में नियंत्रण वर्ण हैं{_1} +@msg {k} is too long (at most {MAX_TEXT} characters) {k} बहुत लंबा है (अधिकांश {MAX_TEXT} वर्णों पर) +@msg {k} must be {{size?, position?}} {k} को {{size?, position?}} होना चाहिए +@msg {k} must be > 0 {k} होना चाहिए > 0 +@msg {k} must be a number (pt) or a length such as "210 mm" {k} को एक नंबर (pt) या "210 मिमी" जैसी लंबाई होना चाहिए। +@msg {k} must be a number from {min} to {max} {k} को {min} से {max} के बीच की संख्या होना चाहिए +@msg {k} must be a number or "auto" {k} एक नंबर या "ऑटो" होना चाहिए। +@msg {k} must be a string {k} एक स्ट्रिंग होना चाहिए +@msg {k} must be text {k} को टेक्स्ट होना चाहिए +@msg {k} must be true or false {k} को सच या झूठा होना चाहिए +@msg {k}: can't read `{s}` as a length {k}: `{s}` को लंबाई के रूप में नहीं पढ़ा जा सकता +@msg {key} must be [x, y] with finite coordinates {key} को [x, y] होना चाहिए, जिसमें परिमित निर्देशांक होंगे। +@msg {key} must be [x,y] {key} होना चाहिए [x,y]] +@msg {key} must be {_1}, got {s} {key} होना चाहिए {_1}, {s} होना चाहिए। +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key} होना चाहिए 0-{MAX_ADD_AROUND} pt +@msg {key} must be a finite coordinate {key} एक परिमित निर्देशांक होना चाहिए +@msg {key} must be a percentage {min}..100 {key} को {min}..100 के बीच प्रतिशत होना चाहिए +@msg {key} must be a positive number, not {n} {key} एक सकारात्मक संख्या होना चाहिए, नहीं {n} +@msg {key} must be a positive number, not {v} {key} एक सकारात्मक संख्या होना चाहिए, नहीं {v} +@msg {key} must be an array of non-negative integer object ids {key} को गैर-नकारात्मक पूर्णांक ऑब्जेक्ट ids की एक सरणी होना चाहिए +@msg {key} must be one of {_1} {key} {_1} में से एक होना चाहिए +@msg {key} must be Unix seconds (an integer) or null {key} को यूनिक्स सेकंड (एक पूर्णांक) या null होना चाहिए +@msg {key} must name a floating panel {key} को फ्लोटिंग पैनल का नाम होना चाहिए +@msg {key} must name a panel in another group {key} को किसी अन्य समूह में एक पैनल का नाम देना चाहिए +@msg {key} must name a panel that shows {key} को एक पैनल का नाम देना चाहिए जो दिखाता है +@msg {key} must name a registered panel {key} एक पंजीकृत पैनल का नाम होना चाहिए +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} फ़ाइलों में पारदर्शिता नहीं होती और इस फ़ाइल में {what} होगा: पहले इसे फ़्लैट करें (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind} इमेज ओपन नहीं हो सकतीं (document.formats देखें) +@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} वर्तमान में एक पाथ या यौगिक पाथ की आवश्यकता होती है। पहले पाथ के लिए प्रकार, इमेज और समूहों को परिवर्तित करें। +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} डॉक्यूमेंट के {n} आर्टबोर्ड में से 1 रखता है: फ़ाइल एक के साथ फिर से खुलती है। उन्हें रखने के लिए संरक्षित संपादन क्षमताओं को चालू करें। +@msg {label} must be a number {label} एक नंबर होना चाहिए +@msg {label} must be a number above 0 and at most {max} {label} 0 से ऊपर और सबसे {max} पर होना चाहिए +@msg {label} must be a number at most {max} {label} सबसे {max} पर एक नंबर होना चाहिए +@msg {label} must be a number from -1296 to 1296 {label} को -1296 से 1296 के बीच की संख्या होना चाहिए +@msg {label} must be a number from {min} to {max} {label} को {min} से {max} तक एक नंबर होना चाहिए +@msg {label} must be a number from 1 to 10000 {label} को 1 से 10000 तक एक नंबर होना चाहिए +@msg {label} must be a number of at least 0.1 {label} को कम से कम 0.1 होना चाहिए। +@msg {label} produced an empty result {label} ने खाली परिणाम का उत्पादन किया +@msg {LABEL} produced an empty result {LABEL} ने खाली परिणाम का उत्पादन किया +@msg {label} requires a shape with at least two anchors {label} को कम से कम दो एंकरों के साथ एक आकार की आवश्यकता होती है +@msg {label}: lost track of a shape's style {label}: एक आकार की स्टाइल का ट्रैक खो गया +@msg {label}: select paths {label}: चुनें पाथ +@msg {label}: select paths, compound paths, groups or text {label}: चुनें पाथ, यौगिक पाथ, समूह या टेक्स्ट +@msg {label}… {label}... +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name} बनाया गया है और इसे हटाया नहीं जा सकता है। +@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} को {lo}-{hi}{unit} ({v}) होना चाहिए। +@msg {name}: {e} {name}: {e} +@msg {name}: CRC mismatch {name}: CRC mismatch +@msg {name}: CRC or size mismatch {name}: CRC or size mismatch +@msg {name}: no local header {name}: कोई स्थानीय हैडर नहीं +@msg {name}: no such recovery entry {name}: ऐसी कोई वसूली प्रविष्टि नहीं +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: केवल इस Affinity फ़ाइल के एम्बेडेड प्रीव्यू को पढ़ा जा सकता है; फ़ाइल का उपयोग करें > इसे अपनी चेतावनी के साथ देखने के लिए ओपन करें, या SVG या PDF को Affinity से पहले निर्यात करें। +@msg {native}; its embedded preview can't be read either ({e}) {native}; इसका एम्बेड किया प्रीव्यू भी पढ़ा नहीं जा सका ({e}) +@msg {note}) ({more} {note} ({more}) +@msg {path} can't be found: relink it first {path} पाया नहीं जा सकता: इसे पहली बार फिर से लिंक करें +@msg {path} is not a folder {path} एक फ़ोल्डर नहीं है +@msg {path}: {e} {path}: {e} +@msg {path}: no file system here (pass dataBase64 to open; omit the path to get dataBase64) {path}: यहाँ फ़ाइल सिस्टम नहीं है (ओपन करने के लिए dataBase64 दें; dataBase64 पाने के लिए पाथ न दें) +@msg {path}: not a file {path}: एक फ़ाइल नहीं +@msg {status} ({e}) {status} ({e}) +@msg {std} files are CMYK, and the file would have colours in {_1} {std} फ़ाइलें CMYK हैं, और फ़ाइल में {_1} में रंग होंगे। +@msg {std} files embed their fonts, and the file would have one that isn't {std} फ़ाइलें अपने फ़ॉन्ट एम्बेड करती हैं, और फ़ाइल में एक ऐसा होता है जो नहीं है। +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway यह डॉक्यूमेंट {target} से पढ़ा गया था और पढ़ते समय कुछ चीज़ें छूट गईं ({what}): उसी फ़ाइल पर लिखने से वे स्थायी रूप से खो जाएँगी। दूसरी फ़ाइल लिखें या फिर भी बदलने के लिए acknowledgeLoss: true दें +@msg {tool} isn't in a toolbar group of several tools {tool} कई टूल्स के टूलबार समूह में नहीं है +@msg {ty} brushes need selected art (or params.{k}) {ty} ब्रश के लिए सिलेक्टेड आर्टवर्क (या params.{k}) चाहिए +@msg {v} is not an asset id {v} एक परिसंपत्ति आईडी नहीं है +@msg {what} can't be intertwined {what} अंतर नहीं किया जा सकता है +@msg {what} doesn't fit the paper with its bleed and marks {what} अपने ब्लेड और मार्क्स के साथ पेपर को फिट नहीं करता है +@msg {what} points outside memory {what} स्मृति के बाहर अंक +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} {MAX_TILES} टाइल्स से अधिक प्रिंट करेगा: इसे नीचे स्केल करें +@msg `{_1}` can't be edited or removed `{_1}` को संपादित या हटाया नहीं जा सकता है +@msg `{_1}` has no brushes to apply `{_1}` को लागू करने के लिए कोई ब्रश नहीं है +@msg `{_1}` has no symbols to place `{_1}` के पास कोई सिंबल नहीं है +@msg `{_1}` is a {_2}, not an exporter `{_1}` एक {_2} है, एक निर्यातक नहीं है +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect"}"}} `{_1}` एक लाइव इफ़ेक्ट है: इसे effect.apply {{"effect"}"}} के साथ लागू करें +@msg `{_1}` is an exporter: export with document.export {{"format"}"}} `{_1}` एक एक्सपोर्टर है: document.export {{"format"}"}} से एक्सपोर्ट करें +@msg `{_1}` is built in and always listed `{_1}` बनाया गया है और हमेशा सूचीबद्ध है +@msg `{_1}` is no save command `{_1}` कोई बचत आदेश नहीं है +@msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}` पिछली text.findFontFiles सर्च में मिली फ़ॉन्ट फ़ाइल नहीं है +@msg `{_1}` would be overwritten by the package: choose a different folder or name `{_1}` पैकेज द्वारा ओवरराइट किया जाएगा: एक अलग फ़ोल्डर या नाम चुनें +@msg `{_1}`: {msg} `{_1}`: {msg} +@msg `{area}` is no recovery area name `{area}` कोई वसूली क्षेत्र का नाम नहीं है +@msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` एक रंग नहीं है (#rrggbb या एक पूर्व निर्धारित नाम) +@msg `{f}` belongs to a VectorCraft that is running `{f}` एक VectorCraft से संबंधित है जो चल रहा है +@msg `{f}` is the copy of a document open now `{f}` एक डॉक्यूमेंट की प्रतिलिपि है जो अब खुला है +@msg `{file}` has no art to place `{file}` के पास कोई कला नहीं है +@msg `{file}` is over {_1} MB `{file}` is over {_1} MB +@msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` एक VectorCraft डॉक्यूमेंट नहीं है, एक PDF या एक PDF-compatible.ai फ़ाइल +@msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` एक लाइब्रेरी पैनल नहीं है (देखें window.swatchLibrary) +@msg `{id}` has no envelope dialog `{id}` में कोई लिफाफा संवाद नहीं है +@msg `{id}` is no writable format (see document.formats) `{id}` लिखने योग्य फ़ॉर्मैट नहीं है (document.formats देखें) +@msg `{id}` is not a colour adjustment `{id}` एक रंग समायोजन नहीं है +@msg `{id}` isn't a loaded library `{id}` एक लोड लाइब्रेरी नहीं है +@msg `{k}.family` is required `{k}.family` की आवश्यकता है +@msg `{k}` is a number 0..1 `{k}` एक नंबर 0..1 है। +@msg `{k}` is true or false `{k}` सही या झूठ है +@msg `{k}` isn't an export setting: {_1} `{k}` एक निर्यात सेटिंग नहीं है: {_1} +@msg `{k}` must be [x, y] `{k}` होना चाहिए [x, y] +@msg `{k}` must be {what} `{k}` होना चाहिए {what} +@msg `{k}` must be {what}, not {v} `{k}` होना चाहिए {what}, नहीं {v} +@msg `{k}` must be a byte offset `{k}` को एक बाइट ऑफ़सेट होना चाहिए +@msg `{k}` must be a number `{k}` होना चाहिए +@msg `{k}` must be a number of points `{k}` को कई अंक होना चाहिए +@msg `{k}` must be a string `{k}` एक स्ट्रिंग होना चाहिए +@msg `{k}` must be a whole number `{k}` होना चाहिए +@msg `{k}` must be from {lo} to {hi} for {key} `{k}` होना चाहिए {lo} से {hi} {key} के लिए +@msg `{k}` must be one of {_1} `{k}` को {_1} में से एक होना चाहिए +@msg `{keep}` is not a side of this axis `{keep}` इस अक्ष का एक पक्ष नहीं है +@msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` और `options.{key}: {inner}` असहमति: एक बार ऑप्शन्स देना +@msg `{key}` has no colours `{key}` में कोई रंग नहीं है +@msg `{key}` is a design name `{key}` एक डिजाइन नाम है +@msg `{key}` is a design name or a list of them `{key}` एक डिजाइन नाम या उनकी सूची है +@msg `{key}` is longer than {MAX_NAME} characters `{key}` {MAX_NAME} अक्षरों से अधिक लंबा है +@msg `{key}` is out of range `{key}` रेंज से बाहर है +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` को प्रतिशत में [min, desired, max] या {{min?, desired?, max?}} होना चाहिए +@msg `{key}` must be [x, y, width, height]: four finite numbers, width and height not negative `{key}` होना चाहिए [x, y, चौड़ाई, ऊंचाई]: चार परिमित संख्या, चौड़ाई और ऊंचाई नकारात्मक नहीं है +@msg `{key}` must be [x, y] `{key}` होना चाहिए [x, y] +@msg `{key}` must be `auto` or a language code such as `en` or `zh-hant` `{key}` को `auto` या `en` या `zh-hant` जैसे भाषा कोड होना चाहिए। +@msg `{key}` must be 0..{max} `{key}` होना चाहिए 0.{max} +@msg `{key}` must be a #rrggbb color `{key}` एक #rrggbb रंग होना चाहिए +@msg `{key}` must be a #rrggbb colour `{key}` एक #rrggbb रंग होना चाहिए +@msg `{key}` must be a non-negative integer `{key}` को एक गैर-नकारात्मक पूर्णांक होना चाहिए +@msg `{key}` must be a number `{key}` होना चाहिए +@msg `{key}` must be a number {_1}..{_2} `{key}` होना चाहिए a number {_1}.{_2} +@msg `{key}` must be a number not below 0 `{key}` को 0 से नीचे नहीं होना चाहिए +@msg `{key}` must be a number, not {v} `{key}` एक नंबर होना चाहिए, नहीं {v} +@msg `{key}` must be a profile name or null `{key}` को प्रोफ़ाइल नाम या null होना चाहिए +@msg `{key}` must be a string `{key}` एक स्ट्रिंग होना चाहिए +@msg `{key}` must be a whole number `{key}` होना चाहिए +@msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` को {min} और {max} ({x}) के बीच पूरी संख्या होना चाहिए। +@msg `{key}` must be a whole number of at least 0, not {n} `{key}` को कम से कम 0 की पूरी संख्या होना चाहिए, नहीं {n} +@msg `{key}` must be an appearance item index (paint order) or null `{key}` एक उपस्थिति आइटम सूचकांक (पेंट ऑर्डर) या null होना चाहिए +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` को परिसंपत्ति ids की एक सरणी होना चाहिए (देखें परिसंपत्तियों.list) +@msg `{key}` must be an array of these names: {_1} `{key}` इन नामों की एक सरणी होना चाहिए: {_1} +@msg `{key}` must be between {min} and {max} (got {x}) `{key}` को {min} और {max} ({x}) के बीच होना चाहिए। +@msg `{key}` must be from {_1} to {shift_max} `{key}` को {_1} से {shift_max} होना चाहिए +@msg `{key}` must be from {lo} to {hi} `{key}` को {lo} से {hi} होना चाहिए। +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}` 0 से 180 डिग्री तक होना चाहिए, नहीं {a} +@msg `{key}` must be one of {_1} `{key}` को {_1} में से एक होना चाहिए +@msg `{key}` must be true or false `{key}` को सच या झूठ होना चाहिए +@msg `{key}`: not a colour: {v} `{key}`: कोई रंग नहीं: {v} +@msg `{l}` isn't a global or spot colour `{l}` एक वैश्विक या स्पॉट रंग नहीं है +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText `{m}` एक बिटमैप नहीं है: clipboard.importSvg, importPdf या importText का उपयोग करें +@msg `{min_key}` is greater than `{max_key}` `{min_key}` `{max_key}` से अधिक है +@msg `{n}` can't be deleted `{n}` को हटाया नहीं जा सकता +@msg `{n}` can't be merged `{n}` को विलय नहीं किया जा सकता है +@msg `{n}` can't be moved `{n}` को स्थानांतरित नहीं किया जा सकता है +@msg `{n}` is not a colour swatch `{n}` एक रंग की घड़ी नहीं है +@msg `{n}` isn't a solid colour `{n}` एक ठोस रंग नहीं है +@msg `{n}`: colour groups hold solid colours only `{n}`: रंग समूहों में केवल ठोस रंग होते हैं +@msg `{name}` can't be deleted `{name}` को हटाया नहीं जा सकता है +@msg `{name}` can't be duplicated `{name}` को दोहराया नहीं जा सकता है +@msg `{name}` can't be edited `{name}` को संपादित नहीं किया जा सकता है +@msg `{name}` can't be edited this way `{name}` को इस तरह से संपादित नहीं किया जा सकता है +@msg `{name}` can't be renamed `{name}` का नाम बदल नहीं जा सकता है +@msg `{name}` can't name a folder `{name}` किसी फ़ोल्डर को नाम नहीं दे सकता है +@msg `{name}` has no art to place `{name}` के पास कोई कला नहीं है +@msg `{name}` has no options `{name}` का कोई ऑप्शन्स नहीं है +@msg `{name}` has no text to place `{name}` में कोई टेक्स्ट नहीं है +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text वर्ड डॉक्यूमेंट में `{name}` UTF-8 या UTF-16 टेक्स्ट नहीं है +@msg `{name}` in the Word document is not well-formed XML: {e} Word डॉक्यूमेंट में `{name}` अच्छी तरह से निर्मित XML नहीं है: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep Word डॉक्यूमेंट घोंसले में `{name}` {MAX_NESTING} गहरी से अधिक तत्वों +@msg `{name}` is a built-in preset and can't change: save it under another name `{name}` एक अंतर्निहित प्रीसेट है और इसे बदल नहीं सकता है: इसे दूसरे नाम के तहत सेव करें +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` एक अंतर्निहित प्रीसेट है और इसे केवल पढ़ा जाता है: इसे दूसरे नाम के तहत सेव करें +@msg `{name}` is a built-in preset and stays `{name}` एक अंतर्निहित प्रीसेट है और रहता है +@msg `{name}` is a built-in preset: save under another name `{name}` एक अंतर्निहित प्रीसेट है: किसी अन्य नाम के तहत सेव करें +@msg `{name}` is a built-in profile and stays `{name}` एक अंतर्निहित प्रोफ़ाइल है और रहता है +@msg `{name}` is a built-in workspace; choose another name `{name}` एक अंतर्निहित वर्कस्पेस है; एक और नाम चुनें +@msg `{name}` is a process colour: tints apply to global and spot colours `{name}` एक प्रक्रिया रंग है: टिंट वैश्विक और स्पॉट रंगों पर लागू होते हैं +@msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` एक स्थिर सिंबल है: अपने सिंबल प्रकार को पहले गतिशील करने के लिए सेट करें +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}` `{base}` का एक टिंट है: `{base}` संपादित करें (केवल एक टिंट swatch केवल एक नया नाम लेता है) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` वर्किंग स्पेस है: पहले edit.colorSettings से दूसरा चुनें +@msg `{name}` is built in and stays `{name}` बनाया गया है और रहता है +@msg `{name}` is no recovery entry name `{name}` कोई वसूली प्रविष्टि नाम नहीं है +@msg `{name}` isn't a colour swatch `{name}` is not a color swatch +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` अपने खुद के प्रकार (रंग, ग्रेडिएंट या पैटर्न) का एक रंग लेता है। +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम इच्छा से अधिक नहीं होना चाहिए, न ही इच्छा अधिकतम +@msg `{other}` doesn't trace an image `{other}` एक इमेज का पता नहीं लगा +@msg `{path}` must be a bool or an object of bools `{path}` एक bool होना चाहिए या एक ऑब्जेक्ट होना चाहिए। +@msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` एक रंग नहीं है (#rrggbb या एक पूर्व निर्धारित नाम) +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: चरण के संदर्भ मूल्य के {_1} MB से अधिक में प्रतिलिपि बनाते हैं +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" `{tag}` एक अक्ष टैग नहीं है: एक टैग चार वर्ण हैं, जैसे कि "wght" +@msg `{text}`: step {i}'s result has no such value (write $$ for a literal $) `{text}`: चरण {i} के परिणाम में ऐसा कोई मूल्य नहीं है (एक साक्षर $ के लिए $$ लिखना) +@msg `{text}`: there is no step {i} before this one (steps count from 0; write $$ for a literal $) `{text}`: इस से पहले कोई स्टेप {i} नहीं है (स्टेप 0 से गिनते हैं; $$ को साक्षर $ के लिए लिखें) +@msg `{to}` is empty or already used `{to}` खाली है या पहले से ही इस्तेमाल किया जाता है +@msg `{to}` is not an available name `{to}` उपलब्ध नहीं है +@msg `{tool}` isn't a freehand tool `{tool}` एक फ्रीहैंड टूल नहीं है +@msg `{tool}` isn't a Liquify tool `{tool}` एक Liquify टूल नहीं है +@msg `{w}` takes no operands `{w}` का कोई संचालन नहीं होता है +@msg `{what}` closes nothing `{what}` कुछ भी बंद नहीं है +@msg `{what}` closes something it didn't open `{what}` कुछ बंद कर देता है जिसे यह नहीं खोलता +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` {MAX_TEXT} bytes से अधिक लंबा है +@msg `{what}` must be text `{what}` को टेक्स्ट होना चाहिए +@msg `a` and `b` must be two different paths `a` और `b` को दो अलग-अलग पाथ होना चाहिए +@msg `align` is start, center or end `align` शुरू, केंद्र या अंत है +@msg `align` must be "left", "center" or "right", not {other} `align` होना चाहिए "left", "सेंटर" या "right", नहीं {other} +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` को [subpath, एंकर] जोड़े की एक सारणी होना चाहिए +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` में एंकर इंडेक्स (0, 1, 2…) की सूची होनी चाहिए, {k} नहीं +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` में एंकर इंडेक्स (0, 1, 2…) की सूची होनी चाहिए, {v} नहीं +@msg `artboards` must be a list of artboard indices `artboards` को आर्टबोर्ड इंडेक्स की सूची होना चाहिए +@msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all या 1, 3-5 जैसी सीमा दें, {v} नहीं +@msg `aspect` must be a number (%) `aspect` को संख्या (%) होना चाहिए +@msg `asset` is the asset id (see assets.list) `asset` परिसंपत्ति आईडी है (aset.list देखें) +@msg `at` must be [x, y] `at` होना चाहिए [x, y] +@msg `at` must be a byte offset `at` to be a byte ऑफसेट +@msg `autoLeading` must be a number `autoLeading` को संख्या होना चाहिए +@msg `background` must be "", "matte" or #rrggbb `background` होना चाहिए "", "matte" या #rrggbb +@msg `burasagari` must be "none", "standard" or "forced" `burasagari` होना चाहिए "none", "standard" या "forced" +@msg `by` must be lines, paragraphs, words or glyphs, not {other} `by` होना चाहिए लाइनों, पैराग्राफ, शब्द या glyphs, नहीं {other} +@msg `center` must be [x, y] `center` होना चाहिए [x, y] +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign` को "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" या "icfBottom" होना चाहिए +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection` होना चाहिए "default", "leftToRight" या "rightToLeft" +@msg `clear` must be a list of type object ids, not {v} `clear` को टाइप ऑब्जेक्ट ids की सूची होनी चाहिए, न कि {v} +@msg `clear` must list type objects; {_1} is not one `clear` को टाइप ऑब्जेक्ट्स को सूचीबद्ध करना चाहिए; {_1} एक नहीं है +@msg `clear` must not list `id` `clear` में `id` नहीं होना चाहिए +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke` के लिए `stroke: false`, `ids: []` चाहिए और `stop` नहीं होना चाहिए +@msg `color` is not a colour `color` एक रंग नहीं है +@msg `color` must be a colour `color` एक रंग होना चाहिए +@msg `color` needs a `rule` to make the theme from `color` को `rule` की आवश्यकता होती है ताकि विषय को बनाया जा सके +@msg `colorGroup` needs `library: "document"` `colorGroup` के लिए `library: "document"` चाहिए +@msg `colorGroup` needs `mode: "color"` `colorGroup` की जरूरत है `mode: "color"`````` +@msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup` की जरूरत है `palette: "documentLibrary"``` +@msg `colors` is empty `colors` खाली है +@msg `columns` must be a whole number 1..50 `columns` को 1..50 के बीच पूर्णांक होना चाहिए +@msg `columnType` is vertical, uniform, repeating or sliding `columnType` को vertical, uniform, repeating या sliding होना चाहिए +@msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` एक ऐसा कमांड होना चाहिए जिसका मेनू आइटम एक संवाद खोलता है (ui.menuDialog देखें) +@msg `commands` must not be empty `commands` को खाली नहीं होना चाहिए +@msg `contents` goes with `to` `contents` के साथ `to` दें +@msg `corners` must be an array of anchor indices, not {v} `corners` को एंकर इंडेक्स की ऐरे होना चाहिए, {v} नहीं +@msg `corners` must be sharp, round or square, not `{other}` `corners` को sharp, round या square होना चाहिए, `{other}` नहीं +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners` में एंकर इंडेक्स (0, 1, 2…) की सूची होनी चाहिए, {v} नहीं +@msg `count` must be a whole number from 1 to 100 `count` 1 से 100 तक पूरी संख्या होना चाहिए +@msg `count` must be a whole number from 3 to 1000 `count` 3 से 1000 तक पूरी संख्या होना चाहिए +@msg `Custom` stands for changed settings: save the preset under another name `Custom` बदली हुई सेटिंग्स दिखाता है: प्रीसेट दूसरे नाम से सेव करें +@msg `dataBase64` is larger than the module limit `dataBase64` मॉड्यूल सीमा से बड़ा है +@msg `dataBase64` is not valid base64 `dataBase64` मान्य नहीं है base64 +@msg `datasetFileNaming` must be `fileNumber`, `fileDataSetName` or `dataSetName` `datasetFileNaming` होना चाहिए `fileNumber`, `fileDataSetName` या `dataSetName` +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` को `ids`, `reverse` या `append` के साथ उपयोग नहीं कर सकते +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` और `childLimit` सारांश के हिस्से चुनते हैं: `summary: true` दें +@msg `design` is a design name, or null for plain columns `design` एक डिजाइन नाम है, या सादे स्तंभों के लिए null है +@msg `design` is a design name, or null for the default marker `design` एक डिजाइन नाम है, या डिफ़ॉल्ट मार्कर के लिए null है +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination` को `none`, `saveAndClose` या `folder` होना चाहिए। +@msg `destinationFolder` is required when destination is `folder` `destinationFolder` की आवश्यकता तब होती है जब गंतव्य `folder` होता है। +@msg `diameter` must be from 0.1 to 2500 pt `diameter` को 0.1 से 2500 pt होना चाहिए +@msg `diameter` must be from 0.25 to 200 pt `diameter` को 0.25 से 200 pt होना चाहिए +@msg `digits` must be one of {_1} `digits` को {_1} में से एक होना चाहिए +@msg `dimImages` is a percentage or false `dimImages` एक प्रतिशत या झूठी है +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction` को "ऑटो", "leftToRight" या "rightToLeft" होना चाहिए +@msg `dither` applies to gradient fills (paint.setFill) `dither` gradient fills (paint.setFill) पर लागू होता है +@msg `dither` applies to gradient fills (stroke: false) `dither` gradient fills (स्ट्रोक: झूठी) पर लागू होता है +@msg `dither` must be true or false `dither` को सच या झूठा होना चाहिए +@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` {size} bytes (limit {MAX_DOCUMENT_DATA}) है। +@msg `each` is the value one design stands for, more than 0 `each` एक डिज़ाइन का मान है, जो 0 से अधिक होना चाहिए +@msg `end` must be "start" or "end" `end` को " start" या "end" होना चाहिए। +@msg `ends` applies to joining exactly two paths `ends` वास्तव में दो पाथ में शामिल होने के लिए लागू होता है +@msg `event` must be one of {_1} `event` is one of the {_1} +@msg `every` must be "all", "odd" or "even", not {v} `every` होना चाहिए "all", "odd" या "even", नहीं {v} +@msg `expand` must be true or false `expand` को सच या झूठ होना चाहिए +@msg `exportPreset` is the name of a preset of document.exportPresets.list `exportPreset`, document.exportPresets.list के किसी प्रीसेट का नाम है +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` में पिछली text.findFontFiles सर्च में मिली फ़ॉन्ट फ़ाइलों के 1 से 1000 पाथ होने चाहिए +@msg `folder` must be an absolute folder path `folder` एक पूर्ण फ़ोल्डर पाथ होना चाहिए +@msg `follow` must be "average", "a" or "b" `follow` को "average", "a" या "b" होना चाहिए। +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` को अक्ष टैग और मानों का एक ऑब्जेक्ट होना चाहिए, जैसे कि {"wght"} +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` को "emBox", "capHeight", "xHeight" या "icfBox" होना चाहिए +@msg `format` must be a string `format` एक स्ट्रिंग होना चाहिए +@msg `format` must be one of {_1} `format` को {_1} में से एक होना चाहिए +@msg `fractions` is chop or scale `fractions` को chop या scale होना चाहिए +@msg `freeform.lines` must be an array `freeform.lines` एक सारणी होना चाहिए +@msg `freeform.points` must be an array `freeform.points` एक सारणी होना चाहिए +@msg `from` and `to` must differ `from` और `to` अलग होने चाहिए +@msg `from` has an empty frame `from` का फ़्रेम खाली है +@msg `from` must be a non-negative integer `from` को गैर-ऋणात्मक पूर्णांक होना चाहिए +@msg `from` must be area type or type on a path `from` को एरिया टाइप या पाथ पर टाइप होना चाहिए +@msg `gap` must be from 0 to 6 pt `gap` 0 से 6 तक होना चाहिए। +@msg `gid` must be a glyph id, not {v} `gid` एक glyph id होना चाहिए, नहीं {v} +@msg `globalAdjust` must be an object `globalAdjust` एक ऑब्जेक्ट होना चाहिए +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate` एक चरित्र से संबंधित है, एक चरित्र स्टाइल के लिए नहीं (text.setGlyphAlternate इसे सेट) +@msg `gradient` must be an object `gradient` एक ऑब्जेक्ट होना चाहिए +@msg `groupColors` must be an array `groupColors` को ऐरे होना चाहिए +@msg `guide` must be a guide index (guide.list) `guide` एक गाइड सूचकांक (guide.list) होना चाहिए। +@msg `hAlign` must be default, left, center or right `hAlign` डिफ़ॉल्ट, बाएं, केंद्र या दाएं होना चाहिए +@msg `id` is not a path `id` एक पाथ नहीं है +@msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` चरण संदर्भ {r} है, जो केवल `run` और `command_batch` का समाधान है। +@msg `id` must be a node id `id` एक नोड आईडी होना चाहिए +@msg `id` must be an object id, not {v} `id` एक ऑब्जेक्ट आईडी होना चाहिए, नहीं {v} +@msg `ids` must be an array of object ids, not {v} `ids` को ऑब्जेक्ट आईडी की ऐरे होना चाहिए, {v} नहीं +@msg `ids` must name Objects on Path groups or objects in them `ids` को ऑब्जेक्ट्स ऑन पाथ समूह या उनके ऑब्जेक्ट बताने चाहिए +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids` में अधिकतम {MAX_INSPECT_IDS} आईडी हो सकती हैं +@msg `imageMap` must be none, rectangle or polygon `imageMap` होना चाहिए कोई नहीं, आयत या बहुभुज +@msg `in` must be [x, y] `in` होना चाहिए [x, y]] +@msg `includeArtboardFill` must be true or false `includeArtboardFill` को true या false होना चाहिए +@msg `includeSubdirs` must be true or false `includeSubdirs` को true या false होना चाहिए +@msg `index` must be a point index `index` एक बिंदु सूचकांक होना चाहिए +@msg `index` must be a whole number or null `index` होना चाहिए पूरी संख्या या null होना चाहिए +@msg `indices` must be a non-empty array of item indices `indices` आइटम सूचकांकों की एक गैर-खाली सरणी होना चाहिए +@msg `items` is a list of {kind, item} `items` {kind, item} की सूची है +@msg `items` is empty `items` खाली है +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` को {{id, anchors?}} की सूची होना चाहिए, {v} नहीं +@msg `items` must be a list of {id, points} `items` को {id, points} की सूची होना चाहिए +@msg `items` must be an array of {{id, corners?}}, not {v} `items` को {{id, corners?}} की ऐरे होना चाहिए, {v} नहीं +@msg `items` must be an array of {id, anchors} `items` को {id, anchors} की ऐरे होना चाहिए +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida` होना चाहिए "none", "short", "medium", "long" या "stylistic"। +@msg `kind` is one of {_1} `kind` {_1} में से एक है +@msg `kind` must be "line" or "paragraph", not {other} `kind` होना चाहिए "line" या "paragraph", नहीं {other} +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind` होना चाहिए "round", "invertedRound" या "chamfer", नहीं {v} +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind` होना चाहिए `text`, `visibility`, `image` या `graph` +@msg `kind` must be a string `kind` एक स्ट्रिंग होना चाहिए +@msg `kind` must be image, noImage or htmlText `kind` को image, noImage या htmlText होना चाहिए +@msg `kind` must be one of: rectangle, ellipse, polygon, star, ring, arrow, cross, heart, gear, bubble `kind` में से एक होना चाहिए: आयत, अंडाकार, बहुभुज, स्टार, रिंग, तीर, क्रॉस, दिल, गियर, बुलबुला +@msg `kind` must be spotColors, colorEffects, rgbImages, cmykImages or grayImages `kind` को spotColors, colorEffects, rgbImages, cmykImages या grayImages होना चाहिए +@msg `kinds` must be a list of issue kinds `kinds` को जारी करने के प्रकार की सूची होना चाहिए +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku` होना चाहिए "one", "hard" या "soft" होना चाहिए। +@msg `label` must be a non-empty name of at most 200 characters `label` को 200 वर्णों में से एक गैर-खाली नाम होना चाहिए +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language` एक भाषा का नाम या टैग होना चाहिए, जैसे "तुर्की" या "tr" +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading` को 0.1 से 5000 तक होना चाहिए, या ऑटो के लिए शून्य होना चाहिए +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel` को "romanBaseline" या "emBoxTop" होना चाहिए +@msg `length` must be a number of at most 1000000 pt either way `length` को 1000000 pt में से एक होना चाहिए। +@msg `library` is a library id or name (see {list}) `library` एक लाइब्रेरी आईडी या नाम है ( {list} देखें) +@msg `line` must be true or false `line` को सही या झूठा होना चाहिए +@msg `method` must be classic or perceptual `method` क्लासिक या अवधारणात्मक होना चाहिए +@msg `min` is greater than `max` `min` अधिकतम `max` से अधिक है +@msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` और `maxAnchors` पूरे नंबर होना चाहिए +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°) `maxAngle` ({max_angle}°) से अधिक नहीं हो सकता है। +@msg `mode` applies to freeform gradients `mode` फ़्रीफ़ॉर्म ग्रेडिएंट्स पर लागू होता है +@msg `mode` must be "free", "keepAngles" or "symmetric" `mode` को "free", "keepAngles" या "symmetric" होना चाहिए +@msg `mode` must be "handles", "straight" or "smooth" `mode` को "handles", "straight" या "smooth" होना चाहिए +@msg `mode` must be "straight", "bezier" or "arc" `mode` को "straight", "bezier" या "arc" होना चाहिए +@msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए +@msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए +@msg `mojikumi` must be "none" or "lineEndHalf" `mojikumi` होना चाहिए "none" or "lineEndHalf" +@msg `name` is empty `name` खाली है +@msg `name` must be 1-64 printable characters `name` को 1-64 प्रिंट करने योग्य वर्ण होना चाहिए +@msg `names` is a list of preset names `names` प्रीसेट नामों की सूची है +@msg `names` lists preset names `names` प्रीसेट नामों की सूची देता है +@msg `names` must be a list of names `names` को नामों की सूची होना चाहिए +@msg `names` must be a list of swatch names `names` को स्वॉच नामों की सूची होना चाहिए +@msg `names` must be an array of style names `names` को स्टाइल नामों की ऐरे होना चाहिए +@msg `new` is a design name, or true `new` डिज़ाइन का नाम या true है +@msg `newName` is empty `newName` खाली है +@msg `params` must be an object `params` एक ऑब्जेक्ट होना चाहिए +@msg `path` must be a folder `path` एक फ़ोल्डर होना चाहिए +@msg `path` must be a path object `path` एक पाथ ऑब्जेक्ट होना चाहिए +@msg `pathfinder` must be an object `pathfinder` एक ऑब्जेक्ट होना चाहिए +@msg `pivot` must be a whole number from 0 to 8 `pivot` 0 से 8 तक पूरी संख्या होना चाहिए +@msg `points` must be a list of [x, y] points `points` को [x, y] अंक की एक सूची होना चाहिए +@msg `points` must be a list of point indexes `points` को पॉइंट इंडेक्स की सूची होना चाहिए +@msg `points` must be an array of point indices `points` को पॉइंट इंडेक्स की ऐरे होना चाहिए +@msg `points` must be point indexes `points` में पॉइंट इंडेक्स होने चाहिए +@msg `port` must be "in" or "out" `port` को "in" या "out" होना चाहिए। +@msg `position` is above or below `position` ऊपर या नीचे है +@msg `preserve` must be an object `preserve` एक ऑब्जेक्ट होना चाहिए +@msg `preset` must be a string `preset` एक स्ट्रिंग होना चाहिए +@msg `radius` must be from 0 to 1000000 pt `radius` 0 से 1000000 pt से होना चाहिए +@msg `ratio` must be from 0.1 to 0.5 `ratio` को 0.1 से 0.5 तक होना चाहिए +@msg `rect` must be [x, y, width, height] with a positive size `rect` होना चाहिए [x, y, चौड़ाई, ऊंचाई] एक सकारात्मक आकार के साथ +@msg `relation` must be overlap, inside or outside `relation` को ओवरलैप, अंदर या बाहर होना चाहिए +@msg `reversed` must be true or false `reversed` को सच या झूठ होना चाहिए +@msg `rotate` must be a finite number `rotate` एक परिमित संख्या होना चाहिए +@msg `rule` must be nonZero or evenOdd `rule` होना चाहिए nonZero or evenOdd होना चाहिए +@msg `sampleSize` must be 1, 3 or 5 `sampleSize` होना चाहिए 1, 3 या 5 +@msg `scale` must be a number in (0, 100] `scale` को (0, 100] के बीच की संख्या होना चाहिए +@msg `scope` must be "selection" or "document", not {other} `scope` को "सिलेक्शन" या "दस्ताव" होना चाहिए, न कि {other} +@msg `script` must be a string `script` एक स्ट्रिंग होना चाहिए +@msg `segment` must be "straight" or "curved" `segment` को "सीधे" या "ठीक" होना चाहिए। +@msg `select` must be true or false `select` को true या false होना चाहिए +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` श्रृंखला सूचकांकों की एक गैर-खाली सूची है +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes` को `type` या `valueAxis` की आवश्यकता होती है +@msg `shift` must be a number of points `shift` को कई अंक होना चाहिए +@msg `showCenter` must be true or false `showCenter` को सच या झूठ होना चाहिए +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification` को "fullJustify", "alignLeft", "alignCenter" या "alignRight" होना चाहिए। +@msg `size` is a percentage of the base text's size, 1 to 100 `size` आधार टेक्स्ट के आकार का एक प्रतिशत है, 1 से 100 +@msg `source` and `target` are the same object `source` और `target` एक ही ऑब्जेक्ट है +@msg `source` must be `folder` or `datasets` `source` होना चाहिए `folder` या `datasets` होना चाहिए +@msg `spacing` must be a number `spacing` होना चाहिए +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` को कई अंक, 0 या उससे अधिक, या "ऑटो" होना चाहिए। +@msg `start` must be a finite number `start` को परिमित संख्या होना चाहिए +@msg `starts` must be an array of anchor indices (or nulls) `starts` को एंकर इंडेक्स (या null) की ऐरे होना चाहिए +@msg `status` must be linked, embedded, missing or modified, or a list of them `status` को लिंक, एम्बेडेड, लापता या संशोधित किया जाना चाहिए, या उनमें से एक सूची +@msg `stop` must be a stop index `stop` एक स्टॉप इंडेक्स होना चाहिए +@msg `stops` must be an array `stops` एक सारणी होना चाहिए +@msg `story` styles the whole story: give no `start` or `end` `story` पूरी स्टोरी को स्टाइल करता है: `start` या `end` न दें +@msg `story` takes the whole story: give no `start` or `end` `story` पूरी स्टोरी लेता है: `start` या `end` न दें +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode` स्ट्रोक पर लागू होता है (स्ट्रोक: सच) +@msg `style` must be roman or japanese `style` को रोमन या जापानी होना चाहिए +@msg `subpaths` must be two integer indices `subpaths` होना चाहिए दो पूर्णांक सूचकांक +@msg `svg` must be an object of SVG options (see document.formats) `svg` को SVG ऑप्शन्स का ऑब्जेक्ट होना चाहिए (document.formats देखें) +@msg `symbol` must be a symbol name `symbol` एक सिंबल नाम होना चाहिए +@msg `t` must be a number from -0.98 to 0.98 `t` को -0.98 से 0.98 के बीच की संख्या होना चाहिए +@msg `t` must be from 0 to 1 `t` 0 से 1 तक होना चाहिए +@msg `target` must be "object" or "contents", not {v} `target` को "object" या "content" होना चाहिए, नहीं {v} +@msg `tint` applies to global and spot colours `tint` वैश्विक और स्पॉट रंगों पर लागू होता है +@msg `tint` goes with a global or spot `swatch` `tint` एक वैश्विक या स्थान `swatch` के साथ चला जाता है +@msg `tint` must be a number (%) `tint` एक नंबर होना चाहिए (%) +@msg `tint` needs a global or spot colour `tint` को वैश्विक या स्पॉट रंग की आवश्यकता होती है +@msg `to` is already threaded `to` पहले से ही पिरोया है +@msg `to` is the design's new name `to` डिजाइन का नया नाम है +@msg `to` must be "corner" or "smooth" `to` होना चाहिए "कॉर्नर" या "चिकना" होना चाहिए। +@msg `to` must be [x, y] `to` होना चाहिए [x, y]] +@msg `to` must be a closed path, area type or type on a path other than `from` `to` को बंद पाथ, एरिया टाइप या पाथ पर टाइप होना चाहिए और `from` से अलग होना चाहिए +@msg `to` must be a whole number `to` एक पूरी संख्या होना चाहिए +@msg `to` takes the rows of one object's stack, not aligned rows `to` एक ऑब्जेक्ट के स्टैक की पंक्तियों को लेता है, पंक्तियां संरेखित नहीं है +@msg `tolerance` must be from 0 to 3 pt `tolerance` को 0 से 3 pt के बीच होना चाहिए +@msg `tolerance` must be from 1 to 100 `tolerance` को 1 से 100 के बीच होना चाहिए +@msg `top` and `below` can't both be true `top` और `below` दोनों सच नहीं हो सकते +@msg `useLab` must be true or false `useLab` को सही या झूठ होना चाहिए +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign` डिफ़ॉल्ट, शीर्ष, मध्य, बेसलाइन या नीचे होना चाहिए +@msg `values` must be a list `values` एक सूची होना चाहिए +@msg `values` must be an object `values` एक ऑब्जेक्ट होना चाहिए +@msg `values` must name hex, rgb, cmyk, lab or gray `values` को हेक्स, rgb, cmyk, लैब या ग्रे नाम होना चाहिए +@msg `values` names a kind twice `values` नाम दो बार +@msg `version`, `description` or `author` is too long `version`, `description` या `author` बहुत लंबा है +@msg `warnings` must be a list of strings `warnings` स्ट्रिंग की एक सूची होना चाहिए +@msg `with` moves points, not a handle `with` पॉइंट मूव करता है, हैंडल नहीं +@msg `with` must be a list of at most 10000 spine point indexes `with` में अधिकतम 10000 स्पाइन पॉइंट इंडेक्स की लिस्ट होनी चाहिए +@msg a {_1} series can't go in a {_2} graph एक {_1} श्रृंखला एक {_2} ग्राफ में नहीं जा सकती +@msg a {width}×{height} screenshot's byte count overflows A {width}×{height} स्क्रीनशॉट की बाइट गिनती ओवरफ्लो +@msg a batch preview cannot switch documents एक बैच प्रीव्यू डॉक्यूमेंट्स को स्विच नहीं कर सकता +@msg a bitmap is empty एक बिटमैप खाली है +@msg a bitmap is too large to read बिटमैप पढ़ने के लिए बहुत बड़ा है +@msg a bristle brush name can have at most {max} characters: `{name}` has {count} ब्रिस्टल ब्रश का नाम सबसे {max} अक्षरों में हो सकता है: `{name}` में {count} है +@msg A browser with WebGPU or WebGL2 is required. WebGPU या WebGL2 के साथ एक ब्राउज़र की आवश्यकता है। +@msg a brush named `{nn}` exists `{nn}` नाम का ब्रश मौजूद है +@msg a calculation has no result, as in a division by zero एक गणना का कोई परिणाम नहीं है, जैसा कि एक विभाजन में शून्य द्वारा होता है +@msg a clipping path can't be attached to a path एक क्लिपिंग पाथ को एक पाथ से जोड़ा नहीं जा सकता है +@msg a clipping path can't take objects एक क्लिपिंग पाथ ऑब्जेक्ट नहीं ले सकता है +@msg a colour index is 0 to {_1}, not {n} एक रंग सूचकांक 0 से {_1} है, नहीं {n} +@msg a colour is an index, #rrggbb or a preset name, not {v} एक रंग एक सूचकांक, #rrggbb या एक पूर्व निर्धारित नाम है, नहीं {v} +@msg a container of the listed objects is gone सूचीबद्ध ऑब्जेक्ट्स का एक कंटेनर चला गया है +@msg a content stream can't be read एक सामग्री स्ट्रीम पढ़ा नहीं जा सकता +@msg a content stream isn't a stream एक कंटेंट स्ट्रीम स्ट्रीम नहीं है +@msg a design holds at most {_1} objects एक डिजाइन सबसे {_1} ऑब्जेक्ट्स पर रखती है +@msg a design needs a name एक डिजाइन को एक नाम की जरूरत है +@msg a dictionary grew too large शब्दकोश बहुत बड़ा हो गया +@msg a document keeps at most {_1} graph designs एक डॉक्यूमेंट सबसे {_1} ग्राफ डिजाइन पर रहता है +@msg a document keeps at most {_1} saved selections एक डॉक्यूमेंट अधिकांश {_1} सेव किए गए सिलेक्शनों पर रहता है +@msg a document keeps at most {_1} views एक डॉक्यूमेंट अधिकांश {_1} विचारों को रखता है +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files अधिकांश {MAX_SVG_SCRIPTS} जावास्क्रिप्ट फ़ाइलों पर एक डॉक्यूमेंट लिंक +@msg a document needs at least one artboard कम से कम एक आर्टबोर्ड की आवश्यकता होती है +@msg a document needs at least one layer डॉक्यूमेंट की कम से कम एक लेयर की आवश्यकता होती है +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard एक DXF ड्राइंग एक मूल है: पास useArtboards: कलाबोर्ड प्रति एक ड्राइंग के लिए सच +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes एक feConvolveMatrix फिल्टर का आदेश {x} ×{y} है, जो कर्नेल-आकार की बहुप्लाई usvg को ओवरफ्लो करता है। +@msg a freeform gradient keeps at least one point एक freeform ग्रेडिएंट कम से कम एक बिंदु रखता है +@msg a gradient needs at least two stops कम से कम दो स्टॉप की आवश्यकता होती है +@msg a gradient preset is already called {n} gradient preset पहले से ही कहा जाता है {n} +@msg a graph has at most {_1} series, so it transposes with at most that many categories एक ग्राफ में सबसे {_1} श्रृंखला है, इसलिए यह उस कई श्रेणियों के साथ ट्रांसपोजित होता है। +@msg a graph's records don't end where they should: its art was read as it is एक ग्राफ का रिकॉर्ड अंत नहीं है जहां उन्हें होना चाहिए: इसकी कला को पढ़ा गया क्योंकि यह है +@msg a graphic style named `{to}` already exists `{to}` नामक एक ग्राफिक स्टाइल पहले से मौजूद है +@msg a group crosses a multi-layer mask एक समूह एक बहुलेयर मास्क पार करता है +@msg a key object sits on that point एक प्रमुख ऑब्जेक्ट उस बिंदु पर बैठती है +@msg a layer can't be merged into its own sublayer एक लेयर को अपने खुद के सबलेयर में विलय नहीं किया जा सकता है +@msg a layer couldn't be read एक लेयर पढ़ा नहीं जा सकता +@msg a layer's form box isn't an array एक लेयर का फॉर्म बॉक्स एक सारणी नहीं है +@msg a layer's form can't be read एक लेयर का रूप नहीं पढ़ा जा सकता है +@msg a layer's form has no box एक लेयर के रूप में कोई बॉक्स नहीं है +@msg a layer's form has no dictionary एक लेयर के रूप में कोई शब्दकोश नहीं है +@msg a legend draws at most {MAX_CHIPS} swatches एक किंवदंती सबसे {MAX_CHIPS} swatches पर आकर्षित होती है +@msg a linked image can't become a gradient mesh: embed it first एक संबद्ध इमेज एक ग्रेडिएंट जाल नहीं बन सकती है: इसे पहले एम्बेड करें +@msg a live effect runs while the document is drawn, so it can't be `heavy` जब डॉक्यूमेंट तैयार हो जाता है, तो यह `heavy` नहीं हो सकता है। +@msg a mask has more than one art block एक मास्क एक से अधिक कला ब्लॉक है +@msg a mask that covers several layers comes in as a clipping group in each layer it covers एक मास्क जो कई लेयर्स को कवर करता है, प्रत्येक लेयर में एक क्लिपिंग समूह के रूप में आता है, यह कवर करता है +@msg a multi-layer mask needs one clipping path बहुलेयर मास्क को एक क्लिपिंग पाथ की आवश्यकता होती है +@msg a multi-layer mask's operators are out of order बहुलेयर मास्क ऑपरेटर क्रम से बाहर हैं +@msg a name names one asset: give multiple: false, or one object नाम एक परिसंपत्ति: एकाधिक देना: झूठा, या एक ऑब्जेक्ट +@msg a new document refuses this file because of these variables: {names} एक नया डॉक्यूमेंट इन चरों के कारण इस फ़ाइल को मना कर देता है: {names} +@msg a new document won't read these variables back with their kind: {names} नया डॉक्यूमेंट इन वेरिएबल्स का प्रकार वापस नहीं पढ़ पाएगा: {names} +@msg a page can't be read एक पेज पढ़ा नहीं जा सकता +@msg a page is missing एक पेज गायब हो रहा है +@msg a page object is used by something else एक पृष्ठ ऑब्जेक्ट का उपयोग किसी अन्य चीज़ के द्वारा किया जाता है +@msg a page out of range श्रेणी से बाहर एक पृष्ठ +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) एक पृष्ठ थंबनेल RGB पिक्सल होना चाहिए, 1 to {THUMBNAIL_SIZE} a side (not {w} × {h}) +@msg a page tree kid isn't a reference एक पृष्ठ पेड़ बच्चा एक संदर्भ नहीं है +@msg a page tree node has no kids पृष्ठ पेड़ नोड में कोई बच्चे नहीं है +@msg a page's placement is not finite एक पृष्ठ का प्लेसमेंट परिमित नहीं है +@msg a path has too many points एक पाथ में बहुत अधिक अंक होते हैं +@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects एक जटिल पाथ के अंदर एक पाथ, मिश्रण, लिफ़ाफ़ाफ़ा, दोहराने या इंटरट्विन समूह ऑब्जेक्ट नहीं ले सकता है +@msg a pattern layer doesn't end what it starts एक पैटर्न लेयर अंत नहीं है कि यह क्या शुरू होता है +@msg a pattern layer's colors hold something else एक पैटर्न लेयर के रंग कुछ और पकड़ते हैं +@msg a pattern named `{n}` exists `{n}` नामक एक पैटर्न मौजूद है +@msg a PDF presets file with over {_1} presets {_1} प्रीसेट के साथ एक PDF प्रीसेट फ़ाइल +@msg a plug-in with id {_1} is already installed आईडी {_1} के साथ एक प्लग-इन पहले से ही स्थापित है +@msg a PostScript error ({name} in `{op}`; {meaning}) एक पोस्टस्क्रिप्ट त्रुटि ({name} in `{op}`; {meaning}) +@msg a PostScript error ({name} in `{op}`; {meaning}), in {procs} PostScript त्रुटि ({name} in `{op}`; {meaning}), {procs} +@msg a PostScript error ({name} in `{op}`: {at}; {meaning}) PostScript त्रुटि (`{op}` में {name}: {at}; {meaning}) +@msg a PostScript error ({name} in `{op}`: {at}; {meaning}), in {procs} PostScript त्रुटि (`{op}` में {name}: {at}; {meaning}), {procs} में +@msg a PostScript error ({name} in `{op}`: {at}) एक पोस्टस्क्रिप्ट त्रुटि ({name} in `{op}`: {at}) +@msg a PostScript error ({name} in `{op}`: {at}), in {procs} एक पोस्टस्क्रिप्ट त्रुटि ({name} in `{op}`: {at}), {procs} +@msg a PostScript error ({name} in `{op}`) पोस्टस्क्रिप्ट त्रुटि ({name} in `{op}`) +@msg a PostScript error ({name} in `{op}`), in {procs} PostScript त्रुटि ({name} in `{op}`), {procs} +@msg a PostScript error ({name}; {meaning}) PostScript त्रुटि ({name}; {meaning}) +@msg a PostScript error ({name}) पोस्टस्क्रिप्ट त्रुटि ({name}) +@msg a preset named `{_1}` exists `{_1}` नामक एक प्रीसेट मौजूद है +@msg a preset named `{n}` exists `{n}` नामक एक प्रीसेट मौजूद है +@msg a print presets file with over {_1} presets {_1} प्रीसेट के साथ एक प्रिंट प्रीसेट फ़ाइल +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white एक प्रक्रिया रंग पारदर्शिता के साथ एक ग्रेस्केल इमेज को रंग नहीं बना सकता है: एक स्पॉट रंग, काले या सफेद रंग का उपयोग करें +@msg a profile is already called {n} प्रोफ़ाइल को पहले से ही {n} कहा जाता है +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. एक प्रोफ़ाइल एक रिवॉल्व इफ़ेक्ट का समर्थन करता है। इसके बजाय मौजूदा इफ़ेक्ट के ऑप्शन्स को संपादित करें। +@msg a row can't go into itself एक पंक्ति अपने आप में नहीं जा सकती +@msg a series goes on the left or the right value axis एक श्रृंखला बाएं या दाएं मूल्य अक्ष पर जाती है +@msg a slice size must be a positive number of points एक स्लाइस आकार अंक की एक सकारात्मक संख्या होना चाहिए +@msg a spine keeps at least two points रीढ़ की हड्डी कम से कम दो अंक रखती है +@msg a start must be an anchor index ≥ 0 or null प्रारंभ में एक एंकर इंडेक्स होना चाहिए ≥ 0 या null +@msg a stream runs past the end एक स्ट्रीम अंत तक चलता है +@msg a stream's length is wrong धारा की लंबाई गलत है +@msg a stream's length isn't a number एक धारा की लंबाई नहीं है +@msg a style named `{name}` already exists `{name}` नामक एक स्टाइल पहले से मौजूद है +@msg a style named `{to}` already exists `{to}` नामक एक स्टाइल पहले से मौजूद है +@msg a swatch needs a colour, gradient or pattern एक swatch एक रंग, ग्रेडिएंट या पैटर्न की जरूरत है +@msg a swatch or color group named `{n}` exists `{n}` नामक एक swatch या रंग समूह मौजूद है +@msg a symbol can't hold an instance of itself एक सिंबल खुद का एक उदाहरण नहीं पकड़ सकता है +@msg a symbol named `{n}` already exists पहले से ही `{n}` नाम का सिंबल मौजूद है +@msg a theme has 1 to {THEME_SIZE} colours थीम में 1 से {THEME_SIZE} रंग होते हैं +@msg a theme is already called {name} (replace: "{name}" overwrites it) एक विषय को पहले से ही {name} कहा जाता है (प्रतिस्थापन: "{name}" इसे ओवरराइट करता है) +@msg a toolbar name has at most {MAX_NAME} characters टूलबार नाम में सबसे {MAX_NAME} वर्ण हैं +@msg a value has the wrong type for the operator एक मूल्य ऑपरेटर के लिए गलत प्रकार है +@msg a value is outside the range the operator takes एक मूल्य सीमा के बाहर है जो ऑपरेटर लेता है +@msg a variable library holds text variables, and the document has none एक परिवर्तनीय लाइब्रेरी टेक्स्ट चर रखती है, और डॉक्यूमेंट में कोई नहीं है +@msg a variable of unknown kind can't be bound to objects अज्ञात प्रकार की एक चर ऑब्जेक्ट्स के लिए बाध्य नहीं किया जा सकता है +@msg a view named `{_1}` exists `{_1}` नामक दृश्य मौजूद है +@msg a view named `{name}` exists `{name}` नामक दृश्य मौजूद है +@msg a workspace keeps at most {MAX} toolbars एक वर्कस्पेस सबसे {MAX} टूलबार में रहता है +@msg a wraparound group is inside a compound path एक रैपराउंड समूह एक मिश्रित पाथ के अंदर है +@msg action is required कार्रवाई की आवश्यकता है +@msg add a format to export निर्यात करने के लिए एक फ़ॉर्मैट जोड़ें +@msg Add Points at Crossings: a path went missing क्रॉसिंग्स में अंक जोड़ें: एक पाथ गायब हो गया +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF-संगत, डिफ़ॉल्ट) या "7" (पुरानी .ai, संस्करण 7) +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 विरासत .ai फ़ाइलों को लिखते हैं, .ait टेम्पलेट नहीं +@msg All colors are within the CMYK gamut सभी रंग CMYK गामट के भीतर हैं +@msg already editing a pattern पहले से ही एक पैटर्न संपादन +@msg already editing an opacity mask पहले से ही एक opacity मास्क संपादित करें +@msg already editing another object's opacity mask पहले से ही किसी अन्य ऑब्जेक्ट के अपारदर्शिता मास्क को संपादित करना +@msg already in pattern editing mode पहले से ही पैटर्न संपादन मोड में +@msg an action in the action set file has more than 10,000 steps एक्शन सेट फ़ाइल में एक कार्रवाई 10,000 से अधिक कदम है +@msg an action is already playing एक कार्रवाई पहले से ही खेल रही है +@msg an action is already recording एक कार्रवाई पहले से ही रिकॉर्डिंग है +@msg an artboard is listed twice एक आर्टबोर्ड को दो बार सूचीबद्ध किया गया है +@msg an empty artboard has no width or height to scale to एक खाली आर्टबोर्ड में स्केल करने के लिए कोई चौड़ाई या ऊंचाई नहीं है +@msg an exporter always gets an export's budget: leave `budget` out एक निर्यातक हमेशा एक निर्यात बजट हो जाता है: `budget` बाहर छोड़ दें +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` एक निर्यातक ने 1 को {MAX_EXTENSIONS} `extensions` को घोषित किया +@msg an image has no pixels and was left out एक इमेज में कोई पिक्सेल नहीं है और इसे छोड़ दिया गया था +@msg an image is too large for DXF and was left out DXF के लिए एक इमेज बहुत बड़ी है और इसे छोड़ दिया गया था +@msg an image of {_1} MB, at most {_2} MB {_1} MB की एक इमेज, अधिकांश {_2} MB पर +@msg an image of {declared_w} × {declared_h} pixels is too large to draw {declared_w} × {declared_h} पिक्सेल की इमेज आकर्षित करने के लिए बहुत बड़ी है +@msg an image of {w} × {h} pixels is shown at reduced size {w} × {h} पिक्सेल की इमेज को कम आकार में दिखाया गया है +@msg an image of {w} × {h} pixels is too large to draw {w} × {h} पिक्सेल की इमेज बहुत बड़ी है +@msg an image of {width} × {height} pixels is too large to draw {width} × {height} पिक्सल की इमेज बहुत बड़ी है, जो आकर्षित करने के लिए बहुत बड़ी है +@msg an image VectorCraft can't read was left out एक इमेज VectorCraft पढ़ा नहीं जा सकता था +@msg an image whose data is cut short was left out जिस इमेज का डेटा छोटा है उसे छोड़ दिया गया था +@msg an index must be a whole number एक सूचकांक होना चाहिए पूरी संख्या +@msg an inline graphic has no glyphs एक इनलाइन ग्राफ़िक में कोई glyph नहीं है +@msg an invisible text form can't be read एक अदृश्य टेक्स्ट फॉर्म नहीं पढ़ा जा सकता है +@msg an object can't be read किसी ऑब्जेक्ट को पढ़ा नहीं जा सकता +@msg an object in perspective would leave the edited grid पर्सपेक्टिव में एक ऑब्जेक्ट संपादित ग्रिड छोड़ देगी +@msg an object is missing एक ऑब्जेक्ट लापता है +@msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. एक ऑब्जेक्ट एक 3D इफ़ेक्ट लेता है। मौजूदा इफ़ेक्ट के ऑप्शन्स को संपादित करें, या इसे पहले हटा दें। +@msg an object's header is missing एक ऑब्जेक्ट का हैडर लापता है +@msg an overprinting form can't be read एक ओवरप्रिंटिंग फॉर्म पढ़ा नहीं जा सकता +@msg an unread object has no readable bounds एक अपठित ऑब्जेक्ट में कोई पठनीय सीमा नहीं है +@msg an unread object holds a frame of threaded type एक अपठित ऑब्जेक्ट में थ्रेडेड टाइप का एक फ्रेम होता है +@msg an unread object is missing from its layer एक अपठित ऑब्जेक्ट अपनी लेयर से लापता है +@msg anchor `{key}` must be [x, y] एंकर `{key}` होना चाहिए [x, y] +@msg anchor `{key}` must be a number एंकर `{key}` को एक नंबर होना चाहिए +@msg anchor `smooth` must be true or false एंकर का `smooth` true या false होना चाहिए +@msg anchor must name a registered panel anchor: एंकर को एक पंजीकृत पैनल का नाम देना चाहिए +@msg angle and roundness must be finite कोण और गोलाई परिमित होना चाहिए +@msg angles must be a list as long as pins (degrees or null) angles: कोण एक सूची होना चाहिए जब तक पिन (डिग्री या null) +@msg Angles require two straight segments कोणों को दो सीधे खंडों की आवश्यकता होती है +@msg antiAlias `{id}`: none, art or type antiAlias `{id}`: none, art या type +@msg appearance must be flat|center|edge appearance को flat|center|edge होना चाहिए +@msg apply is "fill" or "stroke", not `{other}` लागू "भर" या "स्ट्रोक" है, नहीं `{other}` +@msg area must be a closed polygon of 3 to 100000 [x, y] points area: क्षेत्र 3 से 100000 [x, y] अंक के एक बंद बहुभुज होना चाहिए +@msg area type {_1} is named twice क्षेत्र के प्रकार {_1} को दो बार नाम दिया गया है +@msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise फ्रेम में क्षेत्र प्रकार फ़ॉन्ट की एक पंक्ति के लिए बहुत कम है, यह लंबा फ्रेम ({_1}) में दिखाता है: उनका प्रकार अन्यथा नहीं दिखाई देगा +@msg area type needs a path that encloses an area क्षेत्र के प्रकार को एक पाथ की आवश्यकता होती है जो एक क्षेत्र को घेरता है +@msg arrowAlign must be extend|tip, got {o} arrowAlign होना चाहिए thetip, get {o} +@msg arrowScale must be [start, end] arrowScale होना चाहिए [शुरू, अंत] +@msg artboard {0} does not exist आर्टबोर्ड {0} मौजूद नहीं है +@msg artboard {i} doesn't print आर्टबोर्ड {i} प्रिंट नहीं करता है +@msg artboard is a 0-based index artboard: आर्टबोर्ड एक 0-आधारित इंडेक्स है +@msg artboard must be a 0-based index artboard: आर्टबोर्ड एक 0-आधारित इंडेक्स होना चाहिए +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout को {layout?, columns?, spacing?, rightToLeft?} होना चाहिए +@msg artboardLayout.columns must be 1 or more artboardLayout.columns को 1 या अधिक होना चाहिए +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout को gridByRow, gridByColumn, row या column होना चाहिए +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft को true या false होना चाहिए +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing को 0–{MAX_SPACING} pt होना चाहिए +@msg artboards must be a non-empty list artboards: आर्टबोर्ड एक गैर-खाली सूची होना चाहिए +@msg artboards must be a number artboards: आर्टबोर्ड एक नंबर होना चाहिए +@msg asset `{_1}` has no art to export संपत्ति `{_1}` को निर्यात करने के लिए कोई कला नहीं है +@msg at most {MAX_KEYWORDS} keywords सबसे अधिक {MAX_KEYWORDS} कीवर्ड +@msg at most {MAX_MATCHES} matches are kept अधिकांश {MAX_MATCHES} मैचों को रखा जाता है +@msg at most {MAX_POINTS} points {MAX_POINTS} पॉइंट पर +@msg at most {MAX_QUEUE} files सबसे अधिक {MAX_QUEUE} फ़ाइलों में +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` अधिकांश {MAX_UNGROUPED} मापदंडों पर समूहों के बाहर: दूसरों को `group` देना +@msg at must be [x, y] at: [x, y] होना चाहिए +@msg at this scale the drawing is {w} × {h} pt, more than the canvas holds: choose a smaller scale or fit it to the artboard इस पैमाने पर ड्राइंग {w} × {h} pt है, कैनवास से अधिक रखती है: एक छोटे पैमाने सिलेक्ट करें या इसे आर्टबोर्ड पर फिट करें +@msg at/rect lie outside the canvas कैनवास के बाहर / सही झूठ +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute को size|leading|tracking|kerning|baselineShift होना चाहिए +@msg attrs must be an object attrs एक ऑब्जेक्ट होना चाहिए +@msg automation filesystem access is not granted: read authority is absent: {path} स्वचालन फ़ाइल प्रणाली का उपयोग नहीं दिया जाता है: पढ़ने का अधिकार अनुपस्थित है: {path} +@msg automation filesystem access is not granted: write authority is absent: {path} स्वचालन फ़ाइलसिस्टम का उपयोग नहीं दिया जाता है: लिखने का अधिकार अनुपस्थित है: {path} +@msg automation path rejected: {_1} isn't valid text स्वचालन पाथ खारिज: {_1} मान्य टेक्स्ट नहीं है +@msg automation path rejected: {why}: {path} स्वचालन पाथ खारिज: {why}: {path} +@msg automation path rejected: a link that leads nowhere: {path} स्वचालन पाथ खारिज: एक लिंक जो कहीं नहीं जाता है: {path} +@msg automation path rejected: cannot resolve {path}: {e} स्वचालन पाथ खारिज कर दिया: {path} को हल नहीं कर सकता: {e} +@msg automation path rejected: outside the read root {root}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ के बाहर {root}: {path} +@msg automation path rejected: outside the read roots {roots}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ों के बाहर {roots}: {path} +@msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} +@msg automation path rejected: outside the write roots {roots}: {path} स्वचालन पाथ खारिज: लिखने की जड़ों के बाहर {roots}: {path} +@msg automation path rejected: parent traversal below a folder that doesn't exist: {path} स्वचालन पाथ खारिज कर दिया: एक फ़ोल्डर के नीचे माता-पिता traversal जो मौजूद नहीं है: {path} +@msg automation path rejected: path is empty स्वचालन पाथ खारिज: पाथ खाली है +@msg automation path rejected: reserved device names are not allowed: {path} स्वचालन पाथ खारिज कर दिया: आरक्षित उपकरण नामों की अनुमति नहीं है: {path} +@msg automation path rejected: the folder's name isn't valid text स्वचालन पाथ खारिज: फ़ोल्डर का नाम वैध टेक्स्ट नहीं है +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{given}` axis: अक्ष को "vertical", "horizontal" या डिग्री में एक कोण होना चाहिए, नहीं `{given}`` +@msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis: अक्ष को "vertical", "horizontal" या डिग्री में एक कोण होना चाहिए, नहीं `{v}` +@msg background {other}: transparent, white, black or a colour such as "#ff8800" पृष्ठभूमि {other}: पारदर्शी, सफेद, काला या एक रंग जैसे "#ff8800" +@msg backgroundContents must be transparent or white backgroundContents को transparent या white होना चाहिए +@msg bad {k} colour बुरा {k} रंग +@msg bad `runs`: {e} बुरा `runs`: {e} +@msg bad AES key बुरा AES कुंजी +@msg bad arrowScale अमान्य arrowScale +@msg bad base64 बुरा आधार64 +@msg bad color {c} बुरा रंग {c} +@msg bad color {v} बुरा रंग {v} +@msg bad colour बुरा रंग +@msg bad colour {v} बुरा रंग {v} +@msg bad colour {v} in groupColors groupColors में अमान्य रंग {v} +@msg bad colour `{hex}` (#rrggbb) बुरा रंग `{hex}` (#rrggbb) +@msg bad colour in `colors` `colors` में बुरा रंग +@msg bad cross-reference entry बुरा क्रॉस-reference प्रविष्टि +@msg bad cross-reference table खराब क्रॉस-रिफरेंस टेबल +@msg bad current colour {v} बुरा वर्तमान रंग {v} +@msg bad dataBase64 अमान्य dataBase64 +@msg bad edit बुरा संपादन +@msg bad fill {v} बुरा भर {v} +@msg bad fit: {e} बुरा फिट: {e} +@msg bad model {other} (keep, new or document) बुरा मॉडल {other} (keep, नया या डॉक्यूमेंट) +@msg bad new colour {v} बुरा नया रंग {v} +@msg bad object बुरा ऑब्जेक्ट +@msg bad object number खराब ऑब्जेक्ट संख्या +@msg bad offset बुरा ऑफसेट +@msg bad page tree बुरा पेज पेड़ +@msg bad path data: {e} बुरा पाथ डेटा: {e} +@msg bad point {v}: expected [x, y] or [x, y, pressure] बुरा बिंदु {v}: उम्मीद [x, y] या [x, y, दबाव] +@msg bad reference बुरा संदर्भ +@msg bad shortcut बुरा शॉर्टकट +@msg bad stream length खराब धारा की लंबाई +@msg bad trailer बुरा ट्रेलर +@msg bad trailer size बुरा ट्रेलर आकार +@msg balance must be between 0 and 100 balance: 0 से 100 के बीच संतुलन होना चाहिए +@msg batch step {_1} (`{id}`) failed: {e} बैच चरण {_1} (`{id}`) विफल: {e} +@msg Batch: {count} processed बैच: {count} संसाधित +@msg Batch: {count} processed, {failed} failed बैच: {count} संसाधित, {failed} विफल +@msg batches cannot nest बैच घोंसला नहीं कर सकते +@msg before must name a panel before: पहले एक पैनल का नाम देना चाहिए +@msg below and above must name a panel floating in another group नीचे और ऊपर एक पैनल दूसरे समूह में चल रहा है नाम होना चाहिए +@msg bind something to a variable first पहले एक चर के लिए कुछ बांधना +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed होना चाहिए 0-{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} +@msg Blend colors: select at least three objects with filled colours मिश्रित रंग: भरे हुए रंगों के साथ कम से कम तीन ऑब्जेक्ट चुनें +@msg BMP files are RGB or grayscale: colorModel rgb or gray BMP फ़ाइलें RGB या ग्रेस्केल होती हैं: colorModel को rgb या gray रखें +@msg brightness must be dark|mediumDark|mediumLight|light brightness को dark|mediumDark|mediumLight|light होना चाहिए +@msg brush must be a name or null brush: ब्रश एक नाम या null होना चाहिए +@msg brushes move only within their type ब्रश केवल उनके प्रकार के भीतर ही चलते हैं +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) ब्रश VectorCraft को अभी तक नहीं पढ़ा जा सकता है ब्रश पैनल ({_1}) से बाहर छोड़ दिया गया था। +@msg by must be a number by: द्वारा एक नंबर होना चाहिए +@msg can't add page thumbnails: {why} पेज थंबनेल नहीं जोड़ा जा सकता: {why} +@msg can't add the editing data for other apps: {why} अन्य ऐप्स के लिए संपादन डेटा नहीं जोड़ सकते: {why} +@msg can't edit the written PDF: {why} लिखित PDF संपादित नहीं कर सकता: {why} +@msg can't encode the document: {0} डॉक्यूमेंट को एनकोड नहीं कर सकता: {0} +@msg can't encode the input इनपुट को एनकोड नहीं कर सकता +@msg can't encrypt the PDF: {why} PDF को एन्क्रिप्ट नहीं कर सकता: {why} +@msg can't linearise the PDF: {why} PDF को रैखिक नहीं कर सकता: {why} +@msg can't open `{_1}`: {_2} `{_1}` नहीं खोल सकते: {_2} +@msg can't open `{_1}`: {e} `{_1}` नहीं खोल सकते: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) `{name}` ओपन नहीं कर सकते: VectorCraft इस फ़ॉर्मैट को पढ़ नहीं सकता (document.formats देखें) +@msg can't parse shortcut `{c}` नहीं कर सकते हैं a shortcut `{c}` +@msg can't parse shortcut `{s}` for `{k}` `{k}` के लिए शॉर्टकट `{s}` को पार नहीं कर सकता +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) `{name}` प्लेस नहीं कर सकते: VectorCraft इस फ़ॉर्मैट को पढ़ नहीं सकता (document.formats देखें) +@msg can't read back the written PDF: {e} लिखित PDF को वापस नहीं पढ़ सकते: {e} +@msg can't read this Word document: {why} इस वर्ड डॉक्यूमेंट को नहीं पढ़ सकते: {why} +@msg can't save version {0}: VectorCraft writes versions {MIN_VERSION} to {VERSION} संस्करण {0} सेव नहीं सकते: VectorCraft संस्करण {MIN_VERSION} से {VERSION} तक लिखता है +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp .{e} इमेज नहीं लिख सकते: .png, .jpg, .gif, .webp, .tif या .bmp इस्तेमाल करें +@msg can't write .{ext} images .{ext} इमेज नहीं लिख सकते +@msg can't write PDF layers, overprint or invisible text: {why} PDF लेयरें, ओवरप्रिंट या अदृश्य टेक्स्ट नहीं लिख सकते: {why} +@msg can't write the file's copyright: {why} फ़ाइल का कॉपीराइट नहीं लिख सकते: {why} +@msg can't write the file's modification date: {why} फ़ाइल के संशोधन की तारीख नहीं लिख सकते: {why} +@msg can't write the pages' user units: {why} पृष्ठों के उपयोगकर्ता इकाइयों को नहीं लिख सकते: {why} +@msg cancelled; nothing was changed रद्द कर दिया गया; कुछ भी नहीं बदला गया +@msg cannot distort a zero-size bounding box शून्य आकार की बाध्यता बॉक्स को विकृत नहीं कर सकता है +@msg cannot distort a zero-size or non-finite bounding box एक शून्य आकार या गैर-वित्तीय बाध्य बॉक्स को विकृत नहीं कर सकता +@msg cannot move an object into itself किसी ऑब्जेक्ट को अपने आप में नहीं ले सकता है +@msg cannot read PDF: {0} PDF नहीं पढ़ सकते: {0} +@msg cannot split an open path at its end point अपने अंतिम बिंदु पर एक खुले रास्ते को विभाजित नहीं कर सकता है +@msg case must be upper|lower|title|sentence case को upper|lower|title|sentence होना चाहिए +@msg category `{c}`: one of {_1} श्रेणी `{c}`: {_1} में से एक +@msg center must be [x, y] center: केंद्र होना चाहिए [x, y] +@msg check a layer to export निर्यात करने के लिए एक लेयर की जांच करें +@msg check an artboard to export निर्यात करने के लिए एक आर्टबोर्ड की जांच करें +@msg check an asset to export निर्यात करने के लिए एक परिसंपत्ति की जांच करें +@msg choice must be "merge" or "add", not `{choice}` पसंद "merge" या "add" होना चाहिए, नहीं `{choice}` +@msg Choose a circle or a perfect arc एक सर्कल या एक परिपूर्ण चाप चुनें +@msg choose a destination folder एक गंतव्य फ़ोल्डर चुनें +@msg choose a direction to divide in में विभाजित करने के लिए एक दिशा चुनें +@msg choose a folder to export to निर्यात करने के लिए एक फ़ोल्डर चुनें +@msg choose a location for the package पैकेज के लिए एक स्थान चुनें +@msg Choose a precision from 0 to 6 0 से 6 तक परिशुद्धता चुनें +@msg choose a source folder एक स्रोत फ़ोल्डर चुनें +@msg choose anchors where two sides meet at an angle: only those take a corner जहां दो पक्ष एक कोण पर मिलते हैं, वहां एंकर सिलेक्ट करें: केवल वे एक कोने लेते हैं +@msg choose at least one artboard कम से कम एक आर्टबोर्ड चुनें +@msg choose at least one status कम से कम एक स्थिति चुनें +@msg Choose original artwork, not a dimension's generated paths मूल आर्टवर्क चुनें, एक आयाम उत्पन्न पाथ नहीं +@msg choose the font files to add जोड़ने के लिए फ़ॉन्ट फ़ाइलों को चुनें +@msg Choose two different points दो अलग-अलग अंक चुनें +@msg Choose two non-parallel straight segments दो गैर-parallel सीधे खंड चुनें +@msg Choose two nonzero angle arms दो nonzero कोण हथियार चुनें +@msg Click in type with a Type tool to split it इसे विभाजित करने के लिए टाइप टूल के साथ टाइप करें +@msg clip must be true or false clip: क्लिप को सच या झूठा होना चाहिए +@msg clipboard is empty क्लिपबोर्ड खाली है +@msg clippingMask must be true or false clippingMask को true या false होना चाहिए +@msg closed must be a boolean closed: बंद होना चाहिए एक boolean +@msg closing needs three anchors closing: बंद करने की जरूरत है तीन एंकर +@msg collapsed must be true or false collapsed: पतन सच होना चाहिए या गलत होना चाहिए +@msg color.profile: no RGB or CMYK profile is called “{profile}” Color.profile: कोई RGB या CMYK प्रोफ़ाइल को "{profile}" कहा जाता है। +@msg colorMode must be rgb or cmyk, not `{m}` colorMode को rgb या cmyk होना चाहिए, `{m}` नहीं +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel को {own} (डॉक्यूमेंट का मोड), grayscale या bitmap होना चाहिए +@msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" जैसा रंग नहीं है +@msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: अधिकतम {MAX_TABLE} रंग +@msg colour groups can't go into colour groups रंग समूह रंग समूहों में नहीं जा सकते हैं +@msg colour, mode and spot apply to solid-colour swatches only रंग, मोड और स्पॉट केवल ठोस रंग की घड़ी पर लागू होते हैं +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read कॉलम {column}: `{cell}` ग्राफ़ डेटा फ़ाइल का `%` कॉलम है, जिसे पढ़ा नहीं जाता +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable कॉलम {column}: `{cell}` नाम `{name}`, जो एक {_1} चर है +@msg column {column}: `{cell}` names no variable कॉलम {column}: `{cell}` नाम कोई चर नहीं +@msg column {column}: the variable name is longer than {MAX_NAME} characters कॉलम {column}: चर नाम {MAX_NAME} अक्षरों से लंबा है +@msg column docks a set as a dock column, with no anchor or icon कॉलम एक डॉक कॉलम के रूप में सेट करता है, जिसमें कोई एंकर या आइकन नहीं होता है +@msg column must be true or a number from 1 column: कॉलम सही होना चाहिए या 1 से एक नंबर होना चाहिए +@msg column: true floats the whole column and takes no onto, above or below स्तंभ: सच पूरे स्तंभ को तैरता है और ऊपर या नीचे नहीं लेता है +@msg columns {first} and {column} both name the variable `{name}` कॉलम {first} और {column} दोनों नाम चर `{name}` +@msg Combine Slices: the slices have no bounds स्लाइस को मिलाएं: स्लाइस में कोई सीमा नहीं है +@msg command `{0}` is not available right now: {1} आदेश `{0}` अभी उपलब्ध नहीं है: {1} +@msg command must be a shape.* command command: आदेश एक आकार होना चाहिए।* आदेश +@msg commands[{i}]: missing `command` आदेश [{i}]: लापता `command` +@msg composer must be "singleLine" or "everyLine" composer: संगीतकार "singleLine" या "everyLine" होना चाहिए। +@msg compound {_1} must contain exactly one open path to join यौगिक {_1} में शामिल होने के लिए बिल्कुल एक खुला रास्ता होना चाहिए +@msg compound paths can only contain paths यौगिक पाथ में केवल पाथ हो सकते हैं +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes मिश्रित आकार पाथ, यौगिक पाथ, समूह, मिश्रित आकार, प्रकार, मिश्रण और लिफाफे लेते हैं +@msg compressed (RLE) bitmaps can't be read yet संकुचित (RLE) bitmaps अभी तक पढ़ा नहीं जा सकता है +@msg connect end must be "start" or "end" कनेक्ट अंत "शुरू" या "अंत" होना चाहिए +@msg connect needs a path other than the one extended connect: कनेक्ट एक विस्तारित के अलावा एक पाथ की जरूरत है +@msg connect needs id connect: कनेक्ट करने की जरूरत आईडी +@msg connect path has no open end कनेक्ट पाथ का कोई खुला अंत नहीं है +@msg Contour: select paths or shapes कंटूर: पाथ या आकृतियों सिलेक्ट करें +@msg Contour: the Offset Path effect is not available Contour: ऑफसेट पाथ इफ़ेक्ट उपलब्ध नहीं है +@msg control must be fillStroke, coloring, drawMode or screenMode control को fillStroke, coloring, drawMode या screenMode होना चाहिए +@msg Convert to Artboards: selection has no area आर्टबोर्ड में कनवर्ट करें: सिलेक्शन में कोई क्षेत्र नहीं है +@msg Convert to Shape: no rectangles or ellipses selected आकार में कनवर्ट करें: कोई आयत या अंडाकार सिलेक्शन नहीं +@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट +@msg copy needs path: the file to copy into the document's folder copy: प्रतिलिपि की जरूरत है पाथ: फ़ाइल को डॉक्यूमेंट के फ़ोल्डर में कॉपी करने के लिए +@msg copy takes images only: relink placed documents where their files are copy: प्रतिलिपि केवल इमेज को लेती है: डॉक्यूमेंट्स को फिर से लिंक करें जहां उनकी फ़ाइलें हैं +@msg copying a file isn't available on the web एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus को unknown, copyrighted या publicDomain होना चाहिए +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl को URL होना चाहिए (स्पेस नहीं, अधिकतम 2048 अक्षर) +@msg Corners edits the corners of a path कॉर्नर एक पाथ के कोनों को संपादित करता है +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners: कोनों 4 [x, y] अंक (TL, TR, BR, BL) होना चाहिए +@msg could not decode image: {0} इमेज को डीकोड नहीं कर सकता: {0} +@msg Couldn't copy to the system clipboard: {e} सिस्टम क्लिपबोर्ड को कॉपी नहीं कर सका: {e} +@msg Couldn't open {name}: {e} नहीं खोल सकता {name}: {e} +@msg Couldn't paste from the clipboard: {e} क्लिपबोर्ड से पेस्ट नहीं कर सका: {e} +@msg Couldn't paste: the document it was pasted in was closed पेस्ट नहीं कर सका: इसमें चिपकाए गए डॉक्यूमेंट को बंद कर दिया गया था +@msg Couldn't place {name}: {e} नहीं रह सकता {name}: {e} +@msg Couldn't place {name}: the document it was dropped on was closed नहीं था {name}: यह डॉक्यूमेंट बंद हो गया था +@msg Couldn't place {name}: the document it was placed in was closed नहीं था {name}: यह डॉक्यूमेंट बंद किया गया था +@msg Couldn't read {name}: {e} नहीं पढ़ सकता {name}: {e} +@msg Couldn't save recovery data: {e} वसूली डेटा नहीं बचा सकता: {e} +@msg counterPer `{c}`: item or file counterPer `{c}`: item या file +@msg Create from Guides: the document has no artboard गाइड से बनाएँ: डॉक्यूमेंट में कोई आर्टबोर्ड नहीं है +@msg Create from Guides: the guides make more than {MAX_PIECES} slices गाइड से बनाएँ: गाइड {MAX_PIECES} स्लाइस से अधिक बनाते हैं +@msg Create from Selection: the selection has no area सिलेक्शन से बनाएँ: सिलेक्शन में कोई क्षेत्र नहीं है +@msg Create needs fills, strokes or both जरूरतों को पूरा करने, स्ट्रोक या दोनों की जरूरत है +@msg Create Outlines: select text objects आउटलाइन बनाएं: टेक्स्ट ऑब्जेक्ट चुनें +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" फसल `{_1}`: केवल PDF पृष्ठों में कला, ट्रिम, ब्लीड और मीडिया बॉक्स हैं; "crop" या "bounding" का उपयोग करें +@msg crop rectangle doesn't overlap the image फसल आयत इमेज को ओवरलैप नहीं करता है +@msg cross-reference and object streams aren't supported क्रॉस-रिफरेंस और ऑब्जेक्ट स्ट्रीम्स का समर्थन नहीं किया जाता है +@msg CSS options: {e} सीएसएस ऑप्शन्स: {e} +@msg CSV has a header but no data rows CSV एक हेडर है लेकिन कोई डेटा पंक्ति नहीं है +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark CSV ने NUL बाइट्स को रखा: इसे UTF-8 या UTF-16 के रूप में बाइट-ऑर्डर मार्क के साथ बचाओ +@msg CSV is empty CSV खाली है +@msg CSV is larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bytes से बड़ा है +@msg CSV is not UTF-16 CSV UTF-16 नहीं है +@msg CSV is not UTF-8 CSV UTF-8 नहीं है +@msg CSV would be larger than {MAX_CSV_BYTES} bytes CSV {MAX_CSV_BYTES} bytes से बड़ा होगा +@msg damaged क्षतिग्रस्त +@msg damaged compressed data: {e} क्षतिग्रस्त संकुचित डेटा: {e} +@msg dash lengths must be numbers, got {v} डैश की लंबाई नंबर होना चाहिए, {v} होना चाहिए +@msg dash must be a list of lengths or null, got {v} dash: डैश लंबाई या null की एक सूची होना चाहिए, {v} मिला +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) डेटा कुंजी `{k}`: अक्षर, अंक, -, _ और (नाम या vc-...) +@msg data must be an object of key: value, not {v} data: डेटा कुंजी का एक ऑब्जेक्ट होना चाहिए: मान, नहीं {v} +@msg Data Recovery can't keep copies in {path}: {e} डेटा रिकवरी {path} में प्रतियां नहीं रख सकती: {e} +@msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) डेटा रिकवरी की प्रतिलिपियाँ रखने के लिए कहीं नहीं है: निर्धारित प्राथमिकता → फ़ाइल हैंडलिंग → डेटा रिकवरी → फ़ोल्डर (recoveryFolder) +@msg data set `{name}` holds a control character, which a variable library can't hold डेटा सेट `{name}` में एक नियंत्रण चरित्र होता है, जो एक परिवर्तनीय लाइब्रेरी पकड़ नहीं सकता है +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare डेटा सेट `{name}` `{var}` के लिए एक मान रखता है, जिसे लाइब्रेरी घोषित नहीं करती है +@msg data set `{name}` holds two values for `{var}` डेटा सेट `{name}` में `{var}` के लिए दो मान हैं। +@msg data set `{name}` is declared twice डेटा सेट `{name}` को दो बार घोषित किया गया है +@msg data set `{name}` starts or ends with white space, which a variable library can't hold डेटा सेट `{name}` शुरू होता है या व्हाइट स्पेस के साथ समाप्त होता है, जो एक परिवर्तनीय लाइब्रेरी को नहीं पकड़ सकता है +@msg data takes at most {MAX_DATA} keys at once data: डेटा एक बार में सबसे {MAX_DATA} कुंजी लेता है +@msg data the program reads is damaged or cut short, or the program asks for a position in a file that has none प्रोग्राम पढ़ने वाले डेटा को क्षतिग्रस्त या छोटा काट दिया जाता है, या प्रोग्राम एक फ़ाइल में एक स्थिति के लिए पूछता है जिसमें कोई नहीं है। +@msg dataset `{name}` already exists डेटासेट `{name}` पहले से मौजूद है +@msg dataset `{to}` already exists डेटासेट `{to}` पहले से मौजूद है +@msg date `{d}`: YYYY-MM-DD दिनांक `{d}`: YYYYY-MM-DD +@msg decimals must be {_1}–{_2} (got {_3}) decimals: दशमलव होना चाहिए {_1}-{_2} ({_3}) +@msg decoded data is too large डीकोडेड डेटा बहुत बड़ा है +@msg define a variable first पहले एक चर को परिभाषित करना +@msg detect must be true or false detect: पता लगाना सही या गलत होना चाहिए +@msg Dimension is locked or hidden आयाम बंद या छिपा हुआ है +@msg Dimension mode does not match its source आयाम मोड अपने स्रोत से मेल नहीं खाता है +@msg Dimension point is outside the canvas आयाम बिंदु कैनवास के बाहर है +@msg Dimension size is outside its supported range आयाम आकार अपनी समर्थित सीमा से बाहर है +@msg direct-select anchor points of a path एक पाथ के प्रत्यक्ष सिलेक्शन एंकर अंक +@msg direct-select anchor points to cut at (not the end points of open paths) डायरेक्ट-सिलेक्शन एंकर पॉइंट्स को कट करने के लिए ( ओपन पाथ के अंतिम बिंदु नहीं) +@msg direct-select the anchor points to remove हटाने के लिए एंकर पॉइंट्स सिलेक्ट करें +@msg distance must be > 0 distance: दूरी होना चाहिए > 0 +@msg divide into 1 to {MAX_PIECES} slices 1 से {MAX_PIECES} स्लाइस में विभाजित करें +@msg Divide Objects Below: select a path नीचे दिए गए ऑब्जेक्ट्स को विभाजित करें: एक पाथ चुनें +@msg Divide Objects Below: select exactly one path नीचे दिए गए ऑब्जेक्ट्स को विभाजित करें: बिल्कुल एक पाथ चुनें +@msg docking action contains an unknown panel or an excessive split path डॉकिंग एक्शन में एक अज्ञात पैनल या एक अत्यधिक विभाजन पाथ होता है +@msg Downloaded {what} {what} डाउनलोड किया गया +@msg Draw Inside needs exactly one selected path, compound path or text ड्रॉ इनसाइड को बिल्कुल एक सिलेक्टेड पाथ, यौगिक पाथ या टेक्स्ट की आवश्यकता होती है +@msg dx and dy give the arrow's direction डीएक्स और डीई तीर की दिशा देते हैं +@msg dx and dy must be numbers डीएक्स और डीआई होना चाहिए +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg dxf fitTo must be [width, height], positive dxf fitTo को धनात्मक [width, height] होना चाहिए +@msg dxf must be an object of DXF import options dxf: DXF को DXF आयात ऑप्शन्स का एक ऑब्जेक्ट होना चाहिए +@msg DXF options: {e} DXF ऑप्शन्स: {e} +@msg dxf scale must be a positive number up to {_1}, not {s} Dxf स्केल को {_1} तक सकारात्मक संख्या होना चाहिए, न कि {s} +@msg DXF scale must be a positive number up to {_1}, not {scale} DXF स्केल को {_1} तक सकारात्मक संख्या होना चाहिए, न कि {scale} +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf इकाई `{u}`: एक इकाई जैसे mm, cm, in या pt +@msg dxf: {e} Dxf: {e} +@msg each format is an object {format, scale?, suffix?} हर फ़ॉर्मैट एक ऑब्जेक्ट {format, scale?, suffix?} है +@msg each item needs an id प्रत्येक आइटम को एक आईडी की आवश्यकता होती है +@msg each match needs `kind` प्रत्येक मैच की जरूरत है `kind` +@msg each match needs a `name` प्रत्येक मैच को `name` की आवश्यकता होती है +@msg each of `fonts` is {family, style?}; 1 to 1000 of them `fonts` का हर आइटम {family, style?} है; 1 से 1000 आइटम +@msg each of `items` is {{id, corners?}} with an object id, not {it} `items` का हर आइटम ऑब्जेक्ट आईडी वाला {{id, corners?}} है, {it} नहीं +@msg each of `items` is {kind, item} `items` का हर आइटम {kind, item} है +@msg each row needs `from` हर पंक्ति के लिए `from` चाहिए +@msg each stop needs a position प्रत्येक स्टॉप को स्थिति की आवश्यकता होती है +@msg each subpath needs an anchors array प्रत्येक उपपाथ को एक एंकर सरणी की आवश्यकता होती है +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType को easeIn, easeOut, easeInOut या easeOutIn होना चाहिए +@msg Edit Original opens image and document files only; “{name}” is not one मूल रूप से केवल इमेज और डॉक्यूमेंट फ़ाइलों को खोलता है; "{name}" एक नहीं है +@msg editingData must be true or false editingData को true या false होना चाहिए +@msg editingData must be true, false or "always" editingData को true, false या "always" होना चाहिए +@msg edits overlap ओवरलैप संपादित करें +@msg effect {k} is `{_1}`, not `{id}` इफ़ेक्ट {k} `{_1}`` है, नहीं `{id}` +@msg effects of objects whose appearances differ can't be moved together उन ऑब्जेक्ट्स के इफ़ेक्ट जिनकी उपस्थिति भिन्न होती है, उन्हें एक साथ नहीं ले जाया जा सकता है +@msg empty brush stroke खाली ब्रश स्ट्रोक +@msg empty cutter खाली कटर +@msg empty header in column {_1} कॉलम में खाली हैडर {_1} +@msg empty path खाली पाथ +@msg encoding `{_1}`: utf8 or utf16 एन्कोडिंग `{_1}`: utf8 or utf16 +@msg ends must be two of "first" and "last" ends: समाप्त होता है दो "पहली" और "अंतिम" होना चाहिए। +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg EPS flattener: {e} ईपीएस flattener: {e} +@msg EPS options: {e} ईपीएस ऑप्शन्स: {e} +@msg EPS Save retains the artboard and all artwork: use document.export for cropped or selected-only EPS EPS सेव आर्टबोर्ड और पूरा आर्टवर्क रखता है: क्रॉप किए या केवल सिलेक्ट किए आर्टवर्क के EPS के लिए document.export उपयोग करें +@msg every numbered name for {name} is taken in the document's folder {name} के लिए हर नंबर का नाम डॉक्यूमेंट के फ़ोल्डर में लिया जाता है +@msg every numbered name for it is taken in the Fonts folder इसके लिए हर नंबर वाला नाम फ़ॉन्ट फ़ोल्डर में लिया जाता है +@msg every numbered name for the copy is taken प्रति के लिए हर नंबर का नाम लिया जाता है +@msg every numbered name for the result is taken परिणाम के लिए हर नंबर का नाम लिया जाता है +@msg every search thread stopped on an internal error (please report this bug) प्रत्येक खोज धागा एक आंतरिक त्रुटि पर बंद कर दिया (कृपया इस बग की रिपोर्ट करें) +@msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें +@msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है +@msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं +@msg Expand: no gradient fills विस्तार: कोई ग्रेडिएंट भरता नहीं +@msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं +@msg expanded SVG styles exceed the import size limit विस्तारित SVG स्टाइल्स आयात आकार सीमा से अधिक है +@msg expected {"dataBase64"} उम्मीद {"dataBase64"} +@msg expected {"objects"} उम्मीद {"objects"} +@msg export `{name}`: {e} निर्यात `{name}`: {e} +@msg Export cancelled निर्यात रद्द +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft स्क्रीन के लिए एक्सपोर्ट png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai या vectorcraft लिखता है +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes निर्यात प्रीसेट फ़ाइल {MAX_PRESET_FILE_BYTES} bytes से बड़ा है +@msg Exported {path} {path} एक्सपोर्ट किया गया +@msg Exported {what} निर्यात किया गया {what} +@msg Exported {what} with {_1} note(s): {first} {_1} नोट के साथ निर्यात {what}: {first} +@msg Exporting {_1} निर्यात {_1} +@msg exportText must be editable or appearance exportText को editable या appearance होना चाहिए +@msg exportType must be movieClip or graphic, not `{s}` exportType को movieClip या graphic होना चाहिए, `{s}` नहीं +@msg extend needs id extend: विस्तार की जरूरत है आईडी +@msg extension {e} is listed twice एक्सटेंशन {e} को दो बार सूचीबद्ध किया गया है +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot एक्सटेंशन {e}: डॉट के बिना, 1-16 लोअर-केस अक्षरों और अंकों का उपयोग करें +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges list at most {MAX_FEATURE_CHANGES} टैग +@msg featureChanges must be a list of tags featureChanges को टैग की सूची होना चाहिए +@msg features lists at most {max} tags अधिकांश {max} टैग पर सूची +@msg features must be a list of tags features: विशेषताएं टैग की एक सूची होना चाहिए +@msg fidelity must be 0..100 fidelity: निष्ठा 0..100 होना चाहिए +@msg file version {0} is newer than this VectorCraft supports ({VERSION}) फ़ाइल संस्करण {0} इस वेक्टर क्रेफ्ट समर्थन ({VERSION}) की तुलना में नया है। +@msg files must be {name, dataBase64} files: फ़ाइलों को {name, dataBase64} होना चाहिए +@msg finish editing the pattern first पहले पैटर्न को संपादित करना +@msg First measured segment no longer exists पहले मापा खंड अब मौजूद नहीं है +@msg fit must be none|autoHeight|shrinkText, got {id} fit को none|autoHeight|shrinkText होना चाहिए, {id} मिला +@msg Flare click coordinates must be finite numbers फ्लेयर क्लिक निर्देशांक परिमित संख्या होना चाहिए +@msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. फ्लैट लोगो ने {_1} × {_2} पिक्सेल पर इमेज का पता लगाया, जो {_3} × {_4} से नीचे है। +@msg Flatten Transparency: {e} Flatten transparency: {e} +@msg Flatten Transparency: select objects to flatten Flatten Transparency: ऑब्जेक्ट्स को सपाट करने के लिए चुनें +@msg flattener: {e} Flattener: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low या सेव किया हुआ प्रीसेट (flattener.presets.list देखें) +@msg flipProfile must be along|across, got {o} flipProfile को along|across होना चाहिए, {o} मिला +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none, rows, format, item या itemFormat +@msg folders deeper than {MAX_BATCH_DEPTH} levels {MAX_BATCH_DEPTH} स्तरों की तुलना में फ़ोल्डर्स गहरा +@msg folders deeper than {MAX_DEPTH} levels फ़ोल्डर्स {MAX_DEPTH} स्तरों से गहरा +@msg font family `{family}` is not available फ़ॉन्ट परिवार `{family}` उपलब्ध नहीं है +@msg font family `{tf}` is not available फ़ॉन्ट परिवार `{tf}` उपलब्ध नहीं है +@msg fonts not copied: {fonts} फ़ॉन्ट कॉपी नहीं हुए: {fonts} +@msg format `{f}`: pdf or postscript फ़ॉर्मैट `{f}`: pdf or postscript +@msg format `{f}`: text or json फ़ॉर्मैट `{f}`: टेक्स्ट या json +@msg format is `{format}` फ़ॉर्मैट `{format}` है +@msg formats must be an array of rows, not {v} formats: फ़ॉर्मैट पंक्तियों की एक सरणी होना चाहिए, न कि {v} +@msg freeform line {i} must be an array of point indices फ्रीफॉर्म लाइन {i} को पॉइंट इंडेक्स की एक सरणी होना चाहिए +@msg freeform point {i} needs `at` [x, y] and a valid `color` फ्रीफॉर्म पॉइंट {i} को `at` [x, y] और एक वैध `color` की आवश्यकता होती है +@msg frequency must be between 1 and 300 lines per inch frequency: आवृत्ति प्रति इंच 1 और 300 लाइनों के बीच होना चाहिए +@msg from and to must be finite से और होना चाहिए करने के लिए +@msg from must be [x0, y0, x1, y1] from: से होना चाहिए [x0, y0, x1, y1] +@msg give {key, value} or {values} {key, value} or {values} +@msg give `{a}` and `{b}` देना `{a}` and `{b}` +@msg give `anchor`, the index of the anchor to slide खिसकाने वाले एंकर का इंडेक्स `anchor` दें +@msg give `before` or `after`, not both `before` या `after` दें, दोनों नहीं +@msg give `char` or `text` देना `char` or `text` +@msg give `colors`, or `color` and `rule` देना `colors`, या `color` और `rule` +@msg give `event`, such as onclick देना `event`, जैसे onclick +@msg give `file`, the JavaScript file's path or URL देना `file`, जावास्क्रिप्ट फ़ाइल का पाथ या यूआरएल +@msg give `fill` and/or `stroke` `fill` और/or`stroke` +@msg give `fill`, `stroke` or both `fill`, `stroke` या दोनों +@msg give `folder` देना `folder` +@msg give `fonts`, or open a document देना `fonts`, या एक डॉक्यूमेंट ओपन करें +@msg give `from` or `indices`, not both `from` या `indices` दें, दोनों नहीं +@msg give `id` (no text is being edited) देना `id` (कोई टेक्स्ट संपादित नहीं किया जा रहा है) +@msg give `id` and `anchors`, or `items`, not both देना `id` और `anchors`, या `items`, दोनों नहीं +@msg give `id` or `guide`, not both देना `id` or `guide`, दोनों नहीं +@msg give `inkLimit`, `removeWhiteOverprint` or `overprintBlack` देना `inkLimit`, `removeWhiteOverprint` or `overprintBlack` +@msg give `length` or `to` `length` या `to` देना +@msg give `matches`: [{kind, name, target}] `matches`: [{kind, name, target}] +@msg give `name` (or edit a pattern) `name` (या एक पैटर्न संपादित करें) +@msg give `name` or `names` `name` या `names` दें +@msg give `path` (a .wasm file) or `dataBase64` (the module) `path` (a .wasm file) या `dataBase64` (module) +@msg give `path`, `data` or `dataBase64` देना `path`, `data` या `dataBase64` +@msg give `path`, `data`, `dataBase64` or `csv` देना `path`, `data`, `dataBase64` या `csv` +@msg give `path`, `xml` or `dataBase64` देना `path`, `xml` या `dataBase64` +@msg give `script`, the JavaScript the event runs ("" removes the event) देना `script`, जावास्क्रिप्ट घटना रन (""" घटना को हटा देता है) +@msg give `text` (the reading) or `remove` `text` (remove`) या `remove` +@msg give `width` or `height` `width` या `height` दें +@msg give `x` and `y` (and a `tolerance` of 0 or more) `x` और `y` दें (और 0 या अधिक `tolerance`) +@msg give a fraction `t` from 0 to 1 0 से 1 तक एक अंश `t` देना +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments एक मोड या आर / जी / बी, सी / एम / वाई / के, ग्रे या टिंट समायोजन देते हैं +@msg give a name, or paint the active proxy with a saved preset एक सेव किए गए प्रीसेट के साथ सक्रिय प्रॉक्सी को नाम देना, या पेंट करना +@msg give a name, or select a stroke with a saved profile एक नाम देना, या एक बचाया प्रोफ़ाइल के साथ एक स्ट्रोक का सिलेक्शन +@msg give a pattern name or select an object painted with a pattern एक पैटर्न का नाम देना या एक पैटर्न के साथ चित्रित एक ऑब्जेक्ट का सिलेक्शन करना +@msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` इनमें से कम से कम एक दें: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` +@msg give at least one of clip, invert, disabled, linked कम से कम एक क्लिप, उलटा, विकलांग, लिंक्ड देना +@msg give both `start` and `end` [x, y] (or neither) `start` और `end` दोनों [x, y] दें (या दोनों न दें) +@msg give color, none, swatch or gradient रंग, कोई नहीं, घड़ी या ग्रेडिएंट देना +@msg give corners of the path: anchors between two straight sides पाथ के कोने: दो सीधे पक्षों के बीच एंकर +@msg give corners of the path: anchors where its sides meet at an angle पाथ के कोने: एंकर जहां इसके पक्ष एक कोण पर मिलते हैं +@msg give dataBase64 dataBase64 दें +@msg give either at (a click) or area (a path drawn around the overlaps) या तो (एक क्लिक) या क्षेत्र (ओवरलैप के चारों ओर खींचा गया एक पाथ) देना +@msg give fill, stroke, opacity and/or blend भरने, स्ट्रोक, अपारदर्शिता और/या मिश्रण देते हैं +@msg give formats or a preset, not both फ़ॉर्मैट या एक पूर्व निर्धारित देना, दोनों ही नहीं +@msg give horizontal or vertical क्षैतिज या ऊर्ध्वाधर देना +@msg give newName or delete newName या delete दें +@msg give offset or by ऑफसेट देना या by +@msg give one of `to`, `rect` or `at` `to`, `rect` या `at` में से एक देना +@msg give one of assets, layers, selection or fullDocument assets, layers, selection या fullDocument में से एक दें +@msg give only one of onto, above, below, icon and a column place केवल ऊपर, नीचे, आइकन और एक स्तंभ स्थान देने के लिए +@msg give only one of onto, below and above नीचे और ऊपर केवल एक देना +@msg give origin: [x, y], or reset: true मूल देना: [x, y], या रीसेट करें: सच +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note overprintFill, overprintStroke, showCenter, imageMap, url या नोट +@msg give path (a file) or folder पाथ (एक फ़ाइल) या फ़ोल्डर देना +@msg give path, or name and dataBase64 path या name और dataBase64 दें +@msg give paths or files पाथ या फ़ाइलों को देना +@msg give rows, rowHeight, columns or columnWidth rows, rowHeight, columns या columnWidth दें +@msg give svg, or dataBase64 of an SVG or SVGZ file एक SVG या SVGZ फ़ाइल के svg, या dataBase64 देना +@msg give text टेक्स्ट देना +@msg give the asset a name संपत्ति को एक नाम देना +@msg give the path `id` पाथ देना `id` +@msg give the path `id` and the width point `index` पाथ `id` और चौड़ाई बिंदु `index` देना +@msg give the preset a `name` प्रीसेट देना `name` +@msg give the preset a name प्रीसेट को एक नाम देना +@msg give the preset a name (1–64 characters) प्रीसेट का नाम दें (1–64 अक्षर) +@msg give the settings to change, e.g. {"formats"}]} सेटिंग्स को बदलने के लिए, उदाहरण के लिए {"formats"}]} +@msg give the style a name स्टाइल को एक नाम दें +@msg give two or more style `names` दो या अधिक स्टाइल `names` +@msg give two or more swatches दो या अधिक swatch +@msg give x, y, or a handle's length or angle x, y, या एक हैंडल की लंबाई या कोण देना +@msg Global Edit is off ग्लोबल एडिट बंद है +@msg Global Edit works on paths, compound paths, symbol instances and groups of them ग्लोबल एडिट पाथ, मिश्रित पाथ, सिंबल उदाहरणों और उनके समूहों पर काम करता है +@msg global must be true or false global: वैश्विक होना चाहिए या गलत होना चाहिए +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} चरित्र की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है। +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} Glyph {g} {_1} {_2} में {ch} का एक वैकल्पिक नहीं है। +@msg gradient “{name}” isn't defined in the file: a plain colour stands in for it ग्रेडिएंट "{name}" को फ़ाइल में परिभाषित नहीं किया गया है: इसके लिए एक सादे रंग खड़ा है +@msg gradient must be "objects" or "mesh" gradient: ग्रेडिएंट "objects" या "mesh" होना चाहिए +@msg graphs come in as plain art, without their data or settings ग्राफ़ अपने डेटा या सेटिंग्स के बिना सादे कला के रूप में आते हैं +@msg grays must be "profile" or "black", not `{g}` grays: ग्रे "प्रोफ़ाइल" या "काला" होना चाहिए, नहीं `{g}` +@msg gridColors must be a preset name or two colours gridColors को प्रीसेट नाम या दो रंग होना चाहिए +@msg gridSize must be small, medium or large gridSize को small, medium या large होना चाहिए +@msg group must be the id of a Shaper Group group: समूह को एक शेपर ग्रुप का आईडी होना चाहिए +@msg group must be true or false group: समूह को सच या झूठा होना चाहिए +@msg guide {g} is not selected गाइड {g} नहीं चुना गया है +@msg guides are locked गाइड लॉक कर रहे हैं +@msg handle must be 0..3 handle को 0..3 होना चाहिए +@msg handle must be in or out handle: संभालना चाहिए या बाहर होना चाहिए +@msg heightWidth must be from 1 to 1000 % heightWidth को 1 से 1000 % होना चाहिए +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (डिफ़ॉल्ट), "omit" या "visible" +@msg highlight a layer to merge into में विलय करने के लिए एक लेयर को हाइलाइट करें +@msg highlight two or more rows in one layer or group एक लेयर या समूह में दो या अधिक पंक्तियों को हाइलाइट करें +@msg highlight two or more rows to merge दो या अधिक पंक्तियों को मर्ज करने के लिए हाइलाइट करें +@msg HTML Text applies to object slices of type only एचटीएमएल टेक्स्ट केवल टाइप के ऑब्जेक्ट स्लाइस पर लागू होता है +@msg icon docks a panel in the icon column: use window.panel.dock आइकन कॉलम में एक पैनल डॉक करता है: विंडो का उपयोग करें.पैनल.dock +@msg icon must be true or false icon: आइकन सही या झूठी होना चाहिए +@msg icon only docks a panel in the icon column, with no anchor आइकन केवल आइकन कॉलम में एक पैनल को डॉक करता है, जिसमें कोई एंकर नहीं होता है +@msg id {value} is a layer, not an object Id {value} एक लेयर है, कोई ऑब्जेक्ट नहीं है +@msg id {value} is a layer, not an object; move layers with layer.move Id {value} एक लेयर है, कोई ऑब्जेक्ट नहीं है; लेयर के साथ लेयर्स को स्थानांतरित करें। +@msg id must be a dimension id id: आईडी एक आयाम आईडी होना चाहिए +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) ऑब्जेक्ट्स को XML ID से पहचानें: नाम एक वैध XML ID होना चाहिए (एक पत्र, अंडरस्कोर या कॉलोन के साथ शुरू; कोई स्थान नहीं) +@msg ids must contain 1–10000 object ids ids में 1–10000 ऑब्जेक्ट ids होना चाहिए +@msg image '{key}' has no pixels and was left out इमेज '{key}' में कोई पिक्सेल नहीं है और इसे छोड़ दिया गया था +@msg image {_1} is linked already इमेज {_1} पहले से ही जुड़ा हुआ है +@msg image data `{_1}` is missing इमेज डेटा `{_1}` लापता है +@msg image has no bounds इमेज में कोई सीमा नहीं है +@msg image is empty इमेज खाली है +@msg Image Trace failed: {e} इमेज ट्रेस विफल: {e} +@msg Image Trace failed: internal error: its thread stopped (please report this bug) इमेज ट्रेस विफल: आंतरिक त्रुटि: इसके धागे को बंद कर दिया (कृपया इस बग की रिपोर्ट करें) +@msg Image Trace finished, but its document was closed इमेज ट्रेस समाप्त हो गया, लेकिन इसका डॉक्यूमेंट बंद हो गया। +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इस बीच इमेज या इसकी सेटिंग्स बदल गई: इसे फिर से ट्रेस करें +@msg Image Trace: the traced image is missing इमेज ट्रेस: ज्ञात इमेज गायब है +@msg image would be too large; lower the resolution इमेज बहुत बड़ी होगी; संकल्प को कम करें +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client या server +@msg Imported {what}: {_1} आयात {what}: {_1} +@msg Imported library {name} आयातित लाइब्रेरी {name} +@msg included must be true or false included: इसमें सही या गलत होना चाहिए +@msg index must be ≥ 0 index: सूचकांक होना चाहिए ≥ 0 +@msg index must be a number or first, previous, next or last index: सूचकांक एक नंबर या पहले होना चाहिए, पिछले, अगले या आखिरी +@msg index must be a number or first, previous, next or last, not `{other}` index: सूचकांक एक नंबर या पहले होना चाहिए, पिछले, अगले या आखिरी, नहीं `{other}` +@msg index out of range रेंज से बाहर सूचकांक +@msg Installed plug-in {_1} स्थापित प्लग-इन {_1} +@msg installing from a path is not available on the web; pass the module as `dataBase64` एक पाथ से स्थापित वेब पर उपलब्ध नहीं है; मॉड्यूल को `dataBase64`` के रूप में पास करें +@msg instances must be 1..1000 instances: उदाहरण 1..1000 +@msg instruction budget निर्देश बजट +@msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) `{cmd}` में आंतरिक त्रुटि: {msg} (लेखन पहले ही छोड़ दिया गया था); कृपया इस बग की रिपोर्ट करें) +@msg internal error: {msg} (please report this bug) आंतरिक त्रुटि: {msg} (कृपया इस बग की रिपोर्ट करें) +@msg Internal error: {msg} (please report this bug) आंतरिक त्रुटि: {msg} (कृपया इस बग की रिपोर्ट करें) +@msg invalid `color` अमान्य `color` +@msg invalid anchor index {v}: expected a non-negative integer अमान्य एंकर इंडेक्स {v}: एक गैर-नकारात्मक पूर्णांक की उम्मीद +@msg invalid anchor reference {v}: expected [subpath, anchor] अमान्य एंकर संदर्भ {v}: उम्मीद [subpath, एंकर] +@msg invalid angle अमानवीय कोण +@msg invalid brush: {e} अमान्य ब्रश: {e} +@msg invalid color अमान्य रंग +@msg invalid colour {c} अमान्य रंग {c} +@msg invalid delta अवैध डेल्टा +@msg Invalid dimension distance अमान्य आयाम दूरी +@msg Invalid dimension font name अमान्य आयाम फ़ॉन्ट नाम +@msg Invalid dimension offset अमान्य आयाम ऑफसेट +@msg Invalid drawing scale अमान्य ड्राइंग स्केल +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - Invalid id {_1}: A-Z a-z 0-9 से 1-64 अक्षरों का उपयोग करें। +@msg invalid image data for `{0}` `{0}` के लिए अमान्य इमेज डेटा +@msg invalid native panel set अमान्य मूल पैनल सेट +@msg invalid object id {value}: expected a non-negative integer अमान्य ऑब्जेक्ट id {value}: एक गैर-नकारात्मक पूर्णांक की उम्मीद +@msg Invalid panel layout; restored the default dock अमान्य पैनल लेआउट; डिफ़ॉल्ट डॉक पुनर्स्थापित किया गया +@msg invalid parameter name {k} अमान्य पैरामीटर नाम {k} +@msg invalid parameters for `{cmd}`: {msg} `{cmd}` के लिए अमान्य पैरामीटर: {msg} +@msg invalid pattern tile choice अमान्य पैटर्न टाइल ऑप्शन +@msg invalid PDF setting: {0} Invalid PDF सेटिंग: {0} +@msg invalid point अमानवीय बिंदु +@msg Invalid point अमानवीय बिंदु +@msg Invalid real scale अमानवीय वास्तविक पैमाने +@msg invalid restored panel group अमान्य बहाल पैनल समूह +@msg invalid size अमान्य आकार +@msg invalid stroke widths अमान्य स्ट्रोक चौड़ाई +@msg invalid t अमान्य t +@msg invalid tolerance अमान्य सहिष्णुता +@msg is not an image VectorCraft reads एक इमेज VectorCraft पढ़ा नहीं है +@msg it decompresses to more than {_1} MB यह {_1} MB से अधिक करने के लिए decompresses +@msg it ends inside a group or compound path यह एक समूह या मिश्रित पाथ के अंदर समाप्त होता है +@msg it ends inside a layer यह एक लेयर के अंदर समाप्त होता है +@msg it ends inside a multi-layer mask यह एक बहुलेयर मास्क के अंदर समाप्त होता है +@msg it has {_1}, which VectorCraft doesn't read from it yet इसमें {_1} है, जो VectorCraft अभी तक नहीं पढ़ता है +@msg it has art outside its layers इसकी लेयर्स के बाहर कला है +@msg it has more than {MAX_NODES} objects इसमें {MAX_NODES} ऑब्जेक्ट से अधिक है +@msg it has more than one artboard इसमें एक से अधिक आर्टबोर्ड है +@msg it has no layers इसमें कोई लेयर नहीं है +@msg it has no page इसमें कोई पेज नहीं है +@msg it has too many text objects इसमें बहुत सारे टेक्स्ट ऑब्जेक्ट हैं +@msg it has too many values in a row यह एक पंक्ति में बहुत अधिक मूल्य है +@msg it has too much text इसमें बहुत ज्यादा टेक्स्ट है +@msg it uses `{at}`, which VectorCraft's PostScript reader doesn't know यह `{at}` का उपयोग करता है, जो VectorCraft के पोस्टस्क्रिप्ट रीडर को पता नहीं है +@msg it uses `{at}`, which VectorCraft's PostScript reader doesn't know, in {procs} यह `{at}` का उपयोग करता है, जो VectorCraft के पोस्टस्क्रिप्ट रीडर को पता नहीं है, {procs} में +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) इसके आर्टबोर्ड सभी कैनवास से परे हैं (मूल से {_1} pt से अधिक) +@msg its clipping masks are nested too deeply इसके क्लिपिंग मास्क बहुत गहराई से घोंसले होते हैं +@msg its editing data doesn't say where its art is इसके संपादन डेटा का कहना नहीं है कि इसकी कला कहाँ है +@msg its editing data doesn't say where its artboard is इसके संपादन डेटा का कहना नहीं है कि इसका आर्टबोर्ड कहां है? +@msg its editing data has no layers इसके संपादन डेटा में कोई लेयरें नहीं हैं +@msg its editing data is damaged इसके संपादन डेटा क्षतिग्रस्त हो जाता है +@msg its editing data is for a {w} × {h} pt page, not the file's {pw} × {ph} pt page इसके संपादन डेटा एक {w} × {h} pt page के लिए है, फ़ाइल का {pw} × {ph} pt page +@msg its editing data is for a {w} × {h} pt page, the file's {pw} × {ph} pt page at {scale} इसके संपादन डेटा एक {w} × {h} pt page के लिए है, फ़ाइल का {pw} × {ph} pt page {scale} पर +@msg its editing data is for a different page इसके संपादन डेटा एक अलग पृष्ठ के लिए है +@msg its layers use {_1}, which aren't read yet इसकी लेयरें {_1} का उपयोग करती हैं, जो अभी तक पढ़ा नहीं जाता है +@msg its metadata has no description इसके मेटाडाटा में कोई विवरण नहीं है +@msg its metadata has no direct length इसके मेटाडाटा में कोई सीधी लंबाई नहीं है +@msg its objects are nested too deeply इसकी ऑब्जेक्टएं बहुत गहराई से घोंसले हैं +@msg its page has text, and its layers have no text objects to put it in इसके पृष्ठ में टेक्स्ट है, और इसकी लेयर्स में कोई टेक्स्ट ऑब्जेक्ट नहीं है जिसे इसमें डाल दिया जाता है +@msg its preview was placed instead, at screen resolution इसके बजाय इसके प्रीव्यू को स्क्रीन रिज़ॉल्यूशन पर रखा गया था। +@msg its section ending with `%{end}` doesn't end इसका खंड `%{end}` के साथ समाप्त नहीं होता है +@msg its type is to come in as outlines, which only its page has इसके प्रकार को रूपरेखा के रूप में जाना जाता है, जो केवल इसके पेज में है +@msg its Windows metafile preview was opened instead, which may simplify the art इसके बजाय विंडोज मेटाफ़ाइल प्रीव्यू ओपन किया गया था, जो कला को सरल बना सकता है +@msg its zlib compression is damaged इसके zlib संपीड़न क्षतिग्रस्त है +@msg its Zstandard compression is damaged इसके Zstandard संपीड़न क्षतिग्रस्त है +@msg join needs open paths join: खुले रास्ते की जरूरत +@msg join two different paths दो अलग-अलग पाथ में शामिल हों +@msg Join: a subpath went missing जॉइन: कोई सबपाथ नहीं मिला +@msg justify must be auto|left|center|right|justifyAll justify को auto|left|center|right|justifyAll होना चाहिए +@msg kbps must be a positive number, not {kbps} kbps एक सकारात्मक संख्या होना चाहिए, नहीं {kbps} +@msg kerning must be a number, "auto", or "optical" kerning एक संख्या, "ऑटो", या "ऑप्टिकल" होना चाहिए +@msg keywords must be a list of words or a comma-separated string keywords: कीवर्ड शब्दों की एक सूची होना चाहिए या एक अल्पसंख्यक स्ट्रिंग होना चाहिए +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters keywords: कीवर्ड नियंत्रण वर्णों के बिना, अधिकांश {MAX_KEYWORD} वर्णों पर होना चाहिए +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind: टाइप 1, 2 या 3 होना चाहिए, या प्रीसेट `name` देना चाहिए (see पर्सपेक्टिव.presets.list) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind को graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle या paraStyle होना चाहिए +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout: नॉकआउट को "on", "off", "न्यूट्रल" या एक बोल, न {v} होना चाहिए +@msg lang must be one of {_1} lang: लैंग को {_1} में से एक होना चाहिए +@msg larger than 256 MB 256 MB से अधिक +@msg layer `{name}` has no art to export लेयर `{name}` को निर्यात करने के लिए कोई कला नहीं है +@msg layer must name a layer or sublayer layer: लेयर को एक लेयर या सबलेयर नाम देना चाहिए +@msg layers can't be intertwined: select the objects in them लेयर्स में हस्तक्षेप नहीं किया जा सकता है: उनमें ऑब्जेक्ट्स सिलेक्ट करें +@msg layers can't be wrap objects लेयर्स को लपेटा नहीं जा सकता +@msg layers go only at the top level or in layers, objects in layers and groups लेयरें केवल शीर्ष स्तर पर या लेयर्स में, लेयर्स और समूहों में ऑब्जेक्टएं +@msg layers must be true or false layers: लेयरें सत्य या झूठी होनी चाहिए +@msg layout must be gridByRow, gridByColumn, row or column layout को gridByRow, gridByColumn, row या column होना चाहिए +@msg leading must be a number or "auto" leading: अग्रणी एक नंबर या "ऑटो" होना चाहिए +@msg left/right must be non-negative widths बाएं / दाएं गैर-नकारात्मक चौड़ाई होना चाहिए +@msg level `{t}`: 2 or 3 स्तर `{t}`: 2 या 3 +@msg library panel `{given}` isn't missing its library लाइब्रेरी पैनल `{given}` अपने लाइब्रेरी को याद नहीं कर रहा है +@msg library panel `{given}` isn't open लाइब्रेरी पैनल `{given}` खुला नहीं है +@msg line {line}: more than {MAX_CSV_COLS} columns लाइन {line}: {MAX_CSV_COLS} कॉलम से अधिक +@msg line {line}: unclosed quote लाइन {line}: unclosed उद्धरण +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes लाइन {line}: `{var}` के लिए मूल्य {MAX_GRAPH_CSV} बाइट्स से अधिक है +@msg line {line}: value for `{var}` must be true or false लाइन {line}: `{var}` के लिए मान सही या झूठ होना चाहिए +@msg line {line}: value for `{var}` must match its variable kind लाइन {line}: `{var}` के लिए मान इसके परिवर्तनीय प्रकार से मेल खाता होना चाहिए +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf या crlf +@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel लिंक किए गए चित्रों से पता चलता है कि फ़ाइल में सेव किए जाने वाले निम्न-रिज़ॉल्यूशन प्रीव्यू को उनकी फ़ाइलों को मिलने तक: लिंक पैनल में उन्हें फिर से लिंक करें +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel फ़ाइल में कोई प्रीव्यू के साथ जुड़े चित्र एक प्लेसहोल्डर दिखाते हैं जब तक कि उनकी फ़ाइलें नहीं मिलती: उन्हें लिंक पैनल में फिर से लिंक करें +@msg linked type areas past VectorCraft's limits were left out संबंधित प्रकार के क्षेत्र अतीत VectorCraft की सीमाओं को छोड़ दिया गया था +@msg Live Paint Merge: select a Live Paint group and the paths to add लाइव पेंट मर्ज: जोड़ने के लिए एक लाइव पेंट समूह और पाथ सिलेक्ट करें +@msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first लाइव पेंट पाथ और यौगिक पाथ लेता है: प्रकार, इमेज और अन्य ऑब्जेक्ट्स को पहले पाथ में परिवर्तित करें +@msg Live Paint: select paths or compound paths लाइव पेंट: पाथ या यौगिक पाथ सिलेक्ट करें +@msg Live Paint: these paths are too degenerate to paint लाइव पेंट: इन पाथ को पेंट करने के लिए बहुत अलग किया जाता है +@msg loading profiles from disk isn't available in the browser डिस्क से लोडिंग प्रोफ़ाइल ब्राउज़र में उपलब्ध नहीं है +@msg Loading VectorCraft… वेक्टर क्रेफ्ट लोड हो रहा है ... +@msg Lock Workspace is not available in VectorCraft लॉक वर्कस्पेस VectorCraft में उपलब्ध नहीं है +@msg Make Guides: select paths गाइड बनाना: पाथ सिलेक्ट करें +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) प्रकटन {_1} बाइट्स (limit {MAX_MANIFEST_BYTES}) +@msg manifest is not UTF-8 manifest: प्रकट नहीं है UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) प्रकटन बहुत लंबा है (सीमा {MAX_MANIFEST_BYTES} बाइट्स) +@msg manifest: {e} प्रकटन: {e} +@msg margin: a {m} pt margin leaves no imageable area on the paper मार्जिन: एक {m} pt मार्जिन कागज पर कोई इमेजेबल क्षेत्र नहीं छोड़ता है +@msg mask art ends outside a mask dictionary मास्क कला एक मास्क शब्दकोश के बाहर समाप्त होता है +@msg matrix must be finite and invertible, depth finite matrix: मैट्रिक्स को परिमित और उलटा, गहराई परिमित होना चाहिए +@msg matte: {e} मैट: {e} +@msg Measured anchor no longer exists मापने वाला एंकर अब मौजूद नहीं है +@msg Measured segment no longer exists मापदंड अब मौजूद नहीं है +@msg member is for order front, forward, backward or back सदस्य ऑर्डर फ्रंट, फॉरवर्ड, बैकवर्ड या बैक के लिए है +@msg memory budget (the selection is too large to hand over) स्मृति बजट (चुनाव बहुत बड़ा है) +@msg missing `{k}` लापता `{k}` +@msg missing `{key}` लापता `{key}` +@msg missing `align` लापता `align` +@msg missing `artboards` लापता `artboards` +@msg missing `at` [x, y] लापता `at` [x, y] +@msg missing `attrs` लापता `attrs` +@msg missing `color` or `opacity` लापता `color` या `opacity` +@msg missing `colors` लापता `colors` +@msg missing `commands` लापता `commands` +@msg missing `destinationFolder` लापता `destinationFolder` +@msg missing `effect` `effect` अनुपस्थित है +@msg missing `effect` id `effect` आईडी अनुपस्थित है +@msg missing `family` `family` अनुपस्थित है +@msg missing `find` लापता `find` +@msg missing `folder` लापता `folder` +@msg missing `gid` (a glyph id, or null for the default glyph) लापता `gid` (a glyph id, या डिफ़ॉल्ट glyph के लिए null) +@msg missing `group` लापता `group` +@msg missing `id` लापता `id` +@msg missing `id` (see plugin.list) अनुपलब्ध `id` (information.list) +@msg missing `id`: give one, or select one type object लापता `id`: एक देना, या एक प्रकार का ऑब्जेक्ट चुनें +@msg missing `index` (a point index, or null to clear) लापता `index` (a बिंदु सूचकांक, या स्पष्ट करने के लिए null) +@msg missing `index` (a stop index, or null to clear) लापता `index` (a स्टॉप इंडेक्स, या स्पष्ट करने के लिए null) +@msg missing `index` (an item index or null) लापता `index` (एक आइटम सूचकांक या null) +@msg missing `item` लापता `item` +@msg missing `kind` लापता `kind` +@msg missing `library` लापता `library` +@msg missing `library` (see brush.libraries) `library` अनुपस्थित है (brush.libraries देखें) +@msg missing `library` (see graphicStyle.libraries) लापता `library` (graphicStyle.libraries देखें) +@msg missing `library` (see swatch.library.list) लापता `library` (swatch.library.list देखें) +@msg missing `library` (see symbol.libraries) `library` अनुपस्थित है (symbol.libraries देखें) +@msg missing `map` (rows [{from, to}] or {current}) लापता `map` (rows [{from, to}] या {current}) +@msg missing `matrix` [a,b,c,d,e,f] लापता `matrix` [a,b,c,d,e,f] +@msg missing `name` लापता `name` +@msg missing `name` (see gradient.presets.list) लापता `name` (view gradient.presets.list) +@msg missing `offset` (a distance in points) लापता `offset` (बिंदुओं में एक दूरी) +@msg missing `path` लापता `path` +@msg missing `path` (a path object id) लापता `path` (एक पाथ ऑब्जेक्ट आईडी) +@msg missing `rule` लापता `rule` +@msg missing `source` id लापता `source` id +@msg missing `start` (the byte offset of a character) `start` अनुपस्थित है (अक्षर का बाइट ऑफ़सेट) +@msg missing `status`: linked, embedded, missing or modified लापता `status`: लिंक्ड, एम्बेडेड, लापता या संशोधित +@msg missing `target` id लापता `target` id +@msg missing `text` लापता `text` +@msg missing `to` `to` अनुपस्थित है +@msg missing `to` (an index) लापता `to` (an index) +@msg missing `to`: a non-negative integer `to` अनुपस्थित है: एक गैर-ऋणात्मक पूर्णांक चाहिए +@msg missing `tool` लापता `tool` +@msg missing `type` लापता `type` +@msg missing `value` लापता `value` +@msg missing anchor लापता एंकर +@msg missing anchors लापता एंकर +@msg missing anchors [[subpath, anchor]…] लापता एंकर [[subpath, एंकर]...] +@msg missing array `{key}` लापता सरणी `{key}` +@msg missing case लापता मामला +@msg missing color लापता रंग +@msg missing commands लापता आदेश +@msg missing destination folder लापता गंतव्य फ़ोल्डर +@msg missing from से लापता +@msg missing group लापता समूह +@msg missing id लापता आईडी +@msg missing id or ids लापता आईडी या ids +@msg missing ids लापता ids +@msg missing index लापता सूचकांक +@msg missing indexes लापता सूचकांक +@msg missing integer `{key}` लापता integer `{key}` +@msg missing matrix [a,b,c,d,e,f] लापता मैट्रिक्स [a,b,c,d,e,f] +@msg missing name लापता नाम +@msg missing number `{key}` लापता संख्या `{key}` +@msg missing op लापता ओप +@msg missing or invalid `color` लापता या अमान्य `color` +@msg missing or unknown `tool` लापता या अज्ञात `tool` +@msg missing panel layout लापता पैनल लेआउट +@msg missing point लापता बिंदु +@msg missing point [x,y] लापता बिंदु [x,y] +@msg missing point `{key}` ([x, y]) लापता बिंदु `{key}` ([x, y]) +@msg missing points लापता अंक +@msg missing points [[x,y]…] लापता अंक [[x,y]...] +@msg missing segment लापता खंड +@msg missing stops लापता ठहराव +@msg missing subpaths लापता subpaths +@msg missing target लापता लक्ष्य +@msg missing to याद करना +@msg missing x, y लापता xy +@msg mode is set, add or toggle, not `{other}` मोड सेट, ऐड या टॉगल है, नहीं `{other}` +@msg mode must be "cmyk" or "rgb" mode: मोड "cmyk" या "rgb" होना चाहिए +@msg mode must be area|onPath, got {o} mode: मोड होना चाहिए क्षेत्रफल (onPath), {o} मिला +@msg module is {_1} bytes (limit {_2}) मॉड्यूल {_1} बाइट्स (सीम {_2}) है। +@msg more than {MAX_BATCH_FILES} data sets {MAX_BATCH_FILES} डेटा सेट से अधिक +@msg more than {MAX_BATCH_FILES} files {MAX_BATCH_FILES} फ़ाइलों से अधिक +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS} से अधिक चर: आयात डेटा सेट अधिकांश {MAX_CSV_COLS} पर पढ़ा जाता है। +@msg more than {MAX_CSV_ROWS} data rows {MAX_CSV_ROWS} डेटा पंक्तियों से अधिक +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS} डेटा सेट से अधिक: आयात डेटा सेट अधिकांश {MAX_CSV_ROWS} पर पढ़ा जाता है। +@msg more than {MAX_FILES} images {MAX_FILES} इमेज से अधिक +@msg more than {MAX_IMPORT} presets {MAX_IMPORT} प्रीसेट से अधिक +@msg more than 10000 linked files: package dependencies in smaller parts 10000 से अधिक लिंक्ड फ़ाइलें: पैकेज निर्भरता छोटे भागों में +@msg more than 256 commands 256 से अधिक कमांड +@msg more than one action is named “{_1}” एक से अधिक कार्रवाई का नाम "{_1}" रखा गया है। +@msg Move Panel to New Window is not available: floating panels stay in the main window नई विंडो में पैनल को स्थानांतरित करना उपलब्ध नहीं है: अस्थायी पैनल मुख्य विंडो में रहते हैं +@msg move requires a destination panel move: एक गंतव्य पैनल की आवश्यकता होती है +@msg move requires an existing destination panel move: चाल एक मौजूदा गंतव्य पैनल की आवश्यकता है +@msg moved must be [[x,y]…] moved को [[x,y]…] होना चाहिए +@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode मल्टीचैनल PSD फ़ाइलों को पढ़ा नहीं जा सकता: इसे RGB, CMYK या ग्रेस्केल मोड में सेव करें +@msg name (a toolbar's name) is required नाम (एक टूलबार का नाम) की आवश्यकता होती है +@msg name (a toolbar's name) must be a string नाम (एक टूलबार का नाम) एक स्ट्रिंग होना चाहिए +@msg name is empty नाम खाली है +@msg name must be a toolbar's name name: नाम एक टूलबार का नाम होना चाहिए +@msg name the file फ़ाइल नाम +@msg names is empty नाम खाली है +@msg names must be an array of symbol names names: नाम सिंबल नामों की एक सरणी होना चाहिए +@msg need `anchor` or `segment` + `t` की जरूरत `anchor` या `segment` + `t` +@msg need at least one anchor कम से कम एक एंकर की जरूरत है +@msg need at least one point कम से कम एक बिंदु की जरूरत है +@msg need at least two points कम से कम दो बिंदुओं की आवश्यकता +@msg needs points जरूरत अंक +@msg New Window isn't available yet: a document opens in one window नई विंडो अभी तक उपलब्ध नहीं है: एक डॉक्यूमेंट एक विंडो में खुलता है +@msg nineSlice must be true or false nineSlice को true या false होना चाहिए +@msg nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1 nineSliceGuides को [left, top, right, bottom] होना चाहिए, हर मान 0..1, और left + right < 1 तथा top + bottom < 1 +@msg no action set is current कोई कार्रवाई सेट चालू नहीं है +@msg no action set to save बचाने के लिए कोई कार्रवाई सेट नहीं +@msg no active data set कोई सक्रिय डेटा सेट नहीं +@msg no active document कोई सक्रिय डॉक्यूमेंट +@msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं +@msg no anchor points selected कोई एंकर अंक नहीं चुना गया +@msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है +@msg no appearance item {index} कोई उपस्थिति आइटम {index} +@msg no artboard कोई आर्टबोर्ड नहीं +@msg no artboard {_1} नो आर्टबोर्ड {_1} +@msg no artboard {artboard} (0-based; the document has {_1}) कोई आर्टबोर्ड {artboard} (0-based); डॉक्यूमेंट में {_1} है। +@msg no artboard {i} (0-based; the document has {_1}) कोई आर्टबोर्ड {i} (0-based); डॉक्यूमेंट में {_1} है। +@msg no artboard {i} (0-based; the document has {count}) कोई आर्टबोर्ड {i} (0-आधारित); डॉक्यूमेंट में {count} है) +@msg no artboards named नामित कोई आर्टबोर्ड नहीं +@msg no artwork कोई आर्टवर्क नहीं +@msg no asset {id} कोई परिसंपत्ति {id} +@msg no asset {id} (see assets.list) कोई परिसंपत्ति {id} (Ession.list) नहीं है। +@msg no assets to export निर्यात करने के लिए कोई संपत्ति नहीं +@msg no assets yet: collect art for export first (assets.add) अभी तक कोई संपत्ति नहीं: पहले निर्यात के लिए कला इकट्ठा (assets.add) +@msg no blend options कोई मिश्रण ऑप्शन्स नहीं +@msg no bound object reports a value (locked objects and embedded images report none) कोई बाध्य ऑब्जेक्ट एक मूल्य (लॉक ऑब्जेक्ट और एम्बेडेड इमेज की रिपोर्ट नहीं) की रिपोर्ट नहीं करता है। +@msg no bounds कोई सीमा नहीं +@msg no brush `{n}` कोई ब्रश नहीं `{n}` +@msg no brush `{n}` in `{_1}` `{_1}` में कोई ब्रश `{n}` नहीं +@msg no brush library `{key}` (see brush.libraries) `{key}` ब्रश लाइब्रेरी नहीं है (brush.libraries देखें) +@msg no brush named `{n}` `{n}` नामक कोई ब्रश नहीं +@msg no brush named `{name}` कोई ब्रश जिसका नाम `{name}` है +@msg no brush selected कोई ब्रश नहीं चुना गया +@msg no catalog कोई सूची नहीं +@msg no changes since the last save आखिरी सेव के बाद से कोई बदलाव नहीं +@msg no character at byte {start} byte {start} पर कोई चरित्र नहीं +@msg no character style `{name}` कोई कैरेक्टर स्टाइल `{name}` +@msg no clock to keep a heartbeat by दिल की धड़कन को दूर रखने के लिए कोई घड़ी नहीं +@msg no color group `{name}` in the document (see swatch.list) डॉक्यूमेंट में कोई रंग समूह `{name}` (देखें swatch.list) +@msg no colour कोई रंग नहीं +@msg no colour group `{g}` कोई रंग समूह `{g}` +@msg no colour group `{group}` कोई रंग समूह `{group}` +@msg no colour group `{name}` कोई रंग समूह `{name}` +@msg no cross-reference table कोई क्रॉस-रिफरेंस टेबल नहीं +@msg no CSS to copy: select objects with CSS of their own कॉपी करने के लिए कोई सीएसएस नहीं: अपने खुद के सीएसएस के साथ ऑब्जेक्ट्स सिलेक्ट करें +@msg no current layer कोई वर्तमान लेयर नहीं +@msg no data कोई डेटा नहीं +@msg no data sets कोई डेटा सेट +@msg no dataset named `{from}` कोई डेटासेट जिसका नाम `{from}` है +@msg no dataset named `{name}` कोई डेटासेट जिसका नाम `{name}` है +@msg no datasets कोई डेटासेट +@msg no design named `{n}` `{n}` नाम का कोई डिज़ाइन नहीं +@msg no design named `{name}` `{name}` नाम का कोई डिज़ाइन नहीं +@msg no design named `{old}` `{old}` नाम का कोई डिज़ाइन नहीं +@msg no dialog open कोई संवाद नहीं खुला +@msg no document कोई डॉक्यूमेंट नहीं +@msg no document open कोई डॉक्यूमेंट खुला नहीं है +@msg no effect applied yet अभी तक लागू नहीं +@msg no effect at index {k} इंडेक्स {k} पर कोई इफ़ेक्ट नहीं +@msg no empty artboards to delete हटाने के लिए कोई खाली आर्टबोर्ड नहीं +@msg no encoder for {_1} yet अभी तक {_1} के लिए कोई एनकोडर नहीं +@msg no end record कोई अंतिम रिकॉर्ड नहीं +@msg no export preset `{n}` (see document.exportPresets.list) `{n}` एक्सपोर्ट प्रीसेट नहीं है (document.exportPresets.list देखें) +@msg no export preset `{name}` (see document.exportPresets.list) `{name}` एक्सपोर्ट प्रीसेट नहीं है (document.exportPresets.list देखें) +@msg no file manager here यहां कोई फ़ाइल मैनेजर नहीं +@msg no file reader कोई फ़ाइल रीडर नहीं +@msg no file system here यहां कोई फ़ाइल सिस्टम नहीं है +@msg no file writer कोई फ़ाइल लेखक नहीं +@msg no files to place कोई फ़ाइल नहीं +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder कोई फ़ोल्डर नहीं: पास `path` या सेट प्राथमिकताएं › प्लग-इन और स्क्रैच डिस्क › अतिरिक्त प्लग-इन फ़ोल्डर +@msg No fonts are missing कोई फ़ॉन्ट गायब नहीं हैं +@msg No fonts are missing in this document इस डॉक्यूमेंट में कोई फ़ॉन्ट गायब नहीं हैं +@msg no fonts to look for: they are all available देखने के लिए कोई फ़ॉन्ट नहीं: वे सभी उपलब्ध हैं +@msg no format to export to निर्यात करने के लिए कोई फ़ॉर्मैट नहीं +@msg no formats to export निर्यात करने के लिए कोई फ़ॉर्मैट नहीं +@msg no free data set file name in destination folder गंतव्य फ़ोल्डर में कोई मुफ्त डेटा सेट फ़ाइल नाम नहीं +@msg no free recovery area कोई मुफ्त वसूली क्षेत्र +@msg no gradient preset `{name}` (see gradient.presets.list) कोई gradient preset `{name}` (view gradient.presets.list) +@msg no gradient stop or freeform point is selected कोई क्रमिक स्टॉप या फ्रीफॉर्म पॉइंट नहीं चुना जाता है +@msg no gradient swatch `{name}` कोई gradient swatch `{name}` +@msg no graphic style `{n}` कोई ग्राफिक स्टाइल `{n}` +@msg no graphic style `{n}` in `{_1}` `{_1}` में कोई ग्राफिक स्टाइल `{n}` नहीं +@msg no graphic style `{name}` कोई ग्राफिक स्टाइल `{name}` +@msg no graphic style library `{key}` (see graphicStyle.libraries) कोई ग्राफिक स्टाइल लाइब्रेरी `{key}` (graphicStyle.libraries देखें) +@msg no guide {i} कोई गाइड {i} +@msg no guide selected कोई गाइड सिलेक्टेड नहीं +@msg no guide selected (or give an index) कोई गाइड नहीं चुना गया (या एक सूचकांक देना) +@msg no history to clear स्पष्ट करने के लिए कोई इतिहास नहीं +@msg no images in the folder फ़ोल्डर में कोई इमेज नहीं +@msg no interaction in progress प्रगति में कोई बातचीत नहीं +@msg no item at index {_1} इंडेक्स में कोई आइटम नहीं {_1} +@msg no item at index {from} इंडेक्स {from} पर कोई आइटम नहीं +@msg no item at one of the indices {idx} indices {idx} में से एक पर कोई आइटम नहीं +@msg no key object कोई कुंजी ऑब्जेक्ट नहीं +@msg no layer कोई लेयर नहीं +@msg no layer {id} (see layer.list) कोई लेयर {id} (layer.list देखें) +@msg no layers to export निर्यात करने के लिए कोई लेयरें नहीं +@msg no library `{id}` नहीं लाइब्रेरी `{id}` +@msg no library `{key}` नहीं लाइब्रेरी `{key}` +@msg no library `{key}` (see {list}) कोई लाइब्रेरी `{key}` ({list} देखें) +@msg No line breaks to remove हटाने के लिए कोई लाइन ब्रेक नहीं +@msg No linked files to look for देखने के लिए कोई लिंक्ड फ़ाइल नहीं +@msg no Live Paint edge near that point उस बिंदु के पास कोई लाइव पेंट एज नहीं +@msg no Live Paint face at that point उस बिंदु पर कोई लाइव पेंट फेस नहीं +@msg no metafile format कोई मेटाफ़ाइल फ़ॉर्मैट +@msg no native format कोई मूल फ़ॉर्मैट नहीं +@msg no object {_1} कोई ऑब्जेक्ट {_1} +@msg no object at path {shown} in the symbol's art सिंबल की कला में पाथ {shown} पर कोई ऑब्जेक्ट नहीं +@msg no objects कोई ऑब्जेक्ट नहीं +@msg no pages कोई पृष्ठ नहीं +@msg No paragraph breaks to remove हटाने के लिए कोई पैराग्राफ ब्रेक नहीं +@msg no parent layer कोई अभिभावक लेयर नहीं +@msg no Pathfinder operation applied yet अभी तक कोई पाथफाइंडर ऑपरेशन लागू नहीं है +@msg no pattern `{name}` कोई पैटर्न नहीं `{name}` +@msg no pattern named `{choice}` `{choice}` नाम का कोई पैटर्न नहीं +@msg no pattern swatch `{name}` कोई पैटर्न नहीं `{name}` +@msg no PDF preset named `{n}` कोई PDF प्रीसेट नहीं है जिसका नाम `{n}` है +@msg no perspective grid preset named `{b}` (see perspective.presets.list) कोई पर्सपेक्टिव ग्रिड प्रीसेट जिसका नाम `{b}` है (see पर्सपेक्टिव.presets.list) +@msg no perspective grid preset named `{n}` कोई पर्सपेक्टिव ग्रिड प्रीसेट जिसका नाम `{n}` है +@msg no perspective grid preset named `{name}` कोई पर्सपेक्टिव ग्रिड प्रीसेट जिसका नाम `{name}` है +@msg no plug-in {0} is installed कोई प्लग-इन {0} स्थापित नहीं है +@msg no plug-in {id} is installed कोई प्लग-इन {id} स्थापित नहीं है +@msg no PNG encoder नहीं पीएनजी एनकोडर +@msg no point {i} (the gradient has {_1}) कोई बिंदु {i} (ग्रेडेंट {_1} है) +@msg no point selected (give `index`) कोई बिंदु नहीं चुना गया (give `index`) +@msg no preset called `{from}` (see file.newPresets) `{from}` नामक कोई प्रीसेट नहीं ( file.newPresets देखें) +@msg no preset called `{name}` (see file.newPresets) `{name}` नामक कोई पूर्व निर्धारित नहीं है (file.newPresets देखें) +@msg no preset editor कोई पूर्व निर्धारित संपादक +@msg no preset named `{n}` `{n}` नाम से कोई पूर्व निर्धारित नहीं है +@msg no previous transform पिछले कोई परिवर्तन नहीं +@msg no print preset named `{b}` (see print.presets.list) `{b}` नाम से कोई प्रिंट प्रीसेट नहीं (print.presets.list देखें) +@msg no print preset named `{base}` `{base}` नामक कोई प्रिंट प्रीसेट नहीं है +@msg no print preset named `{n}` `{n}` नामक कोई प्रिंट प्रीसेट नहीं है +@msg no print preset named `{name}` कोई प्रिंट प्रीसेट जिसका नाम `{name}` है +@msg no print preset named `{name}` (presets: {_1}) `{name}` नामक कोई प्रिंट प्रीसेट नहीं (presets: {_1}) +@msg no print service कोई प्रिंट सेवा नहीं +@msg no profile named `{name}` `{name}` नामक कोई प्रोफ़ाइल नहीं +@msg no readable files in the folder फ़ोल्डर में कोई पठनीय फ़ाइल नहीं +@msg no recovery copy `{f}` (see file.recovery.list) कोई पुनर्प्राप्ति प्रतिलिपि `{f}` (file.recovery.list देखें) +@msg no revert command कोई रिवर्स कमांड नहीं +@msg no rows कोई पंक्ति नहीं +@msg no saved export preset `{name}` कोई बचाया निर्यात पूर्व निर्धारित `{name}` +@msg no saved export presets to export (name built-in ones in `names`) एक्सपोर्ट करने के लिए सेव किए हुए एक्सपोर्ट प्रीसेट नहीं हैं (अंतर्निहित प्रीसेट के नाम `names` में दें) +@msg no saved gradient preset called {name} कोई बचाया ग्रेडिएंट पूर्व निर्धारित {name} कहा जाता है +@msg no saved gradient presets कोई बचाया ग्रेडिएंट presets +@msg no saved PDF preset named `{name}` कोई बचाया PDF preset नामित `{name}` +@msg no saved PDF preset named `{name}` (built-in presets are read-only: start a new one from them) `{name}` नामक कोई सेव्ड PDF प्रीसेट नहीं (बिल्ट-इन प्रीसेट केवल पढ़ा जाता है: उनमें से एक नया प्रारंभ करें) +@msg no saved preset called `{name}` कोई बचाया प्रीसेट `{name}` कहा जाता है +@msg no saved preset named `{name}` `{name}` नामक सेव्ड प्रीसेट +@msg no saved preset named `{name}` to rename नाम बदलने के लिए `{name}` नाम की कोई बचत पूर्व निर्धारित नहीं है +@msg no saved presets कोई बचाया प्रीसेट नहीं +@msg no saved presets to export (name [Default] in `names` to export it) एक्सपोर्ट करने के लिए सेव किए हुए प्रीसेट नहीं हैं ([Default] एक्सपोर्ट करने के लिए उसका नाम `names` में दें) +@msg no saved presets to export (name built-in ones in `names`) एक्सपोर्ट करने के लिए सेव किए हुए प्रीसेट नहीं हैं (अंतर्निहित प्रीसेट के नाम `names` में दें) +@msg no saved print preset named `{name}` `{name}` नामक कोई सेव्ड प्रिंट प्रीसेट नहीं +@msg no saved print preset named `{name}` ({DEFAULT_PRESET} is protected: start a new one from it) `{name}` ({DEFAULT_PRESET} नामक कोई सेव्ड प्रिंट प्रीसेट संरक्षित नहीं है: इससे एक नया प्रारंभ करें) +@msg no saved profile called {name} कोई बचाया प्रोफ़ाइल {name} कहा जाता है +@msg no saved profiles कोई बचाया प्रोफ़ाइल नहीं +@msg no saved selection `{name}` कोई बचाया सिलेक्शन `{name}` +@msg no saved selection recalled कोई बचाया सिलेक्शन याद नहीं +@msg no saved selections कोई बचाया सिलेक्शन नहीं +@msg No saved selections (Select → Save Selection…) कोई बचाया सिलेक्शन नहीं (चुनें → सिलेक्शन सेव करें) +@msg no saved theme called {name} (see colorTheme.list) कोई बचाया थीम जिसे {name} कहा जाता है (colorTheme.list देखें) +@msg no saved themes कोई बचाया विषयों +@msg no saved views कोई बचाया दृष्टिकोण +@msg No saved views (View → New View…) कोई बचाया दृष्टिकोण (देखें → नया दृश्य) +@msg no segment {segment} on line {line} कोई खंड {segment} लाइन {line} पर +@msg no selected slice in the image: select slices, or save all of them इमेज में कोई सिलेक्टेड स्लाइस नहीं: स्लाइस सिलेक्ट करें, या उनमें से सभी को बचाओ +@msg no selection bounds कोई सिलेक्शन सीमा नहीं +@msg no series {i} कोई श्रृंखला {i} +@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again कोई समान ऑब्जेक्ट नहीं पाया (घूर्णित या परिलक्षित प्रतियां मिलान नहीं की जाती हैं); वैश्विक संपादन ऑप्शन्स बदलें और फिर से प्रयास करें +@msg no slice {n} in the image (see slice.list) इमेज में कोई स्लाइस {n} नहीं ( स्लाइसलिस्ट देखें) +@msg no slice selected सिलेक्टेड कोई स्लाइस नहीं +@msg no source art कोई स्रोत कला +@msg no stop {i} (the gradient has {n}) नहीं रोक {i} (ग्रेडेंट {n} है) +@msg no style `{name}` कोई स्टाइल नहीं `{name}` +@msg no such action ऐसी कोई कार्रवाई नहीं +@msg no such action set ऐसी कोई कार्रवाई सेट नहीं +@msg no such action step ऐसी कोई कार्रवाई नहीं +@msg no such anchor ऐसा कोई एंकर नहीं +@msg no such artboard ऐसा कोई आर्टबोर्ड नहीं +@msg no such assets (see assets.list) ऐसी कोई संपत्ति नहीं (देखें परिसंपत्तियां)। +@msg no such color ऐसा कोई रंग नहीं +@msg no such document ऐसा कोई डॉक्यूमेंट नहीं +@msg no such frame anchor, or the frame would reach past the canvas इस तरह के फ्रेम एंकर नहीं, या फ्रेम कैनवास तक पहुंच जाएगा +@msg no such function key ऐसा कोई कार्य कुंजी नहीं +@msg no such layer or object ऐसी कोई लेयर या ऑब्जेक्ट नहीं +@msg no such object {0} ऐसी कोई ऑब्जेक्ट नहीं {0} +@msg no such object id {value} ऐसी कोई ऑब्जेक्ट नहीं id {value} +@msg no such objects ऐसी कोई ऑब्जेक्ट नहीं +@msg no such path anchor, or the path would reach past the canvas इस तरह के कोई पाथ एंकर नहीं, या पाथ कैनवास तक पहुंच जाएगा +@msg no such perspective grid preset ऐसा कोई पर्सपेक्टिव ग्रिड पूर्व निर्धारित नहीं है +@msg no such recent file ऐसी कोई हाल की फ़ाइल नहीं +@msg no such recent font ऐसा नहीं हाल ही में फ़ॉन्ट +@msg no such rows ऐसी कोई पंक्ति नहीं +@msg no such saved selection इस तरह के बचाया सिलेक्शन नहीं +@msg no such segment ऐसा कोई खंड नहीं +@msg no such spine point ऐसी कोई रीढ़ की हड्डी नहीं +@msg no such spine segment ऐसा कोई खंड नहीं +@msg no such subpath ऐसा कोई उप-पाथ नहीं +@msg no such user library ऐसी कोई उपयोगकर्ता लाइब्रेरी नहीं +@msg no such view कोई ऐसा दृश्य नहीं +@msg no such width point ऐसी कोई चौड़ाई बिंदु नहीं +@msg no swatch `{keep}` नहीं `{keep}` +@msg no swatch `{n}` कोई swatch `{n}` +@msg no swatch `{n}` (swatches and colour groups move separately) कोई swatch `{n}` (swatches और रंग समूहों अलग से स्थानांतरित) +@msg no swatch `{name}` कोई swatch `{name}` +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) कोई swatch लाइब्रेरी `{key}` (देखें swatch.library.list; "{DOCUMENT_SWATCHES}": डॉक्यूमेंट का swatches) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) कोई swatch लाइब्रेरी `{key}` (देखें swatch.library.list; "document": डॉक्यूमेंट के swatches) +@msg no swatch library `{key}` (see swatch.library.list) कोई swatch लाइब्रेरी `{key}` (swatch.library.list देखें) +@msg no swatch library `{l}` (see swatch.library.list) कोई swatch लाइब्रेरी `{l}` (देखें swatch.library.list) +@msg no swatch named `{n}` `{n}` नाम का कोई swatch +@msg no swatch or colour group `{n}` कोई swatch या रंग समूह `{n}` +@msg no swatch or colour group `{n}` in `{_1}` कोई swatch या रंग समूह `{n}` में `{_1}` +@msg no symbol `{n}` कोई सिंबल `{n}` +@msg no symbol `{n}` in `{_1}` `{_1}` में कोई सिंबल `{n}` +@msg no symbol instances selected सिलेक्टेड कोई सिंबल उदाहरण नहीं +@msg no symbol library `{key}` (see symbol.libraries) `{key}` सिंबल लाइब्रेरी नहीं है (symbol.libraries देखें) +@msg no symbol named `{n}` `{n}` नाम का कोई सिंबल नहीं +@msg no symbol named `{name}` `{name}` नाम का कोई सिंबल नहीं +@msg no target object has an opacity mask: select one or give `id` कोई लक्ष्य ऑब्जेक्ट एक opacity मास्क नहीं है: एक सिलेक्ट करें या `id` देना +@msg no text objects selected कोई टेक्स्ट ऑब्जेक्ट नहीं चुना गया +@msg no threaded text selected कोई थ्रेडेड टेक्स्ट नहीं चुना गया +@msg no toolbar named `{_1}` `{_1}` नाम का कोई टूलबार नहीं +@msg no toolbar named `{name}` कोई टूलबार जिसका नाम `{name}` है +@msg no tracing preset `{preset}` (see imageTrace.presets) कोई अनुरेखण पूर्व निर्धारित `{preset}` (imageTrace.presets देखें) +@msg no user library folder here यहां कोई उपयोगकर्ता लाइब्रेरी फ़ोल्डर नहीं +@msg no user library folder here (save with a path, or without one to get the data) यहां कोई उपयोगकर्ता लाइब्रेरी फ़ोल्डर नहीं (एक पाथ के साथ या बिना किसी डेटा को प्राप्त करने के लिए) +@msg no user workspace `{from}` कोई उपयोगकर्ता वर्कस्पेस `{from}` +@msg no variable named `{from}` कोई चर नाम `{from}` +@msg no variable named `{name}` कोई चर नाम `{name}` +@msg no variable named `{v}` कोई चर नाम `{v}` +@msg no variable named `{var}` कोई चर नाम `{var}` +@msg no view named `{name}` `{name}` नाम का कोई दृश्य +@msg node {_1} is not a graph node {_1} एक graph नहीं है +@msg node {_1} is not an image node {_1} एक इमेज नहीं है +@msg node {_1} is not text नोड {_1} टेक्स्ट नहीं है +@msg node {_1} is not type नोड {_1} टाइप नहीं है +@msg node {_1} is on a locked artboard नोड {_1} एक लॉक्ड आर्टबोर्ड पर है +@msg Non-finite dimension गैर-परिष्कृत आयाम +@msg None of these issues are left: check again इन मुद्दों में से कोई भी छोड़ दिया जाता है: फिर से जांच करें +@msg not a blend मिश्रण नहीं +@msg not a closed path एक बंद पाथ नहीं +@msg not a DXF drawing नहीं एक DXF ड्राइंग +@msg not a file फ़ाइल नहीं +@msg not a flattener presets file (format `{_1}`) नहीं एक flattener presets फ़ाइल (format `{_1}`) +@msg not a flattener presets file: {e} नहीं एक flattener presets फ़ाइल: {e} +@msg not a font file एक फ़ॉन्ट फ़ाइल नहीं +@msg not a gradient mesh or mesh envelope एक ग्रेडिएंट जाल या जाल लिफाफे नहीं +@msg not a graphic style library (format `{_1}`) नहीं एक ग्राफिक स्टाइल लाइब्रेरी (format `{_1}`) +@msg not a layer or group एक लेयर या समूह नहीं +@msg not a library file: {e} एक लाइब्रेरी फ़ाइल नहीं: {e} +@msg not a mesh envelope point एक जाल लिफाफा बिंदु नहीं +@msg not a PDF presets file (format `{_1}`) नहीं एक PDF प्रीसेट फ़ाइल (format `{_1}`) +@msg not a PDF presets file: {e} PDF Presets फ़ाइल नहीं: {e} +@msg not a perspective grid presets file (format `{_1}`) नहीं एक पर्सपेक्टिव ग्रिड presets फ़ाइल (format `{_1}`) +@msg not a perspective grid presets file: {e} एक पर्सपेक्टिव ग्रिड प्रीसेट फ़ाइल नहीं: {e} +@msg not a print presets file (format `{_1}`) कोई प्रिंट प्रीसेट फ़ाइल नहीं (format `{_1}`) +@msg not a print presets file: {e} एक प्रिंट प्रीसेट फ़ाइल नहीं: {e} +@msg not a PSD file PSD फ़ाइल नहीं +@msg not a shortcut set: the text doesn't start with a slash name and an opening brace एक शॉर्टकट सेट नहीं: टेक्स्ट एक स्लैश नाम और एक उद्घाटन ब्रेस के साथ शुरू नहीं होता है +@msg not a stored central record संग्रहीत केंद्रीय रिकॉर्ड नहीं +@msg not a stored or deflated central record नहीं एक संग्रहित या deflated केंद्रीय रिकॉर्ड +@msg not a valid plug-in module: {0} एक वैध प्लग-इन मॉड्यूल नहीं: {0} +@msg not a valid SVGZ file: {e} एक मान्य SVGZ फ़ाइल नहीं: {e} +@msg not a VectorCraft file: {0} एक वेक्टर क्रेफ्ट फ़ाइल नहीं: {0} +@msg not a VectorCraft shortcut set (missing `overrides`) एक VectorCraft शॉर्टकट सेट नहीं है ( `overrides`) +@msg not a WebAssembly binary (missing \0asm header) नहीं एक WebAssembly द्विआधारी (missing \0asm header) +@msg not a Word document: its compound file has no WordDocument stream एक वर्ड डॉक्यूमेंट नहीं: इसकी यौगिक फ़ाइल में WordDocument स्ट्रीम नहीं है +@msg not a Word document: its main part is not a WordprocessingML document वर्ड डॉक्यूमेंट नहीं: इसका मुख्य हिस्सा वर्डप्रोसेसिंगएमएल डॉक्यूमेंट नहीं है +@msg not a Word document: its package has no main document part नहीं एक वर्ड डॉक्यूमेंट: इसके पैकेज में कोई मुख्य डॉक्यूमेंट हिस्सा नहीं है +@msg not a Word document: its WordDocument stream doesn't start with a file information block वर्ड डॉक्यूमेंट नहीं: इसकी WordDocument धारा फ़ाइल सूचना ब्लॉक के साथ शुरू नहीं होती है +@msg not an action set file एक एक्शन सेट फ़ाइल नहीं +@msg not an EMF or WMF file नहीं एक EMF या WMF फ़ाइल +@msg not an export presets file (format `{_1}`) नहीं निर्यात presets फ़ाइल (format `{_1}`) +@msg not an export presets file: {e} एक निर्यात प्रीसेट फ़ाइल नहीं: {e} +@msg not an image VectorCraft reads (see document.formats) यह ऐसी इमेज नहीं है जिसे VectorCraft पढ़ सके (document.formats देखें) +@msg not an RTF file: it doesn't start with {\\rtf RTF फ़ाइल नहीं: यह {\rtf के साथ शुरू नहीं होता है +@msg not an RTF file: it doesn't start with not an RTF file: it doesn't start with {\rtf RTF फ़ाइल: यह एक RTF फ़ाइल के साथ शुरू नहीं होता है: यह {\rtf के साथ शुरू नहीं होता है +@msg not area type (text in a frame) outside perspective नहीं क्षेत्र के प्रकार (एक फ्रेम में टेक्स्ट) बाहर पर्सपेक्टिव +@msg not editing an opacity mask एक opacity मास्क संपादित न करें +@msg not found नहीं मिला +@msg not in pattern editing mode पैटर्न संपादन मोड में नहीं +@msg not JSON: {e} नहीं JSON: {e} +@msg not type on a path outside perspective दृष्टिकोण के बाहर एक पाथ पर टाइप न करें +@msg nothing encoded कुछ भी नहीं +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for डेटा सेट {name} में कुछ भी लागू नहीं किया गया था: कोई ऑब्जेक्ट एक चर के लिए बाध्य नहीं है, इसके लिए एक मूल्य है। +@msg nothing prints कुछ भी प्रिंट +@msg nothing selected कुछ भी नहीं चुना +@msg nothing selected is in a group कुछ भी नहीं चुना गया है एक समूह में +@msg nothing to align संरेखित करने के लिए कुछ नहीं +@msg nothing to bind बाध्य करने के लिए कुछ नहीं +@msg nothing to change बदलने के लिए कुछ भी नहीं +@msg nothing to change: give dx, dy, hScale, vScale or rotation कुछ भी बदलने के लिए: देना dx, dy, hScale, vScale या रोटेशन +@msg nothing to crop फसल के लिए कुछ नहीं +@msg nothing to distort विकृत करने के लिए कुछ भी नहीं +@msg nothing to export निर्यात करने के लिए कुछ नहीं +@msg nothing to export: the document has no visible art निर्यात करने के लिए कुछ भी नहीं: डॉक्यूमेंट में कोई दृश्य कला नहीं है +@msg nothing to export: the document has no visible art (or turn on Use Artboards) निर्यात करने के लिए कुछ भी नहीं: डॉक्यूमेंट में कोई दृश्य कला नहीं है (या उपयोग आर्टबोर्ड पर बारी) +@msg nothing to mark निशान करने के लिए कुछ भी नहीं +@msg nothing to preview प्रीव्यू करने के लिए कुछ नहीं +@msg nothing to print प्रिंट करने के लिए कुछ भी नहीं +@msg nothing to print: every artboard picked is blank मुद्रित करने के लिए कुछ भी नहीं: हर आर्टबोर्ड चुना खाली है +@msg nothing to print: the document has no art that prints प्रिंट करने के लिए कुछ भी नहीं: डॉक्यूमेंट में कोई कला नहीं है जो प्रिंट करता है +@msg nothing to redo फिर से करने के लिए कुछ नहीं +@msg nothing to save: the document has no visible art बचाने के लिए कुछ नहीं: डॉक्यूमेंट में कोई दृश्य कला नहीं है +@msg Nothing to split at the cursor कर्सर पर विभाजन करने के लिए कुछ भी नहीं +@msg nothing to undo पूर्ववत करने के लिए कुछ नहीं +@msg nothing to warp कुछ भी नहीं +@msg nothing to wrap लपेटने के लिए कुछ भी नहीं +@msg object {_1} can't be set as point type ऑब्जेक्ट {_1} को पॉइंट टाइप के रूप में सेट नहीं किया जा सकता है +@msg object {_1} has lost its file's contents: relink it ऑब्जेक्ट {_1} ने अपनी फ़ाइल की सामग्री को खो दिया है: इसे फिर से लिंक करें +@msg object {_1} has no path ऑब्जेक्ट {_1} का कोई रास्ता नहीं है +@msg object {_1} has no size ऑब्जेक्ट {_1} का कोई आकार नहीं है +@msg object {_1} is hidden or locked, or on a locked artboard ऑब्जेक्ट {_1} छिपा हुआ है या बंद कर दिया गया है, या एक लॉक्ड आर्टबोर्ड पर +@msg object {_1} is not a placed document ऑब्जेक्ट {_1} एक रखा डॉक्यूमेंट नहीं है +@msg object {_1} is not an image ऑब्जेक्ट {_1} एक इमेज नहीं है +@msg object {_1} is not an image or a linked file ऑब्जेक्ट {_1} एक इमेज या एक लिंक्ड फ़ाइल नहीं है +@msg object {_1} is not an image or a placed document ऑब्जेक्ट {_1} एक इमेज या एक रखा डॉक्यूमेंट नहीं है +@msg object {_1} is not an Intertwine group ऑब्जेक्ट {_1} एक Intertwine समूह नहीं है +@msg object {_1} is not in this Intertwine group ऑब्जेक्ट {_1} इस इंटरवाइन समूह में नहीं है +@msg object {_1} needs a 3D effect at index {index} ऑब्जेक्ट {_1} को इंडेक्स {index} पर 3D इफ़ेक्ट की जरूरत है +@msg object {0} cannot have children ऑब्जेक्ट {0} में बच्चे नहीं हो सकते +@msg object {id} has {n} anchors, so no anchor {past} ऑब्जेक्ट {id} में {n} एंकर हैं, इसलिए कोई एंकर {past} नहीं +@msg object {id} has anchors 0–{_1} for `corners`, not {past} ऑब्जेक्ट {id} में `corners` के लिए एंकर 0–{_1} हैं, {past} नहीं +@msg object {id} is not a path ऑब्जेक्ट {id} एक पाथ नहीं है +@msg object {id} is not a selected top-level object ऑब्जेक्ट {id} एक सिलेक्टेड शीर्ष स्तर की ऑब्जेक्ट नहीं है +@msg object has no weighted stroke ऑब्जेक्ट में कोई भारित स्ट्रोक नहीं है +@msg object ids are non-negative integers, not {v} ऑब्जेक्ट ids गैर-नकारात्मक पूर्णांक हैं, न कि {v} +@msg object is not a path object: ऑब्जेक्ट एक पाथ नहीं है +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object ऑब्जेक्ट पारदर्शिता को हाइलाइट किए गए पात्रों पर नमूने नहीं दिए जा सकते हैं; आइड्रॉपर ऑप्शन्स में पारदर्शिता को अक्षम करें या पूरे ऑब्जेक्ट सिलेक्ट करें +@msg objects can't be nested more than 32 deep ऑब्जेक्ट्स को 32 से अधिक गहराई तक घोंसला नहीं किया जा सकता है +@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path एक मिश्रण, लिफ़ाफ़ाफ़ा, दोहराने या अंतर्जातीय समूह के अंदर ऑब्जेक्ट्स को एक पाथ से जोड़ा नहीं जा सकता है +@msg objects must be none, move or copy objects: ऑब्जेक्टएं कोई नहीं, चाल या प्रतिलिपि होना चाहिए +@msg objects that drew differently from the file's own page came in as its art: {_1} उन ऑब्जेक्ट्स को जो फ़ाइल के स्वयं के पृष्ठ से अलग-अलग तरीके से आकर्षित होते हैं, उनकी कला के रूप में आया: {_1} +@msg objects were left out ऑब्जेक्ट्स को छोड़ दिया गया था +@msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet कई भराव या स्ट्रोक, इफ़ेक्ट या ब्रश के साथ ऑब्जेक्टएं उनके ड्रॉइंग लुक ({_1}) के रूप में आईं: उनकी उपस्थिति अभी तक संपादन योग्य नहीं है +@msg offset out of range सीमा से बाहर ऑफसेट +@msg Offset Path: {e} ऑफसेट पाथ: {e} +@msg Offset Path: select paths ऑफसेट पाथ: सिलेक्शन पाथ +@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ऑफसेट पाथ: ऑफ़सेट सिलेक्टेड पाथ की कुछ भी नहीं छोड़ता है (आकार की तुलना में एक निर्धारित बड़ा) +@msg Offset Path: the path is too complex to offset ऑफसेट पाथ: पाथ ऑफसेट करने के लिए बहुत जटिल है +@msg on must be true or false on: पर सच होना चाहिए या गलत होना चाहिए +@msg only a dock group above or below others collapses, not one beside another केवल दूसरों के ऊपर या नीचे एक डॉक समूह गिर जाता है, एक दूसरे के बगल में नहीं +@msg only an exporter declares `extensions` केवल निर्यातक `extensions` घोषित करता है +@msg only an object of the Global Edit other than the one it started from can be left out केवल ग्लोबल एडिट का एक ऑब्जेक्ट, इसके अलावा इसे शुरू किया जा सकता है, छोड़ दिया जा सकता है +@msg only groups, layers, type and images have a Contents (Characters) row केवल समूहों, लेयर्स, प्रकार और इमेज में एक सामग्री (Character) पंक्ति है +@msg only http, https and mailto URLs open in the browser, not “{url}” केवल http, https और Mailto URL ब्राउज़र में खुलते हैं, न कि "{url}" +@msg only interior mesh lines can be deleted केवल आंतरिक जाल लाइनों को हटाया जा सकता है +@msg only solid colours can be added (not gradients or patterns) केवल ठोस रंगों को जोड़ा जा सकता है (ग्रेडिएंट या पैटर्न नहीं) +@msg only solid-colour swatches can be spot colours केवल ठोस रंग की घड़ी स्पॉट रंग हो सकती है +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning केवल इस Affinity फ़ाइल के एम्बेडेड प्रीव्यू को पढ़ा जा सकता है; फ़ाइल का उपयोग करें > इसे अपनी चेतावनी के साथ देखने के लिए ओपन करें +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first केवल इस Affinity फ़ाइल के एम्बेडेड प्रीव्यू को पढ़ा जा सकता है: फ़ाइल का उपयोग करें > इसे अपनी चेतावनी के साथ देखने के लिए ओपन करें, या पहले Affinity से SVG या PDF निर्यात करें +@msg onto must name a floating panel onto: पर एक फ्लोटिंग पैनल का नाम होना चाहिए +@msg onto must name a panel floating in another group onto: किसी अन्य समूह में फ्लोटिंग पैनल का नाम होना चाहिए +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock ऊपर, नीचे, आइकन और एक स्तंभ स्थान खिड़की से संबंधित है। पैनल.फ्लोट और विंडो.पैनल.डॉक +@msg onto, above, below, icon and a column place take no anchor, side, zone or before ऊपर, नीचे, आइकन और एक स्तंभ स्थान पर कोई एंकर, साइड, जोन या पहले नहीं होता है +@msg onto, above, below, icon and a column place take no x, y, width or height ऊपर, नीचे, आइकन और एक स्तंभ स्थान पर कोई एक्स, वाई, चौड़ाई या ऊंचाई नहीं होती है +@msg open a document to look for its linked files अपनी लिंक्ड फ़ाइलों को देखने के लिए एक डॉक्यूमेंट ओपन करें +@msg open a document with data sets डेटा सेट के साथ एक डॉक्यूमेंट ओपन करें +@msg Opened {url} {url} ओपन किया गया +@msg options must be an object (see file.formatOptions) options: ऑप्शन्स एक ऑब्जेक्ट होना चाहिए (file.formatOptions देखें) +@msg order must be leftToRight or rightToLeft order को leftToRight या rightToLeft होना चाहिए +@msg orientation must be portrait or landscape, not `{o}` orientation: अभिविन्यास चित्र या परिदृश्य होना चाहिए, नहीं `{o}` +@msg others must be true or false others: दूसरों को सच होना चाहिए या गलत होना चाहिए +@msg Outline Stroke: no stroked paths selected आउटलाइन स्ट्रोक: सिलेक्टेड कोई स्ट्रोक पाथ नहीं +@msg outlineText {v}: true or false outlineText {v}: true या false +@msg output intent profile: {e} उत्पादन आशय प्रोफ़ाइल: {e} +@msg output size ({what} is {len} bytes, limit {max}) उत्पादन का आकार ({what} {len} बाइट्स है, {max} को सीमित करें) +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile उत्पादन: {_1} फ़ाइलें CMYK हैं, और "{name}" एक RGB प्रोफ़ाइल है +@msg output.destination: {e} उत्पादन.destination: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” आउटपुट: कोई RGB या CMYK प्रोफ़ाइल को "{name}" कहा जाता है। +@msg output.inks: no ink is set to print आउटपुट.ink: प्रिंट करने के लिए कोई स्याही सेट नहीं है +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: “{name}” ग्रे प्रोफ़ाइल है, जो {std} आउटपुट इंटेंट नहीं हो सकती +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std} फ़ाइलें CMYK में प्रिंट होती हैं और “{name}” RGB प्रोफ़ाइल है +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: “{name}” नाम की प्रोफ़ाइल नहीं है और {std} आउटपुट इंटेंट अपनी प्रोफ़ाइल एम्बेड करता है +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: “{name}” नाम की प्रोफ़ाइल नहीं है: {std} आउटपुट इंटेंट प्रोफ़ाइल एम्बेड करता है या पंजीकृत प्रिंट शर्त का नाम देता है (outputConditionId और registry) +@msg overlap: {o} pt is half a tile or more ओवरलैप: {o} पीटी आधा टाइल या अधिक है +@msg overlapping edits ओवरलैपिंग संपादन +@msg overlapping Shaper paths must be in the same layer or group ओवरलैपिंग शेपर पाथ एक ही लेयर या समूह में होना चाहिए +@msg Packaging {_1} पैकेजिंग {_1} +@msg page {0} does not exist (the PDF has {1}) पृष्ठ {0} मौजूद नहीं है (PDF में {1} है) +@msg page {page} of the PDF has no objects PDF के पेज {page} में कोई ऑब्जेक्ट नहीं है +@msg page {page}: `{file}` has {n} {artboards} पेज {page}: `{file}` में {n} {artboards} हैं +@msg page {page}: `{name}` has {n} {pages} पेज {page}: `{name}` में {n} {pages} हैं +@msg page art conflicts with image data for {key} {key} के लिए इमेज डेटा के साथ पृष्ठ कला संघर्ष +@msg page art conflicts with pattern {name} पैटर्न {name} के साथ पृष्ठ कला संघर्ष +@msg page art conflicts with swatch {name} Swatch {name} के साथ पृष्ठ कला संघर्ष +@msg page art is missing image data for {key} पृष्ठ कला {key} के लिए इमेज डेटा लापता है +@msg page art is missing pattern {name} पृष्ठ कला लापता पैटर्न {name} है +@msg page art is missing swatch {name} पृष्ठ कला लापता है swatch {name} +@msg page must be a whole number from 1 page: पृष्ठ 1 से एक पूरी संख्या होना चाहिए +@msg page size {w} × {h} {w} × {h} +@msg page thumbnail: {e} पेज थंबनेल: {e} +@msg pages must be a range such as "2-3" or a page number, not {v} pages: पृष्ठों को "2-3" या एक पृष्ठ संख्या के रूप में एक श्रेणी होना चाहिए, नहीं {v} +@msg pages: {e} पेज: {e} +@msg panel group is empty पैनल समूह खाली है +@msg panel is not in a dock group panel: पैनल एक डॉक समूह में नहीं है +@msg panel must name a registered panel panel: पैनल का नाम एक पंजीकृत पैनल होना चाहिए +@msg panel position must be finite पैनल की स्थिति परिमित होना चाहिए +@msg parameter `{k}`: {what} पैरामीटर `{k}`: {what} +@msg parameter `{name}`: {what} पैरामीटर `{name}`: {what} +@msg parameters must be an object parameters: पैरामीटर एक ऑब्जेक्ट होना चाहिए +@msg params must be an object params: परम एक ऑब्जेक्ट होना चाहिए +@msg part of the program isn't valid PostScript text कार्यक्रम का हिस्सा मान्य नहीं है PostScript टेक्स्ट +@msg pass newName, registration, exportType, nineSlice and/or type newName, registration, exportType, nineSlice और/या type दें +@msg passwords can have up to {MAX_PASSWORD} bytes पासवर्ड {MAX_PASSWORD} बाइट्स तक हो सकता है +@msg paste unavailable पेस्ट करें अनुपलब्ध +@msg Pasting चिपकाना +@msg path has no open end पाथ का कोई खुला अंत नहीं है +@msg path is already closed path: पाथ पहले से ही बंद हो गया है +@msg path must be a list of child indices path: बच्चे के सूचकांक की सूची होना चाहिए +@msg paths contain invalid coordinates पाथ में अमान्य निर्देशांक होते हैं +@msg paths must be strings paths: पाथ स्ट्रिंग होना चाहिए +@msg paths: give at least one file पाथ: कम से कम एक फ़ाइल दें +@msg pattern missing पैटर्न लापता +@msg patterns nested too deeply are filled with mid-grey पैटर्न घोंसला बहुत गहराई से मध्य ग्रे से भर रहे हैं +@msg PCX files with {bits}-bit pixels in {planes} planes can't be read पीसीएक्स फ़ाइलों के साथ {bits}-बिट पिक्सल {planes} विमानों में पढ़ा नहीं जा सकता है +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported PDF सामग्री अधूरे है या टेक्स्टक की सीमाओं से अधिक है; कोई डॉक्यूमेंट आयात नहीं किया गया था +@msg PDF flattener: {e} PDF flattener: {e} +@msg PDF options: {e} PDF ऑप्शन्स: {e} +@msg PDF security settings are not an object PDF सुरक्षा सेटिंग्स एक ऑब्जेक्ट नहीं हैं +@msg PDF settings are not an object PDF सेटिंग्स एक ऑब्जेक्ट नहीं हैं +@msg PDF writer error: {0} PDF लेखक त्रुटि: {0} +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false में एडिट करने योग्य आर्टवर्क रखने के लिए सभी आर्टबोर्ड चाहिए +@msg pdfs `{m}`: single or multiple pdfs `{m}`: एकल या एकाधिक +@msg percent must be above 0 and at most 6400, not {p} percent: प्रतिशत 0 से अधिक होना चाहिए और अधिक 6400 पर, नहीं {p} +@msg Persistent libraries not found: {files} Persistent लाइब्रेरीों नहीं मिला: {files} +@msg pick a colour, gradient or pattern to save as a swatch एक swatch के रूप में बचाने के लिए एक रंग, ग्रेडिएंट या पैटर्न चुनें +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom को "artwork" या "swatches" होना चाहिए, {v} नहीं +@msg pins and moved must be non-empty lists of the same length पिन और ले जाने के लिए समान लंबाई की गैर-खाली सूची होनी चाहिए +@msg pins must be [[x,y]…] pins: पिन होना चाहिए [[x,y]...] +@msg pins must be finite pins: पिन परिमित होना चाहिए +@msg place is above, below or inside, not `{other}` place: स्थान ऊपर, नीचे या अंदर है, नहीं `{other}` +@msg Placing {_1} पतंग {_1} +@msg plane must be left, right or ground plane: समतल बाएं, दाएं या जमीन होना चाहिए +@msg plane must be left|right|ground plane को left|right|ground होना चाहिए +@msg plane must be left|right|ground|none plane को left|right|ground|none होना चाहिए +@msg plug-in ABI: {0} प्लग-इन ABI: {0} +@msg plug-in exceeded its {0} प्लग-इन अपने {0} से अधिक है +@msg plug-in failed: {0} प्लग-इन विफल: {0} +@msg plug-in manifest: {0} प्लग-इन प्रकटन: {0} +@msg plug-in output: {0} प्लग-इन आउटपुट: {0} +@msg plug-in parameters must be a JSON object प्लग-इन पैरामीटर एक JSON ऑब्जेक्ट होना चाहिए +@msg plug-in parameters: {0} प्लग-इन पैरामीटर: {0} +@msg plug-in trapped: {0} प्लग-इन फँसा: {0} +@msg Plug-ins can't be loaded from {path}: {e} प्लग-इन {path} से लोड नहीं किया जा सकता: {e} +@msg point is outside the mesh बिंदु मेश के बाहर है +@msg points must be [t, left, right] with non-negative widths points: गैर-नकारात्मक चौड़ाई के साथ अंक [t, left, right] होना चाहिए +@msg points must be a non-empty [[x,y,pressure?]…] list points: अंक एक गैर-खाली होना चाहिए [[x,y, दबाव?]...] सूची +@msg points must be a non-empty list of finite [x,y] points: अंक परिमित की एक गैर-खाली सूची होना चाहिए [x,y] +@msg points must be an array or null points: अंक एक सारणी या null होना चाहिए +@msg points must be finite points: अंक परिमित होना चाहिए +@msg points must be finite [x,y] pairs points: अंक परिमित होना चाहिए [x,y] जोड़े +@msg points must contain 1–4096 coordinates points में 1–4096 निर्देशांक होने चाहिए +@msg position must be normal, superscript or subscript position: स्थिति सामान्य, सुपरस्क्रिप्ट या सबस्क्रिप्ट होना चाहिए +@msg position must be topLeft, topRight, bottomLeft or bottomRight position को topLeft, topRight, bottomLeft या bottomRight होना चाहिए +@msg positions must be between 0 and 100000 pt positions: 0 और 100000 pt के बीच होना चाहिए +@msg ppi must be a positive number, not {ppi} ppi एक सकारात्मक संख्या होना चाहिए, नहीं {ppi} +@msg ppi must be between 1 and 2400 ppi: पीपीआई 1 और 2400 के बीच होना चाहिए +@msg precision must be from 0.001 to 10 pt precision: परिशुद्धता 0.001 से 10 pt तक होना चाहिए +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}`, transforms|bounds|fileDimensions|fit|fill में से नहीं है +@msg preserveShape must be clippingMask|transparency preserveShape को clippingMask|transparency होना चाहिए +@msg preset `{id}`: mobile or density प्रीसेट `{id}`: मोबाइल या घनत्व +@msg preset must be standard, diffuse, topLeft or right preset को standard, diffuse, topLeft या right होना चाहिए +@msg preset must be the name of a print preset preset: प्रीसेट एक प्रिंट प्रीसेट का नाम होना चाहिए +@msg Preview in Browser needs the desktop app (the web downloads files instead) ब्राउज़र में प्रीव्यू डेस्कटॉप ऐप (वेब डाउनलोड फ़ाइलों के बजाय) की जरूरत है +@msg previewMode must be default, pixel or overprint previewMode को default, pixel या overprint होना चाहिए +@msg Print Ink Fixes works on CMYK documents: choose File › Document Color Mode › CMYK Color first प्रिंट इंक फिक्स CMYK डॉक्यूमेंट्स पर काम करता है: फ़ाइल चुनें › डॉक्यूमेंट रंग मोड › CMYK कलर फर्स्ट +@msg print settings are not an object प्रिंट सेटिंग एक ऑब्जेक्ट नहीं है +@msg print settings: {e} मुद्रण सेटिंग्स: {e} +@msg printing isn't available here मुद्रण यहाँ उपलब्ध नहीं है +@msg procedures nest too deeply प्रक्रियाओं घोंसला बहुत गहराई से +@msg procedures nested too deeply प्रक्रियाओं ने बहुत गहराई से घोंसले +@msg quotes must be {double?, single?} quotes को {double?, single?} होना चाहिए +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" उद्धरण.{k} एक उद्घाटन और एक समापन उद्धरण होना चाहिए, उदाहरण के लिए """"" +@msg range `{s}` is empty श्रेणी `{s}` खाली है +@msg range `{s}`: `{part}` names no number सीमा `{s}`: `{part}` कोई संख्या नहीं बताता +@msg range `{s}`: `{part}` runs backwards रेंज `{s}`: `{part}` पीछे चल रहा है +@msg range `{s}`: `{t}` is not a number from 1 to {count} सीमा `{s}`: `{t}` 1 से {count} के बीच की संख्या नहीं है +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi को 1–2400 होना चाहिए (72 स्क्रीन, 150 मध्यम, 300 उच्च) +@msg rating must be a whole number from 0 to {MAX_RATING} rating: रेटिंग 0 से {MAX_RATING} तक पूरी संख्या होना चाहिए +@msg Recolor Artwork is no longer open Recolor Artwork अब खुला नहीं है +@msg recovery copy `{file}`: {e} वसूली प्रतिलिपि `{file}`: {e} +@msg rect and {k} contradict each other: give the area or the artboards सही और {k} एक दूसरे के विपरीत: क्षेत्र या आर्टबोर्ड देना +@msg rect applies to raster formats, not {_1} सही रेस्टर फ़ॉर्मैट्स पर लागू होता है, न कि {_1} +@msg rect is [x, y, width, height] in points सही [x, y, चौड़ाई, ऊंचाई] अंक में है +@msg rect must be [x, y, width, height] rect: [x, y, चौड़ाई, ऊंचाई] होना चाहिए +@msg rect must be [x, y, width, height] with a positive width and height rect: सही होना चाहिए [x, y, चौड़ाई, ऊंचाई] सकारात्मक चौड़ाई और ऊंचाई के साथ +@msg rect needs finite numbers and a positive width and height rect: सही की जरूरत परिमित संख्या और सकारात्मक चौड़ाई और ऊंचाई +@msg redraw needs id redraw: ई.डी. की आवश्यकता +@msg redraw within must be a finite distance of 0 or more भीतर वापस लेना 0 या उससे अधिक की एक सीमित दूरी होना चाहिए +@msg registration must be 0..8 registration को 0..8 होना चाहिए +@msg Rejoin Path Pieces: too many paths to rejoin at once Rejoin पाथ के टुकड़े: एक बार में फिर से जुड़ने के लिए कई पाथ +@msg release a layer or a group एक लेयर या एक समूह को छोड़ दें +@msg Release Guides: no guides रिलीज़ गाइड: कोई गाइड नहीं +@msg Release: no layer to put the rectangle in रिलीज: आयत को डालने के लिए कोई लेयर नहीं +@msg Reload the page to go on (changes not saved yet may be lost). पेज को फिर से लोड करने के लिए (बदलने की अभी तक नहीं बचा जा सकता)। +@msg replace keeps the replaced object's place and transform: drop template, at and rect प्रतिस्थापित ऑब्जेक्ट के स्थान को बनाए रखता है और बदल देता है: ड्रॉप टेम्पलेट, पर और आयतन +@msg Replace Spine: select a blend and a path Spine: एक मिश्रण और एक पाथ चुनें +@msg replace: select the one object to replace प्रतिस्थापित करने के लिए एक ऑब्जेक्ट सिलेक्ट करें +@msg replace: the object to replace was changed or deleted प्रतिस्थापित करने के लिए ऑब्जेक्ट को बदल दिया गया था या हटा दिया गया +@msg Reset {_1} रीसेट करें {_1} +@msg resolution must be a number or screen|medium|high resolution: रिज़ॉल्यूशन एक नंबर या स्क्रीन होना चाहिए +@msg resolution must be between 1 and 2400 ppi resolution: संकल्प 1 और 2400 ppi के बीच होना चाहिए +@msg resolutions must be between 1 and 2400 ppi resolutions: संकल्प 1 और 2400 ppi के बीच होना चाहिए +@msg result would exceed the canvas (coordinates out of range) परिणाम कैनवास से अधिक होगा (श्रेणी से बाहर समन्वय) +@msg rotation must be a number of degrees rotation: रोटेशन डिग्री की एक संख्या होना चाहिए +@msg rotation must be finite rotation: रोटेशन को परिमित होना चाहिए +@msg rows and cols must be 1..50 पंक्तियां और कॉल 1..50 होना चाहिए +@msg rows and columns must be 1..500 rows और columns को 1..500 होना चाहिए +@msg rows of objects whose appearances differ can't be reordered together उन ऑब्जेक्ट्स की पंक्तियाँ जिनकी उपस्थिति भिन्न होती हैं, उन्हें एक साथ फिर से व्यवस्थित नहीं किया जा सकता है +@msg Running “{name}”… "{name}"... +@msg Save for Web: the image is empty वेब के लिए सेव करें: इमेज खाली है +@msg save the document first: copy puts the file in its folder पहले डॉक्यूमेंट को सेव करना: प्रतिलिपि फ़ाइल को अपने फ़ोल्डर में डालती है +@msg save the document first: Package collects a saved document पहले डॉक्यूमेंट को सेव करना: पैकेज एक सेव किए गए डॉक्यूमेंट एकत्र करता है +@msg Save writes {_1}, not {_2}: use document.export for other formats सेव {_1} लिखता है, {_2} नहीं: दूसरे फ़ॉर्मैट के लिए document.export उपयोग करें +@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it सेव करें {_1}, not {_2}: use file.saveAsTemplate to write it +@msg Save writes one artboard: name one, or export several with document.export सेव एक आर्टबोर्ड लिखता है: एक का नाम दें या कई आर्टबोर्ड document.export से एक्सपोर्ट करें +@msg Saved {n} files beside {path} {path} के पास {n} फ़ाइलें सेव की गईं +@msg Saved {path} सेव्ड {path} +@msg Saved {path} with {_1} note(s): {first} {_1} नोट के साथ सेव्ड {path}: {first} +@msg saved panel layout is invalid; reset the workspace first सेव किया गया पैनल लेआउट अमान्य है; वर्कस्पेस को पहले रीसेट करें +@msg Saved recovery data for {title} {title} के लिए सेव्ड रिकवरी डेटा +@msg Saved to User Defined: {_1} उपयोगकर्ता परिभाषित करने के लिए सेव किया गया: {_1} +@msg savedPreset: {e} savedPreset: {e} +@msg Saving सेव किया जा रहा है +@msg Saving {_1} बचत {_1} +@msg Saving recovery data for {_1} {_1} के लिए रिकवरी डेटा सेव करना +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) पैमाने `{s}`: एक कारक जैसे 2x, चौड़ाई (100w), ऊंचाई (100h) या एक संकल्प (72ppi) +@msg scale must be a number above 0, at most 64 scale: पैमाने 0 से अधिक होना चाहिए, अधिकांश 64 में +@msg scale must be a number from {_1} to {_2}, not {_3} scale: स्केल {_1} से {_2} के लिए एक नंबर होना चाहिए, नहीं {_3} +@msg scale must be a number from {_1} to {_2}, not {s} scale: स्केल {_1} से {_2} के लिए एक नंबर होना चाहिए, नहीं {s} +@msg Scale must be drawing:real, for example 1:10 स्केल ड्राइंग होना चाहिए:वास्तविक, उदाहरण के लिए 1:10 +@msg scale must be non-zero scale: स्केल होना चाहिए गैर-zero +@msg Scale ratio must be between 1:1000000 and 1000000:1 स्केल अनुपात 1:1000000 और 1000000:1 के बीच होना चाहिए +@msg Scale Text Attributes: selected type has no scale to bake स्केल टेक्स्ट एट्रिब्यूट्स: सिलेक्टेड प्रकार में बेक करने के लिए कोई स्केल नहीं है +@msg scope must be selection or all (got {other}) scope: गुंजाइश का सिलेक्शन होना चाहिए या सभी ({other}) होना चाहिए। +@msg scribble is too long स्क्रिबल बहुत लंबा है +@msg searching a folder isn't available on the web एक फ़ोल्डर खोज वेब पर उपलब्ध नहीं है +@msg Second measured segment no longer exists दूसरा मापा खंड अब मौजूद नहीं है +@msg seconds must be a whole number from 1 to 60 seconds: सेकंड 1 से 60 तक पूरी संख्या होना चाहिए +@msg segment does not exist खंड मौजूद नहीं है +@msg select (or target) objects whose appearance isn't basic सिलेक्शन (या लक्ष्य) ऑब्जेक्ट जिनकी उपस्थिति बुनियादी नहीं है +@msg select a blend मिश्रण सिलेक्ट करें +@msg select a blend or give `id` एक मिश्रण सिलेक्ट करें या `id` देना +@msg select a blend to set easing or color shift Easing या रंग शिफ्ट सेट करने के लिए एक मिश्रण सिलेक्ट करें +@msg select a clip group एक क्लिप समूह चुनें +@msg select a compound shape एक मिश्रित आकार चुनें +@msg Select a dimension first पहले आयाम सिलेक्ट करें +@msg select a gradient mesh एक ग्रेडिएंट जाल सिलेक्ट करें +@msg select a graph एक graph चुनें +@msg select a group or layer with visible, unlocked members दृश्यमान, अनलॉक सदस्यों के साथ एक समूह या लेयर सिलेक्ट करें +@msg select a layer एक लेयर चुनें +@msg select a linked image: an embedded one has no file एक संबद्ध इमेज चुनें: एक एम्बेडेड में कोई फ़ाइल नहीं है +@msg select a Live Paint group एक लाइव पेंट समूह चुनें +@msg select a path एक पाथ चुनें +@msg select a repeat दोहराने सिलेक्ट करें +@msg select a Shaper group एक शेपर समूह चुनें +@msg select a stroke with a variable width एक चर चौड़ाई के साथ एक स्ट्रोक सिलेक्ट करें +@msg select a symbol instance एक सिंबल उदाहरण चुनें +@msg select a text object एक टेक्स्ट ऑब्जेक्ट चुनें +@msg select an envelope एक लिफाफे सिलेक्ट करें +@msg select an image एक इमेज चुनें +@msg select an image (or an Image Trace group) एक इमेज सिलेक्ट करें (या एक इमेज ट्रेस समूह) +@msg select an Image Trace object एक इमेज ट्रेस ऑब्जेक्ट चुनें +@msg select an image, or pass id एक इमेज सिलेक्ट करें, या आईडी पास करें +@msg select an Intertwine group एक Intertwine समूह चुनें +@msg select an object (or pass `id`) किसी ऑब्जेक्ट सिलेक्ट करें (या `id` पास) +@msg select an object in perspective पर्सपेक्टिव में एक ऑब्जेक्ट सिलेक्ट करें +@msg select an object with a freeform gradient एक फ्रीफॉर्म ग्रेडिएंट के साथ एक ऑब्जेक्ट सिलेक्ट करें +@msg select an object with an opacity mask एक opacity मास्क के साथ एक ऑब्जेक्ट सिलेक्ट करें +@msg select an Objects on Path group पाथ समूह पर एक ऑब्जेक्ट चुनें +@msg select area type क्षेत्र प्रकार सिलेक्ट करें +@msg select area type (text in a frame) क्षेत्र प्रकार (एक फ्रेम में टेक्स्ट) सिलेक्ट करें +@msg select area type and closed paths (at least one area type object) क्षेत्र प्रकार और बंद पाथ (कम से कम एक क्षेत्र प्रकार ऑब्जेक्ट) सिलेक्ट करें +@msg select area type whose first line can fit its frame क्षेत्र के प्रकार सिलेक्ट करें जिनकी पहली पंक्ति अपने फ्रेम को फिट कर सकती है +@msg select artwork (or a colour group) to recolor फिर से रंग करने के लिए आर्टवर्क (या एक रंग समूह) सिलेक्ट करें +@msg select artwork to add its colours अपने रंगों को जोड़ने के लिए आर्टवर्क सिलेक्ट करें +@msg select artwork to make a group of its colours अपने रंगों का एक समूह बनाने के लिए आर्टवर्क सिलेक्ट करें +@msg select artwork to recolour, or give a colour `group` रंग बदलने के लिए आर्टवर्क चुनें या रंग `group` दें +@msg select at least two objects कम से कम दो ऑब्जेक्ट चुनें +@msg Select dimensions to update अद्यतन करने के लिए आयाम सिलेक्ट करें +@msg select exactly two objects वास्तव में दो ऑब्जेक्ट चुनें +@msg select exactly two path ends to join वास्तव में दो पाथ में शामिल होने के लिए समाप्त होता है चुनें +@msg Select horizontal point or area type whose text fits क्षैतिज बिंदु या क्षेत्र के प्रकार सिलेक्ट करें जिसका टेक्स्ट फिट बैठता है +@msg select instances of one symbol एक सिंबल के उदाहरण चुनें +@msg select members of a compound shape एक मिश्रित आकार के सदस्यों सिलेक्ट करें +@msg select objects or give `color` ऑब्जेक्ट्स सिलेक्ट करें या `color` देना +@msg select objects or give ids ऑब्जेक्ट्स सिलेक्ट करें या ids देना +@msg select objects to align to the guide गाइड को संरेखित करने के लिए ऑब्जेक्ट चुनें +@msg select objects, not layers ऑब्जेक्ट्स सिलेक्ट करें, लेयर नहीं +@msg select one image or pass id एक इमेज सिलेक्ट करें या आईडी पास करें +@msg select one Intertwine group एक Intertwine समूह चुनें +@msg select one object एक ऑब्जेक्ट सिलेक्ट करें +@msg select one path, or give its `id` एक पाथ चुनें या उसकी `id` दें +@msg Select only dimensions केवल आयाम सिलेक्ट करें +@msg select open paths to close बंद करने के लिए खुले रास्ते सिलेक्ट करें +@msg select paths पाथ चुनें +@msg select paths or anchor points पाथ या एंकर अंक चुनें +@msg select paths or compound paths पाथ या यौगिक पाथ सिलेक्ट करें +@msg select paths to join शामिल होने के लिए पाथ सिलेक्ट करें +@msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें +@msg select paths, or segments, to divide विभाजित करने के लिए पाथ, या खंड चुनें +@msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें +@msg Select point type बिंदु प्रकार चुनें +@msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें +@msg select segments, or paths, to add points to खंडों, या पाथ का सिलेक्ट करने के लिए, अंक जोड़ने के लिए +@msg select some type first पहले कुछ प्रकार का सिलेक्शन +@msg select something to export निर्यात करने के लिए कुछ का सिलेक्शन +@msg select something to export (or turn off selectedOnly) एक्सपोर्ट करने के लिए कुछ चुनें (या selectedOnly बंद करें) +@msg Select text or click into text with the Type tool to insert glyphs टेक्स्ट सिलेक्ट करें या glyphs डालने के लिए टाइप टूल के साथ टेक्स्ट में क्लिक करें +@msg select text to redefine the style from से स्टाइल को फिर से परिभाषित करने के लिए टेक्स्ट सिलेक्ट करें +@msg select the art and, on top of it, the mask object कला सिलेक्ट करें और इसके शीर्ष पर, मास्क ऑब्जेक्ट +@msg select the art for the design डिजाइन के लिए कला का सिलेक्शन +@msg select the art for the pattern tile पैटर्न टाइल के लिए कला का सिलेक्शन +@msg select the art to add first पहले जोड़ने के लिए कला सिलेक्ट करें +@msg select the art to collect (or give its ids) कला को इकट्ठा करने के लिए चुनें (या इसके आईडी देने के लिए) +@msg select the art to export first पहले निर्यात करने के लिए कला सिलेक्ट करें +@msg select the art to repeat दोहराने के लिए कला सिलेक्ट करें +@msg select the artwork to warp ताना करने के लिए आर्टवर्क का सिलेक्शन +@msg select the content and a path on top सामग्री और शीर्ष पर एक पाथ सिलेक्ट करें +@msg select the images to relink, or pass ids इमेज को फिर से लिंक करने के लिए चुनें, या ids को पास करें +@msg select the images, or pass ids इमेज सिलेक्ट करें, या ids पास करें +@msg select the linked images or placed documents, or pass ids संबद्ध इमेज या रखे गए डॉक्यूमेंट्स सिलेक्ट करें, या ids पास करें +@msg select the object to copy from ऑब्जेक्ट को कॉपी करने के लिए चुनें +@msg select the objects (or give their ids) ऑब्जेक्ट्स सिलेक्ट करें (या उनके ids) +@msg select the objects to attach to the path ऑब्जेक्ट्स का सिलेक्ट करने के लिए संलग्न करने के लिए पाथ +@msg select the objects to bind ऑब्जेक्ट्स को बांधने के लिए चुनें +@msg select the objects to transform in perspective ऑब्जेक्ट्स को पर्सपेक्टिव में बदलने के लिए चुनें +@msg select two open path ends, or two open paths, to average and join दो खुले पाथ सिलेक्ट करें, या दो खुले रास्ते, औसतन और जुड़ना +@msg select two or more graphic styles to merge दो या अधिक ग्राफिक स्टाइल्स का सिलेक्ट करने के लिए विलय +@msg select two or more objects to distribute वितरित करने के लिए दो या दो से अधिक ऑब्जेक्ट चुनें +@msg select two or more objects to intertwine दो या दो से अधिक ऑब्जेक्ट्स सिलेक्ट करें +@msg Select two or more objects, or a group दो या अधिक ऑब्जेक्ट चुनें, या एक समूह चुनें +@msg Select two or more one-line point type objects on one baseline to combine गठबंधन करने के लिए एक बेसलाइन पर दो या एक से अधिक बिंदु प्रकार की ऑब्जेक्टएं चुनें +@msg Select two or more one-line point type objects to join शामिल होने के लिए दो या दो से अधिक एक लाइन बिंदु प्रकार के ऑब्जेक्ट चुनें +@msg select two or more slices to combine गठबंधन करने के लिए दो या दो से अधिक स्लाइस चुनें +@msg select type in perspective पर्सपेक्टिव में टाइप करें +@msg select type on a path एक पाथ पर टाइप करें +@msg selection `{m}`: one or each सिलेक्शन `{m}`: एक या प्रत्येक +@msg selection has no bounds सिलेक्शन की कोई सीमा नहीं है +@msg Sent to {_1} Sent to {_1} +@msg settings is an object of document.exportForScreens params settings, document.exportForScreens पैरामीटर का ऑब्जेक्ट है +@msg settings must be an object settings: सेटिंग्स एक ऑब्जेक्ट होना चाहिए +@msg shadings of an unknown type were left out अज्ञात प्रकार के छायांकन को छोड़ दिया गया था +@msg shadings of more than 4096 patches or triangles were left out 4096 से अधिक पैच या त्रिकोणों के छायांकन को छोड़ दिया गया था +@msg shadings whose functions are of an unknown type are filled with their middle colour छायांकन जिसका कार्य अज्ञात प्रकार के होते हैं, उनके मध्य रंग से भरे होते हैं +@msg Shape Builder: no region under the pointer आकृति बिल्डर: सूचक के तहत कोई क्षेत्र नहीं +@msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें +@msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए +@msg shortcut for `{k}` must be a string `{k}` के लिए शॉर्टकट एक स्ट्रिंग होना चाहिए +@msg show `{show}`: all, missing, modified or embedded `{show}``: सभी, लापता, संशोधित या एम्बेडेड +@msg Show All Hidden Attributes: nothing is hidden Show all Hidden Attributes: कुछ भी छिपा नहीं है +@msg show must be true or false show: प्रदर्शन को सच या झूठा होना चाहिए +@msg Simplify Anchors: the paths have too many anchors to simplify at once एंकर को सरलीकृत करें: पाथ में एक बार में सरल बनाने के लिए कई एंकर हैं +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size: आकार "छोटा", "मध्यम", "बड़ा" या 0 से अधिक अंक {_1} तक होना चाहिए +@msg size must be positive size: आकार सकारात्मक होना चाहिए +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode को "fixed" या "pressure" होना चाहिए, {other} नहीं +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode को "fixed" या "pressure" होना चाहिए, `{other}` नहीं +@msg sizeVariation must be 0 or more sizeVariation को 0 या अधिक होना चाहिए +@msg smallCaps must be true or false smallCaps को true या false होना चाहिए +@msg some text is hidden or locked, so its font wasn't replaced कुछ टेक्स्ट छिपा हुआ है या बंद कर दिया गया है, इसलिए इसका फ़ॉन्ट प्रतिस्थापित नहीं किया गया था +@msg sort `{x}`: name, kind or status टाइप `{x}`: नाम, प्रकार या स्थिति +@msg source must be the id of a Shaper Group's original shape source: स्रोत एक शेपर ग्रुप के मूल आकार का आईडी होना चाहिए +@msg source paths are too large for Shaper स्रोत पाथ शेपर के लिए बहुत बड़े हैं +@msg span must be "object" or "selection", got {v} span: स्पैन को "ऑब्जेक्ट" या "सिलेक्शन" होना चाहिए, {v} मिला +@msg span: "selection" places a `gradient`, not a swatch span: "selection" एक `gradient` रखता है, स्वॉच नहीं +@msg span: "selection" places a gradient: give `gradient` span: "selection" ग्रेडिएंट रखता है: `gradient` दें +@msg span: "selection" places a linear or radial gradient, not a freeform one स्पैन: "सिलेक्शन" एक रैखिक या रेडियल ग्रेडिएंट रखता है, एक फ्रीफॉर्म नहीं एक +@msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" खुद ग्रेडिएंट रखता है: `start` और `end` न दें (वे उसे डॉक्यूमेंट निर्देशांकों पर रख देते हैं) +@msg speed must be accelerated, step or pause speed: गति को तेज, कदम या रोकें होना चाहिए +@msg Split Into Grid: select paths large enough for the grid स्प्लिट इनो ग्रिड: ग्रिड के लिए काफी बड़े पाथ सिलेक्ट करें +@msg spot, mode and group apply to solid colours only स्पॉट, मोड और समूह केवल ठोस रंगों पर लागू होते हैं +@msg status `{s}`: linked, embedded, missing or modified स्थिति `{s}`: लिंक्ड, एम्बेडेड, लापता या संशोधित +@msg steps must be 1..{MAX_STEPS} steps: चरण 1 होना चाहिए।{MAX_STEPS} +@msg steps must be 1..1000 steps को 1..1000 होना चाहिए +@msg stop {i} needs `offset` स्टॉप {i} को `offset` की जरूरत है +@msg stop {i} needs a valid `color` स्टॉप {i} को वैध `color` की आवश्यकता है +@msg stop {i}: `{k}` must be a number '{i}': `{k}` होना चाहिए +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) स्टॉप {i}: `plates` में 0 से 1 के बीच चार संख्याएँ होनी चाहिए (C, M, Y, K) +@msg stop editing the opacity mask first पहली बार अपारदर्शिता मास्क संपादित करना बंद करो +@msg stopped before the archive was finished संग्रह समाप्त होने से पहले बंद कर दिया गया +@msg strokeMode must be within|along|across, got {m} strokeMode को within|along|across होना चाहिए, {m} मिला +@msg strokeOptions must be an object of stroke.set options strokeOptions को stroke.set ऑप्शन्स का ऑब्जेक्ट होना चाहिए +@msg strokeWidth must be a positive number of pixels strokeWidth को पिक्सेल की धनात्मक संख्या होना चाहिए +@msg subpath {si} is not an open subpath उपपाथ {si} एक खुला उपपाथ नहीं है +@msg subpaths required when joining the same path एक ही पाथ में शामिल होने पर आवश्यक उप-पाथ +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 SVG UTF-8, UTF-16 या ISO 8859-1 नहीं है। +@msg SVG parse error: {0} SVG पार्स त्रुटि: {0} +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict को "merge" या "add" होना चाहिए, {v} नहीं +@msg Switch x/y is for scatter graphs स्विच x/y स्कैटर ग्राफ़ के लिए है +@msg t, dx and dy must be finite टी, डीएक्स और डीआई को परिमित होना चाहिए +@msg Targa files are RGB: colorModel rgb Targa फ़ाइलें RGB हैं: colorModel rgb +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text को {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} होना चाहिए +@msg Text options: {e} टेक्स्ट ऑप्शन्स: {e} +@msg text transform is collapsed or unrepresentable टेक्स्ट रूपांतरण पतन या प्रतिनिधित्व करने योग्य है +@msg Text Wrap: select a wrap object टेक्स्ट लपेटें: एक रैप ऑब्जेक्ट चुनें +@msg text.{key} `{v}`: use "{_1}" or "{_2}" Text.{key} `{v}`: "{_1}" या "{_2}" का उपयोग करें। +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces को 2 से 100 के बीच पूर्णांक होना चाहिए +@msg textureImage: {e} textureImage: {e} +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: एक इमेज फ़ाइल के {path} या {name, dataBase64}, या इफ़ेक्ट के रूप में बनावट देते हैं। +@msg that anchor can't slide: an end of an open path has nowhere to go कि एंकर स्लाइड नहीं कर सकते: एक खुले रास्ते का अंत कहीं नहीं जाना है +@msg that document is no longer open यह डॉक्यूमेंट अब खुला नहीं है +@msg that makes more than {MAX_PIECES} slices जो {MAX_PIECES} स्लाइस से अधिक बनाता है +@msg that makes too many pieces (at most 100000): make the dashes longer जो बहुत सारे टुकड़े बनाता है (अधिकांश 100000 में): डैश को लंबे समय तक बनाते हैं +@msg that object is not in the overlap उस ऑब्जेक्ट को ओवरलैप में नहीं है +@msg the {tool} tool has no options {tool} टूल में कोई ऑप्शन्स नहीं है +@msg The 3D surface is too complex; simplify the shape 3D सतह बहुत जटिल है; आकार को सरल बनाएं +@msg the action has no included steps कार्रवाई में कोई कदम शामिल नहीं है +@msg the action has no steps कार्रवाई में कोई कदम नहीं है +@msg the action set file holds more than 1,000 actions एक्शन सेट फ़ाइल 1,000 से अधिक कार्यों को रखती है +@msg the action set file is larger than 8 MiB एक्शन सेट फ़ाइल 8 MiB से बड़ा है +@msg the action set file needs a later version of VectorCraft एक्शन सेट फ़ाइल को वेक्टर क्रेफ्ट के बाद के संस्करण की आवश्यकता होती है +@msg the action set ids are not a list कार्रवाई सेट ids एक सूची नहीं हैं +@msg the action sets changed; nothing was deleted कार्रवाई सेट बदल गया; कुछ भी नहीं हटा दिया गया था +@msg the action stopped playing: its document is no longer active कार्रवाई बंद खेल: इसका डॉक्यूमेंट अब सक्रिय नहीं है +@msg the active paint is not a gradient सक्रिय पेंट एक ग्रेडिएंट नहीं है +@msg the Affinity document has no page with a size Affinity डॉक्यूमेंट में एक आकार के साथ कोई पृष्ठ नहीं है +@msg the art could not be sampled कला नमूना नहीं किया जा सकता +@msg the art has no bounds कला में कोई सीमा नहीं है +@msg The art is too large to copy as a picture: other apps get no PNG of it कला एक तस्वीर के रूप में कॉपी करने के लिए बहुत बड़ा है: अन्य एप्लिकेशन इसके बारे में पीएनजी नहीं मिलते हैं +@msg the art is too light for any dots कला किसी भी बिंदु के लिए बहुत हल्का है +@msg the art on them differs from the page's in {_1}% of it उनमें से कला पृष्ठ के {_1}% में भिन्न होती है। +@msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same उनमें से कला पृष्ठ के {_1}% में भिन्न होती है: वे इसके संपादन डेटा से आते हैं। +@msg the artboard is locked आर्टबोर्ड को लॉक किया जाता है +@msg the artboard to fit must be a positive size up to {_1} pt फिट करने के लिए आर्टबोर्ड {_1} pt तक सकारात्मक आकार होना चाहिए +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size आर्टबोर्ड कैनवास पर फिट नहीं हैं: कम आर्टबोर्ड, कम रिक्ति या छोटे आकार +@msg the background worker stopped पृष्ठभूमि कार्यकर्ता बंद कर दिया +@msg the blend has no spine मिश्रण में कोई रीढ़ नहीं है +@msg the character's size can't be measured चरित्र का आकार मापा नहीं जा सकता है +@msg the CMYK image couldn't be written CMYK इमेज को नहीं लिखा जा सकता +@msg the Color Picker is not open रंग पिकर खुला नहीं है +@msg the compound shape is too complex to expand मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है +@msg the compressed file unpacks to more than {_1} MB संकुचित फ़ाइल {_1} MB से अधिक के लिए अनपैक +@msg the compressed file unpacks to more than VectorCraft reads ({_1} MB of document, {_2} MB per image) संकुचित फ़ाइल unpacks से अधिक वेक्टर क्रेफ्ट reads ({_1} MB of document, {_2} MB per image) +@msg the container of the listed objects is gone सूचीबद्ध ऑब्जेक्ट्स का कंटेनर चला गया है +@msg the copy `{user_id}` can't be read as a library प्रतिलिपि `{user_id}` को लाइब्रेरी के रूप में नहीं पढ़ा जा सकता है। +@msg the copy would leave the canvas प्रतिलिपि कैनवास को छोड़ देगी +@msg the cut cannot be made on this art: {e} इस कला में कटौती नहीं की जा सकती: {e} +@msg the data isn't an EMF or WMF picture डेटा एक EMF या WMF चित्र नहीं है +@msg the data isn't an EPS or PostScript picture डेटा एक ईपीएस या पोस्टस्क्रिप्ट तस्वीर नहीं है +@msg the deferred paste is no longer available deferred पेस्ट अब उपलब्ध नहीं है +@msg the design is too big to draw at every data point of this graph डिजाइन इस ग्राफ़ के हर डेटा बिंदु पर आकर्षित करने के लिए बहुत बड़ा है +@msg the design is too big to draw in every column of this graph डिजाइन इस ग्राफ़ के हर स्तंभ में आकर्षित करने के लिए बहुत बड़ा है +@msg the dialog it was opened over is no longer open जिस डायलॉग के ऊपर इसे ओपन किया गया था, वह अब खुला नहीं है +@msg the dictionary stack overflowed शब्दकोश स्टैक अतिप्रवाह +@msg the document has never been saved कभी नहीं बचाया गया है +@msg the document has never been saved: give `folder` डॉक्यूमेंट को कभी बचाया नहीं गया है: `folder` देना +@msg the document has no artboard डॉक्यूमेंट में कोई आर्टबोर्ड नहीं है +@msg the document has no artboards डॉक्यूमेंट में कोई आर्टबोर्ड नहीं है +@msg the document has no brushes to save डॉक्यूमेंट को बचाने के लिए कोई ब्रश नहीं है +@msg the document has no patterns डॉक्यूमेंट में कोई पैटर्न नहीं है +@msg the document has no slices डॉक्यूमेंट में कोई स्लाइस नहीं है +@msg the document has no symbols डॉक्यूमेंट में कोई सिंबल नहीं है +@msg the document has no symbols to save डॉक्यूमेंट में सेव करने के लिए कोई सिंबल नहीं है +@msg the document is too large to save compressed ({0}): save it with Use Compression off डॉक्यूमेंट संपीड़ित ({0}) को बचाने के लिए बहुत बड़ा है: इसे बंद संपीड़न का उपयोग करें +@msg the drawing has no layout `{_1}` (it has {_2}) ड्राइंग में कोई लेआउट नहीं है `{_1}` (इसमें {_2} है) +@msg the drawing is no longer loaded ड्राइंग अब लोड नहीं है +@msg the drawing is too large to open ड्राइंग ओपन करने के लिए बहुत बड़ा है +@msg the editing data's hash has no place संपादन डेटा की हैश में कोई जगह नहीं है +@msg the EMF header is damaged EMF हैडर क्षतिग्रस्त है +@msg the entities the document declares expand to too much text डॉक्यूमेंट की घोषणा करने वाली संस्थाओं ने बहुत अधिक टेक्स्ट का विस्तार किया है +@msg the envelope's content has no bounds लिफाफे की सामग्री में कोई सीमा नहीं है +@msg the envelope's mesh is malformed लिफाफे के जाल को विकृत किया जाता है +@msg the export region is empty निर्यात क्षेत्र खाली है +@msg the export region is not finite निर्यात क्षेत्र परिमित नहीं है +@msg the export returned unreadable data निर्यात अपठनीय डेटा वापस आ गया +@msg the export wrote no file निर्यात ने कोई फ़ाइल नहीं लिखी +@msg the file holds no `variableSets` element फ़ाइल में `variableSets` एलिमेंट नहीं है +@msg the file holds only a placeholder page, not its art (it was saved without PDF compatibility): save it again with PDF compatibility on, or as PDF or SVG फ़ाइल केवल एक प्लेसहोल्डर पेज रखती है, इसकी कला नहीं है (यह PDF संगतता के बिना बचाया गया था): इसे फिर से PDF संगतता के साथ सेव करें, या PDF या SVG के रूप में +@msg the file is larger than {_1} MB फ़ाइल {_1} MB से बड़ा है +@msg the file is too large फ़ाइल बहुत बड़ी है +@msg the file stopped being read (please report this bug) फ़ाइल को पढ़ना बंद कर दिया गया (कृपया इस बग की रिपोर्ट करें) +@msg the file was read up to an error ({why}): what follows it was left out फ़ाइल को एक त्रुटि ({why}) तक पढ़ा गया था: इस प्रकार यह छोड़ दिया गया था +@msg the file was updated or encrypted already फ़ाइल को पहले से ही अद्यतन या एन्क्रिप्ट किया गया था +@msg the file's layers weren't read ({_1}): it comes in as its page, in one layer फ़ाइल की लेयरें नहीं पढ़ी गईं ({_1}): यह अपने पृष्ठ के रूप में आता है, एक लेयर में +@msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part फ़ाइल की लेयर्स को इसके संपादन डेटा ({_1}) से नहीं पढ़ा गया था: वे अपने PDF भाग से आते हैं +@msg the file's preview header points outside the file फ़ाइल के प्रीव्यू शीर्षलेख फ़ाइल के बाहर अंक +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables फ़ाइल के परिवर्तनीय बंधन सभी नहीं पढ़े गए थे (बाइंडिंग्स स्किप: {_1}): वे ऑब्जेक्ट अपने चर के लिए बाध्य नहीं हैं +@msg the file's variable library couldn't be read: the Variables panel doesn't list it फ़ाइल के परिवर्तनीय लाइब्रेरी को पढ़ा नहीं जा सकता: चर पैनल इसे सूचीबद्ध नहीं करता है +@msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest फ़ाइल की परिवर्तनीय लाइब्रेरी आंशिक रूप से पढ़ी गई थी (प्रवेशियों को छोड़ दिया: {_1}): वेरिएबल्स पैनल बाकी हिस्सों को सूचीबद्ध करता है +@msg the files come to more than 1 GB: add fewer at a time फ़ाइलों को 1 GB से अधिक करने के लिए आते हैं: एक समय में कम जोड़ें +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) एक पंक्ति के पहले चरित्र में बर्न से पहले कोई चरित्र नहीं है: यह केवल ऊपर और नीचे चला जाता है (डी) +@msg the font {_1} is not available फ़ॉन्ट {_1} उपलब्ध नहीं है +@msg the format has no file extension फ़ॉर्मैट में कोई फ़ाइल एक्सटेंशन नहीं है +@msg the graphic can't be read: {e} ग्राफिक पढ़ा नहीं जा सकता: {e} +@msg the graphic is empty ग्राफिक खाली है +@msg the graphic's data is damaged ग्राफिक का डेटा क्षतिग्रस्त हो जाता है +@msg the graphic's document has no artboard ग्राफ़िक के डॉक्यूमेंट में कोई आर्टबोर्ड नहीं है +@msg The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} ग्राफिक्स प्रोसेसर ने पहली बार विंडो नहीं दिखायी थी, इसलिए VectorCraft फिर से {summary} पर शुरू हुआ। +@msg The graphics were lost and couldn't be restarted. ग्राफिक्स खो गए थे और फिर से शुरू नहीं किया जा सकता था। +@msg The graphics were lost and have been restarted ग्राफिक्स खो गए थे और फिर से शुरू किया गया है +@msg the guide is on a hidden or locked layer गाइड एक छिपे हुए या बंद लेयर पर है +@msg the header `{cell}` for `{name}` would read back as the variable `{other}`: rename one of them हेडर `{cell}` के लिए `{name}` वापस चर `{other}` के रूप में पढ़ेगा: उनमें से एक का नाम बदलें +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` का हेडर `{header}` दोबारा पढ़ने पर वेरिएबल `{other}` बन जाएगा: किसी एक का नाम बदलें +@msg the image `{path}` isn't followed: {r} इमेज `{path}` का पालन नहीं किया गया है: {r} +@msg the image can't be read as a texture इमेज को बनावट के रूप में नहीं पढ़ा जा सकता है +@msg the image has no embedded pixels इमेज में कोई एम्बेडेड पिक्सेल नहीं है +@msg the image has no usable size or position इमेज में कोई उपयोग करने योग्य आकार या स्थिति नहीं है +@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. इमेज {_1} × {_2} पिक्सेल है, एक तरफ {LARGE_TRACE_SIDE} से अधिक: यह पता लगाया गया है, लेकिन धीरे धीरे धीरे। एक कम निष्ठा पूर्व निर्धारित या इमेज के निशान की एक छोटी प्रतिलिपि तेजी से। +@msg the image is {width} × {height} pixels, more than Image Trace takes ({max} megapixels) इमेज {width} × {height} पिक्सेल है, इमेज ट्रेस से अधिक लेता है ({max} मेगापिक्सेल) +@msg the image is empty इमेज खाली है +@msg the image is fully transparent इमेज पूरी तरह से पारदर्शी है +@msg the image is not on an artboard; pass rect इमेज एक आर्टबोर्ड पर नहीं है; सही होकर गुजरना +@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). इमेज को {_1} × {_2} पिक्सेल पर पता लगाया गया था, जिसे {_3} × {_4} ({_5} मेगापिक्सेल) से नीचे बढ़ाया गया था। +@msg the image's pixels are missing इमेज के पिक्सेल लापता हैं +@msg the image's pixels aren't in the document इमेज के पिक्सेल डॉक्यूमेंट में नहीं हैं +@msg the image's pixels can't be read इमेज के पिक्सेल को पढ़ा नहीं जा सकता है +@msg the image's pixels can't be read: {e} इमेज के पिक्सेल पढ़ा नहीं जा सकता: {e} +@msg the image's pixels don't match its size इमेज के पिक्सेल अपने आकार से मेल नहीं खाते हैं +@msg the image's transparency doesn't fit it इमेज की पारदर्शिता यह फिट नहीं है +@msg the job would print more than {_1} pages नौकरी {_1} पृष्ठों से अधिक प्रिंट करेगी +@msg the job would print more than {MAX_PAGES} pages इस जॉब में {MAX_PAGES} से अधिक पेज प्रिंट होंगे +@msg the JPEG 2000 file can't be read JPEG 2000 फ़ाइल पढ़ा नहीं जा सकता +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000 फ़ाइल में एक unसमर्थित रंग स्थान या JPX सामग्री है +@msg The last start of VectorCraft ended on {name} before its window appeared, so it started on {summary}. To try that graphics processor again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set वेक्टर क्रेफ्ट की अंतिम शुरुआत अपनी विंडो दिखाई देने से पहले {name} पर समाप्त हुई, इसलिए यह {summary} पर शुरू हुआ। उस ग्राफिक्स प्रोसेसर को फिर से आज़माने के लिए, वरीयताओं को बदलें › प्रदर्शन › ग्राफिक्स प्रोसेसर या WGPU_BACKEND सेट के साथ शुरू होता है। +@msg The last start of VectorCraft ended while it listed the graphics processors, so it started on {summary} with OpenGL alone. To try the other graphics backends again, change Preferences › Performance › Graphics Processor or start with WGPU_BACKEND set जब यह ग्राफिक्स प्रोसेसर को सूचीबद्ध करता है, तो यह केवल ओपनजीएल के साथ {summary} पर शुरू हुआ। फिर से अन्य ग्राफिक्स बैकेंड की कोशिश करने के लिए, वरीयताओं को बदलें › प्रदर्शन › ग्राफिक्स प्रोसेसर या WGPU_BACKEND सेट के साथ शुरू होता है। +@msg the layer has no objects to clip by लेयर में क्लिप करने के लिए कोई ऑब्जेक्ट नहीं है +@msg the layer or group is locked लेयर या समूह को बंद कर दिया जाता है +@msg the layer to flatten into is hidden लेयर में समतल करने के लिए छिपा हुआ है +@msg the layers hold no art to mask लेयरें मास्क करने के लिए कोई कला नहीं रखती हैं +@msg the layout moved लेआउट ले जाया गया +@msg the library has a group `{name}` already लाइब्रेरी में पहले से ही एक समूह `{name}` है। +@msg the library has no group `{name}` लाइब्रेरी में कोई समूह नहीं है `{name}` +@msg the library has no item `{item}` लाइब्रेरी में कोई आइटम नहीं है `{item}` +@msg the library has no item `{other}` लाइब्रेरी में कोई आइटम नहीं है `{other}` +@msg the library holds {MAX_GROUPS} groups already लाइब्रेरी में पहले से ही {MAX_GROUPS} समूह हैं। +@msg the library holds {MAX_ITEMS} items of this kind already लाइब्रेरी पहले से ही इस तरह के {MAX_ITEMS} आइटम रखता है +@msg the library item is damaged लाइब्रेरी आइटम क्षतिग्रस्त है +@msg the module imports `{_1}.{_2}`, but plug-ins get no host imports (no WASI, files or network) मॉड्यूल आयात `{_1}.{_2}`, लेकिन प्लग-इन को कोई होस्ट आयात नहीं मिलता है (कोई WASI, फ़ाइल या नेटवर्क नहीं) +@msg the module must export its linear memory as `memory` मॉड्यूल को अपनी रैखिक मेमोरी `memory` के रूप में एक्सपोर्ट करनी चाहिए +@msg the name is empty नाम खाली है +@msg the object already has an opacity mask ऑब्जेक्ट पहले से ही एक अपारदर्शिता मास्क है +@msg the object has no fill, stroke or effect ऑब्जेक्ट में कोई भराव, स्ट्रोक या इफ़ेक्ट नहीं होता है +@msg the object has no geometry ऑब्जेक्ट में कोई ज्यामिति नहीं है +@msg the object has no graphic style (pass `name`) ऑब्जेक्ट की ग्राफ़िक स्टाइल नहीं है (`name` दें) +@msg the object has no opacity mask ऑब्जेक्ट में कोई अपारदर्शिता मास्क नहीं है +@msg the object has no stroke ऑब्जेक्ट में कोई स्ट्रोक नहीं है +@msg the object is beyond the plane's horizon ऑब्जेक्ट विमान के क्षितिज से परे है +@msg the object is hidden or locked ऑब्जेक्ट छिपा हुआ है या बंद कर दिया गया है +@msg the object is not an editable parametric shape ऑब्जेक्ट एक संपादन योग्य पैरामीट्रिक आकार नहीं है +@msg the object is outside the isolated group ऑब्जेक्ट पृथक समूह के बाहर है +@msg the object isn't in perspective ऑब्जेक्ट पर्सपेक्टिव में नहीं है +@msg the object isn't on a perspective plane ऑब्जेक्ट एक पर्सपेक्टिव विमान पर नहीं है +@msg the object would cross the horizon of the perspective plane ऑब्जेक्ट पर्सपेक्टिव विमान के क्षितिज को पार करेगी +@msg the objects don't match the plan ऑब्जेक्ट्स प्लान से मेल नहीं खाते हैं +@msg the objects to change are no longer in the document ऑब्जेक्ट्स को बदलने के लिए अब डॉक्यूमेंट में नहीं हैं +@msg the objects would leave the grid ऑब्जेक्ट्स ग्रिड को छोड़ देंगे +@msg the open and permissions passwords must differ खुला और अनुमति पासवर्ड अलग होना चाहिए +@msg the open dialog has no Reset ओपन संवाद में कोई रीसेट नहीं है +@msg the operand stack overflowed संचालित स्टैक अतिप्रवाह +@msg the operator looks for a mark on the stack and finds none ऑपरेटर स्टैक पर एक निशान की तलाश करता है और कोई नहीं पाता है +@msg the operator needs more values than the stack holds ऑपरेटर को स्टैक की तुलना में अधिक मूल्यों की आवश्यकता होती है +@msg the package came back damaged पैकेज वापस क्षतिग्रस्त हो गया +@msg the page has no area पृष्ठ का कोई क्षेत्र नहीं है +@msg the page's type in an unread object's box isn't in its page art पृष्ठ का प्रकार एक अपठित ऑब्जेक्ट के बॉक्स में नहीं है इसके पृष्ठ कला में +@msg the paint behind the proxy is not a gradient प्रॉक्सी के पीछे पेंट एक ग्रेडिएंट नहीं है +@msg the parent must be a layer or sublayer माता-पिता को एक लेयर या सबलायर होना चाहिए +@msg the path can't be extended पाथ को बढ़ाया नहीं जा सकता +@msg the path can't be inside one of the objects to attach मार्ग संलग्न करने के लिए ऑब्जेक्ट्स में से एक के अंदर नहीं हो सकता है +@msg the path has no open subpath पाथ में कोई खुला उप-पाथ नहीं है +@msg the path has no point to continue from रास्ते से जारी रखने के लिए कोई बिंदु नहीं है +@msg the path has no segments to measure पाथ को मापने के लिए कोई खंड नहीं है +@msg the path is empty पाथ खाली है +@msg the path is locked or hidden पाथ को लॉक या छुपाया जाता है +@msg the path is too short to remove a point from रास्ते से एक बिंदु को हटाने के लिए बहुत कम है +@msg the path is too short to shorten that much पाथ इतना छोटा करने के लिए बहुत छोटा है +@msg the paths are too many or too tangled to find where they cross (at most 10000 segments) पाथ बहुत अधिक हैं या बहुत उलझन में हैं कि वे कहाँ पार करते हैं (अधिकांश 10000 खंडों पर) +@msg the paths have nothing to merge there रास्ते में वहाँ विलय करने के लिए कुछ भी नहीं है +@msg the paths have too many anchors to edit at once पाथ में एक बार में संपादित करने के लिए बहुत सारे एंकर होते हैं +@msg the PCX file is cut short PCX फ़ाइल को छोटा कर दिया जाता है +@msg the PCX file's header is damaged PCX फ़ाइल का हेडर क्षतिग्रस्त हो गया है +@msg the PDF has no pages PDF में कोई पेज नहीं है +@msg the PDF is no longer loaded PDF अब लोड नहीं है +@msg the PDF is password-protected: give its password PDF पासवर्ड-सुरक्षित है: अपना पासवर्ड दें +@msg the PDF part couldn't be read ({_1}): the file opened from its editing data PDF भाग पढ़ा नहीं जा सकता ({_1}): फ़ाइल अपने संपादन डेटा से ओपन किया गया +@msg the PDF password is wrong PDF पासवर्ड गलत है +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF सुरक्षा सेटिंग्स पासवर्ड के बिना सेव की गई थीं: openPassword या permissionsPassword फिर से दें या बिना सुरक्षा एक्सपोर्ट करने के लिए passwordRequired के बिना security दें +@msg the picture has no objects चित्र में कोई ऑब्जेक्ट नहीं है +@msg the Pixar file is cut short पिक्सार फ़ाइल को छोटा कर दिया जाता है +@msg the Pixar file's header is damaged पिक्सार फ़ाइल का हेडर क्षतिग्रस्त हो गया है +@msg the Pixar file's image data is damaged Pixar फ़ाइल की इमेज डेटा क्षतिग्रस्त हो गया है +@msg The point type has no transform to reset पॉइंट टाइप में रीसेट करने के लिए कोई परिवर्तन नहीं होता है +@msg The point type is aligned that way already बिंदु प्रकार को पहले से ही संरेखित किया जाता है +@msg the pointer is beyond the plane's horizon सूचक विमान के क्षितिज से परे है +@msg the preview image is empty प्रीव्यू इमेज खाली है +@msg the print job has no data प्रिंट नौकरी के पास कोई डेटा नहीं है +@msg the program asks for a resource that isn't defined कार्यक्रम एक संसाधन के लिए पूछता है जिसे परिभाषित नहीं किया गया है +@msg the program ends a dictionary it didn't begin कार्यक्रम एक शब्दकोश को समाप्त करता है यह शुरू नहीं हुआ था +@msg the program goes past one of the reader's limits कार्यक्रम रीडर की सीमाओं में से एक के पास जाता है +@msg the program opens a file, which the reader can't do कार्यक्रम एक फ़ाइल खोलता है, जिसे टेक्स्टक नहीं कर सकता +@msg the program restores a saved state that was already restored कार्यक्रम एक बचाया राज्य है कि पहले से ही बहाल किया गया था बहाल कर देता है +@msg the program runs too long कार्यक्रम बहुत लंबे समय तक चलता है +@msg the program runs, deletes or renames a file, which the reader can't do कार्यक्रम एक फ़ाइल को चलाता है, हटाता है या उसका नाम बदलता है, जिसे टेक्स्टक नहीं कर सकता +@msg the program uses too much memory कार्यक्रम बहुत ज्यादा मेमोरी का उपयोग करता है +@msg the PSD file has an unknown colour mode ({m}) PSD फ़ाइल में अज्ञात रंग मोड ({m}) है। +@msg the PSD file is cut short PSD फ़ाइल को छोटा कर दिया जाता है +@msg the PSD file's header is damaged PSD फ़ाइल का हेडर क्षतिग्रस्त हो जाता है +@msg the PSD file's image data can't be read: {e} PSD फ़ाइल की इमेज डेटा पढ़ा नहीं जा सकता: {e} +@msg the PSD file's image data uses an unknown compression ({m}) PSD फ़ाइल की इमेज डेटा एक अज्ञात संपीड़न ({m}) का उपयोग करता है +@msg the PSD image is too large to read ({_1} × {_2} pixels) PSD इमेज पढ़ने के लिए बहुत बड़ी है ({_1} × {_2} पिक्सेल) +@msg the rectangle must have a width and a height आयत की चौड़ाई और ऊंचाई होनी चाहिए +@msg the rectangle needs a size and must lie on the canvas आयत एक आकार की जरूरत है और कैनवास पर झूठ होना चाहिए +@msg the replacement font is not available प्रतिस्थापन फ़ॉन्ट उपलब्ध नहीं है +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) RTF फ़ाइल में कई पैराग्राफ या प्रारूपण परिवर्तन होते हैं जो टाइप (अधिकांश {MAX_PARAGRAPHS} पैराग्राफ और {MAX_RUNS} रन पर) होते हैं। +@msg the RTF file is too large to place as type (at most {_1} MB) RTF फ़ाइल बहुत बड़े प्रकार के रूप में जगह है (अधिकांश {_1} MB पर) +@msg the runtime panicked रनटाइम panicked +@msg the Save PDF dialog didn't open सेव करें PDF संवाद खुला नहीं था +@msg the scale is not a usable number स्केल एक प्रयोग योग्य संख्या नहीं है +@msg the screen color sampler is already open स्क्रीन रंग नमूना पहले से ही खुला है +@msg the search couldn't start: try again in a moment खोज शुरू नहीं हो सका: एक पल में फिर से प्रयास करें +@msg the segment can't be bent that far अब तक खंड नहीं किया जा सकता है +@msg the selected art has no width सिलेक्टेड कला में कोई चौड़ाई नहीं है +@msg the selected stroke's profile is already listed as {_1} सिलेक्टेड स्ट्रोक की प्रोफ़ाइल पहले से ही {_1} के रूप में सूचीबद्ध है +@msg the selection draws nothing सिलेक्शन कुछ नहीं खींचता है +@msg the selection has no area सिलेक्शन में कोई क्षेत्र नहीं है +@msg the selection has no art to export सिलेक्शन में निर्यात करने के लिए कोई कला नहीं है +@msg the selection has no bounds सिलेक्शन की कोई सीमा नहीं है +@msg the selection has no gradient fill सिलेक्शन में कोई क्रमिक भराव नहीं है +@msg the selection has no gradient stroke सिलेक्शन में कोई क्रमिक स्ट्रोक नहीं है +@msg the selection has no graphic style सिलेक्शन में कोई ग्राफिक स्टाइल नहीं है +@msg the selection has no pattern fill सिलेक्शन में कोई पैटर्न भरा नहीं है +@msg the selection has no pattern stroke सिलेक्शन में कोई पैटर्न स्ट्रोक नहीं है +@msg the selection has no URL (or they differ) सिलेक्शन में कोई यूआरएल नहीं है (या वे भिन्न होते हैं) +@msg the selection isn't in perspective सिलेक्शन पर्सपेक्टिव में नहीं है +@msg the shape is not an editable original shape of that Shaper Group आकार उस शेपर ग्रुप का एक संपादन योग्य मूल आकार नहीं है +@msg The shape is too complex for a 3D effect आकार 3D इफ़ेक्ट के लिए बहुत जटिल है +@msg the shape's numbers are out of range आकार की संख्या सीमा से बाहर हैं +@msg the Simplify slider is not open सरलीकृत स्लाइडर खुला नहीं है +@msg the slice would leave the canvas स्लाइस कैनवास छोड़ देंगे +@msg the Smooth slider is not open चिकना स्लाइडर खुला नहीं है +@msg the spine has no segments रीढ़ की हड्डी में कोई खंड नहीं है +@msg the spot colour couldn't be added स्पॉट रंग जोड़ा नहीं जा सकता +@msg the stroke has no weight स्ट्रोक का कोई वजन नहीं है +@msg the subpath has no ends to extend (it is closed or a single point) उपपाथ का विस्तार करने के लिए कोई छोर नहीं है (यह बंद है या एक बिंदु) +@msg the subpath is closed सबपैथ बंद है +@msg the subpath is closed or too short to close सबपैथ बंद है या बंद करने के लिए बहुत कम है +@msg the SVG expands to more than {0} nested SVG images SVG {0} नेस्टेड SVG इमेज से अधिक का विस्तार करता है +@msg the SVG expands to more than {0} objects SVG {0} ऑब्जेक्ट्स से अधिक का विस्तार करता है +@msg the SVG has no drawable objects SVG में कोई आकर्षक ऑब्जेक्ट नहीं है +@msg the SVG's elements are nested more than {0} deep SVG के तत्वों को {0} से अधिक गहरा घोंसला दिया जाता है +@msg the SVGZ file unpacks to more than {_1} MB SVGZ फ़ाइल ने {_1} MB से अधिक के लिए अनपैक किया +@msg the symbols are nested too deeply to expand their instances सिंबल्स को उनके उदाहरणों का विस्तार करने के लिए बहुत गहराई से घोंसला किया जाता है +@msg the target layer is locked or hidden लक्ष्य लेयर को लॉक या छुपाया जाता है +@msg the text file is too large to place as type (at most {_1} MB) टेक्स्ट फ़ाइल के रूप में बहुत बड़ा है (अधिकांश {_1} MB पर) +@msg the text is empty टेक्स्ट खाली है +@msg the text is over {_1} MB टेक्स्ट {_1} MB से अधिक है +@msg the thumbnail image is malformed थंबनेल इमेज विकृत है +@msg the top object must be a path शीर्ष ऑब्जेक्ट एक पाथ होना चाहिए +@msg the top object must be a path, compound path or text object to use as a clipping mask शीर्ष ऑब्जेक्ट एक क्लिपिंग मास्क के रूप में उपयोग करने के लिए एक पाथ, यौगिक पाथ या टेक्स्ट ऑब्जेक्ट होना चाहिए +@msg the trace was cancelled निशान रद्द कर दिया गया था +@msg the trailer has no size ट्रेलर में कोई आकार नहीं है +@msg the type object is flattened to nothing प्रकार ऑब्जेक्ट कुछ भी नहीं करने के लिए flattened है +@msg the value of axis `{tag}` must be a number or null धुरी का मूल्य `{tag}` होना चाहिए एक नंबर या null होना चाहिए +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets परिवर्तनीय लाइब्रेरी {MAX_LIBRARY_DATASETS} डेटा सेट से अधिक घोषित करता है +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities वेरिएबल लाइब्रेरी {MAX_LIBRARY_ENTITIES} संस्थाओं से अधिक की घोषणा करती है। +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables परिवर्तनीय लाइब्रेरी {MAX_LIBRARY_VARIABLES} चर से अधिक घोषित करता है। +@msg the variable library declares no variables वेरिएबल लाइब्रेरी ने कोई वेरिएबल घोषित नहीं किया है +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes परिवर्तनीय लाइब्रेरी {MAX_LIBRARY_BYTES} बाइट्स से बड़ा है +@msg the variable library is not UTF-8 चर लाइब्रेरी UTF-8 नहीं है +@msg the variable library is not well-formed XML: {e} वेरिएबल लाइब्रेरी अच्छी तरह से निर्मित XML नहीं है: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep परिवर्तनीय लाइब्रेरी घोंसला तत्वों से अधिक {MAX_LIBRARY_NESTING} गहरा +@msg the variable library's document type declaration holds something other than entities of plain text वेरिएबल लाइब्रेरी के डॉक्यूमेंट प्रकार की घोषणा सादे टेक्स्ट की संस्थाओं के अलावा कुछ अन्य रखती है +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes वेरिएबल लाइब्रेरी की संस्थाएं {MAX_LIBRARY_BYTES} बाइट्स से अधिक विस्तार करती हैं +@msg the window has no dock विंडो में कोई डॉक नहीं है +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot विंडो का {what} ({points} अंक × {scale} डीपीआई) एक स्क्रीनशॉट का आकार नहीं दे सकता +@msg the WMF header is damaged WMF हेडर क्षतिग्रस्त है +@msg the Word document has more than {_1} MB of formatting properties, too many to place वर्ड डॉक्यूमेंट में स्वरूपण प्रॉपर्टीज़ के {_1} MB से अधिक है, कई जगहों पर +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word डॉक्यूमेंट में गुणों के {MAX_PAGES} से अधिक पेज हैं, रखने के लिए बहुत अधिक +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place वर्ड डॉक्यूमेंट में {MAX_RUNS} से अधिक अक्षर या पैराग्राफ प्रॉपर्टीज़ होते हैं, बहुत से जगह होते हैं। +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) वर्ड डॉक्यूमेंट में टाइप के रूप में बहुत अधिक टेक्स्ट या स्वरूपण होता है (अधिकांश {MAX_PARAGRAPHS} पैराग्राफ, {MAX_RUNS} रन और {_1} MB of text) +@msg the Word document has too much text to place as type (at most {_1} MB) वर्ड डॉक्यूमेंट में टाइप के रूप में बहुत अधिक टेक्स्ट होता है (अधिकांश {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it वर्ड डॉक्यूमेंट को एन्क्रिप्ट किया गया है या पासवर्ड के साथ संरक्षित किया गया है; इसे बिना किसी स्थान के सेव करें +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) वर्ड डॉक्यूमेंट बहुत बड़ा होता है (यह {name} स्ट्रीम {_1} MB से अधिक रखता है) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off वर्ड डॉक्यूमेंट को फास्ट सेव के साथ आखिरी सेव किया गया था, जो VectorCraft को पढ़ा नहीं जाता है; इसे फिर से फास्ट सेव के साथ सेव करना बंद हो गया +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document वर्ड डॉक्यूमेंट को वर्ड 6.0 या वर्ड 95 द्वारा बचाया गया था, जो VectorCraft को पढ़ा नहीं जाता है; इसे वर्ड 97-2003 डॉक्यूमेंट के रूप में सेव करें +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place वर्ड डॉक्यूमेंट का टेक्स्ट {MAX_PIECES} टुकड़ों से भी अधिक है, बहुत से जगह +@msg the written PDF has no catalog लिखित PDF में कोई कैटलॉग नहीं है +@msg the written PDF has no cross-reference table लिखित PDF में कोई क्रॉस-रिफरेंस टेबल नहीं है +@msg the written PDF's metadata can't be edited PDF के मेटाडाटा को संपादित नहीं किया जा सकता है +@msg there are no colour swatches to draw आकर्षित करने के लिए कोई रंग नहीं है +@msg there are no objects to release जारी करने के लिए कोई ऑब्जेक्ट नहीं है +@msg there are no printer settings to open here यहां ओपन करने के लिए कोई प्रिंटर सेटिंग नहीं है +@msg there is already a design named `{name}` there: पहले से ही `{name}` नामक एक डिज़ाइन है। +@msg there is already a design named `{to}` there: पहले से ही `{to}` नामक एक डिजाइन है +@msg there is already a toolbar named `{name}` there: पहले से ही `{name}` नामक एक टूलबार है। +@msg there is already a toolbar named `{to}` there: पहले से ही `{to}` नामक एक टूलबार है। +@msg there is no clock here यहाँ कोई घड़ी नहीं है +@msg there is no clock here: give `time` (Unix seconds) यहाँ घड़ी नहीं है: `time` दें (Unix सेकंड) +@msg there is no library: create one first वहाँ कोई लाइब्रेरी नहीं है: पहले एक बनाना +@msg these paths are too degenerate for Shaper इन पाथ को शेपर के लिए बहुत अलग किया जाता है +@msg thickness must be from 0.01 to 5000 pt thickness: मोटाई 0.01 से 5000 तक होना चाहिए +@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) इस फ़ाइल को PDF संगतता के बिना बचाया गया था, और इसके संपादन डेटा को पढ़ा नहीं जा सकता ({why}) +@msg this file's PostScript couldn't be read ({why}): {what} इस फ़ाइल के पोस्टस्क्रिप्ट को पढ़ा नहीं जा सकता ({why}): {what} +@msg this format holds one artboard: export several as PDF or with document.exportForScreens इस फ़ॉर्मैट में एक आर्टबोर्ड रहता है: कई आर्टबोर्ड PDF में या document.exportForScreens से एक्सपोर्ट करें +@msg this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that this: यह एक डीडब्ल्यूजी ड्राइंग है, जिसे पढ़ा नहीं जा सकता है: इसे सीएडी ऐप से ASCII DXF के रूप में सेव करें और इसे ओपन करें कि +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS this: यह एक पोस्टस्क्रिप्ट फ़ाइल है (एक .ai एक पुराने फ़ॉर्मैट में या बिना PDF संगतता, या एक ईपीएस फ़ाइल में बचाया), एक PDF नहीं: फ़ाइल> खुला और फ़ाइल> इसे ईपीएस के रूप में पढ़े +@msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), which can't be opened yet: save it as PDF, PDF-compatible .ai or SVG this: यह एक पोस्टस्क्रिप्ट फ़ाइल है (एक .ai एक पुराने फ़ॉर्मैट में या बिना PDF संगतता, या एक ईपीएस फ़ाइल में बचाया), जिसे अभी तक ओपन किया नहीं जा सकता है: इसे PDF, PDF-संगत .ai या SVG के रूप में सेव करें +@msg this is not a PostScript file this: यह पोस्टस्क्रिप्ट फ़ाइल नहीं है +@msg this isn't a flat-colour logo ({_1}% of its solid areas match a few flat colours), so Flat Logo mode would turn its gradients into patches: use Color mode instead यह एक फ्लैट रंग का लोगो नहीं है ({_1}% अपने ठोस क्षेत्रों में कुछ फ्लैट रंगों से मेल खाता है), इसलिए फ्लैट लोगो मोड अपने ग्रेडिएंट को पैच में बदल देगा: इसके बजाय कलर मोड का उपयोग करें +@msg this kind of brush has no options dialog yet इस तरह के ब्रश में अभी तक कोई ऑप्शन्स संवाद नहीं है +@msg this PostScript file can't be read ({why}): save it as PDF or SVG in the app that made it इस पोस्टस्क्रिप्ट फ़ाइल को पढ़ा नहीं जा सकता ({why}): इसे उस ऐप में PDF या SVG के रूप में सेव करें जिसने इसे बनाया +@msg This shortcut file is in a form VectorCraft can't read. यह शॉर्टकट फ़ाइल एक फॉर्म VectorCraft में है जिसे पढ़ा नहीं जा सकता है। +@msg this system has no screen color sampler इस प्रणाली में कोई स्क्रीन रंग नमूना नहीं है +@msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset यह निशान {max} एंकर पॉइंट से अधिक होगा, डॉक्यूमेंट की तुलना में अधिक आसानी से दिखा सकते हैं: शोर, निचले पाथ या रंग उठाना, या कम-fidelity प्रीसेट चुनना +@msg thumbnail: no page {n} (the file has 1) थंबनेल: कोई पेज {n} (फ़ाइल में 1 है) +@msg thumbnail: no page {v} (the {what} has {count}) थंबनेल: कोई पेज {v} ({what} में {count} है) +@msg tileRange of {what}: {e} {what} का tileRange: {e} +@msg time budget समय बजट +@msg tintReduction must be from 0 to 100 % tintReduction 0 से 100 % तक होना चाहिए +@msg title can't be empty शीर्षक खाली नहीं हो सकता है +@msg to (the new name) is required (नया नाम) के लिए आवश्यक है +@msg to must be fill or stroke to: होना चाहिए भरने या स्ट्रोक होना चाहिए +@msg to must be smooth or corner to: होना चाहिए चिकनी या कोने होना +@msg too large for a zip archive: package to a folder एक ज़िप संग्रह के लिए बहुत बड़ा: एक फ़ोल्डर में पैकेज +@msg too many `points` (at most 100000) बहुत सारे `points` (अधिकांश 100000 पर) +@msg Too many breaks to remove at once एक बार में हटाने के लिए बहुत सारे ब्रेक +@msg too many changed shortcuts बहुत से बदलाव किए गए शॉर्टकट +@msg too many characters: at most {MAX_CHARS} बहुत सारे अक्षर: at most {MAX_CHARS} +@msg too many dots for this size: lower the frequency इस आकार के लिए बहुत सारे डॉट्स: आवृत्ति को कम करें +@msg too many filters over one file एक फ़ाइल पर बहुत सारे फिल्टर +@msg too many library panels were opened in this session इस सत्र में कई लाइब्रेरी पैनल ओपन किए गए थे। +@msg too many objects selected (at most 20000) बहुत सारे ऑब्जेक्ट्स सिलेक्टेड (अधिकांश 20000 पर) +@msg too many overlapping paths for Shaper शेपर के लिए कई ओवरलैपिंग पाथ +@msg Too many pieces to make at once बहुत सारे टुकड़े एक बार में बनाने के लिए +@msg too many saved clips कई बचाया क्लिप +@msg too many saved graphics states कई बचाया ग्राफिक्स राज्यों +@msg too many Shaper edits बहुत सारे शेपर संपादन +@msg Too many type objects to change at once एक बार में बदलने के लिए कई प्रकार की ऑब्जेक्टएं +@msg tool (a tool id) is required टूल (एक टूल आईडी) की आवश्यकता होती है +@msg tool shortcuts must be a single key (optionally with Shift) टूल शॉर्टकट एक कुंजी होने चाहिए (वैकल्पिक रूप से Shift के साथ) +@msg toolbar (a toolbar's name) must be a string टूलबार (एक टूलबार का नाम) एक स्ट्रिंग होना चाहिए +@msg toolbar name can't be empty टूलबार का नाम खाली नहीं हो सकता +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (डिफ़ॉल्ट) या "omit" +@msg Trap: no edges of different colours meet among the selected objects ट्रैप: विभिन्न रंगों के कोई किनारे सिलेक्टेड ऑब्जेक्ट्स के बीच मिलते हैं +@msg Trap: select two or more objects filled with solid colours ट्रैप: ठोस रंगों से भरे दो या दो से अधिक ऑब्जेक्ट चुनें +@msg truncated छंटनी +@msg two saved selections would be named `{_1}` दो बचाया सिलेक्शन `{_1}` नाम दिया जाएगा +@msg type dimension cannot be represented with this text transform इस टेक्स्ट को बदलने के साथ टाइप आयाम का प्रतिनिधित्व नहीं किया जा सकता है +@msg type dimension must be finite प्रकार आयाम को परिमित होना चाहिए +@msg type must be static or dynamic, not {v} type: प्रकार स्थिर या गतिशील होना चाहिए, न कि {v} +@msg type objects can't be isolated प्रकार ऑब्जेक्ट पृथक नहीं किया जा सकता है +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip प्रकार जुड़े क्षेत्रों में एक मास्क के रूप में इस्तेमाल किया, रैपराउंड टेक्स्ट या एक मिश्रित पाथ क्लिप नहीं करता है +@msg Unembedded to {_1} Unembed to {_1} +@msg unexpected host trap अप्रत्याशित मेजबान जाल +@msg unexpected resources अप्रत्याशित संसाधन +@msg unknown {k} key `{key}` (size, position) अज्ञात {k} कुंजी `{key}` (आकार, स्थिति) +@msg unknown {key} `{v}` (none, short or full) अज्ञात {key} `{v}` (one, short or full) +@msg unknown {key} profile `{n}` अज्ञात {key} प्रोफ़ाइल `{n}` +@msg unknown align `{other}` अज्ञात `{other}` +@msg unknown alignToPath `{a}` अज्ञात alignToPath `{a}` +@msg unknown arrowhead {v} अज्ञात arrowhead {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) अज्ञात artboardLayout कुंजी `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown attribute `{attribute}` अज्ञात विशेषता `{attribute}` +@msg unknown attribute `{k}` अज्ञात विशेषता `{k}` +@msg unknown axis `{other}` (vertical|horizontal|free) अज्ञात धुरी `{other}` (vertical Chhorizontal Chlorfree) +@msg unknown blend mode {b} अज्ञात मिश्रण मोड {b} +@msg unknown blend mode `{b}` अज्ञात मिश्रण मोड `{b}` +@msg unknown brush type `{o}` अज्ञात ब्रश प्रकार `{o}` +@msg unknown category `{c}` अज्ञात श्रेणी `{c}` +@msg unknown category `{c}` ({_1}) अज्ञात श्रेणी `{c}` ({_1}) +@msg unknown character `{c}` अज्ञात चरित्र `{c}` +@msg unknown character style number field अज्ञात चरित्र स्टाइल संख्या क्षेत्र +@msg unknown CMYK profile `{name}` अज्ञात CMYK प्रोफ़ाइल `{name}` +@msg unknown command `{0}` अज्ञात आदेश `{0}` +@msg unknown command `{0}`; did you mean `{1}`? अज्ञात आदेश `{0}`; क्या आपको `{1}` का मतलब है? +@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode अज्ञात नियंत्रण `{name}`: fillStroke, रंग, drawMode या screenMode +@msg Unknown dimension mode अज्ञात आयाम मोड +@msg Unknown dimension option {k} अज्ञात आयाम ऑप्शन {k} +@msg Unknown dimension style अज्ञात आयाम स्टाइल +@msg unknown effect `{e}` अज्ञात इफ़ेक्ट `{e}` +@msg unknown effect `{id}` अज्ञात इफ़ेक्ट `{id}` +@msg unknown end {e} अज्ञात अंत {e} +@msg unknown File Info field `{k}` अज्ञात फ़ाइल जानकारी क्षेत्र `{k}` +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) अज्ञात flattenerPreset `{name}` (उच्च संकल्प, मध्यम संकल्प, कम संकल्प या एक बचाया: flattener.presets.list देखें) +@msg unknown format अज्ञात स्वरूप +@msg unknown format `{f}` (Save writes {_1}) अज्ञात फ़ॉर्मैट `{f}` (Save लिखते हैं {_1}) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) अज्ञात फ़ॉर्मैट `{f}` (vcswatches, gpl, ase या css) +@msg unknown freeform mode `{m}` (points, lines) अज्ञात फ्रीफॉर्म मोड `{m}` (बिंदुओं, लाइनों) +@msg unknown from {f} {f} से अज्ञात +@msg unknown gradient kind `{k}` (linear, radial, freeform) अज्ञात ग्रेडिएंट `{k}` (रैखिक, रेडियल, फ्रीफॉर्म) +@msg unknown graph type `{t}` अज्ञात ग्राफ प्रकार `{t}` +@msg unknown grid colours `{name}` (one of {_1}) अज्ञात ग्रिड रंग `{name}` ({_1} में से एक) +@msg unknown gridType `{t}` अज्ञात gridType `{t}` +@msg unknown highlight `{h}` अज्ञात हाइलाइट `{h}` +@msg unknown highlight `{v}` अज्ञात हाइलाइट `{v}` +@msg unknown intent `{i}` अज्ञात आशय `{i}` +@msg unknown issue kind {id} अज्ञात मुद्दे की तरह {id} +@msg unknown issue kind {v} अज्ञात मुद्दे की तरह {v} +@msg unknown knockout state {k} अज्ञात नॉकआउट स्टेट {k} +@msg unknown language `{l}` (one of {_1}) अज्ञात भाषा `{l}` ({_1} में से एक) +@msg unknown language `{language}` (one of {_1}) अज्ञात भाषा `{language}` ({_1} में से एक) +@msg unknown method `{m}` ({_1}) अज्ञात विधि `{m}` ({_1}) +@msg unknown mode {m} अज्ञात मोड {m} +@msg unknown mode `{o}` अज्ञात मोड `{o}` +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) अज्ञात मोड `{other}` (ग्रे, RGB, hsb, लैब, cmyk या वेब) +@msg unknown mode `{other}` (mono|cmyk) अज्ञात मोड `{other}` (mono trumcmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) अज्ञात मोड `{other}` (rgb trumcmyk Chgray Chlobal) +@msg unknown mode `{other}` (set, add, subtract) अज्ञात मोड `{other}` (सेट, ऐड, घटाना) +@msg unknown model `{other}` अज्ञात मॉडल `{other}` +@msg unknown model `{other}` (keep, new or document) अज्ञात मॉडल `{other}` (keep, नया या डॉक्यूमेंट) +@msg unknown op {o} अज्ञात op {o} +@msg unknown OpenType feature `{t}` अज्ञात ओपन टाइप सुविधा `{t}` +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom; prefix - to turn off) अज्ञात ओपन टाइप सुविधा `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01-ss20, नमक, titl, pnum, lnum, sups, subs, numr, dnom; prefix - बंद करने के लिए) +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) featureChanges में अज्ञात OpenType फ़ीचर `{t}` (वे टैग जो `features` लेता है) +@msg unknown option `{path}.{k}` अज्ञात ऑप्शन `{path}.{k}` +@msg unknown order `{o}`: toggle, front, forward, backward or back अज्ञात आदेश `{o}`: टॉगल, फ्रंट, फॉरवर्ड, बैकवर्ड या बैक +@msg unknown overprints `{o}` (preserve, simulate or discard) अज्ञात ओवरप्रिंट `{o}` (preserve, अनुकरण या discard) +@msg unknown overprints `{v}` (preserve, simulate or discard) अज्ञात ओवरप्रिंट `{v}` (प्ररक्षित, अनुकरण या त्यागपत्र) +@msg unknown panel अज्ञात पैनल +@msg unknown panel `{raw}` अज्ञात पैनल `{raw}` +@msg unknown parameter `{key}`; did you mean `{near}`? अज्ञात पैरामीटर `{key}`; क्या आपको `{near}` का मतलब है? +@msg unknown parameter `{key}`; the command takes no parameters अज्ञात पैरामीटर `{key}`; कमांड कोई पैरामीटर नहीं लेता है +@msg unknown parameter `{key}`; the command takes: {keys} अज्ञात पैरामीटर `{key}`; कमांड लेता है: {keys} +@msg unknown PDF preset `{name}` (presets: {_1}) अज्ञात PDF प्रीसेट `{name}` (presets: {_1}) +@msg unknown pieLegend `{v}` (none, standard or wedges) अज्ञात pieLegend `{v}` (one, मानक या wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) अज्ञात piePosition `{v}` (यहां तक कि अनुपात या स्टैक्ड) +@msg unknown pieSort `{v}` (none, all or first) अज्ञात pieSort `{v}` (one, all या पहले) +@msg unknown plate `{n}` अज्ञात प्लेट `{n}` +@msg unknown preference `{k}` अज्ञात वरीयता `{k}` +@msg unknown preference `{key}` अज्ञात वरीयता `{key}` +@msg unknown preset (one of {_1}) अज्ञात प्रीसेट ({_1} में से एक) +@msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) अज्ञात प्रीसेट `{name}` (उच्च, मध्यम, निम्न या एक बचाया: flattener.presets.list देखें) +@msg unknown preset `{name}` (see flattener.presets.list) अज्ञात प्रीसेट `{name}` (देखें flattener.presets.list) +@msg unknown preset `{name}` (see webExport.presets.list) अज्ञात प्रीसेट `{name}` (see webExport.presets.list) +@msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) अज्ञात प्रीसेट `{name}`: एक अंतर्निहित या सेव किए गए प्रीसेट नहीं (imageTrace.presets देखें) +@msg unknown profile {id} (see stroke.widthProfile.list) अज्ञात प्रोफ़ाइल {id} (view stroke.widthProfile.list) +@msg unknown proof target `{t}` अज्ञात प्रमाण लक्ष्य `{t}` +@msg unknown quotes key `{k}` (double, single) अज्ञात उद्धरण कुंजी `{k}` (डबल, सिंगल) +@msg unknown resolution `{v}` अज्ञात संकल्प `{v}` +@msg unknown rule `{r}` (see color.harmony) अज्ञात नियम `{r}` (देखें color.harmony) +@msg unknown rule `{rule}` ({_1}) अज्ञात नियम `{rule}` ({_1}) +@msg unknown setting `{k}` अज्ञात सेटिंग `{k}` +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) अज्ञात आकार `{v}` (circle Chellipsesquareddiamond filline) +@msg unknown side `{other}` (left|right|top|bottom) अज्ञात पक्ष `{other}` (left |right |topbottom) +@msg unknown snap option `{key}` (use {options}) अज्ञात स्नैप ऑप्शन्स `{key}` (Us {options}) +@msg unknown spacing `{o}` (smooth|steps|distance) अज्ञात रिक्ति `{o}` (स्मोथ ट्रूस्टेप |distance) +@msg unknown tileType `{t}` ({_1}) अज्ञात tileType `{t}` ({_1}) +@msg unknown tool `{t}` अज्ञात टूल `{t}` +@msg unknown tool `{tool}` अज्ञात टूल `{tool}` +@msg unknown tool or command `{key}` अज्ञात टूल या आदेश `{key}` +@msg Unknown unit अज्ञात इकाई +@msg unknown units अज्ञात इकाइयों +@msg unknown units `{u}` अज्ञात इकाइयों `{u}` +@msg unknown value axis `{v}` (left, right or both) अज्ञात मान अक्ष `{v}` (बाएं, दाएं या दोनों) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) अज्ञात variation `{v}` (tintsShades|warmCool|vividMuted) +@msg unknown Warp style अज्ञात ताना स्टाइल +@msg unknown warp style `{s}` अज्ञात ताना स्टाइल `{s}` +@msg unknown workspace (one of {_1}) अज्ञात कार्यक्षेत्र ({_1} में से एक) +@msg unreadable object अप्राप्य ऑब्जेक्ट +@msg unsafe destination file name असुरक्षित गंतव्य फ़ाइल का नाम +@msg unsupported native docking operation असमर्थित मूल डॉकिंग ऑपरेशन +@msg unsupported: {0} unsupported: {0} +@msg use paths or compound paths पाथ या यौगिक पाथ का उपयोग करें +@msg useArtboards must be true or false, not {v} useArtboards को true या false होना चाहिए, {v} नहीं +@msg value for `{var}` must match its variable kind `{var}` के लिए मूल्य अपने परिवर्तनीय प्रकार से मेल खाता होना चाहिए +@msg variable `{_1}` is already defined चर `{_1}` पहले से ही परिभाषित किया गया है +@msg variable `{name}` can't be saved in a variable library: rename it to start with a letter or `_`, without spaces or symbols other than `-`, `_` and `.` वेरिएबल `{name}` वेरिएबल लाइब्रेरी में सेव किया नहीं जा सकता: नाम अक्षर या `_` से शुरू करें, स्पेस और `-`, `_`, `.` के अलावा अन्य चिह्न न रखें +@msg variable `{name}` has no `trait` चर `{name}` में कोई `trait` नहीं है +@msg variable `{name}` is already defined चर `{name}` को पहले से ही परिभाषित किया गया है +@msg variable `{name}` is declared twice परिवर्तनीय `{name}` को दो बार घोषित किया गया है +@msg variable `{to}` already exists चर `{to}` पहले से मौजूद +@msg variables are locked चर लॉक कर रहे हैं +@msg variables that aren't text were left out: {kinds} वेरिएबल जो टेक्स्ट नहीं छोड़े गए थे: {kinds} +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version ने {v} लौटाया; यह होस्ट संस्करण {ABI_VERSION} लागू करता है +@msg vc_alloc returned 0 (out of memory) vc_alloc 0 लौटे (मेमोरी से बाहर) +@msg vc_alloc returned a block outside memory vc_alloc स्मृति के बाहर एक ब्लॉक लौटा +@msg vc_run returned error code {packed} vc_run त्रुटि कोड लौटा {packed} +@msg VectorCraft doesn't search other apps' or the system's folders: {path} वेक्टर क्रेफ्ट अन्य एप्लिकेशन या सिस्टम के फ़ोल्डर्स की खोज नहीं करता है: {path} +@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} वेक्टर क्रेफ्ट उपयोगकर्ताओं में साझा या सार्वजनिक फ़ोल्डर की खोज नहीं करता है: {path} +@msg VectorCraft failed to start: {e} वेक्टर क्रेफ्ट शुरू करने में विफल रहा: {e} +@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it VectorCraft के फ़ॉन्ट फ़ोल्डर यहां सेट नहीं है: डेस्कटॉप ऐप और VectorCraft-क्लाई ने इसे सेट किया +@msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files संस्करण {0} की फ़ाइलें संपीड़ित नहीं हो सकतीं: केवल संस्करण {COMPRESSED_SINCE} और बाद के संस्करण संपीड़ित फ़ाइलें खोलते हैं +@msg videoRulerPixelAspectRatio must be a number from 0.1 to 10 videoRulerPixelAspectRatio को 0.1 से 10 के बीच संख्या होना चाहिए +@msg view is required देखने की आवश्यकता है +@msg view must be one of {_1} view: राय होना चाहिए {_1} +@msg warpStyle can only edit an applied Warp effect warpStyle केवल लागू वार्प इफ़ेक्ट एडिट कर सकता है +@msg width and height are at least 1 pixel चौड़ाई और ऊंचाई कम से कम 1 पिक्सेल हैं +@msg width factors must be finite चौड़ाई कारकों को परिमित होना चाहिए +@msg width must be positive width: चौड़ाई सकारात्मक होना चाहिए +@msg width out of range सीमा से बाहर चौड़ाई +@msg width/height must be > 0 चौड़ाई / ऊंचाई होना चाहिए > 0 +@msg width/height must be positive and within the canvas चौड़ाई / ऊंचाई सकारात्मक होना चाहिए और कैनवास के भीतर होना चाहिए +@msg workspace name can't be empty कार्यक्षेत्र का नाम खाली नहीं हो सकता है +@msg x and y must be finite x और y को परिमित होना चाहिए +@msg x and y must be finite numbers x और y होना चाहिए परिमित संख्या +@msg x and y must be given together x और y को एक साथ दिया जाना चाहिए +@msg x and y must be provided together x और y को एक साथ प्रदान किया जाना चाहिए +@msg x and y must both be numbers x और y दोनों संख्या होना चाहिए +@msg You must choose a side pattern. आपको एक साइड पैटर्न चुनना होगा। +@msg Your unsaved changes are kept in this browser: reload the page to get them back. इस ब्राउज़र में आपके बिना सेव किए गए बदलाव को रखा गया है: उन्हें वापस पाने के लिए पेज को फिर से लोड करें। +@msg zipped 32-bit PSD image data with prediction can't be read भविष्यवाणी के साथ 32-bit PSD इमेज डेटा zipped नहीं किया जा सकता +@msg zone must be a string zone: क्षेत्र एक स्ट्रिंग होना चाहिए +@msg zone must be tab, center, left, right, top or bottom zone: क्षेत्र टैब होना चाहिए, केंद्र, बाएं, दाएं, ऊपर या नीचे +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone: जोन को एक एंकर की आवश्यकता होती है: एंकर के साथ एक पैनल के बगल में, या साइड (स्टार्ट या एंड) के साथ एक नए डॉक कॉलम में +@msg zoom must be positive zoom: ज़ूम सकारात्मक होना चाहिए +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} लिंक्ड फ़ाइल नहीं मिली)|({n} लिंक्ड फ़ाइलें नहीं मिलीं) +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} रंग CMYK गैमट से बाहर है|{n} रंग CMYK गैमट से बाहर हैं +@msgplural {n} font file is now in {folder}; {failed} couldn't be added: {reason}|{n} font files are now in {folder}; {failed} couldn't be added: {reason} {n} फ़ॉन्ट फ़ाइल अब {folder} में है; {failed} जोड़ी नहीं जा सकीं: {reason}|{n} फ़ॉन्ट फ़ाइलें अब {folder} में हैं; {failed} जोड़ी नहीं जा सकीं: {reason} +@msgplural {n} font file is now in {folder}|{n} font files are now in {folder} {n} फ़ॉन्ट फ़ाइल अब {folder} में है|{n} फ़ॉन्ट फ़ाइलें अब {folder} में हैं +@msgplural {n} font isn't available here: its text shows in another font|{n} fonts aren't available here: their text shows in another font {n} फ़ॉन्ट यहाँ उपलब्ध नहीं है: उसका टेक्स्ट दूसरे फ़ॉन्ट में दिखता है|{n} फ़ॉन्ट यहाँ उपलब्ध नहीं हैं: उनका टेक्स्ट दूसरे फ़ॉन्ट में दिखता है +@msgplural {n} image couldn't be decoded and shows as a crossed box|{n} images couldn't be decoded and show as crossed boxes {n} इमेज डिकोड नहीं हुई और क्रॉस वाले बॉक्स में दिखती है|{n} इमेज डिकोड नहीं हुईं और क्रॉस वाले बॉक्स में दिखती हैं +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} इमेज ट्रेस नहीं हुई|{n} इमेज ट्रेस नहीं हुईं +@msgplural {n} linked file can't be read here: its preview shows|{n} linked files can't be read here: their previews show {n} लिंक्ड फ़ाइल यहाँ पढ़ी नहीं जा सकती: उसका प्रीव्यू दिखता है|{n} लिंक्ड फ़ाइलें यहाँ पढ़ी नहीं जा सकतीं: उनके प्रीव्यू दिखते हैं +@msgplural {n} linked file not found|{n} linked files not found {n} लिंक्ड फ़ाइल नहीं मिली|{n} लिंक्ड फ़ाइलें नहीं मिलीं +@msgplural {n} linked image changed on disk: Update Links shows the new version|{n} linked images changed on disk: Update Links shows the new versions डिस्क पर {n} लिंक्ड इमेज बदल गई है: लिंक अपडेट करें से नया संस्करण दिखेगा|डिस्क पर {n} लिंक्ड इमेज बदल गई हैं: लिंक अपडेट करें से नए संस्करण दिखेंगे +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} और अभी सिलेक्टेड नहीं हो सकते|{selected}; {n} और अभी सिलेक्टेड नहीं हो सकते +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} और छिपा हुआ या लॉक है|{selected}; {n} और छिपे हुए या लॉक हैं +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} और टेम्पलेट लेयर पर है|{selected}; {n} और टेम्पलेट लेयर्स पर हैं +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} और अलग किए समूह के बाहर है|{selected}; {n} और अलग किए समूह के बाहर हैं +@msgplural Broke {n} link; {missing} can't be read: relink or update them first|Broke {n} links; {missing} can't be read: relink or update them first {n} लिंक तोड़ा गया; {missing} पढ़े नहीं जा सकते: पहले उन्हें दोबारा लिंक या अपडेट करें|{n} लिंक तोड़े गए; {missing} पढ़े नहीं जा सकते: पहले उन्हें दोबारा लिंक या अपडेट करें +@msgplural Broke {n} link|Broke {n} links {n} लिंक तोड़ा गया|{n} लिंक तोड़े गए +@msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} ऑब्जेक्ट का CSS कॉपी हुआ|{n} ऑब्जेक्ट्स का CSS कॉपी हुआ +@msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} रिकवर किया डॉक्यूमेंट छोड़ा गया|{n} रिकवर किए डॉक्यूमेंट छोड़े गए +@msgplural Downloaded {n} file|Downloaded {n} files {n} फ़ाइल डाउनलोड हुई|{n} फ़ाइलें डाउनलोड हुईं +@msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} इमेज एम्बेड हुई; {missing} अनुपलब्ध: पहले उन्हें दोबारा लिंक करें|{n} इमेज एम्बेड हुईं; {missing} अनुपलब्ध: पहले उन्हें दोबारा लिंक करें +@msgplural Embedded {n} image|Embedded {n} images {n} इमेज एम्बेड हुई|{n} इमेज एम्बेड हुईं +@msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} डॉक्यूमेंट एक्सपोर्ट हुआ; {title} लिखा नहीं गया: {error}|{n} डॉक्यूमेंट एक्सपोर्ट हुए; {title} लिखा नहीं गया: {error} +@msgplural Exported {n} document|Exported {n} documents {n} डॉक्यूमेंट एक्सपोर्ट हुआ|{n} डॉक्यूमेंट एक्सपोर्ट हुए +@msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {folder} में {n} फ़ाइल एक्सपोर्ट हुई|{folder} में {n} फ़ाइलें एक्सपोर्ट हुईं +@msgplural Exported {what} with {n} note: {first}|Exported {what} with {n} notes: {first} {what} एक्सपोर्ट हुआ, {n} नोट के साथ: {first}|{what} एक्सपोर्ट हुआ, {n} नोट्स के साथ: {first} +@msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} {n} नोट के साथ खुला: {first}|{n} नोट्स के साथ खुला: {first} +@msgplural Packaged {n} file ({note}) in {folder}|Packaged {n} files ({note}) in {folder} {folder} में {n} फ़ाइल ({note}) पैकेज हुई|{folder} में {n} फ़ाइलें ({note}) पैकेज हुईं +@msgplural Packaged {n} file {note}|Packaged {n} files {note} {n} फ़ाइल पैकेज हुई {note}|{n} फ़ाइलें पैकेज हुईं {note} +@msgplural Packaged {n} file in {folder}|Packaged {n} files in {folder} {folder} में {n} फ़ाइल पैकेज हुई|{folder} में {n} फ़ाइलें पैकेज हुईं +@msgplural Packaged {n} file|Packaged {n} files {n} फ़ाइल पैकेज हुई|{n} फ़ाइलें पैकेज हुईं +@msgplural Relinked {n} image; {name} couldn't be relinked: {reason}|Relinked {n} images; {name} couldn't be relinked: {reason} {n} इमेज दोबारा लिंक हुई; {name} दोबारा लिंक नहीं हुई: {reason}|{n} इमेज दोबारा लिंक हुईं; {name} दोबारा लिंक नहीं हुई: {reason} +@msgplural Relinked {n} image; not in that folder: {names}|Relinked {n} images; not in that folder: {names} {n} इमेज दोबारा लिंक हुई; उस फ़ोल्डर में नहीं मिलीं: {names}|{n} इमेज दोबारा लिंक हुईं; उस फ़ोल्डर में नहीं मिलीं: {names} +@msgplural Relinked {n} image|Relinked {n} images {n} इमेज दोबारा लिंक हुई|{n} इमेज दोबारा लिंक हुईं +@msgplural Replaced {n} image|Replaced {n} images {n} इमेज बदली गई|{n} इमेज बदली गईं +@msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} रिकवर किया डॉक्यूमेंट बहाल हुआ: रखने के लिए उसे सेव करें|{n} रिकवर किए डॉक्यूमेंट बहाल हुए: रखने के लिए उन्हें सेव करें +@msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} सेव किया गया, {n} नोट के साथ: {first}|{path} सेव किया गया, {n} नोट्स के साथ: {first} +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} एम्बेड की गई इमेज सिलेक्टेड|{n} एम्बेड की गई इमेज सिलेक्टेड +@msgplural Selected {n} image|Selected {n} images {n} इमेज सिलेक्टेड|{n} इमेज सिलेक्टेड +@msgplural Selected {n} linked image|Selected {n} linked images {n} लिंक्ड इमेज सिलेक्टेड|{n} लिंक्ड इमेज सिलेक्टेड +@msgplural Selected {n} missing image|Selected {n} missing images {n} अनुपलब्ध इमेज सिलेक्टेड|{n} अनुपलब्ध इमेज सिलेक्टेड +@msgplural Selected {n} modified image|Selected {n} modified images {n} बदली हुई इमेज सिलेक्टेड|{n} बदली हुई इमेज सिलेक्टेड +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} इमेज ट्रेस हुई; ट्रेस नहीं हुईं: {failed}|{n} इमेज ट्रेस हुईं; ट्रेस नहीं हुईं: {failed} +@msgplural Traced {n} image|Traced {n} images {n} इमेज ट्रेस हुई|{n} इमेज ट्रेस हुईं +@msgplural Updated {n} image|Updated {n} images {n} इमेज अपडेट हुई|{n} इमेज अपडेट हुईं +@msgplural Updated {n} linked file changed on disk|Updated {n} linked files changed on disk डिस्क पर बदली {n} लिंक्ड फ़ाइल अपडेट हुई|डिस्क पर बदली {n} लिंक्ड फ़ाइलें अपडेट हुईं +@plural {n} area highlighted|{n} areas highlighted {n} क्षेत्र हाइलाइट|{n} क्षेत्र हाइलाइट +@plural {n} color|{n} colors {n} रंग|{n} रंग +@plural {n} commit|{n} commits {n} कमिट|{n} कमिट +@plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} में {n} फ़ाइल {note}। पैकेज फ़ोल्डर दिखाएँ?|{folder} में {n} फ़ाइलें {note}। पैकेज फ़ोल्डर दिखाएँ? +@plural {n} file in {folder}. Show the package folder?|{n} files in {folder}. Show the package folder? {folder} में {n} फ़ाइल। पैकेज फ़ोल्डर दिखाएँ?|{folder} में {n} फ़ाइलें। पैकेज फ़ोल्डर दिखाएँ? +@plural {n} file|{n} files {n} फ़ाइल|{n} फ़ाइलें +@plural {n} fill|{n} fills {n} फ़िल|{n} फ़िल +@plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} फ़ोल्डर या फ़ाइल पढ़ी नहीं जा सकी|{n} फ़ोल्डर या फ़ाइलें पढ़ी नहीं जा सकीं +@plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones {n} फ़ोल्डर छोड़ा गया, जैसे किसी दूसरे ऐप या सिस्टम का या छिपा हुआ फ़ोल्डर|{n} फ़ोल्डर छोड़े गए, जैसे दूसरे ऐप्स या सिस्टम के या छिपे हुए फ़ोल्डर +@plural {n} folder|{n} folders {n} फ़ोल्डर|{n} फ़ोल्डर +@plural {n} glyph|{n} glyphs {n} ग्लिफ़|{n} ग्लिफ़ +@plural {n} item|{n} items {n} आइटम|{n} आइटम +@plural {n} Layer|{n} Layers {n} लेयर|{n} लेयरें +@plural {n} linked file not found|{n} linked files not found {n} लिंक्ड फ़ाइल नहीं मिली|{n} लिंक्ड फ़ाइलें नहीं मिलीं +@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? डिस्क पर {n} लिंक्ड इमेज बदली है। नया संस्करण दिखाएँ?|डिस्क पर {n} लिंक्ड इमेज बदली हैं। नए संस्करण दिखाएँ? +@plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? डॉक्यूमेंट सेव करने के बाद {n} लिंक्ड इमेज बदली है। नया संस्करण दिखाएँ?|डॉक्यूमेंट सेव करने के बाद {n} लिंक्ड इमेज बदली हैं। नए संस्करण दिखाएँ? +@plural {n} more export waiting|{n} more exports waiting {n} और एक्सपोर्ट प्रतीक्षा में|{n} और एक्सपोर्ट प्रतीक्षा में +@plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} और नियम: एक्सपोर्ट इसे लिखता है।|{n} और नियम: एक्सपोर्ट सभी लिखता है। +@plural {n} object highlighted|{n} objects highlighted {n} ऑब्जेक्ट हाइलाइट|{n} ऑब्जेक्ट हाइलाइट किए गए +@plural {n} Object|{n} Objects {n} ऑब्जेक्ट|{n} ऑब्जेक्ट्स +@plural {n} part of the file wasn't read|{n} parts of the file weren't read फ़ाइल का {n} हिस्सा पढ़ा नहीं गया|फ़ाइल के {n} हिस्से पढ़े नहीं गए +@plural {n} PR|{n} PRs {n} PR|{n} PR +@plural {n} shortcut is assigned more than once|{n} shortcuts are assigned more than once {n} शॉर्टकट को एक से अधिक बार सौंपा गया है|{n} शॉर्टकट को एक से अधिक बार सौंपा गया है +@plural {n} star|{n} stars {n} स्टार|{n} स्टार +@plural {n} step|{n} steps {n} स्टेप|{n} स्टेप +@plural {n} stroke|{n} strokes {n} स्ट्रोक|{n} स्ट्रोक +@plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. बिना नाम का {n} ऑब्जेक्ट छोड़ा गया: नाम दें या पैनल मेनू में बिना नाम के ऑब्जेक्ट चालू करें।|बिना नाम के {n} ऑब्जेक्ट छोड़े गए: नाम दें या पैनल मेनू में बिना नाम के ऑब्जेक्ट चालू करें। +@plural agrees with {n} default shortcut|agrees with {n} default shortcuts {n} डिफ़ॉल्ट शॉर्टकट से मेल खाता है|{n} डिफ़ॉल्ट शॉर्टकट से मेल खाता है +@plural Apply to All ({n} more missing)|Apply to All ({n} more missing) सभी पर लागू करें ({n} और अनुपलब्ध)|सभी पर लागू करें ({n} और अनुपलब्ध) +@plural Color Table ({n} color)|Color Table ({n} colors) रंग तालिका ({n} रंग)|रंग तालिका ({n} रंग) +@plural Delete this {n} brush?|Delete these {n} brushes? यह {n} ब्रश हटाएँ?|ये {n} ब्रश हटाएँ? +@plural Delete this {n} graphic style?|Delete these {n} graphic styles? यह {n} ग्राफ़िक स्टाइल हटाएँ?|ये {n} ग्राफ़िक स्टाइल्स हटाएँ? +@plural Delete this {n} swatch or group?|Delete these {n} swatches and groups? यह {n} स्वॉच या समूह हटाएँ?|ये {n} स्वॉचेस और समूह हटाएँ? +@plural Packaged {n} file {note} in {folder}|Packaged {n} files {note} in {folder} {folder} में {n} फ़ाइल {note} पैकेज हुई|{folder} में {n} फ़ाइलें {note} पैकेज हुईं +@plural Packaged {n} file {note}|Packaged {n} files {note} {n} फ़ाइल पैकेज हुई {note}|{n} फ़ाइलें पैकेज हुईं {note} +@plural Packaged {n} file in {folder}|Packaged {n} files in {folder} {folder} में {n} फ़ाइल पैकेज हुई|{folder} में {n} फ़ाइलें पैकेज हुईं +@plural Packaged {n} file|Packaged {n} files {n} फ़ाइल पैकेज हुई|{n} फ़ाइलें पैकेज हुईं +@plural Result: {n}|Results: {n} परिणाम: {n}|परिणाम: {n} +3d Bevel बेवल +3d Cap कैप +3d Hollow खोखले +3d Light लाइट +3d Rounded गोल +3d Solid ठोस +3d Space Space +anchor Points: पॉइंट्स: +axis Both दोनों +axis Horizontal क्षैतिज +axis Vertical लंबवत +axis X Axis X अक्ष +axis Y Axis Y अक्ष +breakText Glyphs ग्लिफ़्स +breakText Lines रेखाएँ +breakText Words शब्द +diagnostics render रेंडर +diagnostics ui यूआई +digits Bengali बंगाली +digits Devanagari देवनगरी +digits Gujarati गुजराती +digits Gurmukhi गुर्मुकी +digits Hindi हिन्दी +digits Kannada कन्नड़ +digits Malayalam मालायम +digits Odia ओडिया +digits Tamil तमिल +digits Telugu तेलुगु +effect Horizontal क्षैतिज +effect Points पॉइंट्स +effect Regular सामान्य +effect Soft सॉफ़्ट +effect Vertical लंबवत +file-filter All placeable files सभी प्लेसेबल फ़ाइलें +file-filter All readable files सभी पठनीय फ़ाइलों +file-filter Export presets प्रीसेट्स एक्सपोर्ट करें +file-filter Flattener presets फ़्लैटनर प्रीसेट्स +file-filter PDF presets PDF प्रीसेट्स +file-filter PDF-compatible .ai PDF-संगत .ai +file-filter Print presets प्रिंट प्रीसेट्स +file-filter SVG Compressed SVG संपीड़ित +file-filter Swatch libraries स्वॉच लाइब्रेरीज़ +file-filter Templates टेम्पलेट्स +file-filter VectorCraft Template वेक्टर क्राफ्ट टेम्पलेट +font-script Japanese जापानी +font-technology Variable चर +gradient-kind Radial रेडियल +imageTrace Outline रूपरेखा +lighting Light लाइट +mark-style Japanese जापानी +shape Open ओपन +swatch [None] [कोई नहीं] +swatch [Registration] [पंजीकरण] +swatch Amber एम्बर +swatch Aqua एक्वा +swatch Azure नीला +swatch Black काला +swatch Blue नीला +swatch Bright Blue ब्राइट ब्लू +swatch Bright Green ब्राइट ग्रीन +swatch Bright Red ब्राइट रेड +swatch Bright Violet ब्राइट वायलेट +swatch Bright Yellow ब्राइट येलो +swatch Brights चमकीले +swatch Brown भूरा +swatch Chocolate चॉकलेट +swatch Coffee कॉफी +swatch Copper तांबा +swatch Cyan सियान +swatch Cyan Green सियान ग्रीन +swatch Emerald पन्ना हरा +swatch Espresso एस्प्रेसो +swatch Grays ग्रे +swatch Green हरा +swatch Indigo नील +swatch Lime लाइम +swatch Magenta मैजेंटा +swatch Ocean महासागर +swatch Orange नारंगी +swatch Orange Red ऑरेंज रेड +swatch Pink गुलाबी +swatch Purple बैंगनी +swatch Radial White, Black रेडियल व्हाइट, ब्लैक +swatch Red लाल +swatch Rose गुलाब +swatch Rust रुस्ट +swatch Sand सैंड +swatch Sunset सनसेट +swatch Tan टैन +swatch Teal टेलर +swatch Violet बैंगनी +swatch Walnut अखरोट +swatch White सफ़ेद +swatch White, Black सफ़ेद, काला +swatch Yellow पीला +swatch Yellow Green पीला हरा +theme Appearance अपीयरेंस diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8e67cbe935..9e313975e1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -554,12 +554,14 @@ font-technology Variable Változó Character / Paragraph Karakter / bekezdés Character Alignment Karakterigazítás Character options Karakterbeállítások + Paragraph options Bekezdésbeállítások Character Rotation Karakterforgatás Character Set: Karakterkészlet: Character Style Karakterstílus Character Style Options Karakterstílus beállításai Character Styles Karakterstílusok Character: Karakter: + Paragraph: Bekezdés: Check Links Csatolások ellenőrzése # Check Script (File › Scripts) and the report it shows on a script written for the reference app. Check Script Szkript ellenőrzése @@ -4689,6 +4691,9 @@ imageTrace Outline Körvonal @msg graphs come in as plain art, without their data or settings a diagramok egyszerű grafikaként kerülnek be, adataik és beállításaik nélkül @msg an image whose data is cut short was left out kimaradt egy csonka adatú kép @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel a csatolt képek a fájlban mentett kis felbontású előnézetet mutatják, amíg a fájljaik elő nem kerülnek: csatold őket újra a Csatolások panelen +@msg linked type areas past VectorCraft's limits were left out a VectorCraft korlátain túli csatolt szövegterületek kimaradtak +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip a csatolt területeken, körbefuttatott szövegben vagy összetett útvonalban maszkként használt szöveg nem vág ki +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel a fájlban előnézet nélküli csatolt képek helyőrzőt mutatnak, amíg a fájljaik elő nem kerülnek: csatold őket újra a Csatolások panelen @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise a túl alacsony keretben lévő területszöveg, amelybe a megjelenítő betűtípus egy sora sem fér el, magasabb keretet kapott ({_1}): különben nem látszana @msg an object can't be read egy objektum nem olvasható @msg an object in perspective would leave the edited grid egy perspektivikus objektum kikerülne a szerkesztett rácsból @@ -4775,6 +4780,7 @@ imageTrace Outline Körvonal @msg damaged sérült @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Az adat-helyreállításnak nincs hova mentenie a másolatokat: állítsd be a Beállítások → Fájlkezelés → Adat-helyreállítás → Mappa értéket (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Az adat-helyreállítás nem tud másolatokat menteni ide: {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Innen nem tölthetők be bővítmények: {path}: {e} @msg decimals must be {_1}–{_2} (got {_3}) a tizedesjegyek száma {_1}–{_2} lehet (kapott érték: {_3}) @msg direct-select anchor points to cut at (not the end points of open paths) jelöld ki közvetlen kijelöléssel a vágási horgonypontokat (nyitott útvonal végpontja nem lehet) @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Elvetett helyreállított dokumentumok: {n} @@ -5003,6 +5009,8 @@ imageTrace Outline Körvonal @msg no such saved selection nincs ilyen mentett kijelölés @msg no such segment nincs ilyen szakasz @msg no such spine point nincs ilyen gerincpont +@msg `with` must be a list of at most 10000 spine point indexes `with`: legfeljebb 10000 gerincpont-indexből álló lista kell +@msg `with` moves points, not a handle `with` pontokat mozgat, nem fogantyút @msg no such spine segment nincs ilyen gerincszakasz @msg no such subpath nincs ilyen részútvonal @msg no such user library nincs ilyen felhasználói könyvtár @@ -6083,6 +6091,9 @@ anchor Points: Pontok: Find Nearest Swatch… Legközelebbi színminta keresése… Find Nearest Swatch Legközelebbi színminta keresése Apply Nearest Swatch Legközelebbi színminta alkalmazása +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Kitöltés alkalmazása a körvonalra + Apply Stroke to Fill Körvonal alkalmazása a kitöltésre Select objects to find the swatches nearest their colors. Jelöljön ki objektumokat a színeikhez legközelebbi színminták megkereséséhez. @msg select objects or give `color` jelöljön ki objektumokat, vagy adja meg ezt: `color` @msg `color` is not a colour a(z) `color` nem szín @@ -6319,6 +6330,10 @@ breakText Glyphs Glifák Bow Ív Spike Csúcs Skip Spaces Szóközök kihagyása + Release Type on a Path… Útvonalszöveg szétválasztása… + Release Type on a Path Útvonalszöveg szétválasztása + Text and Path Szöveg és útvonal + Path Only Csak útvonal @msg The art is too large to copy as a picture: other apps get no PNG of it A grafika túl nagy ahhoz, hogy képként másolható legyen: más alkalmazások nem kapnak róla PNG-t # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6330,3 +6345,43 @@ breakText Glyphs Glifák Fully Outside Teljesen kívül No artboards match. Nincs egyező rajztábla. Chosen: {n} of {total} Kiválasztva: {n} / {total} + +# Contour add-on + Contour Kontúr + Contour Tool Kontúr eszköz + Sharp Hegyes + Bake Kibontás + Turn the Contour into plain paths A kontúrt egyszerű útvonalakká alakítja + Set Corners… Sarkok beállítása… + All Anchors Összes horgonypont + Odd-Numbered Anchors Páratlan horgonypontok + Even-Numbered Anchors Páros horgonypontok + Minimum angle Legkisebb szög + Maximum angle Legnagyobb szög + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Csatoltak kijelölése + Select Embedded Beágyazottak kijelölése + Select Missing Hiányzók kijelölése + Select Modified Módosítottak kijelölése + Select by Link Status Kijelölés csatolási állapot szerint + Select by Link Status… Kijelölés csatolási állapot szerint… + Search images Képek keresése + No images match. Nincs egyező kép. +@msgplural Selected {n} linked image|Selected {n} linked images Kijelölt csatolt képek: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images Kijelölt beágyazott képek: {n} +@msgplural Selected {n} missing image|Selected {n} missing images Kijelölt hiányzó képek: {n} +@msgplural Selected {n} modified image|Selected {n} modified images Kijelölt módosított képek: {n} +@msgplural Selected {n} image|Selected {n} images Kijelölt képek: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; további rejtett vagy zárolt: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; további sablonrétegen: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; további az elkülönített csoporton kívül: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; további most nem jelölhető ki: {n} + +# Compound Shapes add-on + Compound Shapes Összetett alakzatok + Shape Mode Buttons Make Compound Shapes Az alakzatmód-gombok összetett alakzatokat hoznak létre + +# 3D Box add-on + 3D Box 3D doboz + 3D Box Tool 3D doboz eszköz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8fc99dbdf4..0a6c910fcb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1403,7 +1403,9 @@ digits Malayalam Malayalam Standard Vertical Roman Alignment Perataan Romawi vertikal standar Strikethrough Coret Character: Karakter: + Paragraph: Paragraf: Character options Opsi karakter + Paragraph options Opsi paragraf Subscript Subskrip Subscript (on the roadmap) Subskrip (masih dalam roadmap) Superscript Superskrip @@ -4611,6 +4613,9 @@ imageTrace Outline Kontur @msg an image VectorCraft can't read was left out gambar yang tidak dapat dibaca VectorCraft tidak disertakan @msg an image whose data is cut short was left out gambar yang datanya terpotong tidak disertakan @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel gambar tertaut menampilkan pratinjau resolusi rendah yang tersimpan dalam berkas sampai berkasnya ditemukan: tautkan ulang di panel Tautan +@msg linked type areas past VectorCraft's limits were left out area teks tertaut di luar batas VectorCraft dihilangkan +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip teks yang digunakan sebagai masker di area tertaut, teks terbungkus, atau jalur majemuk tidak memotong +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel gambar tertaut tanpa pratinjau dalam berkas menampilkan penanda tempat sampai berkasnya ditemukan: tautkan ulang di panel Tautan @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise teks area dalam bingkai yang terlalu pendek untuk satu baris font yang ditampilkannya mendapat bingkai yang lebih tinggi ({_1}): tanpa itu teksnya tidak akan tampil @msg its editing data doesn't say where its art is data pengeditannya tidak menyatakan di mana karya seninya berada @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) berkas ini disimpan tanpa kompatibilitas PDF, dan data pengeditannya tidak dapat dibaca ({why}) @@ -5966,6 +5971,9 @@ anchor Points: Titik: Find Nearest Swatch… Cari Swatch Terdekat… Find Nearest Swatch Cari Swatch Terdekat Apply Nearest Swatch Terapkan Swatch Terdekat +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Terapkan isian ke guratan + Apply Stroke to Fill Terapkan guratan ke isian Select objects to find the swatches nearest their colors. Pilih objek untuk menemukan swatch yang paling dekat dengan warnanya. @msg select objects or give `color` pilih objek atau berikan `color` @msg `color` is not a colour `color` bukan warna @@ -6202,6 +6210,10 @@ breakText Glyphs Glif Bow Busur Spike Puncak Skip Spaces Lewati Spasi + Release Type on a Path… Lepaskan Teks pada Jalur… + Release Type on a Path Lepaskan Teks pada Jalur + Text and Path Teks dan jalur + Path Only Hanya jalur @msg The art is too large to copy as a picture: other apps get no PNG of it Gambar terlalu besar untuk disalin sebagai gambar: aplikasi lain tidak mendapatkan PNG darinya # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6213,3 +6225,43 @@ breakText Glyphs Glif Fully Outside Sepenuhnya di luar No artboards match. Tidak ada artboard yang cocok. Chosen: {n} of {total} Dipilih: {n} dari {total} + +# Contour add-on + Contour Kontur + Contour Tool Alat kontur + Sharp Tajam + Bake Perluas + Turn the Contour into plain paths Ubah kontur menjadi jalur biasa + Set Corners… Atur sudut… + All Anchors Semua jangkar + Odd-Numbered Anchors Jangkar bernomor ganjil + Even-Numbered Anchors Jangkar bernomor genap + Minimum angle Sudut minimum + Maximum angle Sudut maksimum + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Pilih yang Tertaut + Select Embedded Pilih yang Tersemat + Select Missing Pilih yang Hilang + Select Modified Pilih yang Diubah + Select by Link Status Pilih menurut Status Tautan + Select by Link Status… Pilih menurut Status Tautan… + Search images Cari gambar + No images match. Tidak ada gambar yang cocok. +@msgplural Selected {n} linked image|Selected {n} linked images Telah memilih {n} gambar tertaut +@msgplural Selected {n} embedded image|Selected {n} embedded images Telah memilih {n} gambar tersemat +@msgplural Selected {n} missing image|Selected {n} missing images Telah memilih {n} gambar yang hilang +@msgplural Selected {n} modified image|Selected {n} modified images Telah memilih {n} gambar yang diubah +@msgplural Selected {n} image|Selected {n} images Telah memilih {n} gambar +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} lainnya tersembunyi atau terkunci +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} lainnya berada di layer templat +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} lainnya berada di luar grup yang diisolasi +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} lainnya tidak dapat dipilih sekarang + +# Compound Shapes add-on + Compound Shapes Bentuk majemuk + Shape Mode Buttons Make Compound Shapes Tombol mode bentuk membuat bentuk majemuk + +# 3D Box add-on + 3D Box Kotak 3D + 3D Box Tool Alat Kotak 3D diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cddf63e822..3459374cad 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3327,7 +3327,9 @@ digits Malayalam Malayalam Patterns Motivi Stroke Options Opzioni traccia Character: Carattere: + Paragraph: Paragrafo: Character options Opzioni carattere + Paragraph options Opzioni di paragrafo Stroke options Opzioni traccia Transform options Opzioni di trasformazione Stroke Weight Spessore traccia @@ -4026,6 +4028,7 @@ axis Both Entrambi @msg Create from Selection: the selection has no area Crea da selezione: la selezione non ha area @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Il recupero dati non ha dove conservare le copie: imposta Preferenze → Gestione file → Recupero dati → Cartella (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Il recupero dati non può conservare copie in {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Impossibile caricare plug-in da {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) seleziona con Selezione diretta i punti di ancoraggio in cui tagliare (non i punti finali dei tracciati aperti) @msg Divide Objects Below: select a path Dividi oggetti sottostanti: seleziona un tracciato @msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato @@ -4371,6 +4374,8 @@ axis Both Entrambi @msg no such saved selection selezione salvata inesistente @msg no such segment segmento inesistente @msg no such spine point punto della dorsale inesistente +@msg `with` must be a list of at most 10000 spine point indexes `with` deve essere un elenco di al massimo 10000 indici di punti della dorsale +@msg `with` moves points, not a handle `with` sposta punti, non una maniglia @msg no such spine segment segmento della dorsale inesistente @msg no such subpath sottotracciato inesistente @msg no such user library libreria utente inesistente @@ -4716,6 +4721,9 @@ axis Both Entrambi @msg graphs come in as plain art, without their data or settings i grafici vengono importati come grafica semplice, senza i loro dati e le loro impostazioni @msg an image whose data is cut short was left out un'immagine con dati incompleti è stata omessa @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel le immagini collegate mostrano l'anteprima a bassa risoluzione salvata nel file finché i loro file non vengono trovati: ricollegale nel pannello Collegamenti +@msg linked type areas past VectorCraft's limits were left out le aree di testo concatenate oltre i limiti di VectorCraft sono state omesse +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip il testo usato come maschera in aree concatenate, testo attorno o un tracciato composto non ritaglia +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel le immagini collegate senza anteprima nel file mostrano un segnaposto finché i loro file non vengono trovati: ricollegale nel pannello Collegamenti @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise il testo in area in cornici troppo basse per una riga del font in cui viene mostrato ha ricevuto cornici più alte ({_1}): altrimenti non sarebbe visibile @msg its editing data doesn't say where its art is i suoi dati di modifica non dicono dove si trova la grafica @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) questo file è stato salvato senza compatibilità PDF e i suoi dati di modifica non si possono leggere ({why}) @@ -5718,6 +5726,9 @@ anchor Points: Punti: Find Nearest Swatch… Trova campione più vicino… Find Nearest Swatch Trova campione più vicino Apply Nearest Swatch Applica campione più vicino +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Applica riempimento alla traccia + Apply Stroke to Fill Applica traccia al riempimento Select objects to find the swatches nearest their colors. Seleziona gli oggetti per trovare i campioni più vicini ai loro colori. @msg select objects or give `color` seleziona gli oggetti o indica `color` @msg `color` is not a colour `color` non è un colore @@ -5955,6 +5966,10 @@ breakText Glyphs Glifi Bow Arco Spike Picco Skip Spaces Salta gli spazi + Release Type on a Path… Rilascia testo su tracciato… + Release Type on a Path Rilascia testo su tracciato + Text and Path Testo e tracciato + Path Only Solo tracciato @msg The art is too large to copy as a picture: other apps get no PNG of it La grafica è troppo grande per essere copiata come immagine: le altre app non ne ricevono un PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5966,3 +5981,43 @@ breakText Glyphs Glifi Fully Outside Completamente esterno No artboards match. Nessuna tavola da disegno corrisponde. Chosen: {n} of {total} Scelte: {n} di {total} + +# Contour add-on + Contour Contorno + Contour Tool Strumento Contorno + Sharp Appuntito + Bake Espandi + Turn the Contour into plain paths Trasforma il contorno in tracciati semplici + Set Corners… Imposta angoli… + All Anchors Tutti gli ancoraggi + Odd-Numbered Anchors Ancoraggi dispari + Even-Numbered Anchors Ancoraggi pari + Minimum angle Angolo minimo + Maximum angle Angolo massimo + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Seleziona collegate + Select Embedded Seleziona incorporate + Select Missing Seleziona mancanti + Select Modified Seleziona modificate + Select by Link Status Seleziona per stato del collegamento + Select by Link Status… Seleziona per stato del collegamento… + Search images Cerca immagini + No images match. Nessuna immagine corrisponde. +@msgplural Selected {n} linked image|Selected {n} linked images Selezionata {n} immagine collegata|Selezionate {n} immagini collegate +@msgplural Selected {n} embedded image|Selected {n} embedded images Selezionata {n} immagine incorporata|Selezionate {n} immagini incorporate +@msgplural Selected {n} missing image|Selected {n} missing images Selezionata {n} immagine mancante|Selezionate {n} immagini mancanti +@msgplural Selected {n} modified image|Selected {n} modified images Selezionata {n} immagine modificata|Selezionate {n} immagini modificate +@msgplural Selected {n} image|Selected {n} images Selezionata {n} immagine|Selezionate {n} immagini +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; altra {n} è nascosta o bloccata|{selected}; altre {n} sono nascoste o bloccate +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; altra {n} è su un livello modello|{selected}; altre {n} sono su livelli modello +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; altra {n} è fuori dal gruppo isolato|{selected}; altre {n} sono fuori dal gruppo isolato +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; altra {n} non può essere selezionata ora|{selected}; altre {n} non possono essere selezionate ora + +# Compound Shapes add-on + Compound Shapes Forme composte + Shape Mode Buttons Make Compound Shapes I pulsanti dei metodi forma creano forme composte + +# 3D Box add-on + 3D Box Scatola 3D + 3D Box Tool Strumento Scatola 3D diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3263faaf57..715f1fc461 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3090,7 +3090,9 @@ mark-style Japanese 日本式 Strikethrough 打ち消し線 Stroke Options 線オプション Character: 文字: + Paragraph: 段落: Character options 文字オプション + Paragraph options 段落オプション Stroke options 線オプション Transform options 変形オプション Stroke: 線: @@ -4151,6 +4153,8 @@ swatch Bright Violet ビビッドバイオレット @msg no such anchor 指定されたアンカーポイントが見つかりません @msg no such segment 指定されたセグメントが見つかりません @msg no such spine point 指定されたスパインポイントが見つかりません +@msg `with` must be a list of at most 10000 spine point indexes `with` には最大 10000 個のスパインポイントのインデックスのリストを指定してください +@msg `with` moves points, not a handle `with` はポイントを移動します。ハンドルには使えません @msg no such spine segment 指定されたスパインセグメントが見つかりません @msg no such subpath 指定されたサブパスが見つかりません @msg object {id} is not a path オブジェクト {id} はパスではありません @@ -4321,6 +4325,7 @@ swatch Bright Violet ビビッドバイオレット @msg unknown preference `{key}` `{key}` は不明な環境設定の項目です @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) データ復帰のコピーを保存する場所がありません: 環境設定 → ファイル管理 → データ復帰 → フォルダー (recoveryFolder) を設定してください @msg Data Recovery can't keep copies in {path}: {e} データ復帰は {path} にコピーを保存できません: {e} +@msg Plug-ins can't be loaded from {path}: {e} {path} からプラグインを読み込めません: {e} @msg `{area}` is no recovery area name `{area}` は復帰用領域の名前として使えません @msg `{name}` is no recovery entry name `{name}` は復帰用エントリの名前として使えません @msg no clock to keep a heartbeat by ハートビートの記録に必要な時刻を取得できません @@ -4403,6 +4408,9 @@ swatch Bright Violet ビビッドバイオレット @msg graphs come in as plain art, without their data or settings グラフは通常のアートとして読み込まれ、データと設定は保持されません @msg an image whose data is cut short was left out データが途中で切れている画像は除外されました @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel リンク画像は、元のファイルが見つかるまで、ファイルに保存された低解像度のプレビューで表示されます:リンクパネルで再リンクしてください +@msg linked type areas past VectorCraft's limits were left out VectorCraft の上限を超えるリンクされたテキストエリアは省略されました +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip リンクされたエリア、テキストの回り込み、複合パス内でマスクとして使われた文字はクリップしません +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel ファイルにプレビューのないリンク画像は、元のファイルが見つかるまでプレースホルダーで表示されます:リンクパネルで再リンクしてください @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 表示に使われるフォントの 1 行に対して低すぎるフレーム内のエリア内文字は、フレームを高くしました ({_1}): そうしないと文字が表示されません @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it グラデーション「{name}」はファイル内で定義されていません: 代わりに単色を使用しています @msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft がまだ読み込めないブラシ {_1} 個はブラシパネルに追加されませんでした @@ -5783,6 +5791,9 @@ anchor Points: ポイント: Find Nearest Swatch… 最も近いスウォッチを検索… Find Nearest Swatch 最も近いスウォッチを検索 Apply Nearest Swatch 最も近いスウォッチを適用 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 塗りを線に適用 + Apply Stroke to Fill 線を塗りに適用 Select objects to find the swatches nearest their colors. カラーに最も近いスウォッチを探すオブジェクトを選択してください。 @msg select objects or give `color` オブジェクトを選択するか `color` を指定してください @msg `color` is not a colour `color` はカラーではありません @@ -6020,6 +6031,10 @@ breakText Glyphs 字形 Bow 弓形 Spike 山形 Skip Spaces スペースをスキップ + Release Type on a Path… パス上文字を解除… + Release Type on a Path パス上文字を解除 + Text and Path テキストとパス + Path Only パスのみ @msg The art is too large to copy as a picture: other apps get no PNG of it アートワークが大きすぎるため画像としてコピーできません:他のアプリには PNG が渡されません # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6031,3 +6046,43 @@ breakText Glyphs 字形 Fully Outside 完全に外側 No artboards match. 一致するアートボードはありません。 Chosen: {n} of {total} 選択中: {n} / {total} + +# Contour add-on + Contour 輪郭 + Contour Tool 輪郭ツール + Sharp 鋭角 + Bake 分割 + Turn the Contour into plain paths 輪郭を通常のパスに変換します + Set Corners… コーナーを設定… + All Anchors すべてのアンカー + Odd-Numbered Anchors 奇数番目のアンカー + Even-Numbered Anchors 偶数番目のアンカー + Minimum angle 最小角度 + Maximum angle 最大角度 + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked リンク済みを選択 + Select Embedded 埋め込みを選択 + Select Missing 見つからない画像を選択 + Select Modified 変更された画像を選択 + Select by Link Status リンクの状態で選択 + Select by Link Status… リンクの状態で選択… + Search images 画像を検索 + No images match. 一致する画像はありません。 +@msgplural Selected {n} linked image|Selected {n} linked images リンク済みの画像を {n} 個選択しました +@msgplural Selected {n} embedded image|Selected {n} embedded images 埋め込み画像を {n} 個選択しました +@msgplural Selected {n} missing image|Selected {n} missing images 見つからない画像を {n} 個選択しました +@msgplural Selected {n} modified image|Selected {n} modified images 変更された画像を {n} 個選択しました +@msgplural Selected {n} image|Selected {n} images 画像を {n} 個選択しました +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}。ほかに {n} 個が非表示またはロックされています +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}。ほかに {n} 個がテンプレートレイヤー上にあります +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}。ほかに {n} 個が分離したグループの外にあります +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}。ほかに {n} 個は今は選択できません + +# Compound Shapes add-on + Compound Shapes 複合シェイプ + Shape Mode Buttons Make Compound Shapes シェイプモードボタンで複合シェイプを作成 + +# 3D Box add-on + 3D Box 3Dボックス + 3D Box Tool 3Dボックスツール diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7c73e2f990..2c80751738 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -191,6 +191,7 @@ Shape ფიგურა Convert to Shape ფიგურად გარდაქმნა Expand Shape ფიგურის გაშლა + Expand Object ობიექტის გაშლა Pattern პატერნი Edit Pattern პატერნის რედაქტირება Tile Edge Color… ფილის კიდის ფერი… @@ -1328,7 +1329,9 @@ digits Malayalam მალაიალამური Standard Vertical Roman Alignment სტანდარტული ვერტიკალური ლათინური სწორება Strikethrough გადახაზული Character: სიმბოლო: + Paragraph: აბზაცი: Character options სიმბოლოს პარამეტრები + Paragraph options აბზაცის პარამეტრები Subscript ქვედა ინდექსი Subscript (on the roadmap) ქვედა ინდექსი (სამომავლო გეგმაშია) Superscript ზედა ინდექსი @@ -3771,6 +3774,7 @@ font-technology Variable ცვლადი @msg Create from Selection: the selection has no area მონიშნულიდან შექმნა: მონიშნულს ფართობი არ აქვს @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) მონაცემთა აღდგენას ასლების შესანახი ადგილი არ აქვს: მიუთითეთ პარამეტრები → ფაილების დამუშავება → მონაცემთა აღდგენა → საქაღალდე (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} მონაცემთა აღდგენა ვერ ინახავს ასლებს აქ: {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} პლაგინების ჩატვირთვა ვერ ხერხდება აქედან: {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) პირდაპირი მონიშვნით მონიშნეთ საყრდენი წერტილები, სადაც გაიჭრება (არა ღია ტრაექტორიების ბოლო წერტილები) @msg Divide Objects Below: select a path ქვედა ობიექტების დაყოფა: მონიშნეთ ტრაექტორია @msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია @@ -4778,6 +4782,9 @@ font-technology Variable ცვლადი Even თანაბრად Stacked დასტად @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel დაკავშირებული გამოსახულებები ფაილში შენახულ დაბალი გარჩევადობის მინიატურას აჩვენებს, სანამ მათი ფაილები არ მოიძებნება: დაუკავშირეთ ისინი ხელახლა ბმულების პანელში +@msg linked type areas past VectorCraft's limits were left out VectorCraft-ის ლიმიტების მიღმა დაკავშირებული ტექსტის არეები გამოტოვებულია +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip დაკავშირებულ არეებში, გარსშემოვლებულ ტექსტში ან შედგენილ ტრაექტორიაში ნიღბად გამოყენებული ტექსტი არ ჭრის +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel დაკავშირებული გამოსახულებები, რომელთა მინიატურაც ფაილში არ არის, ადგილის შემნახველს აჩვენებს, სანამ მათი ფაილები არ მოიძებნება: დაუკავშირეთ ისინი ხელახლა ბმულების პანელში @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise არის ტექსტს ჩარჩოებში, რომლებიც მისი შრიფტის ერთი სტრიქონისთვის ზედმეტად დაბალი იყო, ჩარჩოები გაეზარდა ({_1}): სხვაგვარად ტექსტი არ გამოჩნდებოდა @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same მათზე არსებული ნახატი გვერდისგან {_1}%-ით განსხვავდება: მიუხედავად ამისა, ისინი რედაქტირების მონაცემებიდან აიღება @msg every numbered name for {name} is taken in the document's folder დოკუმენტის საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია @@ -5522,6 +5529,8 @@ imageTrace Outline კონტური @msg missing number `{key}` აკლია რიცხვი `{key}` @msg missing integer `{key}` აკლია მთელი რიცხვი `{key}` @msg no such spine point ხერხემლის ასეთი წერტილი არ არსებობს +@msg `with` must be a list of at most 10000 spine point indexes `with` უნდა იყოს ხერხემლის წერტილების არაუმეტეს 10000 ინდექსის სია +@msg `with` moves points, not a handle `with` წერტილებს გადაადგილებს და არა სახელურს @msg no such spine segment ხერხემლის ასეთი სეგმენტი არ არსებობს @msg not a blend ეს გადასვლა არ არის @msg only http, https and mailto URLs open in the browser, not “{url}” ბრაუზერში მხოლოდ http, https და mailto URL-ები იხსნება და არა „{url}“ @@ -6095,6 +6104,9 @@ anchor Points: წერტილები: Find Nearest Swatch… უახლოესი ფერის ნიმუშის პოვნა… Find Nearest Swatch უახლოესი ფერის ნიმუშის პოვნა Apply Nearest Swatch უახლოესი ფერის ნიმუშის გამოყენება +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke შევსების გამოყენება კონტურზე + Apply Stroke to Fill კონტურის გამოყენება შევსებაზე Select objects to find the swatches nearest their colors. აირჩიეთ ობიექტები მათ ფერებთან უახლოესი ფერის ნიმუშების საპოვნელად. @msg select objects or give `color` აირჩიეთ ობიექტები ან მიუთითეთ `color` @msg `color` is not a colour `color` ფერი არ არის @@ -6346,6 +6358,10 @@ font-script Japanese იაპონური Bow რკალი Spike პიკი Skip Spaces ჰარების გამოტოვება + Release Type on a Path… ტექსტის ტრაექტორიიდან მოხსნა… + Release Type on a Path ტექსტის ტრაექტორიიდან მოხსნა + Text and Path ტექსტი და ტრაექტორია + Path Only მხოლოდ ტრაექტორია @msg The art is too large to copy as a picture: other apps get no PNG of it ნახატი ზედმეტად დიდია სურათად დასაკოპირებლად: სხვა აპები მის PNG-ს ვერ მიიღებენ # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6357,3 +6373,43 @@ font-script Japanese იაპონური Fully Outside მთლიანად გარეთ No artboards match. შესაბამისი სამუშაო დაფა არ არის. Chosen: {n} of {total} არჩეულია: {n} / {total} + +# Contour add-on + Contour მოხაზულობა + Contour Tool მოხაზულობის ხელსაწყო + Sharp მახვილი + Bake გაშლა + Turn the Contour into plain paths მოხაზულობას ჩვეულებრივ ტრაექტორიებად აქცევს + Set Corners… კუთხეების დაყენება… + All Anchors ყველა საყრდენი წერტილი + Odd-Numbered Anchors კენტი საყრდენი წერტილები + Even-Numbered Anchors ლუწი საყრდენი წერტილები + Minimum angle მინიმალური კუთხე + Maximum angle მაქსიმალური კუთხე + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked დაკავშირებულების არჩევა + Select Embedded ჩაშენებულების არჩევა + Select Missing დაკარგულების არჩევა + Select Modified შეცვლილების არჩევა + Select by Link Status კავშირის მდგომარეობით არჩევა + Select by Link Status… კავშირის მდგომარეობით არჩევა… + Search images გამოსახულებების ძებნა + No images match. შესაბამისი გამოსახულება არ არის. +@msgplural Selected {n} linked image|Selected {n} linked images არჩეულია დაკავშირებული გამოსახულებები: {n} +@msgplural Selected {n} embedded image|Selected {n} embedded images არჩეულია ჩაშენებული გამოსახულებები: {n} +@msgplural Selected {n} missing image|Selected {n} missing images არჩეულია დაკარგული გამოსახულებები: {n} +@msgplural Selected {n} modified image|Selected {n} modified images არჩეულია შეცვლილი გამოსახულებები: {n} +@msgplural Selected {n} image|Selected {n} images არჩეულია გამოსახულებები: {n} +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; დამალული ან ჩაკეტილია კიდევ: {n} +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; შაბლონის ფენაზეა კიდევ: {n} +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; იზოლირებული ჯგუფის გარეთაა კიდევ: {n} +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ახლა ვერ აირჩევა კიდევ: {n} + +# Compound Shapes add-on + Compound Shapes შედგენილი ფიგურები + Shape Mode Buttons Make Compound Shapes ფიგურის რეჟიმის ღილაკები ქმნის შედგენილ ფიგურებს + +# 3D Box add-on + 3D Box 3D ყუთი + 3D Box Tool 3D ყუთის ხელსაწყო diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 04ce6904bf..01c96a7383 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3079,7 +3079,9 @@ mark-style Japanese 일본식 Strikethrough 취소선 Stroke Options 선 옵션 Character: 문자: + Paragraph: 단락: Character options 문자 옵션 + Paragraph options 단락 옵션 Stroke options 선 옵션 Transform options 변형 옵션 Stroke: 선: @@ -4078,6 +4080,8 @@ theme Appearance 외관 @msg no such anchor 해당 앵커가 없습니다 @msg no such segment 해당 세그먼트가 없습니다 @msg no such spine point 해당 스파인 포인트가 없습니다 +@msg `with` must be a list of at most 10000 spine point indexes `with`는 스파인 포인트 인덱스 최대 10000개의 목록이어야 합니다 +@msg `with` moves points, not a handle `with`는 포인트를 이동하며 핸들에는 쓸 수 없습니다 @msg no such spine segment 해당 스파인 세그먼트가 없습니다 @msg no such subpath 해당 하위 패스가 없습니다 @msg object {id} is not a path 개체 {id}은(는) 패스가 아닙니다 @@ -4248,6 +4252,7 @@ theme Appearance 외관 @msg unknown preference `{key}` 알 수 없는 환경 설정 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 데이터 복구에 복사본을 보관할 곳이 없습니다. 환경 설정 → 파일 처리 → 데이터 복구 → 폴더(recoveryFolder)를 지정하세요 @msg Data Recovery can't keep copies in {path}: {e} 데이터 복구가 {path}에 복사본을 보관할 수 없습니다: {e} +@msg Plug-ins can't be loaded from {path}: {e} {path}에서 플러그인을 불러올 수 없습니다: {e} @msg `{area}` is no recovery area name `{area}`은(는) 복구 영역 이름이 아닙니다 @msg `{name}` is no recovery entry name `{name}`은(는) 복구 항목 이름이 아닙니다 @msg no clock to keep a heartbeat by 하트비트를 유지할 시계가 없습니다 @@ -4330,6 +4335,9 @@ theme Appearance 외관 @msg graphs come in as plain art, without their data or settings 그래프는 데이터와 설정 없이 일반 아트로 가져왔습니다 @msg an image whose data is cut short was left out 데이터가 잘린 이미지는 제외했습니다 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 연결된 그림은 해당 파일을 찾을 때까지 파일에 저장된 저해상도 미리 보기로 표시됩니다: 링크 패널에서 다시 연결하세요 +@msg linked type areas past VectorCraft's limits were left out VectorCraft 한도를 넘는 연결된 문자 영역은 제외되었습니다 +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 연결된 영역, 문자 감싸기 또는 컴파운드 패스에서 마스크로 사용된 문자는 클리핑하지 않습니다 +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 파일에 미리 보기가 없는 연결된 그림은 해당 파일을 찾을 때까지 자리 표시자로 표시됩니다: 링크 패널에서 다시 연결하세요 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 표시되는 글꼴의 한 줄보다 낮은 프레임의 영역 문자는 프레임을 더 높였습니다({_1}). 그렇지 않으면 문자가 표시되지 않습니다 @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it 그레이디언트 “{name}”이(가) 파일에 정의되어 있지 않아 단색으로 대체했습니다 @msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft에서 아직 읽을 수 없는 브러시는 브러시 패널에서 제외되었습니다({_1}) @@ -5679,6 +5687,9 @@ anchor Points: 포인트: Find Nearest Swatch… 가장 가까운 견본 찾기… Find Nearest Swatch 가장 가까운 견본 찾기 Apply Nearest Swatch 가장 가까운 견본 적용 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 칠을 선에 적용 + Apply Stroke to Fill 선을 칠에 적용 Select objects to find the swatches nearest their colors. 색상에 가장 가까운 견본을 찾을 개체를 선택하십시오. @msg select objects or give `color` 개체를 선택하거나 `color`를 지정하십시오 @msg `color` is not a colour `color`은(는) 색상이 아닙니다 @@ -5916,6 +5927,10 @@ breakText Glyphs 글리프 Bow 활 모양 Spike 뾰족한 모양 Skip Spaces 공백 건너뛰기 + Release Type on a Path… 패스 위 문자 해제… + Release Type on a Path 패스 위 문자 해제 + Text and Path 문자와 패스 + Path Only 패스만 @msg The art is too large to copy as a picture: other apps get no PNG of it 아트워크가 너무 커서 이미지로 복사할 수 없습니다: 다른 앱에는 PNG가 전달되지 않습니다 # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5927,3 +5942,43 @@ breakText Glyphs 글리프 Fully Outside 완전히 바깥쪽 No artboards match. 일치하는 아트보드가 없습니다. Chosen: {n} of {total} 선택됨: {n} / {total} + +# Contour add-on + Contour 윤곽 + Contour Tool 윤곽 도구 + Sharp 뾰족하게 + Bake 확장 + Turn the Contour into plain paths 윤곽을 일반 패스로 바꿉니다 + Set Corners… 모퉁이 설정… + All Anchors 모든 앵커 + Odd-Numbered Anchors 홀수 번째 앵커 + Even-Numbered Anchors 짝수 번째 앵커 + Minimum angle 최소 각도 + Maximum angle 최대 각도 + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 연결됨 선택 + Select Embedded 포함됨 선택 + Select Missing 없는 이미지 선택 + Select Modified 수정된 이미지 선택 + Select by Link Status 링크 상태로 선택 + Select by Link Status… 링크 상태로 선택… + Search images 이미지 검색 + No images match. 일치하는 이미지가 없습니다. +@msgplural Selected {n} linked image|Selected {n} linked images 연결된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} embedded image|Selected {n} embedded images 포함된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} missing image|Selected {n} missing images 없는 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} modified image|Selected {n} modified images 수정된 이미지 {n}개를 선택했습니다 +@msgplural Selected {n} image|Selected {n} images 이미지 {n}개를 선택했습니다 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}. {n}개는 숨겨졌거나 잠겨 있습니다 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}. {n}개는 템플릿 레이어에 있습니다 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}. {n}개는 격리된 그룹 밖에 있습니다 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}. {n}개는 지금 선택할 수 없습니다 + +# Compound Shapes add-on + Compound Shapes 컴파운드 모양 + Shape Mode Buttons Make Compound Shapes 모양 모드 버튼으로 컴파운드 모양 만들기 + +# 3D Box add-on + 3D Box 3D 상자 + 3D Box Tool 3D 상자 도구 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 02004bb0ca..fe34d035de 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1417,7 +1417,9 @@ digits Malayalam Malayalam Standard Vertical Roman Alignment Standaard verticale Romeinse uitlijning Strikethrough Doorhalen Character: Teken: + Paragraph: Alinea: Character options Tekenopties + Paragraph options Alineaopties Subscript Subscript Subscript (on the roadmap) Subscript (op de roadmap) Superscript Superscript @@ -4623,6 +4625,9 @@ imageTrace Outline Contour @msg an image VectorCraft can't read was left out een afbeelding die VectorCraft niet kan lezen, is weggelaten @msg an image whose data is cut short was left out een afbeelding waarvan de gegevens zijn afgekapt, is weggelaten @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel gekoppelde afbeeldingen tonen het in het bestand opgeslagen voorbeeld met lage resolutie totdat hun bestanden zijn gevonden: koppel ze opnieuw in het paneel Koppelingen +@msg linked type areas past VectorCraft's limits were left out gekoppelde tekstvlakken buiten de limieten van VectorCraft zijn weggelaten +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst die als masker wordt gebruikt in gekoppelde vlakken, tekstomloop of een samengesteld pad knipt niet uit +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel gekoppelde afbeeldingen zonder voorbeeld in het bestand tonen een tijdelijke aanduiding totdat hun bestanden zijn gevonden: koppel ze opnieuw in het paneel Koppelingen @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise vlaktekst in kaders die te kort zijn voor één regel van het lettertype waarin de tekst wordt weergegeven, heeft hogere kaders gekregen ({_1}): anders zou de tekst niet zichtbaar zijn @msg its editing data doesn't say where its art is zijn bewerkingsgegevens zeggen niet waar de illustratie zich bevindt @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) dit bestand is opgeslagen zonder PDF-compatibiliteit en de bewerkingsgegevens kunnen niet worden gelezen ({why}) @@ -5580,6 +5585,8 @@ swatch Bright Violet Felviolet @msg missing number `{key}` getal `{key}` ontbreekt @msg missing integer `{key}` geheel getal `{key}` ontbreekt @msg no such spine point dat aspunt bestaat niet +@msg `with` must be a list of at most 10000 spine point indexes `with` moet een lijst van hoogstens 10000 aspuntindexen zijn +@msg `with` moves points, not a handle `with` verplaatst punten, geen handgreep @msg no such spine segment dat assegment bestaat niet @msg not a blend geen vermenging @msg select a blend or give `id` selecteer een vermenging of geef `id` op @@ -6010,6 +6017,9 @@ anchor Points: Punten: Find Nearest Swatch… Dichtstbijzijnde staal zoeken… Find Nearest Swatch Dichtstbijzijnde staal zoeken Apply Nearest Swatch Dichtstbijzijnde staal toepassen +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Vulling op streek toepassen + Apply Stroke to Fill Streek op vulling toepassen Select objects to find the swatches nearest their colors. Selecteer objecten om de stalen te vinden die het dichtst bij hun kleuren liggen. @msg select objects or give `color` selecteer objecten of geef `color` op @msg `color` is not a colour `color` is geen kleur @@ -6246,6 +6256,10 @@ breakText Glyphs Glyphs Bow Boog Spike Piek Skip Spaces Spaties overslaan + Release Type on a Path… Tekst op pad vrijgeven… + Release Type on a Path Tekst op pad vrijgeven + Text and Path Tekst en pad + Path Only Alleen pad @msg The art is too large to copy as a picture: other apps get no PNG of it Het illustratiewerk is te groot om als afbeelding te kopiëren: andere apps krijgen er geen PNG van # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6257,3 +6271,43 @@ breakText Glyphs Glyphs Fully Outside Volledig buiten No artboards match. Geen tekengebied komt overeen. Chosen: {n} of {total} Gekozen: {n} van {total} + +# Contour add-on + Contour Omtrek + Contour Tool Omtrek-gereedschap + Sharp Scherp + Bake Uitbreiden + Turn the Contour into plain paths Zet de omtrek om in gewone paden + Set Corners… Hoeken instellen… + All Anchors Alle ankerpunten + Odd-Numbered Anchors Oneven ankerpunten + Even-Numbered Anchors Even ankerpunten + Minimum angle Minimale hoek + Maximum angle Maximale hoek + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Gekoppelde selecteren + Select Embedded Ingesloten selecteren + Select Missing Ontbrekende selecteren + Select Modified Gewijzigde selecteren + Select by Link Status Selecteren op koppelingsstatus + Select by Link Status… Selecteren op koppelingsstatus… + Search images Afbeeldingen zoeken + No images match. Geen afbeelding komt overeen. +@msgplural Selected {n} linked image|Selected {n} linked images {n} gekoppelde afbeelding geselecteerd|{n} gekoppelde afbeeldingen geselecteerd +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} ingesloten afbeelding geselecteerd|{n} ingesloten afbeeldingen geselecteerd +@msgplural Selected {n} missing image|Selected {n} missing images {n} ontbrekende afbeelding geselecteerd|{n} ontbrekende afbeeldingen geselecteerd +@msgplural Selected {n} modified image|Selected {n} modified images {n} gewijzigde afbeelding geselecteerd|{n} gewijzigde afbeeldingen geselecteerd +@msgplural Selected {n} image|Selected {n} images {n} afbeelding geselecteerd|{n} afbeeldingen geselecteerd +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; nog {n} is verborgen of vergrendeld|{selected}; nog {n} zijn verborgen of vergrendeld +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; nog {n} staat op een sjabloonlaag|{selected}; nog {n} staan op sjabloonlagen +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; nog {n} staat buiten de geïsoleerde groep|{selected}; nog {n} staan buiten de geïsoleerde groep +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; nog {n} kan nu niet worden geselecteerd|{selected}; nog {n} kunnen nu niet worden geselecteerd + +# Compound Shapes add-on + Compound Shapes Samengestelde vormen + Shape Mode Buttons Make Compound Shapes Vormmodus-knoppen maken samengestelde vormen + +# 3D Box add-on + 3D Box 3D-doos + 3D Box Tool 3D-doosgereedschap diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 61b2e60ccd..6bb9ee44cf 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1406,7 +1406,9 @@ digits Malayalam Malajalam Standard Vertical Roman Alignment Standardowe pionowe wyrównanie łacińskie Strikethrough Przekreślenie Character: Znak: + Paragraph: Akapit: Character options Opcje znaków + Paragraph options Opcje akapitu Subscript Indeks dolny Subscript (on the roadmap) Indeks dolny (w planach) Superscript Indeks górny @@ -4115,6 +4117,7 @@ imageTrace Outline Kontur @msg Create from Selection: the selection has no area Utwórz z zaznaczenia: zaznaczenie nie ma powierzchni @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Odzyskiwanie danych nie ma gdzie przechowywać kopii: ustaw Preferencje → Obsługa plików → Odzyskiwanie danych → Folder (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Odzyskiwanie danych nie może przechowywać kopii w {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Nie można wczytać wtyczek z {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) zaznacz bezpośrednio punkty kontrolne, w których ma nastąpić cięcie (nie punkty końcowe otwartych ścieżek) @msg Divide Objects Below: select a path Podziel obiekty poniżej: zaznacz ścieżkę @msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę @@ -4459,6 +4462,8 @@ imageTrace Outline Kontur @msg no such saved selection brak takiego zapisanego zaznaczenia @msg no such segment brak takiego segmentu @msg no such spine point brak takiego punktu grzbietu +@msg `with` must be a list of at most 10000 spine point indexes `with` musi być listą co najwyżej 10000 indeksów punktów grzbietu +@msg `with` moves points, not a handle `with` przesuwa punkty, nie uchwyt @msg no such spine segment brak takiego segmentu grzbietu @msg no such subpath brak takiej ścieżki podrzędnej @msg no such user library brak takiej biblioteki użytkownika @@ -4806,6 +4811,9 @@ imageTrace Outline Kontur @msg graphs come in as plain art, without their data or settings wykresy są wczytywane jako zwykła grafika, bez ich danych i ustawień @msg an image whose data is cut short was left out pominięto obraz z uciętymi danymi @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel połączone obrazy pokazują zapisany w pliku podgląd niskiej rozdzielczości, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza +@msg linked type areas past VectorCraft's limits were left out połączone obszary tekstu poza limitami VectorCraft zostały pominięte +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst użyty jako maska w połączonych obszarach, oblewanym tekście lub ścieżce złożonej nie przycina +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel połączone obrazy bez podglądu w pliku pokazują symbol zastępczy, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise tekst akapitowy w ramkach niższych niż wiersz wyświetlanej czcionki otrzymał wyższe ramki ({_1}): inaczej tekst nie byłby widoczny @msg its editing data doesn't say where its art is jego dane edycyjne nie określają położenia kompozycji @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ten plik zapisano bez zgodności z PDF, a jego danych edycyjnych nie można odczytać ({why}) @@ -5953,6 +5961,9 @@ anchor Points: Punkty: Find Nearest Swatch… Znajdź najbliższą próbkę… Find Nearest Swatch Znajdź najbliższą próbkę Apply Nearest Swatch Zastosuj najbliższą próbkę +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Zastosuj wypełnienie do obrysu + Apply Stroke to Fill Zastosuj obrys do wypełnienia Select objects to find the swatches nearest their colors. Zaznacz obiekty, aby znaleźć próbki najbliższe ich kolorom. @msg select objects or give `color` zaznacz obiekty lub podaj `color` @msg `color` is not a colour `color` nie jest kolorem @@ -6190,6 +6201,10 @@ breakText Glyphs Glify Bow Łuk Spike Szpic Skip Spaces Pomiń spacje + Release Type on a Path… Uwolnij tekst na ścieżce… + Release Type on a Path Uwolnij tekst na ścieżce + Text and Path Tekst i ścieżka + Path Only Tylko ścieżka @msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6201,3 +6216,43 @@ breakText Glyphs Glify Fully Outside Całkowicie na zewnątrz No artboards match. Żaden obszar kompozycji nie pasuje. Chosen: {n} of {total} Wybrano: {n} z {total} + +# Contour add-on + Contour Kontur + Contour Tool Narzędzie Kontur + Sharp Ostry + Bake Rozszerz + Turn the Contour into plain paths Zamienia kontur w zwykłe ścieżki + Set Corners… Ustaw narożniki… + All Anchors Wszystkie punkty + Odd-Numbered Anchors Punkty nieparzyste + Even-Numbered Anchors Punkty parzyste + Minimum angle Kąt minimalny + Maximum angle Kąt maksymalny + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Zaznacz połączone + Select Embedded Zaznacz osadzone + Select Missing Zaznacz brakujące + Select Modified Zaznacz zmodyfikowane + Select by Link Status Zaznacz według stanu połączenia + Select by Link Status… Zaznacz według stanu połączenia… + Search images Szukaj obrazów + No images match. Żaden obraz nie pasuje. +@msgplural Selected {n} linked image|Selected {n} linked images Zaznaczono {n} połączony obraz|Zaznaczono {n} połączone obrazy|Zaznaczono {n} połączonych obrazów +@msgplural Selected {n} embedded image|Selected {n} embedded images Zaznaczono {n} osadzony obraz|Zaznaczono {n} osadzone obrazy|Zaznaczono {n} osadzonych obrazów +@msgplural Selected {n} missing image|Selected {n} missing images Zaznaczono {n} brakujący obraz|Zaznaczono {n} brakujące obrazy|Zaznaczono {n} brakujących obrazów +@msgplural Selected {n} modified image|Selected {n} modified images Zaznaczono {n} zmodyfikowany obraz|Zaznaczono {n} zmodyfikowane obrazy|Zaznaczono {n} zmodyfikowanych obrazów +@msgplural Selected {n} image|Selected {n} images Zaznaczono {n} obraz|Zaznaczono {n} obrazy|Zaznaczono {n} obrazów +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; jeszcze {n} jest ukryty lub zablokowany|{selected}; jeszcze {n} są ukryte lub zablokowane|{selected}; jeszcze {n} jest ukrytych lub zablokowanych +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; jeszcze {n} jest na warstwie szablonu|{selected}; jeszcze {n} są na warstwach szablonu|{selected}; jeszcze {n} jest na warstwach szablonu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; jeszcze {n} jest poza izolowaną grupą|{selected}; jeszcze {n} są poza izolowaną grupą|{selected}; jeszcze {n} jest poza izolowaną grupą +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć|{selected}; jeszcze {n} nie można teraz zaznaczyć + +# Compound Shapes add-on + Compound Shapes Kształty złożone + Shape Mode Buttons Make Compound Shapes Przyciski trybów kształtu tworzą kształty złożone + +# 3D Box add-on + 3D Box Bryła 3D + 3D Box Tool Narzędzie Bryła 3D diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0221a45e0a..cbdda2921a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2748,7 +2748,9 @@ digits Malayalam Malaiala Stroke Options Opções de Traçado Stroke Weight Peso do Traçado Character: Caractere: + Paragraph: Parágrafo: Character options Opções de caractere + Paragraph options Opções de parágrafo Stroke options Opções de traçado Transform options Opções de transformação Stroke: Traçado: @@ -3573,6 +3575,7 @@ axis Both Ambos @msg Create from Selection: the selection has no area Criar a partir da seleção: a seleção não tem área @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) A recuperação de dados não tem onde guardar cópias: defina Preferências → Manipulação de arquivos → Recuperação de dados → Pasta (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} A recuperação de dados não pode guardar cópias em {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Não é possível carregar plug-ins de {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) selecione diretamente os pontos de ancoragem onde cortar (não as extremidades de traçados abertos) @msg Divide Objects Below: select a path Dividir objetos abaixo: selecione um traçado @msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado @@ -3909,6 +3912,8 @@ axis Both Ambos @msg no such saved selection seleção salva inexistente @msg no such segment segmento inexistente @msg no such spine point ponto da coluna inexistente +@msg `with` must be a list of at most 10000 spine point indexes `with` deve ser uma lista de no máximo 10000 índices de pontos da coluna +@msg `with` moves points, not a handle `with` move pontos, não uma alça @msg no such spine segment segmento da coluna inexistente @msg no such subpath subtraçado inexistente @msg no such user library biblioteca do usuário inexistente @@ -4900,6 +4905,9 @@ axis Both Ambos @msg object {id} is not a selected top-level object o objeto {id} não é um objeto selecionado de nível superior @msg {path}: not a file {path}: não é um arquivo @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel as imagens vinculadas mostram a visualização de baixa resolução salva no arquivo até que seus arquivos sejam encontrados: revincule-as no painel Links +@msg linked type areas past VectorCraft's limits were left out as áreas de texto encadeadas além dos limites do VectorCraft foram omitidas +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip o texto usado como máscara em áreas encadeadas, texto com quebra ou um caminho composto não recorta +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel as imagens vinculadas sem visualização no arquivo mostram um espaço reservado até que seus arquivos sejam encontrados: revincule-as no painel Links @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise o texto de área em molduras baixas demais para uma linha da fonte em que aparece recebeu molduras mais altas ({_1}): senão o texto não apareceria @msg every numbered name for {name} is taken in the document's folder todos os nomes numerados para {name} já existem na pasta do documento @msg No linked files to look for Nenhum arquivo vinculado para procurar @@ -6015,6 +6023,9 @@ anchor Points: Pontos: Find Nearest Swatch… Localizar Amostra Mais Próxima… Find Nearest Swatch Localizar Amostra Mais Próxima Apply Nearest Swatch Aplicar Amostra Mais Próxima +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Aplicar Preenchimento ao Traçado + Apply Stroke to Fill Aplicar Traçado ao Preenchimento Select objects to find the swatches nearest their colors. Selecione objetos para localizar as amostras mais próximas de suas cores. @msg select objects or give `color` selecione objetos ou informe `color` @msg `color` is not a colour `color` não é uma cor @@ -6408,6 +6419,10 @@ swatch Yellow Green Verde-amarelado Bow Arco Spike Pico Skip Spaces Ignorar espaços + Release Type on a Path… Liberar Texto em um Caminho… + Release Type on a Path Liberar Texto em um Caminho + Text and Path Texto e caminho + Path Only Somente caminho @msg The art is too large to copy as a picture: other apps get no PNG of it A arte é grande demais para ser copiada como imagem: outros aplicativos não recebem um PNG dela # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6419,3 +6434,43 @@ swatch Yellow Green Verde-amarelado Fully Outside Totalmente fora No artboards match. Nenhuma mesa de trabalho corresponde. Chosen: {n} of {total} Escolhidas: {n} de {total} + +# Contour add-on + Contour Contorno + Contour Tool Ferramenta Contorno + Sharp Pontiagudo + Bake Expandir + Turn the Contour into plain paths Transforma o contorno em caminhos simples + Set Corners… Definir Cantos… + All Anchors Todas as Âncoras + Odd-Numbered Anchors Âncoras Ímpares + Even-Numbered Anchors Âncoras Pares + Minimum angle Ângulo Mínimo + Maximum angle Ângulo Máximo + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Selecionar vinculadas + Select Embedded Selecionar incorporadas + Select Missing Selecionar ausentes + Select Modified Selecionar modificadas + Select by Link Status Selecionar por status do vínculo + Select by Link Status… Selecionar por status do vínculo… + Search images Pesquisar imagens + No images match. Nenhuma imagem corresponde. +@msgplural Selected {n} linked image|Selected {n} linked images {n} imagem vinculada selecionada|{n} imagens vinculadas selecionadas +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} imagem incorporada selecionada|{n} imagens incorporadas selecionadas +@msgplural Selected {n} missing image|Selected {n} missing images {n} imagem ausente selecionada|{n} imagens ausentes selecionadas +@msgplural Selected {n} modified image|Selected {n} modified images {n} imagem modificada selecionada|{n} imagens modificadas selecionadas +@msgplural Selected {n} image|Selected {n} images {n} imagem selecionada|{n} imagens selecionadas +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; mais {n} está oculta ou bloqueada|{selected}; mais {n} estão ocultas ou bloqueadas +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; mais {n} está em uma camada de modelo|{selected}; mais {n} estão em camadas de modelo +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; mais {n} está fora do grupo isolado|{selected}; mais {n} estão fora do grupo isolado +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; mais {n} não pode ser selecionada agora|{selected}; mais {n} não podem ser selecionadas agora + +# Compound Shapes add-on + Compound Shapes Formas Compostas + Shape Mode Buttons Make Compound Shapes Os Botões de Modo de Forma Criam Formas Compostas + +# 3D Box add-on + 3D Box Caixa 3D + 3D Box Tool Ferramenta Caixa 3D diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index bdf6dd16dc..df48bf8abe 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3322,7 +3322,9 @@ digits Malayalam Малаялам Patterns Узоры Stroke Options Параметры обводки Character: Символ: + Paragraph: Абзац: Character options Параметры символа + Paragraph options Параметры абзаца Stroke options Параметры обводки Transform options Параметры трансформирования Stroke Weight Толщина обводки @@ -4021,6 +4023,7 @@ axis Both Оба @msg Create from Selection: the selection has no area Создание из выделения: у выделения нет области @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Восстановлению данных негде хранить копии: задайте Настройки → Работа с файлами → Восстановление данных → Папка (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Восстановление данных не может хранить копии в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Не удается загрузить модули из {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) выделите прямым выделением опорные точки для разреза (не конечные точки открытых контуров) @msg Divide Objects Below: select a path Разделение объектов ниже: выделите контур @msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур @@ -4366,6 +4369,8 @@ axis Both Оба @msg no such saved selection такого сохранённого выделения нет @msg no such segment такого сегмента нет @msg no such spine point такой точки остова нет +@msg `with` must be a list of at most 10000 spine point indexes `with` должен быть списком не более чем из 10000 индексов точек остова +@msg `with` moves points, not a handle `with` перемещает точки, а не маркер @msg no such spine segment такого сегмента остова нет @msg no such subpath такого вложенного контура нет @msg no such user library такой пользовательской библиотеки нет @@ -4711,6 +4716,9 @@ axis Both Оба @msg graphs come in as plain art, without their data or settings диаграммы импортируются как обычная графика, без их данных и настроек @msg an image whose data is cut short was left out изображение с обрезанными данными пропущено @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel связанные изображения показываются как сохранённый в файле просмотр низкого разрешения, пока их файлы не найдены: восстановите связи на панели «Связи» +@msg linked type areas past VectorCraft's limits were left out связанные текстовые области за пределами ограничений VectorCraft пропущены +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, используемый как маска в связанных областях, обтекающем тексте или составном контуре, не обрезает +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel связанные изображения без просмотра в файле показываются как заполнитель, пока их файлы не найдены: восстановите связи на панели «Связи» @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise текст в области в рамках, слишком низких для строки шрифта, которым он отображается, получил более высокие рамки ({_1}): иначе он не был бы виден @msg its editing data doesn't say where its art is в его данных редактирования не указано, где находится графика @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) этот файл сохранён без совместимости с PDF, и его данные редактирования не удаётся прочитать ({why}) @@ -6076,6 +6084,9 @@ anchor Points: Точки: Find Nearest Swatch… Найти ближайший образец… Find Nearest Swatch Найти ближайший образец Apply Nearest Swatch Применить ближайший образец +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Применить заливку к обводке + Apply Stroke to Fill Применить обводку к заливке Select objects to find the swatches nearest their colors. Выделите объекты, чтобы найти образцы, ближайшие к их цветам. @msg select objects or give `color` выделите объекты или укажите `color` @msg `color` is not a colour `color` не является цветом @@ -6424,6 +6435,10 @@ shape Open Открытый Bow Дуга Spike Пик Skip Spaces Пропускать пробелы + Release Type on a Path… Освободить текст по контуру… + Release Type on a Path Освободить текст по контуру + Text and Path Текст и контур + Path Only Только контур @msg The art is too large to copy as a picture: other apps get no PNG of it Графика слишком велика для копирования в виде изображения: другие приложения не получат её PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6435,3 +6450,43 @@ shape Open Открытый Fully Outside Полностью снаружи No artboards match. Нет подходящих монтажных областей. Chosen: {n} of {total} Выбрано: {n} из {total} + +# Contour add-on + Contour Эквидистанта + Contour Tool Инструмент «Эквидистанта» + Sharp Острый + Bake Разобрать + Turn the Contour into plain paths Преобразует эквидистанту в обычные контуры + Set Corners… Задать углы… + All Anchors Все опорные точки + Odd-Numbered Anchors Нечётные опорные точки + Even-Numbered Anchors Чётные опорные точки + Minimum angle Минимальный угол + Maximum angle Максимальный угол + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Выделить связанные + Select Embedded Выделить внедрённые + Select Missing Выделить отсутствующие + Select Modified Выделить изменённые + Select by Link Status Выделить по состоянию связи + Select by Link Status… Выделить по состоянию связи… + Search images Поиск изображений + No images match. Нет подходящих изображений. +@msgplural Selected {n} linked image|Selected {n} linked images Выделено {n} связанное изображение|Выделено {n} связанных изображения|Выделено {n} связанных изображений +@msgplural Selected {n} embedded image|Selected {n} embedded images Выделено {n} внедрённое изображение|Выделено {n} внедрённых изображения|Выделено {n} внедрённых изображений +@msgplural Selected {n} missing image|Selected {n} missing images Выделено {n} отсутствующее изображение|Выделено {n} отсутствующих изображения|Выделено {n} отсутствующих изображений +@msgplural Selected {n} modified image|Selected {n} modified images Выделено {n} изменённое изображение|Выделено {n} изменённых изображения|Выделено {n} изменённых изображений +@msgplural Selected {n} image|Selected {n} images Выделено {n} изображение|Выделено {n} изображения|Выделено {n} изображений +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ещё {n} скрыто или заблокировано|{selected}; ещё {n} скрыты или заблокированы|{selected}; ещё {n} скрыты или заблокированы +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ещё {n} на слое-шаблоне|{selected}; ещё {n} на слоях-шаблонах|{selected}; ещё {n} на слоях-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы|{selected}; ещё {n} вне изолированной группы +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить|{selected}; ещё {n} сейчас нельзя выделить + +# Compound Shapes add-on + Compound Shapes Составные фигуры + Shape Mode Buttons Make Compound Shapes Кнопки режимов фигур создают составные фигуры + +# 3D Box add-on + 3D Box 3D-параллелепипед + 3D Box Tool Инструмент «3D-параллелепипед» diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e488cf3175..26fc08841d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -845,7 +845,7 @@ font-technology Variable Variabla Double-click to edit Dubbelklicka för att redigera Alternates for Current Selection Alternativ för aktuell markering Select a character with the Type tool to see its alternates. Markera ett tecken med textverktyget för att se dess alternativ. - The selected character's font is not available. Teckensnittet för det markerade tecknet är inte tillgängligt. + The selected character's font is not available. Typsnittet för det markerade tecknet är inte tillgängligt. No alternates for the selected character. Inga alternativ för det markerade tecknet. Double-click to replace Dubbelklicka för att ersätta Double-click to insert Dubbelklicka för att infoga @@ -3213,7 +3213,9 @@ digits Malayalam Malayalam Patterns Mönster Stroke Options Konturalternativ Character: Tecken: + Paragraph: Stycke: Character options Teckenalternativ + Paragraph options Styckealternativ Stroke options Konturalternativ Transform options Transformeringsalternativ Stroke Weight Konturtjocklek @@ -3895,6 +3897,7 @@ axis Both Båda @msg Create from Selection: the selection has no area Skapa från markering: markeringen har ingen area @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Dataåterställning har ingenstans att spara kopior: ange Inställningar → Filhantering → Dataåterställning → Mapp (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Dataåterställning kan inte spara kopior i {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Det går inte att läsa in plugins från {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) direktmarkera ankarpunkter att klippa vid (inte slutpunkterna på öppna banor) @msg Divide Objects Below: select a path Dela objekt under: markera en bana @msg Divide Objects Below: select exactly one path Dela objekt under: markera exakt en bana @@ -4234,6 +4237,8 @@ axis Both Båda @msg no such saved selection den sparade markeringen finns inte @msg no such segment segmentet finns inte @msg no such spine point ryggradspunkten finns inte +@msg `with` must be a list of at most 10000 spine point indexes `with` måste vara en lista med högst 10000 ryggradspunktsindex +@msg `with` moves points, not a handle `with` flyttar punkter, inte ett handtag @msg no such spine segment ryggradssegmentet finns inte @msg no such subpath delbanan finns inte @msg no such user library användarbiblioteket finns inte @@ -4573,6 +4578,9 @@ axis Both Båda @msg graphs come in as plain art, without their data or settings diagram läses in som vanlig grafik, utan sina data och inställningar @msg an image whose data is cut short was left out en bild med avkortade data utelämnades @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel länkade bilder visar förhandsgranskningen med låg upplösning som sparats i filen tills deras filer hittas: länka om dem i panelen Länkar +@msg linked type areas past VectorCraft's limits were left out länkade textområden utöver VectorCrafts gränser utelämnades +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip text som används som mask i länkade områden, ombruten text eller en sammansatt bana beskär inte +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel länkade bilder utan förhandsgranskning i filen visar en platshållare tills deras filer hittas: länka om dem i panelen Länkar @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise områdestext i ramar som var för låga för en rad i det typsnitt den visas med fick högre ramar ({_1}): annars skulle texten inte synas @msg its editing data doesn't say where its art is dess redigeringsdata anger inte var dess grafik finns @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) den här filen sparades utan PDF-kompatibilitet och dess redigeringsdata kan inte läsas ({why}) @@ -6151,6 +6159,9 @@ shape Open Öppen Find Nearest Swatch… Sök närmaste färgruta… Find Nearest Swatch Sök närmaste färgruta Apply Nearest Swatch Använd närmaste färgruta +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Använd fyllning på kontur + Apply Stroke to Fill Använd kontur på fyllning Select objects to find the swatches nearest their colors. Markera objekt för att hitta de färgrutor som ligger närmast deras färger. @msg select objects or give `color` markera objekt eller ange `color` @msg `color` is not a colour `color` är ingen färg @@ -6391,6 +6402,10 @@ digits Hindi Hindi Bow Båge Spike Spets Skip Spaces Hoppa över mellanslag + Release Type on a Path… Släpp text på bana… + Release Type on a Path Släpp text på bana + Text and Path Text och bana + Path Only Endast bana @msg The art is too large to copy as a picture: other apps get no PNG of it Teckningen är för stor för att kopieras som en bild: andra appar får ingen PNG av den # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6402,3 +6417,1475 @@ digits Hindi Hindi Fully Outside Helt utanför No artboards match. Ingen rityta matchar. Chosen: {n} of {total} Valda: {n} av {total} + +# Contour add-on + Contour Kantlinje + Contour Tool Kantlinjeverktyg + Sharp Spetsig + Bake Expandera + Turn the Contour into plain paths Gör om kantlinjen till vanliga banor + Set Corners… Ange hörn… + All Anchors Alla ankare + Odd-Numbered Anchors Udda ankare + Even-Numbered Anchors Jämna ankare + Minimum angle Minsta vinkel + Maximum angle Största vinkel + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Markera länkade + Select Embedded Markera inbäddade + Select Missing Markera saknade + Select Modified Markera ändrade + Select by Link Status Markera efter länkstatus + Select by Link Status… Markera efter länkstatus… + Search images Sök bilder + No images match. Ingen bild matchar. +@msgplural Selected {n} linked image|Selected {n} linked images Markerade {n} länkad bild|Markerade {n} länkade bilder +@msgplural Selected {n} embedded image|Selected {n} embedded images Markerade {n} inbäddad bild|Markerade {n} inbäddade bilder +@msgplural Selected {n} missing image|Selected {n} missing images Markerade {n} saknad bild|Markerade {n} saknade bilder +@msgplural Selected {n} modified image|Selected {n} modified images Markerade {n} ändrad bild|Markerade {n} ändrade bilder +@msgplural Selected {n} image|Selected {n} images Markerade {n} bild|Markerade {n} bilder +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} till är dold eller låst|{selected}; {n} till är dolda eller låsta +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} till ligger på ett mallager|{selected}; {n} till ligger på mallager +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} till ligger utanför den isolerade gruppen|{selected}; {n} till ligger utanför den isolerade gruppen +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} till kan inte markeras nu|{selected}; {n} till kan inte markeras nu + +# Compound Shapes add-on + Compound Shapes Sammansatta former + Shape Mode Buttons Make Compound Shapes Formlägesknapparna skapar sammansatta former + +# 3D Box add-on + 3D Box 3D-låda + 3D Box Tool 3D-lådverktyg + Apply Gradient Preset Använd gradientförinställning + Cancel Image Trace Avbryt bildkalkering + Caps Lock Cursor State Caps Lock-status för textmarkör + Catalan Katalanska + Chinese Kinesiska + Configure Shape Konfigurera form + Croatian Kroatiska + Czech Tjeckiska + Danish Danska + Delete Gradient Preset Radera gradientförinställning + Edit Character Style Redigera teckenstil + Export All Open Documents Exportera alla öppna dokument + Finnish Finska + German: Swiss Tyska: Schweiz + Gradient Presets Gradientförinställningar + Hide Presets Dölj förinställningar + Move Document Flytta dokument + Norwegian Norska + Polish Polska + Reshape Type Path Omforma textbana + Russian Ryska + Save Gradient Preset Spara gradientförinställning + Save Gradient Preset… Spara gradientförinställning… + Serbian: Cyrillic Serbiska: kyrilliska + Serbian: Latin Serbiska: latin + Show Presets Visa förinställningar + Swedish Svenska + Turkish Turkiska +@msg {_1} × {_2} pixels is too large for {_3} (at most {max} pixels a side): lower the scale {_1} × {_2} pixlar är för stort för {_3} (högst {max} pixlar per sida): minska skalan +@msg {_1} bytes of RGBA data for a {width} × {height} image {_1} byte RGBA-data för en bild på {width} × {height} +@msg {_1} can't be read, or changed since it was read: relink or update it first {_1} kan inte läsas eller har ändrats sedan den lästes: länka om eller uppdatera den först +@msg {_1} can't go into {into} {_1} kan inte placeras i {into} +@msg {_1} can't limit printing to low resolution: choose PDF 1.4 or later, or allow high-resolution printing {_1} kan inte begränsa utskrift till låg upplösning: välj PDF 1.4 eller senare, eller tillåt utskrift med hög upplösning +@msg {_1} files can't be {_2} {_1}-filer kan inte vara {_2} +@msg {_1} files can't be opened yet {_1}-filer kan inte öppnas än +@msg {_1} files can't be password-protected: remove the passwords or choose no standard {_1}-filer kan inte lösenordsskyddas: ta bort lösenorden eller välj ingen standard +@msg {_1} files can't carry editing data: turn off preserveEditing {_1}-filer kan inte innehålla redigeringsdata: stäng av preserveEditing +@msg {_1} files can't have PDF layers: turn off createLayers {_1}-filer kan inte ha PDF-lager: stäng av createLayers +@msg {_1} files need a creation date, and this platform has no clock to give one {_1}-filer behöver ett skapandedatum, och den här plattformen har ingen klocka som kan ge ett +@msg {_1} is {_2} bytes (limit {_3}) {_1} är {_2} byte (högst {_3}) +@msg {_1} is not a file {_1} är inte en fil +@msg {_1} isn't a path {_1} är inte en bana +@msg {_1} MB of document, at most {_2} MB {_1} MB dokument, högst {_2} MB +@msg {_1} MB of images, at most {_2} MB {_1} MB bilder, högst {_2} MB +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objekt (högst {MAX_OBJECTS}) +@msg {_1} options: {e} {_1}-alternativ: {e} +@msg {_1} paints nothing to rasterize {_1} målar ingenting att rastrera +@msg {_1} passwords can have up to {MAX_LEGACY_PASSWORD} ASCII characters (PDF 1.7 and later take any) {_1}-lösenord kan ha upp till {MAX_LEGACY_PASSWORD} ASCII-tecken (PDF 1.7 och senare tar emot alla) +@msg {_1} with linked images or an image map writes several files: use document.export {_1} med länkade bilder eller en bildkarta skriver flera filer: använd document.export +@msg {_1} writes one file per artboard here: use document.export, or name one artboard {_1} skriver här en fil per rityta: använd document.export eller ange en rityta +@msg {_1}: belongs to another account {_1}: tillhör ett annat konto +@msg {_1}: not a folder of its own {_1}: inte en egen mapp +@msg {_1}: not a plain file {_1}: inte en vanlig fil +@msg {at}: {msg} {at}: {msg} +@msg {C}: no effect at index {list} {C}: ingen effekt vid index {list} +@msg {DEFAULT_PRESET} is protected and stays {DEFAULT_PRESET} är skyddad och finns kvar +@msg {DEFAULT_PRESET} is protected: save the settings under another name {DEFAULT_PRESET} är skyddad: spara inställningarna under ett annat namn +@msg {dest}: {e} {dest}: {e} +@msg {doc} has no folder {doc} har ingen mapp +@msg {file} isn't linked {file} är inte länkad +@msg {folder} is not a package folder {folder} är inte en paketmapp +@msg {folder}: {e} {folder}: {e} +@msg {folder}: more than {max} files and folders {folder}: fler än {max} filer och mappar +@msg {g} is not a Live Paint group {g} är inte en direktmålningsgrupp +@msg {id} is not a slice {id} är inte en skiva +@msg {k} `{v}` is not one of the choices {k} `{v}` är inte ett av valen +@msg {k} has control characters{_1} {k} innehåller styrtecken{_1} +@msg {k} is too long (at most {MAX_TEXT} characters) {k} är för lång (högst {MAX_TEXT} tecken) +@msg {k} must be {{size?, position?}} {k} måste vara {{size?, position?}} +@msg {k} must be > 0 {k} måste vara > 0 +@msg {k} must be a number (pt) or a length such as "210 mm" {k} måste vara ett tal (pt) eller en längd som "210 mm" +@msg {k} must be a number or "auto" {k} måste vara ett tal eller "auto" +@msg {k} must be text {k} måste vara text +@msg {k}: can't read `{s}` as a length {k}: kan inte läsa `{s}` som en längd +@msg {key} must be {_1}, got {s} {key} måste vara {_1}, fick {s} +@msg {key} must be 0–{MAX_ADD_AROUND} pt {key} måste vara 0–{MAX_ADD_AROUND} pt +@msg {key} must be a percentage {min}..100 {key} måste vara en procentsats {min}..100 +@msg {key} must be a positive number, not {n} {key} måste vara ett positivt tal, inte {n} +@msg {key} must be a positive number, not {v} {key} måste vara ett positivt tal, inte {v} +@msg {key} must name a floating panel {key} måste vara namnet på en flytande panel +@msg {key} must name a panel in another group {key} måste vara namnet på en panel i en annan grupp +@msg {key} must name a panel that shows {key} måste vara namnet på en panel som visas +@msg {key} must name a registered panel {key} måste vara namnet på en registrerad panel +@msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind}-filer saknar transparens, och filen skulle innehålla {what}: platta till den först (object.flattenTransparency) +@msg {kind} images can't be opened (see document.formats) {kind}-bilder kan inte öppnas (se document.formats) +@msg {label} must be a number at most {max} {label} måste vara ett tal på högst {max} +@msg {label} must be a number from -1296 to 1296 {label} måste vara ett tal från -1296 till 1296 +@msg {label} must be a number from 1 to 10000 {label} måste vara ett tal från 1 till 10 000 +@msg {LABEL} produced an empty result {LABEL} gav ett tomt resultat +@msg {name} `{s}`: {ids} {name} `{s}`: {ids} +@msg {name} is built in and can't be deleted {name} är inbyggd och kan inte tas bort +@msg {name} must be {lo}–{hi}{unit} (got {v}) {name} måste vara {lo}–{hi}{unit} (fick {v}) +@msg {name}: {e} {name}: {e} +@msg {name}: CRC or size mismatch {name}: CRC eller storlek stämmer inte +@msg {name}: only this Affinity file's embedded preview could be read; use File › Open to see it with its warning, or export SVG or PDF from Affinity before placing {name}: endast den inbäddade förhandsgranskningen i den här Affinity-filen kunde läsas; använd Arkiv › Öppna för att se den med dess varning, eller exportera SVG eller PDF från Affinity innan du placerar den +@msg {native}; its embedded preview can't be read either ({e}) {native}; dess inbäddade förhandsgranskning kan inte heller läsas ({e}) +@msg {std} files are CMYK, and the file would have colours in {_1} {std}-filer är CMYK, och filen skulle innehålla färger i {_1} +@msg {std} files embed their fonts, and the file would have one that isn't {std}-filer bäddar in sina typsnitt, och filen skulle innehålla ett som inte är inbäddat +@msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target} är filen som det här dokumentet lästes från, och när den lästes utelämnades vissa delar ({what}): om du skriver över den går de förlorade för gott. Skriv till en annan fil i stället, eller ange acknowledgeLoss: true för att ersätta den ändå +@msg {ty} brushes need selected art (or params.{k}) {ty}-penslar kräver markerade objekt (eller params.{k}) +@msg {v} is not an asset id {v} är inte ett resurs-id +@msg {what} can't be intertwined {what} kan inte flätas samman +@msg {what} doesn't fit the paper with its bleed and marks {what} får inte plats på papperet med utfall och märken +@msg {what} points outside memory {what} pekar utanför minnet +@msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} skulle skrivas ut på fler än {MAX_TILES} rutor: skala ned det +@msg `{_1}` can't be edited or removed `{_1}` kan inte redigeras eller tas bort +@msg `{_1}` is a {_2}, not an exporter `{_1}` är av typen {_2}, inte en exportfunktion +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect"}"}} `{_1}` är en live-effekt: använd den med effect.apply {{"effect"}"}} +@msg `{_1}` is an exporter: export with document.export {{"format"}"}} `{_1}` är en exportfunktion: exportera med document.export {{"format"}"}} +@msg `{_1}` is built in and always listed `{_1}` är inbyggd och listas alltid +@msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}` är inte en typsnittsfil som den senaste sökningen med text.findFontFiles hittade +@msg `{_1}` would be overwritten by the package: choose a different folder or name `{_1}` skulle skrivas över av paketet: välj en annan mapp eller ett annat namn +@msg `{f}` belongs to a VectorCraft that is running `{f}` tillhör en VectorCraft-instans som körs +@msg `{f}` is the copy of a document open now `{f}` är kopian av ett dokument som är öppet nu +@msg `{file}` has no art to place `{file}` har ingen grafik att placera +@msg `{file}` is over {_1} MB `{file}` är större än {_1} MB +@msg `{id}` is no writable format (see document.formats) `{id}` är inget skrivbart format (se document.formats) +@msg `{id}` isn't a loaded library `{id}` är inte ett inläst bibliotek +@msg `{k}.family` is required `{k}.family` är obligatoriskt +@msg `{k}` is a number 0..1 `{k}` är ett tal 0..1 +@msg `{k}` is true or false `{k}` är true eller false +@msg `{k}` isn't an export setting: {_1} `{k}` är inte en exportinställning: {_1} +@msg `{k}` must be {what} `{k}` måste vara {what} +@msg `{k}` must be {what}, not {v} `{k}` måste vara {what}, inte {v} +@msg `{k}` must be a byte offset `{k}` måste vara en byteförskjutning +@msg `{k}` must be a number of points `{k}` måste vara ett antal punkter +@msg `{k}` must be from {lo} to {hi} for {key} `{k}` måste vara från {lo} till {hi} för {key} +@msg `{key}` has no colours `{key}` har inga färger +@msg `{key}` is a design name `{key}` är ett designnamn +@msg `{key}` is a design name or a list of them `{key}` är ett designnamn eller en lista med sådana +@msg `{key}` is longer than {MAX_NAME} characters `{key}` är längre än {MAX_NAME} tecken +@msg `{key}` is out of range `{key}` är utanför intervallet +@msg `{key}` must be [min, desired, max] or {{min?, desired?, max?}}, in percent `{key}` måste vara [min, desired, max] eller {{min?, desired?, max?}}, i procent +@msg `{key}` must be a non-negative integer `{key}` måste vara ett icke-negativt heltal +@msg `{key}` must be a number {_1}..{_2} `{key}` måste vara ett tal {_1}..{_2} +@msg `{key}` must be a profile name or null `{key}` måste vara ett profilnamn eller null +@msg `{key}` must be a whole number of at least 0, not {n} `{key}` måste vara ett heltal på minst 0, inte {n} +@msg `{key}` must be an appearance item index (paint order) or null `{key}` måste vara ett index för ett utseendeobjekt (målningsordning) eller null +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` måste vara en array med resurs-id:n (se assets.list) +@msg `{key}` must be from {_1} to {shift_max} `{key}` måste vara från {_1} till {shift_max} +@msg `{key}` must be from 0 to 180 degrees, not {a} `{key}` måste vara från 0 till 180 grader, inte {a} +@msg `{key}`: not a colour: {v} `{key}`: inte en färg: {v} +@msg `{l}` isn't a global or spot colour `{l}` är inte en global färg eller dekorfärg +@msg `{m}` isn't a bitmap: use clipboard.importSvg, importPdf or importText `{m}` är inte en bitmapp: använd clipboard.importSvg, importPdf eller importText +@msg `{n}` can't be deleted `{n}` kan inte tas bort +@msg `{n}` can't be merged `{n}` kan inte sammanfogas +@msg `{n}` can't be moved `{n}` kan inte flyttas +@msg `{n}` is not a colour swatch `{n}` är ingen färgruta +@msg `{n}` isn't a solid colour `{n}` är ingen enhetlig färg +@msg `{n}`: colour groups hold solid colours only `{n}`: färggrupper innehåller bara enhetliga färger +@msg `{name}` can't be deleted `{name}` kan inte tas bort +@msg `{name}` can't be duplicated `{name}` kan inte dupliceras +@msg `{name}` can't be edited `{name}` kan inte redigeras +@msg `{name}` can't be edited this way `{name}` kan inte redigeras på det här sättet +@msg `{name}` can't be renamed Det går inte att byta namn på `{name}` +@msg `{name}` can't name a folder `{name}` kan inte användas som mappnamn +@msg `{name}` has no art to place `{name}` har ingen grafik att placera +@msg `{name}` has no text to place `{name}` har ingen text att placera +@msg `{name}` in the Word document is not UTF-8 or UTF-16 text `{name}` i Word-dokumentet är inte UTF-8- eller UTF-16-text +@msg `{name}` in the Word document is not well-formed XML: {e} `{name}` i Word-dokumentet är inte välformad XML: {e} +@msg `{name}` in the Word document nests elements more than {MAX_NESTING} deep `{name}` i Word-dokumentet nästlar element djupare än {MAX_NESTING} nivåer +@msg `{name}` is a built-in preset and is read-only: save it under another name `{name}` är en inbyggd förinställning och är skrivskyddad: spara den under ett annat namn +@msg `{name}` is a built-in preset: save under another name `{name}` är en inbyggd förinställning: spara under ett annat namn +@msg `{name}` is a tint of `{base}`: edit `{base}` (a tint swatch only takes a new name) `{name}` är en färgton av `{base}`: redigera `{base}` (en färgtonsfärgruta kan bara få ett nytt namn) +@msg `{name}` is a working space: choose another with edit.colorSettings first `{name}` är en arbetsfärgrymd: välj en annan med edit.colorSettings först +@msg `{name}` is built in and stays `{name}` är inbyggd och finns kvar +@msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` tar en färgsättning av sin egen typ (färg, gradient eller mönster) +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: Minimum får inte överstiga Önskat, och Önskat inte Maximum +@msg `{other}` doesn't trace an image `{other}` vektoriserar inte en bild +@msg `{s}`: the step's references copy in more than {_1} MB of values `{s}`: stegets referenser kopierar in mer än {_1} MB värden +@msg `{tag}` is not an axis tag: a tag is four characters, such as "wght" `{tag}` är ingen axeltagg: en tagg består av fyra tecken, till exempel "wght" +@msg `{to}` is empty or already used `{to}` är tomt eller används redan +@msg `{what}` is longer than {MAX_TEXT} bytes `{what}` är längre än {MAX_TEXT} byte +@msg `{what}` must be text `{what}` måste vara text +@msg `align` is start, center or end `align` är start, center eller end +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` måste vara en array av par [delbana, ankarpunkt] +@msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` måste lista ankarpunktsindex (0, 1, 2…), inte {k} +@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` måste lista ankarpunktsindex (0, 1, 2…), inte {v} +@msg `artboards` must be a list of artboard indices `artboards` måste vara en lista med ritytsindex +@msg `asset` is the asset id (see assets.list) `asset` är resursens id (se assets.list) +@msg `at` must be a byte offset `at` måste vara en byteförskjutning +@msg `autoLeading` must be a number `autoLeading` måste vara ett tal +@msg `burasagari` must be "none", "standard" or "forced" `burasagari` måste vara "none", "standard" eller "forced" +@msg `center` must be [x, y] `center` måste vara [x, y] +@msg `charAlign` must be "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" or "icfBottom" `charAlign` måste vara "romanBaseline", "emBoxTop", "emBoxCenter", "emBoxBottom", "icfTop" eller "icfBottom" +@msg `charDirection` must be "default", "leftToRight" or "rightToLeft" `charDirection` måste vara "default", "leftToRight" eller "rightToLeft" +@msg `clear` must be a list of type object ids, not {v} `clear` måste vara en lista med id:n för textobjekt, inte {v} +@msg `clear` must list type objects; {_1} is not one `clear` måste lista textobjekt; {_1} är inget textobjekt +@msg `clear` must not list `id` `clear` får inte lista `id` +@msg `clearStroke` requires `stroke: false`, `ids: []` and no `stop` `clearStroke` kräver `stroke: false`, `ids: []` och ingen `stop` +@msg `color` needs a `rule` to make the theme from `color` behöver en `rule` att skapa temat utifrån +@msg `colors` is empty `colors` är tom +@msg `columns` must be a whole number 1..50 `columns` måste vara ett heltal 1..50 +@msg `columnType` is vertical, uniform, repeating or sliding `columnType` är vertical, uniform, repeating eller sliding +@msg `commands` must not be empty `commands` får inte vara tom +@msg `contents` goes with `to` `contents` används tillsammans med `to` +@msg `corners` must be sharp, round or square, not `{other}` `corners` måste vara sharp, round eller square, inte `{other}` +@msg `corners` must list anchor indices (0, 1, 2…), not {v} `corners` måste lista ankarpunktsindex (0, 1, 2…), inte {v} +@msg `dataBase64` is larger than the module limit `dataBase64` är större än modulgränsen +@msg `dataBase64` is not valid base64 `dataBase64` är inte giltig base64 +@msg `defaultsOnly` cannot be combined with `ids`, `reverse` or `append` `defaultsOnly` kan inte kombineras med `ids`, `reverse` eller `append` +@msg `depth` and `childLimit` slice the summary: pass `summary: true` `depth` och `childLimit` begränsar sammanfattningen: ange `summary: true` +@msg `design` is a design name, or null for plain columns `design` är ett designnamn, eller null för vanliga kolumner +@msg `design` is a design name, or null for the default marker `design` är ett designnamn, eller null för standardmarkören +@msg `destination` must be `none`, `saveAndClose` or `folder` `destination` måste vara `none`, `saveAndClose` eller `folder` +@msg `destinationFolder` is required when destination is `folder` `destinationFolder` krävs när destination är `folder` +@msg `digits` must be one of {_1} `digits` måste vara något av {_1} +@msg `dimImages` is a percentage or false `dimImages` är en procentsats eller false +@msg `direction` must be "auto", "leftToRight" or "rightToLeft" `direction` måste vara "auto", "leftToRight" eller "rightToLeft" +@msg `each` is the value one design stands for, more than 0 `each` är värdet som en design motsvarar, större än 0 +@msg `end` must be "start" or "end" `end` måste vara "start" eller "end" +@msg `ends` applies to joining exactly two paths `ends` gäller bara när exakt två banor sammanfogas +@msg `event` must be one of {_1} `event` måste vara något av {_1} +@msg `every` must be "all", "odd" or "even", not {v} `every` måste vara "all", "odd" eller "even", inte {v} +@msg `expand` must be true or false `expand` måste vara true eller false +@msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` måste vara 1 till 1000 sökvägar till typsnittsfiler som den senaste text.findFontFiles-sökningen hittade +@msg `folder` must be an absolute folder path `folder` måste vara en absolut mappsökväg +@msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` måste vara ett objekt med axeltaggar och värden, till exempel {"wght"} +@msg `format` must be a string `format` måste vara en sträng +@msg `format` must be one of {_1} `format` måste vara något av {_1} +@msg `fractions` is chop or scale `fractions` är chop eller scale +@msg `from` and `to` must differ `from` och `to` måste skilja sig åt +@msg `from` has an empty frame `from` har en tom ram +@msg `from` must be a non-negative integer `from` måste vara ett icke-negativt heltal +@msg `from` must be area type or type on a path `from` måste vara områdestext eller text på bana +@msg `gid` must be a glyph id, not {v} `gid` måste vara ett glyf-id, inte {v} +@msg `glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it) `glyphAlternate` hör till ett enskilt tecken, inte till en teckenstil (text.setGlyphAlternate anger det) +@msg `guide` must be a guide index (guide.list) `guide` måste vara ett stödlinjeindex (guide.list) +@msg `hAlign` must be default, left, center or right `hAlign` måste vara default, left, center eller right +@msg `id` must be a node id `id` måste vara ett nod-id +@msg `id` must be an object id, not {v} `id` måste vara ett objekt-id, inte {v} +@msg `ids` must name Objects on Path groups or objects in them `ids` måste ange grupper av typen Objekt på bana eller objekt i dem +@msg `ids` takes at most {MAX_INSPECT_IDS} ids `ids` tar högst {MAX_INSPECT_IDS} id:n +@msg `imageMap` must be none, rectangle or polygon `imageMap` måste vara none, rectangle eller polygon +@msg `in` must be [x, y] `in` måste vara [x, y] +@msg `includeArtboardFill` must be true or false `includeArtboardFill` måste vara true eller false +@msg `includeSubdirs` must be true or false `includeSubdirs` måste vara true eller false +@msg `index` must be a point index `index` måste vara ett punktindex +@msg `index` must be a whole number or null `index` måste vara ett heltal eller null +@msg `indices` must be a non-empty array of item indices `indices` måste vara en icke-tom array av objektindex +@msg `items` is a list of {kind, item} `items` är en lista med {kind, item} +@msg `items` is empty `items` är tom +@msg `items` must be a list of {{id, anchors?}}, not {v} `items` måste vara en lista med {{id, anchors?}}, inte {v} +@msg `items` must be a list of {id, points} `items` måste vara en lista med {id, points} +@msg `items` must be an array of {{id, corners?}}, not {v} `items` måste vara en array av {{id, corners?}}, inte {v} +@msg `items` must be an array of {id, anchors} `items` måste vara en array av {id, anchors} +@msg `kashida` must be "none", "short", "medium", "long" or "stylistic" `kashida` måste vara "none", "short", "medium", "long" eller "stylistic" +@msg `kind` is one of {_1} `kind` är något av {_1} +@msg `kind` must be "round", "invertedRound" or "chamfer", not {v} `kind` måste vara "round", "invertedRound" eller "chamfer", inte {v} +@msg `kind` must be `text`, `visibility`, `image` or `graph` `kind` måste vara `text`, `visibility`, `image` eller `graph` +@msg `kind` must be a string `kind` måste vara en sträng +@msg `kind` must be image, noImage or htmlText `kind` måste vara image, noImage eller htmlText +@msg `kinsoku` must be "none", "hard" or "soft" `kinsoku` måste vara "none", "hard" eller "soft" +@msg `label` must be a non-empty name of at most 200 characters `label` måste vara ett namn som inte är tomt och har högst 200 tecken +@msg `language` must be a language name or tag, such as "Turkish" or "tr" `language` måste vara ett språknamn eller en språktagg, till exempel "Turkish" eller "tr" +@msg `leading` must be from 0.1 to 5000, or null for Auto `leading` måste vara från 0,1 till 5000, eller null för Auto +@msg `leadingModel` must be "romanBaseline" or "emBoxTop" `leadingModel` måste vara "romanBaseline" eller "emBoxTop" +@msg `length` must be a number of at most 1000000 pt either way `length` måste vara ett tal på högst 1000000 pt åt vardera hållet +@msg `line` must be true or false `line` måste vara true eller false +@msg `minAngle` ({min_angle}°) can't be more than `maxAngle` ({max_angle}°) `minAngle` ({min_angle}°) får inte vara större än `maxAngle` ({max_angle}°) +@msg `mode` must be "handles", "straight" or "smooth" `mode` måste vara "handles", "straight" eller "smooth" +@msg `mode` must be "straight", "bezier" or "arc" `mode` måste vara "straight", "bezier" eller "arc" +@msg `mode` must be one of {_1} `mode` måste vara något av {_1} +@msg `mojikumi` must be "none" or "lineEndHalf" `mojikumi` måste vara "none" eller "lineEndHalf" +@msg `name` must be 1-64 printable characters `name` måste vara 1-64 utskrivbara tecken +@msg `names` is a list of preset names `names` är en lista med namn på förinställningar +@msg `names` lists preset names `names` listar namn på förinställningar +@msg `names` must be a list of names `names` måste vara en lista med namn +@msg `names` must be a list of swatch names `names` måste vara en lista med namn på färgrutor +@msg `names` must be an array of style names `names` måste vara en array med stilnamn +@msg `new` is a design name, or true `new` är ett designnamn eller true +@msg `path` must be a folder `path` måste vara en mapp +@msg `path` must be a path object `path` måste vara ett banobjekt +@msg `pivot` must be a whole number from 0 to 8 `pivot` måste vara ett heltal från 0 till 8 +@msg `points` must be a list of [x, y] points `points` måste vara en lista med punkter [x, y] +@msg `points` must be a list of point indexes `points` måste vara en lista med punktindex +@msg `points` must be an array of point indices `points` måste vara en array med punktindex +@msg `points` must be point indexes `points` måste vara punktindex +@msg `port` must be "in" or "out" `port` måste vara "in" eller "out" +@msg `position` is above or below `position` är above eller below +@msg `preset` must be a string `preset` måste vara en sträng +@msg `ratio` must be from 0.1 to 0.5 `ratio` måste vara från 0.1 till 0.5 +@msg `rect` must be [x, y, width, height] with a positive size `rect` måste vara [x, y, width, height] med en positiv storlek +@msg `relation` must be overlap, inside or outside `relation` måste vara overlap, inside eller outside +@msg `reversed` must be true or false `reversed` måste vara true eller false +@msg `rotate` must be a finite number `rotate` måste vara ett ändligt tal +@msg `rule` must be nonZero or evenOdd `rule` måste vara nonZero eller evenOdd +@msg `scale` must be a number in (0, 100] `scale` måste vara ett tal i (0, 100] +@msg `scope` must be "selection" or "document", not {other} `scope` måste vara "selection" eller "document", inte {other} +@msg `script` must be a string `script` måste vara en sträng +@msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` är en icke-tom lista med serieindex +@msg `seriesIndexes` needs a `type` or a `valueAxis` `seriesIndexes` behöver en `type` eller en `valueAxis` +@msg `shift` must be a number of points `shift` måste vara ett antal punkter +@msg `showCenter` must be true or false `showCenter` måste vara true eller false +@msg `singleWordJustification` must be "fullJustify", "alignLeft", "alignCenter" or "alignRight" `singleWordJustification` måste vara "fullJustify", "alignLeft", "alignCenter" eller "alignRight" +@msg `size` is a percentage of the base text's size, 1 to 100 `size` är en procentandel av bastextens storlek, 1 till 100 +@msg `source` and `target` are the same object `source` och `target` är samma objekt +@msg `source` must be `folder` or `datasets` `source` måste vara `folder` eller `datasets` +@msg `spacing` must be a number `spacing` måste vara ett tal +@msg `spacing` must be a number of points, 0 or more, or "auto" `spacing` måste vara ett antal punkter, 0 eller mer, eller "auto" +@msg `start` must be a finite number `start` måste vara ett ändligt tal +@msg `starts` must be an array of anchor indices (or nulls) `starts` måste vara en array med ankarpunktsindex (eller null) +@msg `status` must be linked, embedded, missing or modified, or a list of them `status` måste vara linked, embedded, missing eller modified, eller en lista med sådana +@msg `stop` must be a stop index `stop` måste vara ett stoppindex +@msg `story` styles the whole story: give no `start` or `end` `story` formaterar hela artikeln: ange inte `start` eller `end` +@msg `story` takes the whole story: give no `start` or `end` `story` tar hela artikeln: ange inte `start` eller `end` +@msg `strokeMode` applies to strokes (stroke: true) `strokeMode` gäller för konturer (stroke: true) +@msg `style` must be roman or japanese `style` måste vara roman eller japanese +@msg `subpaths` must be two integer indices `subpaths` måste vara två heltalsindex +@msg `symbol` must be a symbol name `symbol` måste vara ett symbolnamn +@msg `target` must be "object" or "contents", not {v} `target` måste vara "object" eller "contents", inte {v} +@msg `tint` applies to global and spot colours `tint` gäller för globala färger och dekorfärger +@msg `tint` goes with a global or spot `swatch` `tint` används med en `swatch` som är en global färg eller dekorfärg +@msg `tint` must be a number (%) `tint` måste vara ett tal (%) +@msg `tint` needs a global or spot colour `tint` kräver en global färg eller dekorfärg +@msg `to` is already threaded `to` är redan sammanlänkad +@msg `to` is the design's new name `to` är designens nya namn +@msg `to` must be a closed path, area type or type on a path other than `from` `to` måste vara en sluten bana, områdestext eller text på bana som inte är `from` +@msg `to` must be a whole number `to` måste vara ett heltal +@msg `to` takes the rows of one object's stack, not aligned rows `to` tar raderna i ett objekts stapel, inte justerade rader +@msg `useLab` must be true or false `useLab` måste vara true eller false +@msg `vAlign` must be default, top, middle, baseline or bottom `vAlign` måste vara default, top, middle, baseline eller bottom +@msg `values` must be a list `values` måste vara en lista +@msg `values` must be an object `values` måste vara ett objekt +@msg `values` must name hex, rgb, cmyk, lab or gray `values` måste ange hex, rgb, cmyk, lab eller gray +@msg `values` names a kind twice `values` anger en typ två gånger +@msg `version`, `description` or `author` is too long `version`, `description` eller `author` är för lång +@msg `warnings` must be a list of strings `warnings` måste vara en lista med strängar +@msg a {_1} series can't go in a {_2} graph en serie av typen {_1} kan inte ingå i ett diagram av typen {_2} +@msg a batch preview cannot switch documents en förhandsgranskning av batch kan inte byta dokument +@msg a brush named `{nn}` exists det finns redan en pensel med namnet `{nn}` +@msg a container of the listed objects is gone en behållare för de listade objekten finns inte längre +@msg a content stream can't be read en innehållsström kan inte läsas +@msg a content stream isn't a stream en innehållsström är ingen ström +@msg a design holds at most {_1} objects en design innehåller högst {_1} objekt +@msg a design needs a name en design behöver ett namn +@msg a dictionary grew too large ett dictionary-objekt blev för stort +@msg a document keeps at most {_1} graph designs ett dokument rymmer högst {_1} diagramdesigner +@msg a document keeps at most {_1} saved selections ett dokument rymmer högst {_1} sparade markeringar +@msg a document keeps at most {_1} views ett dokument rymmer högst {_1} vyer +@msg a document links at most {MAX_SVG_SCRIPTS} JavaScript files ett dokument länkar högst {MAX_SVG_SCRIPTS} JavaScript-filer +@msg a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard en DXF-ritning har ett origo: ange useArtboards: true för en ritning per rityta +@msg a feConvolveMatrix filter's order is {x}×{y}, which overflows the kernel-size multiply usvg makes ordningen för ett feConvolveMatrix-filter är {x}×{y}, vilket får multiplikationen av kärnstorleken i usvg att spilla över +@msg a gradient preset is already called {n} det finns redan en gradientförinställning som heter {n} +@msg a graph has at most {_1} series, so it transposes with at most that many categories ett diagram har högst {_1} serier, så det kan bara transponeras med högst lika många kategorier +@msg a layer can't be merged into its own sublayer ett lager kan inte sammanfogas med sitt eget underlager +@msg a layer's form box isn't an array avgränsningsrutan i ett lagers formobjekt är ingen array +@msg a layer's form can't be read ett lagers formobjekt kan inte läsas +@msg a layer's form has no box ett lagers formobjekt saknar avgränsningsruta +@msg a layer's form has no dictionary ett lagers formobjekt saknar dictionary +@msg a legend draws at most {MAX_CHIPS} swatches en förklaring visar högst {MAX_CHIPS} färgrutor +@msg a name names one asset: give multiple: false, or one object ett namn avser en resurs: ange multiple: false eller ett objekt +@msg a page can't be read en sida kan inte läsas +@msg a page object is used by something else ett sidobjekt används av något annat +@msg a page thumbnail must be RGB pixels, 1 to {THUMBNAIL_SIZE} a side (got {w} × {h}) en sidminiatyr måste bestå av RGB-pixlar, 1 till {THUMBNAIL_SIZE} per sida (fick {w} × {h}) +@msg a pattern layer doesn't end what it starts ett mönsterlager avslutar inte det som det påbörjar +@msg a pattern layer's colors hold something else ett mönsterlagers färger innehåller något annat +@msg a pattern named `{n}` exists det finns redan ett mönster med namnet `{n}` +@msg a PDF presets file with over {_1} presets en fil med PDF-förinställningar med fler än {_1} förinställningar +@msg a plug-in with id {_1} is already installed ett plugin med id {_1} är redan installerat +@msg a print presets file with over {_1} presets en fil med utskriftsförinställningar med fler än {_1} förinställningar +@msg a profile is already called {n} det finns redan en profil som heter {n} +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. En profil stöder en effekt av typen Rotera runt axel. Redigera den befintliga effektens alternativ i stället. +@msg a row can't go into itself en rad kan inte placeras i sig själv +@msg a series goes on the left or the right value axis en serie hamnar på den vänstra eller den högra värdeaxeln +@msg a start must be an anchor index ≥ 0 or null en start måste vara ett ankarpunktsindex ≥ 0 eller null +@msg a style named `{name}` already exists det finns redan en stil med namnet `{name}` +@msg a style named `{to}` already exists det finns redan en stil med namnet `{to}` +@msg a swatch needs a colour, gradient or pattern en färgruta behöver en färg, en gradient eller ett mönster +@msg a symbol named `{n}` already exists det finns redan en symbol med namnet `{n}` +@msg a theme has 1 to {THEME_SIZE} colours ett tema har 1 till {THEME_SIZE} färger +@msg a theme is already called {name} (replace: "{name}" overwrites it) det finns redan ett tema som heter {name} (replace: "{name}" skriver över det) +@msg a toolbar name has at most {MAX_NAME} characters ett verktygsfältsnamn har högst {MAX_NAME} tecken +@msg a view named `{_1}` exists det finns redan en vy med namnet `{_1}` +@msg a view named `{name}` exists det finns redan en vy med namnet `{name}` +@msg a workspace keeps at most {MAX} toolbars en arbetslayout rymmer högst {MAX} verktygsfält +@msg Add Points at Crossings: a path went missing Lägg till punkter vid korsningar: en bana försvann +@msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF-kompatibel, standard) eller "7" (äldre .ai, version 7) +@msg already editing an opacity mask redigerar redan en opacitetsmask +@msg already editing another object's opacity mask redigerar redan ett annat objekts opacitetsmask +@msg already in pattern editing mode redan i läget för mönsterredigering +@msg an artboard is listed twice en rityta finns med två gånger i listan +@msg an empty artboard has no width or height to scale to en tom rityta har ingen bredd eller höjd att skala till +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` en exportfunktion anger 1 till {MAX_EXTENSIONS} `extensions` +@msg an image is too large for DXF and was left out en bild är för stor för DXF och utelämnades +@msg an image of {_1} MB, at most {_2} MB en bild på {_1} MB, högst {_2} MB +@msg an image of {declared_w} × {declared_h} pixels is too large to draw en bild på {declared_w} × {declared_h} pixlar är för stor för att ritas +@msg an index must be a whole number ett index måste vara ett heltal +@msg an inline graphic has no glyphs en grafik i texten har inga glyfer +@msg an invisible text form can't be read ett formobjekt med osynlig text kan inte läsas +@msg an object is missing ett objekt saknas +@msg an object's header is missing deklarationen för ett objekt saknas +@msg an overprinting form can't be read ett formobjekt med övertryck kan inte läsas +@msg an unread object has no readable bounds ett oläst objekt har inga läsbara gränser +@msg an unread object holds a frame of threaded type ett oläst objekt innehåller en ram med länkad text +@msg an unread object is missing from its layer ett oläst objekt saknas i sitt lager +@msg anchor `{key}` must be [x, y] ankarpunktens `{key}` måste vara [x, y] +@msg anchor `{key}` must be a number ankarpunktens `{key}` måste vara ett tal +@msg anchor `smooth` must be true or false ankarpunktens `smooth` måste vara true eller false +@msg angle and roundness must be finite vinkel och rundhet måste vara ändliga +@msg angles must be a list as long as pins (degrees or null) angles måste vara en lista lika lång som pins (grader eller null) +@msg appearance must be flat|center|edge appearance måste vara flat|center|edge +@msg apply is "fill" or "stroke", not `{other}` apply är "fill" eller "stroke", inte `{other}` +@msg area must be a closed polygon of 3 to 100000 [x, y] points area måste vara en sluten polygon med 3 till 100 000 [x, y]-punkter +@msg area type {_1} is named twice områdestext {_1} anges två gånger +@msg area type needs a path that encloses an area områdestext behöver en bana som omsluter en yta +@msg arrowAlign must be extend|tip, got {o} arrowAlign måste vara extend|tip, fick {o} +@msg arrowScale must be [start, end] arrowScale måste vara [start, end] +@msg artboard {i} doesn't print rityta {i} skrivs inte ut +@msg artboard is a 0-based index artboard är ett 0-baserat index +@msg artboard must be a 0-based index artboard måste vara ett 0-baserat index +@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout måste vara {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout.columns must be 1 or more artboardLayout.columns måste vara 1 eller mer +@msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout måste vara gridByRow, gridByColumn, row eller column +@msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft måste vara true eller false +@msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing måste vara 0–{MAX_SPACING} pt +@msg artboards must be a non-empty list artboards måste vara en lista som inte är tom +@msg artboards must be a number artboards måste vara ett tal +@msg asset `{_1}` has no art to export resursen `{_1}` har inget innehåll att exportera +@msg at most {MAX_KEYWORDS} keywords högst {MAX_KEYWORDS} nyckelord +@msg at most {MAX_MATCHES} matches are kept högst {MAX_MATCHES} träffar sparas +@msg at most {MAX_POINTS} points högst {MAX_POINTS} punkter +@msg at most {MAX_QUEUE} files högst {MAX_QUEUE} filer +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` högst {MAX_UNGROUPED} parametrar utanför grupper: ge de övriga en `group` +@msg at/rect lie outside the canvas at/rect ligger utanför arbetsytan +@msg attribute must be size|leading|tracking|kerning|baselineShift attribute måste vara size|leading|tracking|kerning|baselineShift +@msg attrs must be an object attrs måste vara ett objekt +@msg automation path rejected: {_1} isn't valid text automatiseringssökvägen avvisades: {_1} är inte giltig text +@msg automation path rejected: {why}: {path} automatiseringssökvägen avvisades: {why}: {path} +@msg automation path rejected: the folder's name isn't valid text automatiseringssökvägen avvisades: mappens namn är inte giltig text +@msg backgroundContents must be transparent or white backgroundContents måste vara transparent eller white +@msg bad {k} colour ogiltig {k}-färg +@msg bad `runs`: {e} ogiltigt värde för `runs`: {e} +@msg bad AES key ogiltig AES-nyckel +@msg bad arrowScale ogiltig arrowScale +@msg bad base64 ogiltig base64 +@msg bad colour ogiltig färg +@msg bad colour {v} in groupColors ogiltig färg {v} i groupColors +@msg bad colour in `colors` ogiltig färg i `colors` +@msg bad cross-reference entry ogiltig korsreferenspost +@msg bad cross-reference table ogiltig korsreferenstabell +@msg bad current colour {v} ogiltig aktuell färg {v} +@msg bad dataBase64 ogiltig dataBase64 +@msg bad edit ogiltig redigering +@msg bad fill {v} ogiltig fyllning {v} +@msg bad fit: {e} ogiltig anpassning: {e} +@msg bad model {other} (keep, new or document) ogiltig modell {other} (keep, new eller document) +@msg bad new colour {v} ogiltig ny färg {v} +@msg bad object ogiltigt objekt +@msg bad object number ogiltigt objektnummer +@msg bad offset ogiltig förskjutning +@msg bad path data: {e} ogiltiga data för bana: {e} +@msg bad point {v}: expected [x, y] or [x, y, pressure] ogiltig punkt {v}: väntade [x, y] eller [x, y, pressure] +@msg bad reference ogiltig referens +@msg bad trailer size ogiltig trailerstorlek +@msg batches cannot nest batchar kan inte kapslas +@msg bind something to a variable first koppla något till en variabel först +@msg bleed must be 0–{MAX_BLEED} pt: a number, [top, bottom, left, right] or {{top, bottom, left, right}} bleed måste vara 0–{MAX_BLEED} pt: ett tal, [top, bottom, left, right] eller {{top, bottom, left, right}} +@msg brush must be a name or null brush måste vara ett namn eller null +@msg by must be a number by måste vara ett tal +@msg can't add page thumbnails: {why} kan inte lägga till sidminiatyrer: {why} +@msg can't add the editing data for other apps: {why} kan inte lägga till redigeringsdata för andra appar: {why} +@msg can't edit the written PDF: {why} kan inte redigera den skrivna PDF-filen: {why} +@msg can't encode the input kan inte koda indata +@msg can't encrypt the PDF: {why} kan inte kryptera PDF-filen: {why} +@msg can't linearise the PDF: {why} kan inte linjärisera PDF-filen: {why} +@msg can't open `{_1}`: {_2} kan inte öppna `{_1}`: {_2} +@msg can't open `{_1}`: {e} kan inte öppna `{_1}`: {e} +@msg can't open `{name}`: not a format VectorCraft reads (see document.formats) kan inte öppna `{name}`: VectorCraft kan inte läsa formatet (se document.formats) +@msg can't place `{name}`: not a format VectorCraft reads (see document.formats) kan inte placera `{name}`: VectorCraft kan inte läsa formatet (se document.formats) +@msg can't read back the written PDF: {e} kan inte läsa in den skrivna PDF-filen igen: {e} +@msg can't read this Word document: {why} kan inte läsa det här Word-dokumentet: {why} +@msg can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp kan inte skriva .{e}-bilder: använd .png, .jpg, .gif, .webp, .tif eller .bmp +@msg can't write PDF layers, overprint or invisible text: {why} kan inte skriva PDF-lager, övertryck eller osynlig text: {why} +@msg can't write the file's copyright: {why} kan inte skriva filens upphovsrättsinformation: {why} +@msg can't write the file's modification date: {why} kan inte skriva filens ändringsdatum: {why} +@msg can't write the pages' user units: {why} kan inte skriva sidornas användarenheter: {why} +@msg cannot distort a zero-size or non-finite bounding box kan inte förvränga en avgränsningsram med storleken noll eller icke-ändliga värden +@msg cannot move an object into itself kan inte flytta ett objekt in i sig självt +@msg case must be upper|lower|title|sentence case måste vara upper|lower|title|sentence +@msg category `{c}`: one of {_1} kategori `{c}`: en av {_1} +@msg center must be [x, y] center måste vara [x, y] +@msg choose at least one artboard välj minst en rityta +@msg choose at least one status välj minst en status +@msg Choose original artwork, not a dimension's generated paths Välj ursprungligt bildmaterial, inte banor som genererats av ett mått +@msg clip must be true or false clip måste vara true eller false +@msg clippingMask must be true or false clippingMask måste vara true eller false +@msg closed must be a boolean closed måste vara ett booleskt värde +@msg collapsed must be true or false collapsed måste vara true eller false +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: det finns ingen RGB- eller CMYK-profil som heter ”{profile}” +@msg colorMode must be rgb or cmyk, not `{m}` colorMode måste vara rgb eller cmyk, inte `{m}` +@msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel måste vara {own} (dokumentets läge), grayscale eller bitmap +@msg colour groups can't go into colour groups färggrupper kan inte läggas i färggrupper +@msg colour, mode and spot apply to solid-colour swatches only färg, läge och dekor gäller endast enfärgade färgrutor +@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumn {column}: `{cell}` är en `%`-kolumn i diagramdatafiler, som inte läses +@msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumn {column}: `{cell}` anger `{name}`, som är en {_1}-variabel +@msg column {column}: `{cell}` names no variable kolumn {column}: `{cell}` anger ingen variabel +@msg column {column}: the variable name is longer than {MAX_NAME} characters kolumn {column}: variabelnamnet är längre än {MAX_NAME} tecken +@msg column: true floats the whole column and takes no onto, above or below column: true gör hela kolumnen flytande och tar inte onto, above eller below +@msg command must be a shape.* command command måste vara ett shape.*-kommando +@msg commands[{i}]: missing `command` commands[{i}]: `command` saknas +@msg composer must be "singleLine" or "everyLine" composer måste vara "singleLine" eller "everyLine" +@msg compound {_1} must contain exactly one open path to join sammansatt {_1} måste innehålla exakt en öppen bana att foga samman +@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammansatta former tar banor, sammansatta banor, grupper, sammansatta former, text, övergångar och kuvert +@msg connect end must be "start" or "end" connect end måste vara "start" eller "end" +@msg connect needs a path other than the one extended connect behöver en annan bana än den som förlängs +@msg connect needs id connect behöver id +@msg connect path has no open end connect-banan har ingen öppen ände +@msg Contour: select paths or shapes Kontur: markera banor eller former +@msg Contour: the Offset Path effect is not available Kontur: effekten Förskjut bana är inte tillgänglig +@msg copy needs path: the file to copy into the document's folder copy behöver path: filen som ska kopieras till dokumentets mapp +@msg copy takes images only: relink placed documents where their files are copy tar endast bilder: länka om placerade dokument där deras filer finns +@msg copying a file isn't available on the web det går inte att kopiera filer på webben +@msg copyrightStatus must be unknown, copyrighted or publicDomain copyrightStatus måste vara unknown, copyrighted eller publicDomain +@msg copyrightUrl must be a URL (no spaces, at most 2048 characters) copyrightUrl måste vara en URL (inga blanksteg, högst 2048 tecken) +@msg corners must be 4 [x, y] points (TL, TR, BR, BL) corners måste vara 4 [x, y]-punkter (TL, TR, BR, BL) +@msg counterPer `{c}`: item or file counterPer `{c}`: item eller file +@msg Create needs fills, strokes or both Skapa behöver fyllningar, konturer eller båda +@msg crop `{_1}`: only PDF pages have art, trim, bleed and media boxes; use "crop" or "bounding" crop `{_1}`: endast PDF-sidor har konst-, trim-, utfalls- och mediarutor; använd "crop" eller "bounding" +@msg crop rectangle doesn't overlap the image beskärningsrektangeln överlappar inte bilden +@msg cross-reference and object streams aren't supported korsreferens- och objektströmmar stöds inte +@msg CSS options: {e} CSS-alternativ: {e} +@msg CSV has a header but no data rows CSV-filen har en rubrikrad men inga datarader +@msg CSV holds NUL bytes: save it as UTF-8, or as UTF-16 with a byte-order mark CSV-filen innehåller NUL-byte: spara den som UTF-8 eller som UTF-16 med byteordningsmarkering +@msg CSV is empty CSV-filen är tom +@msg CSV is larger than {MAX_CSV_BYTES} bytes CSV-filen är större än {MAX_CSV_BYTES} byte +@msg CSV is not UTF-16 CSV-filen är inte UTF-16 +@msg CSV is not UTF-8 CSV-filen är inte UTF-8 +@msg CSV would be larger than {MAX_CSV_BYTES} bytes CSV-filen skulle bli större än {MAX_CSV_BYTES} byte +@msg damaged compressed data: {e} skadade komprimerade data: {e} +@msg dash lengths must be numbers, got {v} dash-längder måste vara tal, fick {v} +@msg dash must be a list of lengths or null, got {v} dash måste vara en lista med längder eller null, fick {v} +@msg data key `{k}`: letters, digits, -, _ and . (not name or vc-…) datanyckel `{k}`: bokstäver, siffror, -, _ och . (inte name eller vc-…) +@msg data must be an object of key: value, not {v} data måste vara ett objekt med nyckel: värde, inte {v} +@msg data set `{name}` holds a value for `{var}`, which the library doesn't declare datauppsättningen `{name}` innehåller ett värde för `{var}`, som biblioteket inte deklarerar +@msg data set `{name}` holds two values for `{var}` datauppsättningen `{name}` innehåller två värden för `{var}` +@msg data set `{name}` is declared twice datauppsättningen `{name}` deklareras två gånger +@msg data takes at most {MAX_DATA} keys at once data tar högst {MAX_DATA} nycklar åt gången +@msg dataset `{name}` already exists datauppsättningen `{name}` finns redan +@msg dataset `{to}` already exists datauppsättningen `{to}` finns redan +@msg date `{d}`: YYYY-MM-DD datum `{d}`: ÅÅÅÅ-MM-DD +@msg decoded data is too large avkodade data är för stora +@msg define a variable first definiera en variabel först +@msg detect must be true or false detect måste vara true eller false +@msg Dimension is locked or hidden Måttet är låst eller dolt +@msg Dimension mode does not match its source Måttets läge matchar inte dess källa +@msg direct-select anchor points of a path direktmarkera ankarpunkter på en bana +@msg distance must be > 0 distance måste vara > 0 +@msg Draw Inside needs exactly one selected path, compound path or text Rita inuti kräver exakt en markerad bana, sammansatt bana eller text +@msg dx and dy give the arrow's direction dx och dy anger pilens riktning +@msg dx and dy must be numbers dx och dy måste vara tal +@msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} +@msg dxf fitTo must be [width, height], positive dxf fitTo måste vara [width, height], positiva +@msg dxf must be an object of DXF import options dxf måste vara ett objekt med importalternativ för DXF +@msg DXF options: {e} DXF-alternativ: {e} +@msg dxf scale must be a positive number up to {_1}, not {s} dxf scale måste vara ett positivt tal upp till {_1}, inte {s} +@msg DXF scale must be a positive number up to {_1}, not {scale} DXF-skalan måste vara ett positivt tal upp till {_1}, inte {scale} +@msg dxf unit `{u}`: a unit such as mm, cm, in or pt dxf-enhet `{u}`: en enhet som mm, cm, in eller pt +@msg dxf: {e} dxf: {e} +@msg each format is an object {format, scale?, suffix?} varje format är ett objekt {format, scale?, suffix?} +@msg each item needs an id varje objekt behöver ett id +@msg each match needs `kind` varje matchning behöver `kind` +@msg each match needs a `name` varje matchning behöver ett `name` +@msg each of `fonts` is {family, style?}; 1 to 1000 of them varje post i `fonts` är {family, style?}; 1 till 1000 stycken +@msg each of `items` is {{id, corners?}} with an object id, not {it} varje post i `items` är {{id, corners?}} med ett objekt-id, inte {it} +@msg each of `items` is {kind, item} varje post i `items` är {kind, item} +@msg each row needs `from` varje rad behöver `from` +@msg each stop needs a position varje stopp behöver en position +@msg each subpath needs an anchors array varje delbana behöver en anchors-array +@msg easingType must be easeIn, easeOut, easeInOut or easeOutIn easingType måste vara easeIn, easeOut, easeInOut eller easeOutIn +@msg editingData must be true or false editingData måste vara true eller false +@msg editingData must be true, false or "always" editingData måste vara true, false eller "always" +@msg edits overlap redigeringarna överlappar +@msg effects of objects whose appearances differ can't be moved together effekter för objekt med olika utseende kan inte flyttas tillsammans +@msg empty header in column {_1} tom rubrik i kolumn {_1} +@msg encoding `{_1}`: utf8 or utf16 kodning `{_1}`: utf8 eller utf16 +@msg ends must be two of "first" and "last" ends måste vara två av "first" och "last" +@msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} +@msg EPS flattener: {e} EPS-utplattning: {e} +@msg EPS options: {e} EPS-alternativ: {e} +@msg EPS Save retains the artboard and all artwork: use document.export for cropped or selected-only EPS När du sparar som EPS behålls ritytan och allt bildmaterial: använd document.export för beskuren EPS eller EPS med bara det markerade +@msg every numbered name for the result is taken alla numrerade namn för resultatet är upptagna +@msg expanded SVG styles exceed the import size limit de expanderade SVG-stilarna överskrider storleksgränsen för import +@msg expected {"dataBase64"} förväntade {"dataBase64"} +@msg expected {"objects"} förväntade {"objects"} +@msg export `{name}`: {e} export av `{name}`: {e} +@msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft Exportera för skärmar skriver png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai eller vectorcraft +@msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes filen med exportförinställningar är större än {MAX_PRESET_FILE_BYTES} byte +@msg exportText must be editable or appearance exportText måste vara editable eller appearance +@msg exportType must be movieClip or graphic, not `{s}` exportType måste vara movieClip eller graphic, inte `{s}` +@msg extend needs id extend behöver id +@msg extension {e} is listed twice filändelsen {e} anges två gånger +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot filändelse {e}: använd 1-16 gemener och siffror, utan punkt +@msg featureChanges lists at most {MAX_FEATURE_CHANGES} tags featureChanges innehåller högst {MAX_FEATURE_CHANGES} taggar +@msg featureChanges must be a list of tags featureChanges måste vara en lista med taggar +@msg features must be a list of tags features måste vara en lista med taggar +@msg fidelity must be 0..100 fidelity måste vara 0..100 +@msg files must be {name, dataBase64} files måste vara {name, dataBase64} +@msg fit must be none|autoHeight|shrinkText, got {id} fit måste vara none|autoHeight|shrinkText, fick {id} +@msg Flare click coordinates must be finite numbers Klickkoordinaterna för Ljusreflex måste vara ändliga tal +@msg flattener: {e} utplattning: {e} +@msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low eller en sparad (se flattener.presets.list) +@msg flipProfile must be along|across, got {o} flipProfile måste vara along|across, fick {o} +@msg folders `{f}`: none, rows, format, item or itemFormat folders `{f}`: none, rows, format, item eller itemFormat +@msg folders deeper than {MAX_BATCH_DEPTH} levels mapparna är djupare än {MAX_BATCH_DEPTH} nivåer +@msg folders deeper than {MAX_DEPTH} levels mapparna är djupare än {MAX_DEPTH} nivåer +@msg font family `{family}` is not available typsnittsfamiljen `{family}` är inte tillgänglig +@msg font family `{tf}` is not available typsnittsfamiljen `{tf}` är inte tillgänglig +@msg format `{f}`: pdf or postscript format `{f}`: pdf eller postscript +@msg format `{f}`: text or json format `{f}`: text eller json +@msg format is `{format}` formatet är `{format}` +@msg formats must be an array of rows, not {v} formats måste vara en array av rader, inte {v} +@msg frequency must be between 1 and 300 lines per inch frequency måste vara mellan 1 och 300 linjer per tum +@msg from and to must be finite from och to måste vara ändliga +@msg from must be [x0, y0, x1, y1] from måste vara [x0, y0, x1, y1] +@msg give {key, value} or {values} ange {key, value} eller {values} +@msg give `before` or `after`, not both ange `before` eller `after`, inte båda +@msg give `char` or `text` ange `char` eller `text` +@msg give `colors`, or `color` and `rule` ange `colors`, eller `color` och `rule` +@msg give `event`, such as onclick ange `event`, till exempel onclick +@msg give `file`, the JavaScript file's path or URL ange `file`, JavaScript-filens sökväg eller URL +@msg give `fill` and/or `stroke` ange `fill` och/eller `stroke` +@msg give `fill`, `stroke` or both ange `fill`, `stroke` eller båda +@msg give `folder` ange `folder` +@msg give `fonts`, or open a document ange `fonts` eller öppna ett dokument +@msg give `from` or `indices`, not both ange `from` eller `indices`, inte båda +@msg give `id` (no text is being edited) ange `id` (ingen text redigeras) +@msg give `id` and `anchors`, or `items`, not both ange `id` och `anchors`, eller `items`, inte båda +@msg give `id` or `guide`, not both ange `id` eller `guide`, inte båda +@msg give `length` or `to` ange `length` eller `to` +@msg give `matches`: [{kind, name, target}] ange `matches`: [{kind, name, target}] +@msg give `name` (or edit a pattern) ange `name` (eller redigera ett mönster) +@msg give `name` or `names` ange `name` eller `names` +@msg give `path` (a .wasm file) or `dataBase64` (the module) ange `path` (en .wasm-fil) eller `dataBase64` (modulen) +@msg give `path`, `data` or `dataBase64` ange `path`, `data` eller `dataBase64` +@msg give `path`, `data`, `dataBase64` or `csv` ange `path`, `data`, `dataBase64` eller `csv` +@msg give `path`, `xml` or `dataBase64` ange `path`, `xml` eller `dataBase64` +@msg give `script`, the JavaScript the event runs ("" removes the event) ange `script`, det JavaScript som händelsen kör ("" tar bort händelsen) +@msg give `text` (the reading) or `remove` ange `text` (läsningen) eller `remove` +@msg give `x` and `y` (and a `tolerance` of 0 or more) ange `x` och `y` (och en `tolerance` på 0 eller mer) +@msg give a mode or r/g/b, c/m/y/k, gray or tint adjustments ange ett läge eller r/g/b-, c/m/y/k-, gråton- eller färgtonsjusteringar +@msg give a name, or paint the active proxy with a saved preset ange ett namn, eller måla den aktiva proxyn med en sparad förinställning +@msg give a name, or select a stroke with a saved profile ange ett namn, eller markera en kontur med en sparad profil +@msg give a pattern name or select an object painted with a pattern ange ett mönsternamn eller markera ett objekt som är målat med ett mönster +@msg give at least one of clip, invert, disabled, linked ange minst en av clip, invert, disabled, linked +@msg give color, none, swatch or gradient ange color, none, swatch eller gradient +@msg give dataBase64 ange dataBase64 +@msg give either at (a click) or area (a path drawn around the overlaps) ange antingen at (ett klick) eller area (en bana ritad runt överlappningarna) +@msg give formats or a preset, not both ange formats eller en förinställning, inte båda +@msg give newName or delete ange newName eller delete +@msg give offset or by ange offset eller by +@msg give one of `to`, `rect` or `at` ange en av `to`, `rect` eller `at` +@msg give one of assets, layers, selection or fullDocument ange en av assets, layers, selection eller fullDocument +@msg give only one of onto, above, below, icon and a column place ange bara en av onto, above, below, icon och en kolumnplacering +@msg give origin: [x, y], or reset: true ange origin: [x, y], eller reset: true +@msg give overprintFill, overprintStroke, showCenter, imageMap, url or note ange overprintFill, overprintStroke, showCenter, imageMap, url eller note +@msg give path (a file) or folder ange path (en fil) eller folder +@msg give path, or name and dataBase64 ange path, eller name och dataBase64 +@msg give paths or files ange paths eller files +@msg give rows, rowHeight, columns or columnWidth ange rows, rowHeight, columns eller columnWidth +@msg give svg, or dataBase64 of an SVG or SVGZ file ange svg, eller dataBase64 för en SVG- eller SVGZ-fil +@msg give text ange text +@msg give the asset a name ge resursen ett namn +@msg give the preset a `name` ge förinställningen ett `name` +@msg give the preset a name ge förinställningen ett namn +@msg give the preset a name (1–64 characters) ge förinställningen ett namn (1–64 tecken) +@msg give the settings to change, e.g. {"formats"}]} ange inställningarna som ska ändras, t.ex. {"formats"}]} +@msg give the style a name ge stilen ett namn +@msg give two or more style `names` ange två eller fler stilnamn i `names` +@msg give two or more swatches ange två eller fler färgrutor +@msg give x, y, or a handle's length or angle ange x, y eller ett handtags längd eller vinkel +@msg global must be true or false global måste vara true eller false +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) glyfen {_1} ritas inte för {ch} med tecknets stil (till exempel Versaler, Kapitäler eller ett siffersystem) +@msg glyph {g} is not an alternate of {ch} in {_1} {_2} glyfen {g} är inte ett alternativ till {ch} i {_1} {_2} +@msg gradient must be "objects" or "mesh" gradient måste vara "objects" eller "mesh" +@msg grays must be "profile" or "black", not `{g}` grays måste vara "profile" eller "black", inte `{g}` +@msg gridColors must be a preset name or two colours gridColors måste vara namnet på en förinställning eller två färger +@msg gridSize must be small, medium or large gridSize måste vara small, medium eller large +@msg guide {g} is not selected stödlinje {g} är inte markerad +@msg handle must be 0..3 handle måste vara 0..3 +@msg hiddenObjects {v}: "layer" (the default), "omit" or "visible" hiddenObjects {v}: "layer" (standard), "omit" eller "visible" +@msg highlight a layer to merge into välj ett lager att sammanfoga med +@msg highlight two or more rows in one layer or group välj två eller fler rader i ett och samma lager eller grupp +@msg highlight two or more rows to merge välj två eller fler rader att sammanfoga +@msg HTML Text applies to object slices of type only HTML-text gäller endast objektskivor av texttyp +@msg icon docks a panel in the icon column: use window.panel.dock icon dockar en panel i ikonkolumnen: använd window.panel.dock +@msg id must be a dimension id id måste vara ett mått-id +@msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) Identifiera objekt efter är XML-id: namnet måste vara ett giltigt XML-id (börja med en bokstav, ett understreck eller ett kolon; inga blanksteg) +@msg image {_1} is linked already bild {_1} är redan länkad +@msg image has no bounds bilden har inga gränser +@msg Image Trace failed: {e} Bildkalkering misslyckades: {e} +@msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildkalkering misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet) +@msg Image Trace finished, but its document was closed Bildkalkeringen är klar, men dess dokument har stängts +@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildkalkeringen är klar, men bilden eller dess inställningar ändrades under tiden: vektorisera den igen +@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client eller server +@msg index out of range index utanför intervallet +@msg instances must be 1..1000 instances måste vara 1..1000 +@msg instruction budget instruktionsbudget +@msg invalid `color` ogiltig `color` +@msg invalid anchor index {v}: expected a non-negative integer ogiltigt ankarindex {v}: ett icke-negativt heltal förväntades +@msg invalid anchor reference {v}: expected [subpath, anchor] ogiltig ankarreferens {v}: [delbana, ankare] förväntades +@msg invalid angle ogiltig vinkel +@msg invalid brush: {e} ogiltig pensel: {e} +@msg invalid color ogiltig färg +@msg invalid colour {c} ogiltig färg {c} +@msg invalid delta ogiltigt delta +@msg Invalid dimension offset Ogiltig måttförskjutning +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - ogiltigt id {_1}: använd 1-64 tecken bland A-Z a-z 0-9 . _ - +@msg invalid parameter name {k} ogiltigt parameternamn {k} +@msg invalid point ogiltig punkt +@msg Invalid point Ogiltig punkt +@msg invalid size ogiltig storlek +@msg invalid t ogiltigt t +@msg invalid tolerance ogiltig tolerans +@msg its artboards all lie beyond the canvas (more than {_1} pt from the origin) alla dess ritytor ligger utanför arbetsytan (mer än {_1} pt från origo) +@msg its clipping masks are nested too deeply dess klippmasker är för djupt nästlade +@msg its metadata has no description dess metadata saknar beskrivning +@msg its metadata has no direct length dess metadata saknar direkt längd +@msg join two different paths foga samman två olika banor +@msg Join: a subpath went missing Foga samman: en delbana försvann +@msg justify must be auto|left|center|right|justifyAll justify måste vara auto|left|center|right|justifyAll +@msg kbps must be a positive number, not {kbps} kbps måste vara ett positivt tal, inte {kbps} +@msg keywords must be a list of words or a comma-separated string keywords måste vara en lista med ord eller en kommaavgränsad sträng +@msg keywords must be at most {MAX_KEYWORD} characters, without control characters keywords får vara högst {MAX_KEYWORD} tecken, utan styrtecken +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind måste vara 1, 2 eller 3, eller ange `name` för en förinställning (se perspective.presets.list) +@msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind måste vara graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle eller paraStyle +@msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout måste vara "on", "off", "neutral" eller ett booleskt värde, inte {v} +@msg layer `{name}` has no art to export lagret `{name}` har ingen grafik att exportera +@msg layer must name a layer or sublayer layer måste ange namnet på ett lager eller underlager +@msg layers can't be intertwined: select the objects in them lager kan inte flätas samman: markera objekten i dem +@msg layers go only at the top level or in layers, objects in layers and groups lager kan bara ligga på översta nivån eller i lager, objekt i lager och grupper +@msg layers must be true or false layers måste vara true eller false +@msg layout must be gridByRow, gridByColumn, row or column layout måste vara gridByRow, gridByColumn, row eller column +@msg leading must be a number or "auto" leading måste vara ett tal eller "auto" +@msg left/right must be non-negative widths left/right måste vara icke-negativa bredder +@msg level `{t}`: 2 or 3 level `{t}`: 2 eller 3 +@msg line {line}: more than {MAX_CSV_COLS} columns rad {line}: fler än {MAX_CSV_COLS} kolumner +@msg line {line}: unclosed quote rad {line}: oavslutat citattecken +@msg line {line}: value for `{var}` must match its variable kind rad {line}: värdet för `{var}` måste matcha variabelns typ +@msg lineEndings `{other}`: lf or crlf lineEndings `{other}`: lf eller crlf +@msg loading profiles from disk isn't available in the browser det går inte att läsa in profiler från disk i webbläsaren +@msg Lock Workspace is not available in VectorCraft Lås arbetslayout är inte tillgängligt i VectorCraft +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) manifestet är {_1} byte (gränsen är {MAX_MANIFEST_BYTES}) +@msg manifest is not UTF-8 manifestet är inte UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) manifestet är för långt (gränsen är {MAX_MANIFEST_BYTES} byte) +@msg manifest: {e} manifest: {e} +@msg margin: a {m} pt margin leaves no imageable area on the paper margin: en marginal på {m} pt lämnar ingen tryckbar yta på papperet +@msg matrix must be finite and invertible, depth finite matrix måste vara ändlig och inverterbar, depth ändligt +@msg matte: {e} bakgrundsfärg: {e} +@msg member is for order front, forward, backward or back member gäller ordningen front, forward, backward eller back +@msg memory budget (the selection is too large to hand over) minnesbudget (markeringen är för stor för att lämnas över) +@msg missing `{k}` `{k}` saknas +@msg missing `{key}` `{key}` saknas +@msg missing `artboards` `artboards` saknas +@msg missing `at` [x, y] `at` [x, y] saknas +@msg missing `attrs` `attrs` saknas +@msg missing `color` or `opacity` `color` eller `opacity` saknas +@msg missing `colors` `colors` saknas +@msg missing `commands` `commands` saknas +@msg missing `destinationFolder` `destinationFolder` saknas +@msg missing `family` `family` saknas +@msg missing `gid` (a glyph id, or null for the default glyph) `gid` saknas (ett glyf-id, eller null för standardglyfen) +@msg missing `group` `group` saknas +@msg missing `id`: give one, or select one type object `id` saknas: ange ett, eller markera ett textobjekt +@msg missing `index` (a point index, or null to clear) `index` saknas (ett punktindex, eller null för att rensa) +@msg missing `index` (a stop index, or null to clear) `index` saknas (ett stoppindex, eller null för att rensa) +@msg missing `index` (an item index or null) `index` saknas (ett objektindex eller null) +@msg missing `item` `item` saknas +@msg missing `library` `library` saknas +@msg missing `library` (see graphicStyle.libraries) `library` saknas (se graphicStyle.libraries) +@msg missing `library` (see swatch.library.list) `library` saknas (se swatch.library.list) +@msg missing `map` (rows [{from, to}] or {current}) `map` saknas (rader [{from, to}] eller {current}) +@msg missing `matrix` [a,b,c,d,e,f] `matrix` [a,b,c,d,e,f] saknas +@msg missing `name` (see gradient.presets.list) `name` saknas (se gradient.presets.list) +@msg missing `offset` (a distance in points) `offset` saknas (ett avstånd i punkter) +@msg missing `path` `path` saknas +@msg missing `path` (a path object id) `path` saknas (id för ett banobjekt) +@msg missing `rule` `rule` saknas +@msg missing `source` id `source`-id saknas +@msg missing `start` (the byte offset of a character) `start` saknas (byteförskjutningen för ett tecken) +@msg missing `status`: linked, embedded, missing or modified `status` saknas: linked, embedded, missing eller modified +@msg missing `target` id `target`-id saknas +@msg missing `text` `text` saknas +@msg missing `to` (an index) `to` saknas (ett index) +@msg missing `to`: a non-negative integer `to` saknas: ett icke-negativt heltal +@msg missing `type` `type` saknas +@msg missing `value` `value` saknas +@msg missing anchor ankare saknas +@msg missing anchors ankare saknas +@msg missing anchors [[subpath, anchor]…] ankare saknas [[delbana, ankare]…] +@msg missing array `{key}` arrayen `{key}` saknas +@msg missing case skiftläge saknas +@msg missing color färg saknas +@msg missing commands kommandon saknas +@msg missing destination folder målmapp saknas +@msg missing from from saknas +@msg missing group grupp saknas +@msg missing id or ids id eller id:n saknas +@msg missing matrix [a,b,c,d,e,f] matris saknas [a,b,c,d,e,f] +@msg missing op op saknas +@msg missing or invalid `color` `color` saknas eller är ogiltig +@msg missing or unknown `tool` `tool` saknas eller är okänt +@msg missing point punkt saknas +@msg missing point [x,y] punkt saknas [x,y] +@msg missing point `{key}` ([x, y]) punkt `{key}` saknas ([x, y]) +@msg missing points punkter saknas +@msg missing points [[x,y]…] punkter saknas [[x,y]…] +@msg missing segment segment saknas +@msg missing stops stopp saknas +@msg missing subpaths delbanor saknas +@msg missing target mål saknas +@msg missing to to saknas +@msg missing x, y x, y saknas +@msg mode is set, add or toggle, not `{other}` mode ska vara set, add eller toggle, inte `{other}` +@msg mode must be "cmyk" or "rgb" mode måste vara "cmyk" eller "rgb" +@msg mode must be area|onPath, got {o} mode måste vara area|onPath, fick {o} +@msg module is {_1} bytes (limit {_2}) modulen är {_1} byte (gräns {_2}) +@msg more than {MAX_BATCH_FILES} data sets fler än {MAX_BATCH_FILES} datauppsättningar +@msg more than {MAX_BATCH_FILES} files fler än {MAX_BATCH_FILES} filer +@msg more than {MAX_CSV_ROWS} data rows fler än {MAX_CSV_ROWS} datarader +@msg more than {MAX_FILES} images fler än {MAX_FILES} bilder +@msg more than {MAX_IMPORT} presets fler än {MAX_IMPORT} förinställningar +@msg more than 10000 linked files: package dependencies in smaller parts fler än 10000 länkade filer: paketera beroenden i mindre delar +@msg more than 256 commands fler än 256 kommandon +@msg Move Panel to New Window is not available: floating panels stay in the main window Flytta panel till nytt fönster är inte tillgängligt: flytande paneler stannar i huvudfönstret +@msg moved must be [[x,y]…] moved måste vara [[x,y]…] +@msg name (a toolbar's name) is required name (ett verktygsfälts namn) krävs +@msg name (a toolbar's name) must be a string name (ett verktygsfälts namn) måste vara en sträng +@msg name must be a toolbar's name name måste vara namnet på ett verktygsfält +@msg names must be an array of symbol names names måste vara en array av symbolnamn +@msg need `anchor` or `segment` + `t` `anchor` eller `segment` + `t` krävs +@msg need at least one anchor minst en ankarpunkt krävs +@msg need at least one point minst en punkt krävs +@msg need at least two points minst två punkter krävs +@msg needs points punkter krävs +@msg nineSlice must be true or false nineSlice måste vara true eller false +@msg nineSliceGuides must be [left, top, right, bottom], each 0..1, with left + right < 1 and top + bottom < 1 nineSliceGuides måste vara [left, top, right, bottom], vart och ett 0..1, med left + right < 1 och top + bottom < 1 +@msg no action set is current ingen åtgärdsuppsättning är aktuell +@msg no active data set ingen aktiv datauppsättning +@msg no appearance item {index} inget utseendeobjekt {index} +@msg no artboard {_1} ingen rityta {_1} +@msg no asset {id} ingen resurs {id} +@msg no asset {id} (see assets.list) ingen resurs {id} (se assets.list) +@msg no assets to export inga resurser att exportera +@msg no assets yet: collect art for export first (assets.add) inga resurser än: samla grafik för export först (assets.add) +@msg no character at byte {start} inget tecken vid byte {start} +@msg no colour ingen färg +@msg no colour group `{name}` ingen färggrupp `{name}` +@msg no data sets inga datauppsättningar +@msg no dataset named `{from}` ingen datauppsättning med namnet `{from}` +@msg no dataset named `{name}` ingen datauppsättning med namnet `{name}` +@msg no datasets inga datauppsättningar +@msg no design named `{n}` ingen design med namnet `{n}` +@msg no design named `{name}` ingen design med namnet `{name}` +@msg no design named `{old}` ingen design med namnet `{old}` +@msg no encoder for {_1} yet ingen kodare för {_1} än +@msg no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder ingen mapp: ange `path` eller ställ in Inställningar › Plugins & arbetsdiskar › Mapp för ytterligare plugins +@msg no fonts to look for: they are all available inga typsnitt att leta efter: alla är tillgängliga +@msg no gradient preset `{name}` (see gradient.presets.list) ingen gradientförinställning `{name}` (se gradient.presets.list) +@msg no graphic style `{n}` in `{_1}` ingen grafisk stil `{n}` i `{_1}` +@msg no graphic style library `{key}` (see graphicStyle.libraries) inget grafikstilbibliotek `{key}` (se graphicStyle.libraries) +@msg no guide {i} ingen stödlinje {i} +@msg no guide selected ingen stödlinje markerad +@msg no guide selected (or give an index) ingen stödlinje markerad (eller ange ett index) +@msg no images in the folder inga bilder i mappen +@msg no item at index {_1} inget objekt vid index {_1} +@msg no item at index {from} inget objekt vid index {from} +@msg no item at one of the indices {idx} inget objekt vid något av indexen {idx} +@msg no layer inget lager +@msg no layer {id} (see layer.list) inget lager {id} (se layer.list) +@msg no layers to export inga lager att exportera +@msg no library `{key}` inget bibliotek `{key}` +@msg no metafile format inget metafilformat +@msg no object {_1} inget objekt {_1} +@msg no objects inga objekt +@msg no parent layer inget överordnat lager +@msg no PDF preset named `{n}` ingen PDF-förinställning med namnet `{n}` +@msg no perspective grid preset named `{b}` (see perspective.presets.list) ingen förinställning för perspektivrutnät med namnet `{b}` (se perspective.presets.list) +@msg no point selected (give `index`) ingen punkt markerad (ange `index`) +@msg no preset called `{from}` (see file.newPresets) ingen förinställning med namnet `{from}` (se file.newPresets) +@msg no preset called `{name}` (see file.newPresets) ingen förinställning med namnet `{name}` (se file.newPresets) +@msg no preset named `{n}` ingen förinställning med namnet `{n}` +@msg no print preset named `{b}` (see print.presets.list) ingen utskriftsförinställning med namnet `{b}` (se print.presets.list) +@msg no print preset named `{name}` (presets: {_1}) ingen utskriftsförinställning med namnet `{name}` (förinställningar: {_1}) +@msg no profile named `{name}` ingen profil med namnet `{name}` +@msg no readable files in the folder inga läsbara filer i mappen +@msg no recovery copy `{f}` (see file.recovery.list) ingen återställningskopia `{f}` (se file.recovery.list) +@msg no rows inga rader +@msg no saved export preset `{name}` ingen sparad exportförinställning `{name}` +@msg no saved gradient preset called {name} ingen sparad gradientförinställning med namnet {name} +@msg no saved gradient presets inga sparade gradientförinställningar +@msg no saved presets to export (name [Default] in `names` to export it) inga sparade förinställningar att exportera (ange [Standard] i `names` för att exportera den) +@msg no saved profile called {name} ingen sparad profil med namnet {name} +@msg no saved selection `{name}` ingen sparad markering `{name}` +@msg no saved theme called {name} (see colorTheme.list) inget sparat tema med namnet {name} (se colorTheme.list) +@msg no saved views inga sparade vyer +@msg no series {i} ingen serie {i} +@msg no slice {n} in the image (see slice.list) ingen skiva {n} i bilden (se slice.list) +@msg no source art ingen källgrafik +@msg no stop {i} (the gradient has {n}) inget stopp {i} (gradienten har {n}) +@msg no style `{name}` ingen stil `{name}` +@msg no such assets (see assets.list) inga sådana resurser (se assets.list) +@msg no such frame anchor, or the frame would reach past the canvas inget sådant ankare för ramen, eller så skulle ramen nå utanför arbetsytan +@msg no such objects inga sådana objekt +@msg no such path anchor, or the path would reach past the canvas inget sådant ankare för banan, eller så skulle banan nå utanför arbetsytan +@msg no such rows inga sådana rader +@msg no swatch `{keep}` ingen färgruta `{keep}` +@msg no swatch `{n}` (swatches and colour groups move separately) ingen färgruta `{n}` (färgrutor och färggrupper flyttas separat) +@msg no swatch library `{key}` (see swatch.library.list; "{DOCUMENT_SWATCHES}": the document's swatches) inget färgrutebibliotek `{key}` (se swatch.library.list; "{DOCUMENT_SWATCHES}": dokumentets färgrutor) +@msg no swatch library `{key}` (see swatch.library.list; "document": the document's swatches) inget färgrutebibliotek `{key}` (se swatch.library.list; "document": dokumentets färgrutor) +@msg no swatch named `{n}` ingen färgruta med namnet `{n}` +@msg no swatch or colour group `{n}` ingen färgruta eller färggrupp `{n}` +@msg no swatch or colour group `{n}` in `{_1}` ingen färgruta eller färggrupp `{n}` i `{_1}` +@msg no text objects selected inga textobjekt markerade +@msg no toolbar named `{_1}` inget verktygsfält med namnet `{_1}` +@msg no toolbar named `{name}` inget verktygsfält med namnet `{name}` +@msg no tracing preset `{preset}` (see imageTrace.presets) ingen vektoriseringsförinställning `{preset}` (se imageTrace.presets) +@msg no user library folder here (save with a path, or without one to get the data) ingen mapp för användarbibliotek här (spara med en sökväg, eller utan för att få data) +@msg no variable named `{from}` ingen variabel med namnet `{from}` +@msg no variable named `{name}` ingen variabel med namnet `{name}` +@msg no variable named `{v}` ingen variabel med namnet `{v}` +@msg no variable named `{var}` ingen variabel med namnet `{var}` +@msg no view named `{name}` ingen vy med namnet `{name}` +@msg node {_1} is not a graph nod {_1} är inte ett diagram +@msg node {_1} is not an image nod {_1} är inte en bild +@msg not a closed path inte en sluten bana +@msg not a flattener presets file (format `{_1}`) inte en fil med förinställningar för plattning (format `{_1}`) +@msg not a flattener presets file: {e} inte en fil med förinställningar för plattning: {e} +@msg not a gradient mesh or mesh envelope inte ett gradientnät eller nätkuvert +@msg not a layer or group inte ett lager eller en grupp +@msg not a library file: {e} inte en biblioteksfil: {e} +@msg not a mesh envelope point inte en punkt i ett nätkuvert +@msg not a PDF presets file (format `{_1}`) inte en fil med PDF-förinställningar (format `{_1}`) +@msg not a PDF presets file: {e} inte en fil med PDF-förinställningar: {e} +@msg not a perspective grid presets file (format `{_1}`) inte en fil med förinställningar för perspektivrutnät (format `{_1}`) +@msg not a perspective grid presets file: {e} inte en fil med förinställningar för perspektivrutnät: {e} +@msg not a print presets file (format `{_1}`) inte en fil med utskriftsförinställningar (format `{_1}`) +@msg not a print presets file: {e} inte en fil med utskriftsförinställningar: {e} +@msg not a stored or deflated central record inte en central katalogpost av typen stored eller deflated +@msg not a valid SVGZ file: {e} inte en giltig SVGZ-fil: {e} +@msg not a WebAssembly binary (missing \0asm header) inte en WebAssembly-binärfil (huvudet \0asm saknas) +@msg not a Word document: its compound file has no WordDocument stream inte ett Word-dokument: dess sammansatta fil saknar WordDocument-ström +@msg not a Word document: its main part is not a WordprocessingML document inte ett Word-dokument: dess huvuddel är inte ett WordprocessingML-dokument +@msg not a Word document: its package has no main document part inte ett Word-dokument: dess paket saknar huvuddokumentdel +@msg not a Word document: its WordDocument stream doesn't start with a file information block inte ett Word-dokument: dess WordDocument-ström börjar inte med ett filinformationsblock +@msg not an image VectorCraft reads (see document.formats) inte en bild som VectorCraft kan läsa (se document.formats) +@msg not an RTF file: it doesn't start with not an RTF file: it doesn't start with {\rtf inte en RTF-fil: den börjar inte med inte en RTF-fil: den börjar inte med {\rtf +@msg not area type (text in a frame) outside perspective inte områdestext (text i en ram) utanför perspektivet +@msg not editing an opacity mask redigerar inte en opacitetsmask +@msg not JSON: {e} inte JSON: {e} +@msg not type on a path outside perspective inte text på bana utanför perspektivet +@msg nothing prints ingenting skrivs ut +@msg nothing to bind inget att bädda in +@msg nothing to change inget att ändra +@msg nothing to change: give dx, dy, hScale, vScale or rotation inget att ändra: ange dx, dy, hScale, vScale eller rotation +@msg nothing to crop inget att beskära +@msg nothing to export inget att exportera +@msg nothing to mark inget att märka +@msg nothing to print: every artboard picked is blank inget att skriva ut: alla valda ritytor är tomma +@msg nothing to print: the document has no art that prints inget att skriva ut: dokumentet har inget bildmaterial som skrivs ut +@msg object {_1} can't be set as point type objekt {_1} kan inte göras till punkttext +@msg object {_1} has lost its file's contents: relink it objekt {_1} har förlorat filens innehåll: länka om det +@msg object {_1} has no path objekt {_1} har ingen bana +@msg object {_1} has no size objekt {_1} har ingen storlek +@msg object {_1} is hidden or locked, or on a locked artboard objekt {_1} är dolt eller låst, eller ligger på en låst rityta +@msg object {_1} is not a placed document objekt {_1} är inte ett placerat dokument +@msg object {_1} is not an image objekt {_1} är inte en bild +@msg object {_1} is not an image or a linked file objekt {_1} är inte en bild eller en länkad fil +@msg object {_1} is not an image or a placed document objekt {_1} är inte en bild eller ett placerat dokument +@msg object {_1} is not an Intertwine group objekt {_1} är inte en Sammanfläta-grupp +@msg object {_1} is not in this Intertwine group objekt {_1} ingår inte i den här Sammanfläta-gruppen +@msg object {_1} needs a 3D effect at index {index} objekt {_1} behöver en 3D-effekt vid index {index} +@msg object {id} has {n} anchors, so no anchor {past} objekt {id} har {n} ankarpunkter, så det finns ingen ankarpunkt {past} +@msg object {id} has anchors 0–{_1} for `corners`, not {past} objekt {id} har ankarpunkterna 0–{_1} för `corners`, inte {past} +@msg object is not a path objektet är inte en bana +@msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object objektets transparens kan inte hämtas till markerade tecken; inaktivera Transparens i Pipettalternativ eller markera hela objektet +@msg objects must be none, move or copy objects måste vara none, move eller copy +@msg objects were left out objekt utelämnades +@msg offset out of range förskjutningen ligger utanför intervallet +@msg Offset Path: {e} Förskjut bana: {e} +@msg Offset Path: the path is too complex to offset Förskjut bana: banan är för komplex för att förskjutas +@msg only an exporter declares `extensions` endast en exportfunktion deklarerar `extensions` +@msg only groups, layers, type and images have a Contents (Characters) row endast grupper, lager, text och bilder har en rad för Innehåll (Tecken) +@msg only interior mesh lines can be deleted endast inre nätlinjer kan raderas +@msg only solid colours can be added (not gradients or patterns) endast enhetliga färger kan läggas till (inte gradienter eller mönster) +@msg only solid-colour swatches can be spot colours endast färgrutor med enhetlig färg kan vara dekorfärger +@msg only this Affinity file's embedded preview could be read; use File › Open to see it with its warning endast den inbäddade förhandsgranskningen i den här Affinity-filen kunde läsas; använd Arkiv › Öppna för att visa den med varningen +@msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first endast den inbäddade förhandsgranskningen i den här Affinity-filen kunde läsas: använd Arkiv › Öppna för att visa den med varningen, eller exportera SVG eller PDF från Affinity först +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto, above, below, icon och en column-placering hör till window.panel.float och window.panel.dock +@msg onto, above, below, icon and a column place take no anchor, side, zone or before onto, above, below, icon och en column-placering tar inget anchor, side, zone eller before +@msg onto, above, below, icon and a column place take no x, y, width or height onto, above, below, icon och en column-placering tar inget x, y, width eller height +@msg open a document to look for its linked files öppna ett dokument för att söka efter dess länkade filer +@msg options must be an object (see file.formatOptions) options måste vara ett objekt (se file.formatOptions) +@msg order must be leftToRight or rightToLeft order måste vara leftToRight eller rightToLeft +@msg orientation must be portrait or landscape, not `{o}` orientation måste vara portrait eller landscape, inte `{o}` +@msg outlineText {v}: true or false outlineText {v}: true eller false +@msg output intent profile: {e} profil för utgångsavsikt: {e} +@msg output size ({what} is {len} bytes, limit {max}) utdatastorlek ({what} är {len} byte, gräns {max}) +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1}-filer är CMYK, och ”{name}” är en RGB-profil +@msg output.destination: {e} output.destination: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: ingen RGB- eller CMYK-profil heter ”{name}” +@msg output.inks: no ink is set to print output.inks: ingen tryckfärg är inställd för utskrift +@msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: ”{name}” är en gråskaleprofil, som inte kan vara en {std}-utgångsavsikt +@msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std}-filer skrivs ut i CMYK, och ”{name}” är en RGB-profil +@msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: ingen profil heter ”{name}”, och en {std}-utgångsavsikt bäddar in sin profil +@msg output.outputIntent: no profile is called “{name}”: a {std} output intent embeds a profile, or names a registered printing condition (outputConditionId and registry) output.outputIntent: ingen profil heter ”{name}”: en {std}-utgångsavsikt bäddar in en profil eller anger ett registrerat tryckvillkor (outputConditionId och registry) +@msg overlap: {o} pt is half a tile or more överlappning: {o} pt är en halv sida eller mer +@msg overlapping edits överlappande redigeringar +@msg overlapping Shaper paths must be in the same layer or group överlappande banor från Formning måste ligga i samma lager eller grupp +@msg page {page} of the PDF has no objects sida {page} i PDF-filen har inga objekt +@msg page {page}: `{file}` has {n} {artboards} sida {page}: `{file}` har {n} {artboards} +@msg page {page}: `{name}` has {n} {pages} sida {page}: `{name}` har {n} {pages} +@msg page art conflicts with image data for {key} sidans bildmaterial står i konflikt med bilddata för {key} +@msg page art conflicts with pattern {name} sidans bildmaterial står i konflikt med mönstret {name} +@msg page art conflicts with swatch {name} sidans bildmaterial står i konflikt med färgrutan {name} +@msg page art is missing image data for {key} sidans bildmaterial saknar bilddata för {key} +@msg page art is missing pattern {name} sidans bildmaterial saknar mönstret {name} +@msg page art is missing swatch {name} sidans bildmaterial saknar färgrutan {name} +@msg page must be a whole number from 1 sidan måste vara ett heltal från och med 1 +@msg page thumbnail: {e} sidminiatyr: {e} +@msg pages must be a range such as "2-3" or a page number, not {v} pages måste vara ett intervall som "2-3" eller ett sidnummer, inte {v} +@msg pages: {e} sidor: {e} +@msg panel position must be finite panelens position måste vara ändlig +@msg parameter `{k}`: {what} parameter `{k}`: {what} +@msg parameter `{name}`: {what} parameter `{name}`: {what} +@msg parameters must be an object parametrarna måste vara ett objekt +@msg passwords can have up to {MAX_PASSWORD} bytes lösenord får vara högst {MAX_PASSWORD} byte +@msg path has no open end banan har ingen öppen ände +@msg paths must be strings sökvägar måste vara strängar +@msg PDF content is incomplete or exceeds the reader's limits; no document was imported PDF-innehållet är ofullständigt eller överskrider läsarens gränser; inget dokument importerades +@msg PDF flattener: {e} PDF-plattning: {e} +@msg PDF options: {e} PDF-alternativ: {e} +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false kräver att varje rityta behåller det redigerbara bildmaterialet +@msg pdfs `{m}`: single or multiple pdfs `{m}`: single eller multiple +@msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom är "artwork" eller "swatches", inte {v} +@msg pins and moved must be non-empty lists of the same length pins och moved måste vara icke-tomma listor av samma längd +@msg pins must be [[x,y]…] pins måste vara [[x,y]…] +@msg pins must be finite pins måste vara ändliga +@msg place is above, below or inside, not `{other}` place är above, below eller inside, inte `{other}` +@msg plane must be left|right|ground plane måste vara left|right|ground +@msg plane must be left|right|ground|none plane måste vara left|right|ground|none +@msg plug-in parameters must be a JSON object pluginparametrarna måste vara ett JSON-objekt +@msg point is outside the mesh punkten ligger utanför nätet +@msg points must be [t, left, right] with non-negative widths points måste vara [t, left, right] med icke-negativa bredder +@msg points must be a non-empty [[x,y,pressure?]…] list points måste vara en icke-tom lista [[x,y,pressure?]…] +@msg points must be a non-empty list of finite [x,y] points måste vara en icke-tom lista med ändliga [x,y] +@msg points must be an array or null points måste vara en array eller null +@msg points must be finite points måste vara ändliga +@msg points must be finite [x,y] pairs points måste vara ändliga [x,y]-par +@msg points must contain 1–4096 coordinates points måste innehålla 1–4096 koordinater +@msg position must be normal, superscript or subscript position måste vara normal, superscript eller subscript +@msg position must be topLeft, topRight, bottomLeft or bottomRight position måste vara topLeft, topRight, bottomLeft eller bottomRight +@msg positions must be between 0 and 100000 pt positionerna måste vara mellan 0 och 100 000 pt +@msg ppi must be a positive number, not {ppi} ppi måste vara ett positivt tal, inte {ppi} +@msg ppi must be between 1 and 2400 ppi måste vara mellan 1 och 2400 +@msg preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill preserve `{v}` är inte transforms|bounds|fileDimensions|fit|fill +@msg preserveShape must be clippingMask|transparency preserveShape måste vara clippingMask|transparency +@msg preset `{id}`: mobile or density preset `{id}`: mobile eller density +@msg preset must be standard, diffuse, topLeft or right preset måste vara standard, diffuse, topLeft eller right +@msg preset must be the name of a print preset preset måste vara namnet på en utskriftsförinställning +@msg previewMode must be default, pixel or overprint previewMode måste vara default, pixel eller overprint +@msg print settings: {e} utskriftsinställningar: {e} +@msg procedures nest too deeply procedurerna är nästlade för djupt +@msg procedures nested too deeply procedurerna nästlades för djupt +@msg quotes must be {double?, single?} quotes måste vara {double?, single?} +@msg quotes.{k} must be an opening and a closing quote, e.g. "“”" quotes.{k} måste vara ett inledande och ett avslutande citattecken, t.ex. "“”" +@msg rasterEffectsPpi must be 1–2400 (72 screen, 150 medium, 300 high) rasterEffectsPpi måste vara 1–2400 (72 skärm, 150 medel, 300 hög) +@msg rating must be a whole number from 0 to {MAX_RATING} rating måste vara ett heltal från 0 till {MAX_RATING} +@msg Recolor Artwork is no longer open Färga om grafik är inte längre öppet +@msg rect and {k} contradict each other: give the area or the artboards rect och {k} motsäger varandra: ange området eller ritytorna +@msg rect applies to raster formats, not {_1} rect gäller för rasterformat, inte {_1} +@msg rect is [x, y, width, height] in points rect är [x, y, width, height] i punkter +@msg rect must be [x, y, width, height] rect måste vara [x, y, width, height] +@msg rect must be [x, y, width, height] with a positive width and height rect måste vara [x, y, width, height] med positiv bredd och höjd +@msg rect needs finite numbers and a positive width and height rect kräver ändliga tal och positiv bredd och höjd +@msg redraw needs id redraw kräver id +@msg redraw within must be a finite distance of 0 or more redraw within måste vara ett ändligt avstånd på 0 eller mer +@msg registration must be 0..8 registration måste vara 0..8 +@msg release a layer or a group släpp ett lager eller en grupp +@msg replace keeps the replaced object's place and transform: drop template, at and rect replace behåller det ersatta objektets placering och transformering: ta bort template, at och rect +@msg replace: select the one object to replace replace: markera det objekt som ska ersättas +@msg resolution must be a number or screen|medium|high resolution måste vara ett tal eller screen|medium|high +@msg rotation must be a number of degrees rotation måste vara ett antal grader +@msg rotation must be finite rotation måste vara ändlig +@msg rows and cols must be 1..50 rows och cols måste vara 1..50 +@msg rows and columns must be 1..500 rader och kolumner måste vara 1..500 +@msg rows of objects whose appearances differ can't be reordered together rader med objekt vars utseende skiljer sig åt kan inte ordnas om tillsammans +@msg save the document first: copy puts the file in its folder spara dokumentet först: copy lägger filen i dess mapp +@msg save the document first: Package collects a saved document spara dokumentet först: Paketera samlar ett sparat dokument +@msg Save writes one artboard: name one, or export several with document.export Spara skriver en rityta: ange en, eller exportera flera med document.export +@msg savedPreset: {e} savedPreset: {e} +@msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) scale `{s}`: en faktor som 2x, en bredd (100w), en höjd (100h) eller en upplösning (72ppi) +@msg scale must be a number above 0, at most 64 scale måste vara ett tal över 0, högst 64 +@msg scale must be non-zero scale får inte vara noll +@msg scope must be selection or all (got {other}) scope måste vara selection eller all (fick {other}) +@msg scribble is too long klottret är för långt +@msg segment does not exist segmentet finns inte +@msg select a blend to set easing or color shift markera en blandning för att ange hastighetskurva eller färgförskjutning +@msg select a compound shape markera en sammansatt form +@msg Select a dimension first Markera ett mått först +@msg select a graph markera ett diagram +@msg select a group or layer with visible, unlocked members markera en grupp eller ett lager med synliga, upplåsta medlemmar +@msg select a layer markera ett lager +@msg select a path markera en bana +@msg select a Shaper group markera en formningsgrupp +@msg select a text object markera ett textobjekt +@msg select an image (or an Image Trace group) markera en bild (eller en bildkalkeringsgrupp) +@msg select an image, or pass id markera en bild eller ange id +@msg select an object (or pass `id`) markera ett objekt (eller ange `id`) +@msg select an object with a freeform gradient markera ett objekt med fri gradient +@msg select an object with an opacity mask markera ett objekt med en opacitetsmask +@msg select area type markera områdestext +@msg select area type (text in a frame) markera områdestext (text i en ram) +@msg select area type and closed paths (at least one area type object) markera områdestext och slutna banor (minst ett områdestextobjekt) +@msg select area type whose first line can fit its frame markera områdestext vars första rad får plats i ramen +@msg select artwork to add its colours markera grafik för att lägga till dess färger +@msg select artwork to make a group of its colours markera grafik för att skapa en grupp av dess färger +@msg select artwork to recolour, or give a colour `group` markera grafik att färga om, eller ange en färggrupp (`group`) +@msg Select dimensions to update Markera mått att uppdatera +@msg select exactly two path ends to join markera exakt två banändar att foga samman +@msg select members of a compound shape markera medlemmar i en sammansatt form +@msg select objects or give ids markera objekt eller ange id:n +@msg select objects to align to the guide markera objekt att justera mot stödlinjen +@msg select one image or pass id markera en bild eller ange id +@msg Select only dimensions Markera endast mått +@msg select paths markera banor +@msg select paths or compound paths markera banor eller sammansatta banor +@msg select rows or objects to collect markera rader eller objekt att samla +@msg select something to export markera något att exportera +@msg select something to export (or turn off selectedOnly) markera något att exportera (eller stäng av selectedOnly) +@msg select text to redefine the style from markera text att omdefiniera stilen från +@msg select the art and, on top of it, the mask object markera grafiken och, ovanpå den, maskobjektet +@msg select the art for the design markera grafiken för designen +@msg select the art for the pattern tile markera grafiken för mönsterrutan +@msg select the art to add first markera först grafiken som ska läggas till +@msg select the art to collect (or give its ids) markera grafiken att samla (eller ange dess id:n) +@msg select the content and a path on top markera innehållet och en bana ovanpå +@msg select the images to relink, or pass ids markera bilderna att länka om, eller ange id:n +@msg select the images, or pass ids markera bilderna, eller ange id:n +@msg select the linked images or placed documents, or pass ids markera de länkade bilderna eller placerade dokumenten, eller ange id:n +@msg select the object to copy from markera objektet att kopiera från +@msg select the objects (or give their ids) markera objekten (eller ange deras id:n) +@msg select the objects to attach to the path markera objekten att fästa vid banan +@msg select the objects to bind markera objekten att bädda in +@msg select two or more objects to intertwine markera två eller fler objekt att sammanfläta +@msg Select two or more objects, or a group Markera två eller fler objekt, eller en grupp +@msg select two or more slices to combine markera två eller fler skivor att kombinera +@msg select type on a path markera text på bana +@msg selection `{m}`: one or each selection `{m}`: one eller each +@msg settings is an object of document.exportForScreens params settings är ett objekt med parametrar för document.exportForScreens +@msg settings must be an object settings måste vara ett objekt +@msg Shaper needs 1–64 source paths Formning kräver 1–64 källbanor +@msg show `{show}`: all, missing, modified or embedded show `{show}`: all, missing, modified eller embedded +@msg show must be true or false show måste vara true eller false +@msg size must be "small", "medium", "large" or a number of points over 0 up to {_1} size måste vara "small", "medium", "large" eller ett antal punkter över 0 upp till {_1} +@msg size must be positive size måste vara positiv +@msg sizeMode is "fixed" or "pressure", not {other} sizeMode är "fixed" eller "pressure", inte {other} +@msg sizeMode is "fixed" or "pressure", not `{other}` sizeMode är "fixed" eller "pressure", inte `{other}` +@msg sizeVariation must be 0 or more sizeVariation måste vara 0 eller mer +@msg smallCaps must be true or false smallCaps måste vara true eller false +@msg sort `{x}`: name, kind or status sort `{x}`: name, kind eller status +@msg source paths are too large for Shaper källbanorna är för stora för Formning +@msg spot, mode and group apply to solid colours only spot, mode och group gäller endast enhetliga färger +@msg status `{s}`: linked, embedded, missing or modified status `{s}`: linked, embedded, missing eller modified +@msg steps must be 1..{MAX_STEPS} steps måste vara 1..{MAX_STEPS} +@msg steps must be 1..1000 steps måste vara 1..1000 +@msg stop {i}: `plates` must be four numbers from 0 to 1 (C, M, Y, K) stopp {i}: `plates` måste vara fyra tal från 0 till 1 (C, M, Y, K) +@msg stopped before the archive was finished stoppades innan arkivet var klart +@msg strokeMode must be within|along|across, got {m} strokeMode måste vara within|along|across, men var {m} +@msg strokeOptions must be an object of stroke.set options strokeOptions måste vara ett objekt med alternativ för stroke.set +@msg strokeWidth must be a positive number of pixels strokeWidth måste vara ett positivt antal pixlar +@msg subpath {si} is not an open subpath delbana {si} är inte en öppen delbana +@msg subpaths required when joining the same path delbanor krävs när samma bana sammanfogas +@msg SVG is not UTF-8, UTF-16 or ISO 8859-1 SVG-filen är inte i UTF-8, UTF-16 eller ISO 8859-1 +@msg swatchConflict must be "merge" or "add", not {v} swatchConflict måste vara "merge" eller "add", inte {v} +@msg Switch x/y is for scatter graphs Växla x/y gäller spridningsdiagram +@msg text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} text måste vara {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?} +@msg Text options: {e} Textalternativ: {e} +@msg text transform is collapsed or unrepresentable texttransformeringen är kollapsad eller kan inte återges +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: använd "{_1}" eller "{_2}" +@msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces måste vara ett heltal från 2 till 100 +@msg textureImage: {e} textureImage: {e} +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: ange {path} eller {name, dataBase64} för en bildfil, eller en textur så som effect.list anger den +@msg that makes more than {MAX_PIECES} slices det ger fler än {MAX_PIECES} skivor +@msg that object is not in the overlap det objektet ingår inte i överlappningen +@msg the action set ids are not a list åtgärdsuppsättningarnas id:n är inte en lista +@msg the active paint is not a gradient den aktiva färgen är inte en gradient +@msg the Affinity document has no page with a size Affinity-dokumentet har ingen sida med en storlek +@msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size ritytorna får inte plats på arbetsytan: använd färre ritytor, mindre avstånd eller en mindre storlek +@msg the character's size can't be measured tecknets storlek kan inte mätas +@msg the CMYK image couldn't be written CMYK-bilden kunde inte skrivas +@msg the compound shape is too complex to expand den sammansatta formen är för komplex för att expanderas +@msg the container of the listed objects is gone behållaren för de listade objekten finns inte längre +@msg the copy `{user_id}` can't be read as a library kopian `{user_id}` kan inte läsas som ett bibliotek +@msg the copy would leave the canvas kopian skulle hamna utanför arbetsytan +@msg the cut cannot be made on this art: {e} snittet kan inte göras i de här objekten: {e} +@msg the data isn't an EMF or WMF picture data är inte en EMF- eller WMF-bild +@msg the data isn't an EPS or PostScript picture data är inte en EPS- eller PostScript-bild +@msg the deferred paste is no longer available den fördröjda inklistringen är inte längre tillgänglig +@msg the design is too big to draw at every data point of this graph designen är för stor för att ritas vid varje datapunkt i det här diagrammet +@msg the design is too big to draw in every column of this graph designen är för stor för att ritas i varje kolumn i det här diagrammet +@msg the dialog it was opened over is no longer open dialogrutan som den öppnades över är inte längre öppen +@msg the dictionary stack overflowed ordlistestacken flödade över +@msg the editing data's hash has no place hashvärdet för redigeringsdata har ingen plats +@msg the entities the document declares expand to too much text entiteterna som dokumentet deklarerar expanderar till för mycket text +@msg the envelope's content has no bounds kuvertets innehåll har inga gränser +@msg the envelope's mesh is malformed kuvertets nät är felformat +@msg the file holds no `variableSets` element filen innehåller inget `variableSets`-element +@msg the file is larger than {_1} MB filen är större än {_1} MB +@msg the file is too large filen är för stor +@msg the file was updated or encrypted already filen har redan uppdaterats eller krypterats +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) det första tecknet på en rad har inget tecken före sig att knipa mot: det flyttas bara upp och ned (dy) +@msg the font {_1} is not available typsnittet {_1} är inte tillgängligt +@msg the format has no file extension formatet har ingen filändelse +@msg the graphic can't be read: {e} grafiken kan inte läsas: {e} +@msg the graphic is empty grafiken är tom +@msg the graphic's data is damaged grafikens data är skadade +@msg the graphic's document has no artboard grafikens dokument har ingen rityta +@msg the image `{path}` isn't followed: {r} bilden `{path}` följs inte: {r} +@msg the image has no embedded pixels bilden har inga inbäddade pixlar +@msg the image is empty bilden är tom +@msg the image is fully transparent bilden är helt transparent +@msg the image is not on an artboard; pass rect bilden ligger inte på en rityta; ange rect +@msg the image's pixels are missing bildens pixlar saknas +@msg the image's pixels aren't in the document bildens pixlar finns inte i dokumentet +@msg the image's transparency doesn't fit it bildens transparens passar inte bilden +@msg the job would print more than {_1} pages jobbet skulle skriva ut fler än {_1} sidor +@msg the job would print more than {MAX_PAGES} pages jobbet skulle skriva ut fler än {MAX_PAGES} sidor +@msg the layers hold no art to mask lagren innehåller inga objekt att maskera +@msg the layout moved layouten har flyttats +@msg the library has a group `{name}` already biblioteket har redan en grupp `{name}` +@msg the library has no group `{name}` biblioteket har ingen grupp `{name}` +@msg the library has no item `{item}` biblioteket har inget objekt `{item}` +@msg the library has no item `{other}` biblioteket har inget objekt `{other}` +@msg the library holds {MAX_GROUPS} groups already biblioteket innehåller redan {MAX_GROUPS} grupper +@msg the library holds {MAX_ITEMS} items of this kind already biblioteket innehåller redan {MAX_ITEMS} objekt av den här typen +@msg the module imports `{_1}.{_2}`, but plug-ins get no host imports (no WASI, files or network) modulen importerar `{_1}.{_2}`, men plugins får inga värdimporter (ingen WASI, inga filer eller nätverk) +@msg the module must export its linear memory as `memory` modulen måste exportera sitt linjära minne som `memory` +@msg the name is empty namnet är tomt +@msg the object has no fill, stroke or effect objektet har ingen fyllning, kontur eller effekt +@msg the object has no graphic style (pass `name`) objektet har ingen grafikstil (ange `name`) +@msg the objects don't match the plan objekten stämmer inte med planen +@msg the objects to change are no longer in the document objekten som ska ändras finns inte längre i dokumentet +@msg the open and permissions passwords must differ lösenorden för öppning och behörigheter måste vara olika +@msg the operand stack overflowed operandstacken flödade över +@msg the page has no area sidan har ingen area +@msg the page's type in an unread object's box isn't in its page art sidans text i ett oläst objekts ruta finns inte i dess sidgrafik +@msg the paint behind the proxy is not a gradient färgen bakom proxyn är inte en gradient +@msg the parent must be a layer or sublayer det överordnade objektet måste vara ett lager eller underlager +@msg the path can't be extended banan kan inte förlängas +@msg the path can't be inside one of the objects to attach banan kan inte ligga inuti något av objekten som ska fästas +@msg the path has no segments to measure banan har inga segment att mäta +@msg the path is empty banan är tom +@msg the path is too short to shorten that much banan är för kort för att kortas så mycket +@msg the PDF security settings were saved without their passwords: give openPassword or permissionsPassword again, or security without passwordRequired to export unprotected PDF-säkerhetsinställningarna sparades utan sina lösenord: ange openPassword eller permissionsPassword igen, eller security utan passwordRequired för att exportera utan skydd +@msg the picture has no objects bilden har inga objekt +@msg the program runs too long programmet körs för länge +@msg the program uses too much memory programmet använder för mycket minne +@msg the rectangle must have a width and a height rektangeln måste ha en bredd och en höjd +@msg the rectangle needs a size and must lie on the canvas rektangeln behöver en storlek och måste ligga på arbetsytan +@msg the RTF file has too many paragraphs or formatting changes to place as type (at most {MAX_PARAGRAPHS} paragraphs and {MAX_RUNS} runs) RTF-filen har för många stycken eller formateringsändringar för att placeras som text (högst {MAX_PARAGRAPHS} stycken och {MAX_RUNS} textavsnitt) +@msg the RTF file is too large to place as type (at most {_1} MB) RTF-filen är för stor för att placeras som text (högst {_1} MB) +@msg the runtime panicked körmiljön kraschade +@msg the selected art has no width de markerade objekten har ingen bredd +@msg the selection draws nothing markeringen ritar ingenting +@msg the selection has no area markeringen har ingen area +@msg the selection has no art to export markeringen innehåller inget att exportera +@msg the selection has no graphic style markeringen har ingen grafikstil +@msg the slice would leave the canvas skivan skulle hamna utanför arbetsytan +@msg the spot colour couldn't be added dekorfärgen kunde inte läggas till +@msg the subpath has no ends to extend (it is closed or a single point) delbanan har inga ändar att förlänga (den är stängd eller en enkel punkt) +@msg the SVG expands to more than {0} nested SVG images SVG-filen expanderar till fler än {0} kapslade SVG-bilder +@msg the SVG expands to more than {0} objects SVG-filen expanderar till fler än {0} objekt +@msg the SVG has no drawable objects SVG-filen har inga ritbara objekt +@msg the SVGZ file unpacks to more than {_1} MB SVGZ-filen packas upp till mer än {_1} MB +@msg the symbols are nested too deeply to expand their instances symbolerna är kapslade för djupt för att deras instanser ska kunna expanderas +@msg the text file is too large to place as type (at most {_1} MB) textfilen är för stor för att placeras som text (högst {_1} MB) +@msg the text is empty texten är tom +@msg the text is over {_1} MB texten är större än {_1} MB +@msg the top object must be a path det översta objektet måste vara en bana +@msg the trace was cancelled vektoriseringen avbröts +@msg the trailer has no size trailern saknar Size-post +@msg the type object is flattened to nothing textobjektet blir tomt när det plattas till +@msg the value of axis `{tag}` must be a number or null värdet för axeln `{tag}` måste vara ett tal eller null +@msg the variable library declares more than {MAX_LIBRARY_DATASETS} data sets variabelbiblioteket deklarerar fler än {MAX_LIBRARY_DATASETS} datauppsättningar +@msg the variable library declares more than {MAX_LIBRARY_ENTITIES} entities variabelbiblioteket deklarerar fler än {MAX_LIBRARY_ENTITIES} entiteter +@msg the variable library declares more than {MAX_LIBRARY_VARIABLES} variables variabelbiblioteket deklarerar fler än {MAX_LIBRARY_VARIABLES} variabler +@msg the variable library declares no variables variabelbiblioteket deklarerar inga variabler +@msg the variable library is larger than {MAX_LIBRARY_BYTES} bytes variabelbiblioteket är större än {MAX_LIBRARY_BYTES} byte +@msg the variable library is not UTF-8 variabelbiblioteket är inte UTF-8 +@msg the variable library is not well-formed XML: {e} variabelbiblioteket är inte välformad XML: {e} +@msg the variable library nests elements more than {MAX_LIBRARY_NESTING} deep variabelbiblioteket nästlar element djupare än {MAX_LIBRARY_NESTING} nivåer +@msg the variable library's document type declaration holds something other than entities of plain text variabelbibliotekets dokumenttypdeklaration innehåller annat än entiteter med oformaterad text +@msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes variabelbibliotekets entiteter expanderar till mer än {MAX_LIBRARY_BYTES} byte +@msg the window has no dock fönstret saknar dockningsyta +@msg the Word document has more than {_1} MB of formatting properties, too many to place Word-dokumentet har mer än {_1} MB formateringsegenskaper, för mycket för att placeras +@msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word-dokumentet har mer än {MAX_PAGES} sidor med egenskaper, för många för att placeras +@msg the Word document has more than {MAX_RUNS} runs of character or paragraph properties, too many to place Word-dokumentet har fler än {MAX_RUNS} segment med tecken- eller styckeegenskaper, för många för att placeras +@msg the Word document has too much text or formatting to place as type (at most {MAX_PARAGRAPHS} paragraphs, {MAX_RUNS} runs and {_1} MB of text) Word-dokumentet har för mycket text eller formatering för att placeras som text (högst {MAX_PARAGRAPHS} stycken, {MAX_RUNS} segment och {_1} MB text) +@msg the Word document has too much text to place as type (at most {_1} MB) Word-dokumentet har för mycket text för att placeras som text (högst {_1} MB) +@msg the Word document is encrypted or protected with a password; save it without one to place it Word-dokumentet är krypterat eller lösenordsskyddat. Spara det utan lösenord för att placera det +@msg the Word document is too large to place (its {name} stream holds more than {_1} MB) Word-dokumentet är för stort för att placeras (dess {name}-ström innehåller mer än {_1} MB) +@msg the Word document was last saved with fast save, which VectorCraft doesn't read; save it again with fast save turned off Word-dokumentet sparades senast med snabbsparning, som VectorCraft inte kan läsa. Spara det igen med snabbsparning avstängd +@msg the Word document was saved by Word 6.0 or Word 95, which VectorCraft doesn't read; save it as a Word 97-2003 document Word-dokumentet sparades med Word 6.0 eller Word 95, som VectorCraft inte kan läsa. Spara det som ett Word 97-2003-dokument +@msg the Word document's text is made of more than {MAX_PIECES} pieces, too many to place Word-dokumentets text består av fler än {MAX_PIECES} delar, för många för att placeras +@msg the written PDF has no catalog den skrivna PDF-filen saknar katalog +@msg the written PDF has no cross-reference table den skrivna PDF-filen saknar korsreferenstabell +@msg the written PDF's metadata can't be edited den skrivna PDF-filens metadata kan inte redigeras +@msg there are no colour swatches to draw det finns inga färgrutor att rita +@msg there is already a design named `{name}` det finns redan en design med namnet `{name}` +@msg there is already a design named `{to}` det finns redan en design med namnet `{to}` +@msg there is already a toolbar named `{name}` det finns redan ett verktygsfält med namnet `{name}` +@msg there is already a toolbar named `{to}` det finns redan ett verktygsfält med namnet `{to}` +@msg there is no library: create one first det finns inget bibliotek: skapa ett först +@msg these paths are too degenerate for Shaper banorna är för degenererade för Formning +@msg thumbnail: no page {v} (the {what} has {count}) miniatyr: ingen sida {v} ({what} har {count}) +@msg tileRange of {what}: {e} tileRange för {what}: {e} +@msg time budget tidsbudget +@msg title can't be empty titeln får inte vara tom +@msg to (the new name) is required to (det nya namnet) krävs +@msg to must be fill or stroke to måste vara fill eller stroke +@msg to must be smooth or corner to måste vara smooth eller corner +@msg too large for a zip archive: package to a folder för stort för ett zip-arkiv: paketera till en mapp +@msg too many `points` (at most 100000) för många `points` (högst 100 000) +@msg too many characters: at most {MAX_CHARS} för många tecken: högst {MAX_CHARS} +@msg too many dots for this size: lower the frequency för många punkter för den här storleken: sänk frekvensen +@msg too many filters over one file för många filter på en fil +@msg too many overlapping paths for Shaper för många överlappande banor för Formning +@msg too many saved clips för många sparade klippbanor +@msg too many saved graphics states för många sparade grafiklägen +@msg too many Shaper edits för många redigeringar med Formning +@msg toolbar (a toolbar's name) must be a string toolbar (verktygsfältets namn) måste vara en sträng +@msg toolbar name can't be empty verktygsfältets namn får inte vara tomt +@msg transparentImages {v}: "flatten" (the default) or "omit" transparentImages {v}: "flatten" (standard) eller "omit" +@msg two saved selections would be named `{_1}` två sparade markeringar skulle få namnet `{_1}` +@msg type dimension cannot be represented with this text transform textmåttet kan inte återges med den här texttransformationen +@msg type dimension must be finite textmåttet måste vara ändligt +@msg unexpected host trap oväntat avbrott (trap) i värdmiljön +@msg unexpected resources oväntade resurser +@msg unknown {k} key `{key}` (size, position) okänd {k}-nyckel `{key}` (size, position) +@msg unknown {key} `{v}` (none, short or full) okänt värde för {key}: `{v}` (none, short eller full) +@msg unknown {key} profile `{n}` okänd {key}-profil `{n}` +@msg unknown align `{other}` okänd justering `{other}` +@msg unknown alignToPath `{a}` okänt alignToPath-värde `{a}` +@msg unknown arrowhead {v} okänd pilspets {v} +@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) okänd artboardLayout-nyckel `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown attribute `{attribute}` okänt attribut `{attribute}` +@msg unknown attribute `{k}` okänt attribut `{k}` +@msg unknown axis `{other}` (vertical|horizontal|free) okänd axel `{other}` (vertical|horizontal|free) +@msg unknown blend mode {b} okänt blandningsläge {b} +@msg unknown blend mode `{b}` okänt blandningsläge `{b}` +@msg unknown brush type `{o}` okänd penseltyp `{o}` +@msg unknown category `{c}` okänd kategori `{c}` +@msg unknown category `{c}` ({_1}) okänd kategori `{c}` ({_1}) +@msg unknown character `{c}` okänt tecken `{c}` +@msg unknown character style number field okänt nummerfält i teckenstil +@msg unknown CMYK profile `{name}` okänd CMYK-profil `{name}` +@msg unknown end {e} okänd ände {e} +@msg unknown File Info field `{k}` okänt fält i Filinformation `{k}` +@msg unknown flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution or a saved one: see flattener.presets.list) okänd flattenerPreset `{name}` (High Resolution, Medium Resolution, Low Resolution eller en sparad: se flattener.presets.list) +@msg unknown format `{f}` (vcswatches, gpl, ase or css) okänt format `{f}` (vcswatches, gpl, ase eller css) +@msg unknown from {f} okänt from-värde {f} +@msg unknown graph type `{t}` okänd diagramtyp `{t}` +@msg unknown grid colours `{name}` (one of {_1}) okända rutnätsfärger `{name}` (en av {_1}) +@msg unknown gridType `{t}` okänd gridType `{t}` +@msg unknown intent `{i}` okänd återgivningsmetod `{i}` +@msg unknown issue kind {id} okänd problemtyp {id} +@msg unknown issue kind {v} okänd problemtyp {v} +@msg unknown knockout state {k} okänt utsparningsläge {k} +@msg unknown language `{l}` (one of {_1}) okänt språk `{l}` (ett av {_1}) +@msg unknown language `{language}` (one of {_1}) okänt språk `{language}` (ett av {_1}) +@msg unknown method `{m}` ({_1}) okänd metod `{m}` ({_1}) +@msg unknown mode {m} okänt läge {m} +@msg unknown mode `{o}` okänt läge `{o}` +@msg unknown mode `{other}` (gray, rgb, hsb, lab, cmyk or web) okänt läge `{other}` (gray, rgb, hsb, lab, cmyk eller web) +@msg unknown mode `{other}` (mono|cmyk) okänt läge `{other}` (mono|cmyk) +@msg unknown mode `{other}` (rgb|cmyk|gray|global) okänt läge `{other}` (rgb|cmyk|gray|global) +@msg unknown mode `{other}` (set, add, subtract) okänt läge `{other}` (set, add, subtract) +@msg unknown model `{other}` okänd modell `{other}` +@msg unknown model `{other}` (keep, new or document) okänd modell `{other}` (keep, new eller document) +@msg unknown op {o} okänd operation {o} +@msg unknown OpenType feature `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom; prefix - to turn off) okänd OpenType-funktion `{t}` (liga, calt, dlig, smcp, frac, onum, tnum, ordn, swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom; inled med - för att stänga av) +@msg unknown OpenType feature `{t}` in featureChanges (the tags `features` takes) okänd OpenType-funktion `{t}` i featureChanges (de taggar som `features` tar emot) +@msg unknown order `{o}`: toggle, front, forward, backward or back okänd ordning `{o}`: toggle, front, forward, backward eller back +@msg unknown panel okänd panel +@msg unknown PDF preset `{name}` (presets: {_1}) okänd PDF-förinställning `{name}` (förinställningar: {_1}) +@msg unknown pieLegend `{v}` (none, standard or wedges) okänd pieLegend `{v}` (none, standard eller wedges) +@msg unknown piePosition `{v}` (even, ratio or stacked) okänd piePosition `{v}` (even, ratio eller stacked) +@msg unknown pieSort `{v}` (none, all or first) okänd pieSort `{v}` (none, all eller first) +@msg unknown plate `{n}` okänd plåt `{n}` +@msg unknown profile {id} (see stroke.widthProfile.list) okänd profil {id} (se stroke.widthProfile.list) +@msg unknown proof target `{t}` okänt korrekturmål `{t}` +@msg unknown quotes key `{k}` (double, single) okänd quotes-nyckel `{k}` (double, single) +@msg unknown resolution `{v}` okänd upplösning `{v}` +@msg unknown rule `{r}` (see color.harmony) okänd regel `{r}` (se color.harmony) +@msg unknown rule `{rule}` ({_1}) okänd regel `{rule}` ({_1}) +@msg unknown setting `{k}` okänd inställning `{k}` +@msg unknown shape `{v}` (circle|ellipse|square|diamond|line) okänd form `{v}` (circle|ellipse|square|diamond|line) +@msg unknown spacing `{o}` (smooth|steps|distance) okänt avstånd `{o}` (smooth|steps|distance) +@msg unknown tileType `{t}` ({_1}) okänd tileType `{t}` ({_1}) +@msg unknown units okända enheter +@msg unknown units `{u}` okända enheter `{u}` +@msg unknown value axis `{v}` (left, right or both) okänd värdeaxel `{v}` (left, right eller both) +@msg unknown variation `{v}` (tintsShades|warmCool|vividMuted) okänd variation `{v}` (tintsShades|warmCool|vividMuted) +@msg unknown Warp style okänd stil för Förvräng +@msg unknown warp style `{s}` okänd stil för Förvräng `{s}` +@msg unreadable object oläsbart objekt +@msg unsafe destination file name osäkert filnamn för målfilen +@msg use paths or compound paths använd banor eller sammansatta banor +@msg useArtboards must be true or false, not {v} useArtboards måste vara true eller false, inte {v} +@msg value for `{var}` must match its variable kind värdet för `{var}` måste passa variabelns typ +@msg variable `{_1}` is already defined variabeln `{_1}` är redan definierad +@msg variable `{name}` has no `trait` variabeln `{name}` har ingen `trait` +@msg variable `{name}` is already defined variabeln `{name}` är redan definierad +@msg variable `{name}` is declared twice variabeln `{name}` deklareras två gånger +@msg variable `{to}` already exists variabeln `{to}` finns redan +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version returnerade {v}; den här värden implementerar version {ABI_VERSION} +@msg vc_alloc returned 0 (out of memory) vc_alloc returnerade 0 (slut på minne) +@msg vc_alloc returned a block outside memory vc_alloc returnerade ett block utanför minnet +@msg vc_run returned error code {packed} vc_run returnerade felkoden {packed} +@msg view is required view krävs +@msg view must be one of {_1} view måste vara något av {_1} +@msg warpStyle can only edit an applied Warp effect warpStyle kan bara redigera en tillämpad Förvräng-effekt +@msg width factors must be finite breddfaktorerna måste vara ändliga +@msg width must be positive bredden måste vara positiv +@msg width out of range bredden ligger utanför tillåtet omfång +@msg width/height must be > 0 bredd/höjd måste vara > 0 +@msg width/height must be positive and within the canvas bredd/höjd måste vara positiva och inom arbetsytan +@msg x and y must be finite numbers x och y måste vara ändliga tal +@msg x and y must be given together x och y måste anges tillsammans +@msg zone needs an anchor: dock beside a panel with anchor, or in a new dock column with side (Start or End) zone behöver ett ankare: docka bredvid en panel med anchor eller i en ny dockkolumn med side (Start eller End) +@msg zoom must be positive zoom måste vara positiv diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 39ac29fa78..0f960961e2 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3,6 +3,35 @@ use super::*; const ZH: fn() -> Lang = || Lang::from_code("zh-hant").expect("zh-hant registered"); +#[test] +fn hindi_resolves_locales_and_uses_zero_one_plurals() { + let hi = Lang::from_code("hi").expect("hi registered"); + for tag in ["hi", "hi-IN", "hi_IN.UTF-8", "HI-in", "hi-Deva-IN"] { + assert_eq!(lang_from_tag(tag), Some(hi), "{tag}"); + } + assert_eq!(hi.name(), "हिन्दी"); + assert_eq!([0, 1, 2, 21, u64::MAX].map(hi.0.plural), [0, 0, 1, 1, 1]); + assert_eq!(tr(hi, "Save"), "सेव"); + assert_eq!(tr(hi, "Save As…"), "सेव ऐज़…"); + assert_eq!(tr(hi, "Path"), "पाथ"); + assert_eq!(tr(hi, "Selection"), "सिलेक्शन"); + assert_eq!(tr(hi, "Properties"), "प्रॉपर्टीज़"); + assert_eq!(tr(hi, "Options"), "ऑप्शन्स"); + assert_eq!(tr(hi, "Open"), "ओपन"); + let (entries, errors) = parse_entries(hi.0.source); + assert!(errors.is_empty(), "{errors:?}"); + for (ctx, src, translation) in entries.iter().filter(|(ctx, _, _)| ctx == "@plural" || ctx == "@msgplural") { + let (one, other) = src.split_once('|').expect("one|other source"); + let forms: Vec<_> = translation.split('|').collect(); + assert_eq!(forms.len(), 2, "{ctx}: {src}"); + if ctx == "@plural" { + for (n, index) in [(0, 0), (1, 0), (2, 1), (21, 1)] { + assert_eq!(trn(hi, n, one, other), forms[index].replace("{n}", &n.to_string())); + } + } + } +} + /// Locale tags name their language by region or script (in either case, with an encoding or /// modifier), and a tag that names no language resolves to none. #[test] @@ -404,6 +433,11 @@ fn is_georgian(c: char) -> bool { matches!(c as u32, 0x10A0..=0x10FF | 0x1C90..=0x1CBF | 0x2D00..=0x2D2F) } +#[cfg(feature = "interface-fonts")] +fn is_devanagari(c: char) -> bool { + matches!(c as u32, 0x0900..=0x097F | 0x1CD0..=0x1CFF | 0xA8E0..=0xA8FF) +} + /// The UI fonts draw every character the catalogs use, in every family the UI draws text with /// (the web build has no system fonts to fall back to). Chinese and Japanese characters come from /// the craft-fonts build input, which is optional: without it they are left to the installed @@ -416,6 +450,7 @@ fn is_georgian(c: char) -> bool { fn bundled_fonts_cover_the_catalogs() { let japanese_ui_font = vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.is_japanese()); let georgian_ui_font = vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.is_georgian()); + let devanagari_ui_font = vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.scripts.contains(&"Deva")); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); @@ -434,7 +469,12 @@ fn bundled_fonts_cover_the_catalogs() { let chars: std::collections::BTreeSet = entries .iter() .flat_map(|(_, _, tr)| tr.chars()) - .filter(|c| !c.is_whitespace() && (cjk_checked || !is_cjk(*c)) && (georgian_ui_font || !is_georgian(*c))) + .filter(|c| { + !c.is_whitespace() + && (cjk_checked || !is_cjk(*c)) + && (georgian_ui_font || !is_georgian(*c)) + && (devanagari_ui_font || !is_devanagari(*c)) + }) .collect(); for family in &families { let font = egui::FontId::new(13.0, family.clone()); @@ -1082,8 +1122,8 @@ fn cs() -> Lang { } /// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English. -const KEEPS_MENU_NAMES: [&str; 19] = - ["cs", "de", "el", "es", "fr", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca"]; +const KEEPS_MENU_NAMES: [&str; 20] = + ["cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "fi", "tr", "ca"]; /// Menu labels the menu-complete catalogs (Czech, German, Spanish, Italian, Japanese, Brazilian Portuguese) show as they are: the product name, a format name, the built-in workspace /// names and the perspective grid presets (names, shown untranslated wherever else they appear). @@ -1823,6 +1863,12 @@ fn blend_spine_param_errors_say_what_is_wrong() { ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 1e12, "y": 0}), "x and y must be finite"), ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 0, "handle": "up"}), "handle must be in or out"), ("object.blend.spine.moveAnchor", json!({"anchor": 5, "x": 0, "y": 0}), "no such spine point"), + ( + "object.blend.spine.moveAnchor", + json!({"anchor": 0, "x": 0, "y": 0, "with": "1"}), + "`with` must be a list of at most 10000 spine point indexes", + ), + ("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 0, "with": [1], "handle": "in"}), "`with` moves points, not a handle"), ("object.blend.spine.moveAnchor", json!({"id": other, "anchor": 0, "x": 0, "y": 0}), "not a blend"), ("object.blend.spine.reshapeSegment", json!({"segment": 0, "dx": 1e12}), "t, dx and dy must be finite"), ("object.blend.spine.reshapeSegment", json!({"segment": 5, "dy": 10}), "no such spine segment"), @@ -2018,8 +2064,9 @@ fn shared_param_check_errors_show_their_values_as_given() { /// Languages whose catalogs translate status and error messages; [`untranslated_report`] lists /// the messages each one lacks. -const COMPLETE_MESSAGES: &[&str] = - &["cs", "de", "el", "es", "fr", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca"]; +const COMPLETE_MESSAGES: &[&str] = &[ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca", +]; /// Crates whose error and status messages reach the status bar. const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace"]; diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a39ca73666..c296f66aa0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3115,7 +3115,9 @@ digits Malayalam Malayalam Patterns Desenler Stroke Options Kontur Seçenekleri Character: Karakter: + Paragraph: Paragraf: Character options Karakter seçenekleri + Paragraph options Paragraf seçenekleri Stroke options Kontur seçenekleri Transform options Dönüştürme seçenekleri Stroke Weight Kontur Kalınlığı @@ -3779,6 +3781,7 @@ axis Both Her İkisi @msg Create from Selection: the selection has no area Seçimden Oluştur: Seçimin alanı yok @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Veri Kurtarma'nın kopyaları saklayacak yeri yoktur: Tercihleri ayarlayın → Dosya İşleme → Veri Kurtarma → Klasör (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Veri Kurtarma kopyaları {path} konumunda saklayamıyor: {e} +@msg Plug-ins can't be loaded from {path}: {e} Eklentiler {path} konumundan yüklenemiyor: {e} @msg direct-select anchor points to cut at (not the end points of open paths) kesilecek bağlantı noktalarını doğrudan seçin (açık yolların bitiş noktalarını değil) @msg Divide Objects Below: select a path Aşağıdaki Nesneleri Böl: bir yol seçin @msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin @@ -4410,6 +4413,9 @@ axis Both Her İkisi @msg graphs come in as plain art, without their data or settings grafikler, verileri ve ayarları olmadan düz çizim olarak içe aktarılır @msg an image whose data is cut short was left out verileri kısa kesilen bir resim dışarıda bırakıldı @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel bağlantılı resimler, dosyaları bulunana kadar dosyaya kaydedilen düşük çözünürlüklü önizlemeyi gösterir: bunları Bağlantılar panelinde yeniden bağlayın +@msg linked type areas past VectorCraft's limits were left out VectorCraft sınırlarını aşan bağlantılı metin alanları dışarıda bırakıldı +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip bağlantılı alanlarda, kaydırılan metinde veya bileşik yolda maske olarak kullanılan metin kırpmaz +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel dosyada önizlemesi olmayan bağlantılı resimler, dosyaları bulunana kadar bir yer tutucu gösterir: bunları Bağlantılar panelinde yeniden bağlayın @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise çerçevelerdeki alan türü, daha uzun çerçevelerde gösterdiği yazı tipinin bir satırı için çok kısa ({_1}): bunların türü aksi halde gösterilmez @msg its editing data doesn't say where its art is düzenleme verileri sanatın nerede olduğunu söylemiyor @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) bu dosya PDF uyumluluğu olmadan kaydedildi ve düzenleme verileri okunamıyor ({why}) @@ -5426,6 +5432,8 @@ theme Appearance Görünüm @msg mask art ends outside a mask dictionary maske çizimi bir maske sözlüğünün dışında bitiyor @msg missing number `{key}` `{key}` sayısı eksik @msg no such spine point böyle bir omurga noktası yok +@msg `with` must be a list of at most 10000 spine point indexes `with` en fazla 10000 omurga noktası dizininden oluşan bir liste olmalıdır +@msg `with` moves points, not a handle `with` noktaları taşır, tutamacı değil @msg no such spine segment böyle bir omurga segmenti yok @msg not a blend bir karışım değil @msg select a blend or give `id` bir karışım seçin veya `id` belirtin @@ -6056,6 +6064,9 @@ anchor Points: Noktalar: Find Nearest Swatch… En Yakın Renk Örneğini Bul… Find Nearest Swatch En Yakın Renk Örneğini Bul Apply Nearest Swatch En Yakın Renk Örneğini Uygula +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Dolguyu Kontura Uygula + Apply Stroke to Fill Konturu Dolguya Uygula Select objects to find the swatches nearest their colors. Renklerine en yakın renk örneklerini bulmak için nesneleri seçin. @msg select objects or give `color` nesneleri seçin veya `color` verin @msg `color` is not a colour `color` bir renk değil @@ -6292,6 +6303,10 @@ breakText Glyphs Glifler Bow Yay Spike Sivri Uç Skip Spaces Boşlukları Atla + Release Type on a Path… Yoldaki Metni Ayır… + Release Type on a Path Yoldaki Metni Ayır + Text and Path Metin ve yol + Path Only Yalnızca yol @msg The art is too large to copy as a picture: other apps get no PNG of it Çizim, resim olarak kopyalanamayacak kadar büyük: diğer uygulamalar bunun PNG'sini almaz # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6303,3 +6318,43 @@ breakText Glyphs Glifler Fully Outside Tamamen dışarıda No artboards match. Eşleşen çalışma yüzeyi yok. Chosen: {n} of {total} Seçilen: {n}/{total} + +# Contour add-on + Contour Dış Hat + Contour Tool Dış Hat Aracı + Sharp Keskin + Bake Genişlet + Turn the Contour into plain paths Dış hattı sade yollara dönüştürür + Set Corners… Köşeleri Ayarla… + All Anchors Tüm Çapalar + Odd-Numbered Anchors Tek Numaralı Çapalar + Even-Numbered Anchors Çift Numaralı Çapalar + Minimum angle En Küçük Açı + Maximum angle En Büyük Açı + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Bağlantılıları Seç + Select Embedded Gömülüleri Seç + Select Missing Eksikleri Seç + Select Modified Değiştirilenleri Seç + Select by Link Status Bağlantı Durumuna Göre Seç + Select by Link Status… Bağlantı Durumuna Göre Seç… + Search images Görüntülerde ara + No images match. Eşleşen görüntü yok. +@msgplural Selected {n} linked image|Selected {n} linked images {n} bağlantılı görüntü seçildi +@msgplural Selected {n} embedded image|Selected {n} embedded images {n} gömülü görüntü seçildi +@msgplural Selected {n} missing image|Selected {n} missing images {n} eksik görüntü seçildi +@msgplural Selected {n} modified image|Selected {n} modified images {n} değiştirilmiş görüntü seçildi +@msgplural Selected {n} image|Selected {n} images {n} görüntü seçildi +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; {n} tane daha gizli veya kilitli +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; {n} tane daha şablon katmanında +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; {n} tane daha izole grubun dışında +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; {n} tane daha şu anda seçilemiyor + +# Compound Shapes add-on + Compound Shapes Bileşik Şekiller + Shape Mode Buttons Make Compound Shapes Şekil Modu Düğmeleri Bileşik Şekiller Yapar + +# 3D Box add-on + 3D Box 3B Kutu + 3D Box Tool 3B Kutu Aracı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 81be50a597..5f823ba124 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3320,7 +3320,9 @@ effect Points Точки Patterns Візерунки Stroke Options Параметри обведення Character: Символ: + Paragraph: Абзац: Character options Параметри символу + Paragraph options Параметри абзацу Stroke options Параметри обведення Transform options Параметри трансформування Stroke Weight Товщина обведення @@ -4010,6 +4012,7 @@ axis Both Обидві @msg Create from Selection: the selection has no area Створення з виділення: виділення немає області @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Відновлення даних ніде зберігати копії: задайте Установки → Робота з файлами → Відновлення даних → Папка (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Відновлення даних не може зберігати копії в {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Не вдається завантажити модулі з {path}: {e} @msg direct-select anchor points to cut at (not the end points of open paths) виділіть прямим виділенням опорні точки для розрізу (не кінцеві точки відкритих контурів) @msg Divide Objects Below: select a path Поділ об’єктів нижче: виділіть контур @msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур @@ -4355,6 +4358,8 @@ axis Both Обидві @msg no such saved selection такого збереженого виділення немає @msg no such segment такого сегменту немає @msg no such spine point такої точки осі немає +@msg `with` must be a list of at most 10000 spine point indexes `with` має бути списком щонайбільше з 10000 індексів точок осі +@msg `with` moves points, not a handle `with` переміщує точки, а не маркер @msg no such spine segment такого сегмента осі немає @msg no such subpath такого вкладеного контуру немає @msg no such user library такої користувацької бібліотеки немає @@ -4700,6 +4705,9 @@ axis Both Обидві @msg graphs come in as plain art, without their data or settings діаграми імпортуються як звичайна графіка, без їхніх даних і налаштувань @msg an image whose data is cut short was left out зображення з обрізаними даними пропущено @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel пов’язані зображення показуються як збережений у файлі перегляд низької роздільності, доки їхні файли не знайдено: відновіть зв’язки на панелі «Зв’язки» +@msg linked type areas past VectorCraft's limits were left out пов’язані текстові області понад обмеження VectorCraft пропущено +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, використаний як маска у пов’язаних областях, тексті з обтіканням або складеному контурі, не обрізає +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel пов’язані зображення без перегляду у файлі показуються як заповнювач, доки їхні файли не знайдено: відновіть зв’язки на панелі «Зв’язки» @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise текст в області в рамках, занизьких для рядка шрифту, яким він показується, отримав вищі рамки ({_1}): інакше його не було б видно @msg its editing data doesn't say where its art is у даних редагування не зазначено, де знаходиться графіка @msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) цей файл збережений без сумісності з PDF, і його дані редагування не вдається прочитати ({why}) @@ -5698,6 +5706,9 @@ anchor Points: Точки: Find Nearest Swatch… Знайти найближчий зразок… Find Nearest Swatch Знайти найближчий зразок Apply Nearest Swatch Застосувати найближчий зразок +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Застосувати заливку до обведення + Apply Stroke to Fill Застосувати обведення до заливки Select objects to find the swatches nearest their colors. Виділіть об’єкти, щоб знайти зразки, найближчі до їхніх кольорів. @msg select objects or give `color` виділіть об’єкти або вкажіть `color` @msg `color` is not a colour `color` не є кольором @@ -5935,6 +5946,10 @@ breakText Glyphs Гліфи Bow Дуга Spike Пік Skip Spaces Пропускати пробіли + Release Type on a Path… Звільнити текст за контуром… + Release Type on a Path Звільнити текст за контуром + Text and Path Текст і контур + Path Only Лише контур @msg The art is too large to copy as a picture: other apps get no PNG of it Графіка завелика, щоб скопіювати її як зображення: інші програми не отримають її PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5946,3 +5961,43 @@ breakText Glyphs Гліфи Fully Outside Повністю зовні No artboards match. Немає відповідних монтажних областей. Chosen: {n} of {total} Вибрано: {n} з {total} + +# Contour add-on + Contour Еквідистанта + Contour Tool Інструмент «Еквідистанта» + Sharp Гострий + Bake Розібрати + Turn the Contour into plain paths Перетворює еквідистанту на звичайні контури + Set Corners… Задати кути… + All Anchors Усі опорні точки + Odd-Numbered Anchors Непарні опорні точки + Even-Numbered Anchors Парні опорні точки + Minimum angle Мінімальний кут + Maximum angle Максимальний кут + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Виділити пов’язані + Select Embedded Виділити вбудовані + Select Missing Виділити відсутні + Select Modified Виділити змінені + Select by Link Status Виділити за станом зв’язку + Select by Link Status… Виділити за станом зв’язку… + Search images Пошук зображень + No images match. Немає відповідних зображень. +@msgplural Selected {n} linked image|Selected {n} linked images Виділено {n} пов’язане зображення|Виділено {n} пов’язані зображення|Виділено {n} пов’язаних зображень +@msgplural Selected {n} embedded image|Selected {n} embedded images Виділено {n} вбудоване зображення|Виділено {n} вбудовані зображення|Виділено {n} вбудованих зображень +@msgplural Selected {n} missing image|Selected {n} missing images Виділено {n} відсутнє зображення|Виділено {n} відсутні зображення|Виділено {n} відсутніх зображень +@msgplural Selected {n} modified image|Selected {n} modified images Виділено {n} змінене зображення|Виділено {n} змінені зображення|Виділено {n} змінених зображень +@msgplural Selected {n} image|Selected {n} images Виділено {n} зображення|Виділено {n} зображення|Виділено {n} зображень +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; ще {n} приховане або заблоковане|{selected}; ще {n} приховані або заблоковані|{selected}; ще {n} приховані або заблоковані +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; ще {n} на шарі-шаблоні|{selected}; ще {n} на шарах-шаблонах|{selected}; ще {n} на шарах-шаблонах +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою|{selected}; ще {n} поза ізольованою групою +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити|{selected}; ще {n} зараз не можна виділити + +# Compound Shapes add-on + Compound Shapes Складені фігури + Shape Mode Buttons Make Compound Shapes Кнопки режимів фігур створюють складені фігури + +# 3D Box add-on + 3D Box 3D-паралелепіпед + 3D Box Tool Інструмент «3D-паралелепіпед» diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 66ad83aea3..7d157502cf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -468,12 +468,14 @@ font-technology Variable Biến thiên Character / Paragraph Ký tự / Đoạn văn Character Alignment Căn chỉnh ký tự Character options Tùy chọn ký tự + Paragraph options Tùy chọn đoạn văn Character Rotation Xoay ký tự Character Set: Bộ ký tự: Character Style Kiểu ký tự Character Style Options Tùy chọn kiểu ký tự Character Styles Các kiểu ký tự Character: Ký tự: + Paragraph: Đoạn văn: Check Links Kiểm tra liên kết # Check Script (File › Scripts) and the report it shows on a script written for the reference app. Check Script Kiểm tra script @@ -4427,6 +4429,7 @@ theme Appearance Giao diện @msg damaged bị hỏng @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Phục hồi dữ liệu không có nơi lưu bản sao: đặt Tùy chọn → Xử lý tệp → Phục hồi dữ liệu → Thư mục (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} Phục hồi dữ liệu không thể lưu bản sao vào {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Không thể tải plug-in từ {path}: {e} @msg decimals must be {_1}–{_2} (got {_3}) số thập phân phải từ {_1}–{_2} (nhận được {_3}) @msg direct-select anchor points to cut at (not the end points of open paths) chọn trực tiếp các điểm neo để cắt (không phải điểm cuối của đường dẫn mở) @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Đã loại bỏ {n} tài liệu đã phục hồi @@ -4534,6 +4537,9 @@ theme Appearance Giao diện @msg line {line}: value for `{var}` must be true or false dòng {line}: giá trị của `{var}` phải là true hoặc false @msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes dòng {line}: giá trị của `{var}` dài hơn {MAX_GRAPH_CSV} byte @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel ảnh liên kết hiển thị bản xem trước độ phân giải thấp đã lưu trong tệp cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết +@msg linked type areas past VectorCraft's limits were left out các vùng chữ liên kết vượt quá giới hạn của VectorCraft đã bị bỏ qua +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip chữ dùng làm mặt nạ trong các vùng liên kết, chữ bao quanh hoặc đường dẫn phức không cắt xén +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel ảnh liên kết không có bản xem trước trong tệp hiển thị ô giữ chỗ cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết @msg Live Paint Merge: select a Live Paint group and the paths to add Hợp nhất tô trực tiếp: chọn nhóm tô trực tiếp và các đường dẫn để thêm @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first Tô trực tiếp nhận đường dẫn và đường dẫn phức: hãy chuyển văn bản, hình ảnh và các đối tượng khác thành đường dẫn trước @msg Live Paint: select paths or compound paths Tô trực tiếp: chọn đường dẫn hoặc đường dẫn phức @@ -4655,6 +4661,8 @@ theme Appearance Giao diện @msg no such saved selection không có vùng chọn đã lưu như vậy @msg no such segment không có đoạn như vậy @msg no such spine point không có điểm trục như vậy +@msg `with` must be a list of at most 10000 spine point indexes `with` phải là danh sách tối đa 10000 chỉ số điểm trục +@msg `with` moves points, not a handle `with` di chuyển các điểm, không phải tay nắm @msg no such spine segment không có đoạn trục như vậy @msg no such subpath không có nhánh con như vậy @msg no such user library không có thư viện người dùng như vậy @@ -5699,6 +5707,9 @@ anchor Points: Điểm: Find Nearest Swatch… Tìm mẫu màu gần nhất… Find Nearest Swatch Tìm mẫu màu gần nhất Apply Nearest Swatch Áp dụng mẫu màu gần nhất +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke Áp dụng màu tô cho nét + Apply Stroke to Fill Áp dụng nét cho màu tô Select objects to find the swatches nearest their colors. Chọn đối tượng để tìm các mẫu màu gần nhất với màu của chúng. @msg select objects or give `color` chọn đối tượng hoặc cung cấp `color` @msg `color` is not a colour `color` không phải là màu @@ -5936,6 +5947,10 @@ breakText Glyphs Glyph Bow Cung Spike Đỉnh nhọn Skip Spaces Bỏ qua khoảng trắng + Release Type on a Path… Giải phóng chữ trên đường dẫn… + Release Type on a Path Giải phóng chữ trên đường dẫn + Text and Path Văn bản và đường dẫn + Path Only Chỉ đường dẫn @msg The art is too large to copy as a picture: other apps get no PNG of it Hình vẽ quá lớn để sao chép dưới dạng ảnh: các ứng dụng khác không nhận được PNG của nó # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5947,3 +5962,43 @@ breakText Glyphs Glyph Fully Outside Hoàn toàn bên ngoài No artboards match. Không có bảng vẽ nào khớp. Chosen: {n} of {total} Đã chọn: {n} trên {total} + +# Contour add-on + Contour Đường viền + Contour Tool Công cụ Đường viền + Sharp Nhọn + Bake Mở rộng + Turn the Contour into plain paths Chuyển đường viền thành các đường dẫn thường + Set Corners… Đặt góc… + All Anchors Tất cả điểm neo + Odd-Numbered Anchors Điểm neo số lẻ + Even-Numbered Anchors Điểm neo số chẵn + Minimum angle Góc tối thiểu + Maximum angle Góc tối đa + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked Chọn ảnh đã liên kết + Select Embedded Chọn ảnh đã nhúng + Select Missing Chọn ảnh bị thiếu + Select Modified Chọn ảnh đã sửa đổi + Select by Link Status Chọn theo trạng thái liên kết + Select by Link Status… Chọn theo trạng thái liên kết… + Search images Tìm ảnh + No images match. Không có ảnh nào khớp. +@msgplural Selected {n} linked image|Selected {n} linked images Đã chọn {n} ảnh đã liên kết +@msgplural Selected {n} embedded image|Selected {n} embedded images Đã chọn {n} ảnh đã nhúng +@msgplural Selected {n} missing image|Selected {n} missing images Đã chọn {n} ảnh bị thiếu +@msgplural Selected {n} modified image|Selected {n} modified images Đã chọn {n} ảnh đã sửa đổi +@msgplural Selected {n} image|Selected {n} images Đã chọn {n} ảnh +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected}; thêm {n} ảnh bị ẩn hoặc khóa +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected}; thêm {n} ảnh nằm trên lớp mẫu +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected}; thêm {n} ảnh nằm ngoài nhóm đã tách biệt +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected}; thêm {n} ảnh hiện không thể chọn + +# Compound Shapes add-on + Compound Shapes Hình phức hợp + Shape Mode Buttons Make Compound Shapes Nút chế độ hình dạng tạo hình phức hợp + +# 3D Box add-on + 3D Box Hộp 3D + 3D Box Tool Công cụ Hộp 3D diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d134298ebe..643b922180 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1883,6 +1883,8 @@ file-filter Templates 模板 @msg the blend has no spine 混合对象没有脊线 @msg the spine has no segments 脊线没有线段 @msg no such spine point 没有此脊线点 +@msg `with` must be a list of at most 10000 spine point indexes `with` 必须是最多 10000 个脊线点索引的列表 +@msg `with` moves points, not a handle `with` 移动的是点,不是手柄 @msg no such spine segment 没有此脊线线段 @msg a key object sits on that point 该点上有关键对象 @msg a spine keeps at least two points 脊线至少保留两个点 @@ -3158,7 +3160,9 @@ digits Malayalam 马拉雅拉姆数字 Patterns 图案 Stroke Options 描边选项 Character: 字符: + Paragraph: 段落: Character options 字符选项 + Paragraph options 段落选项 Stroke options 描边选项 Transform options 变换选项 Stroke Weight 描边粗细 @@ -3464,6 +3468,9 @@ digits Malayalam 马拉雅拉姆数字 Update Changed Links 更新已更改的链接 @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 个链接图像已在磁盘上更改。要显示新版本吗? @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 链接的图片在找到其文件之前显示文件中存储的低分辨率预览:请在“链接”面板中重新链接 +@msg linked type areas past VectorCraft's limits were left out 超出 VectorCraft 限制的串接文字区域已省略 +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 在串接区域、绕排文字或复合路径中用作蒙版的文字不会剪切 +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 文件中没有预览的链接图片在找到其文件之前显示占位符:请在“链接”面板中重新链接 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容纳所显示字体一行的区域文字已加高框架 ({_1}):否则文字不会显示 Update Modified Links 更新已修改的链接 UPPERCASE 大写 @@ -4047,6 +4054,7 @@ imageTrace Outline 轮廓 @msg unknown preference `{key}` 未知首选项 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 数据恢复没有可保存副本的位置:请设置“首选项 → 文件处理 → 数据恢复 → 文件夹” (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 数据恢复无法将副本保存到 {path}:{e} +@msg Plug-ins can't be loaded from {path}: {e} 无法从 {path} 载入增效工具:{e} @msg `{area}` is no recovery area name `{area}` 不是恢复区域名称 @msg `{name}` is no recovery entry name `{name}` 不是恢复条目名称 @msg no clock to keep a heartbeat by 没有可用于维持心跳的时钟 @@ -5940,6 +5948,9 @@ anchor Points: 点: Find Nearest Swatch… 查找最接近的色板… Find Nearest Swatch 查找最接近的色板 Apply Nearest Swatch 应用最接近的色板 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 将填色应用于描边 + Apply Stroke to Fill 将描边应用于填色 Select objects to find the swatches nearest their colors. 选择对象以查找与其颜色最接近的色板。 @msg select objects or give `color` 请选择对象或提供 `color` @msg `color` is not a colour `color` 不是颜色 @@ -6176,6 +6187,10 @@ breakText Glyphs 字形 Bow 弓形 Spike 尖峰 Skip Spaces 跳过空格 + Release Type on a Path… 释放路径文字… + Release Type on a Path 释放路径文字 + Text and Path 文字和路径 + Path Only 仅路径 @msg The art is too large to copy as a picture: other apps get no PNG of it 图稿太大,无法作为图片复制:其他应用不会获得它的 PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -6187,3 +6202,43 @@ breakText Glyphs 字形 Fully Outside 完全在外 No artboards match. 没有匹配的画板。 Chosen: {n} of {total} 已选:{n} / {total} + +# Contour add-on + Contour 轮廓 + Contour Tool 轮廓工具 + Sharp 尖角 + Bake 扩展 + Turn the Contour into plain paths 将轮廓转为普通路径 + Set Corners… 设置转角… + All Anchors 所有锚点 + Odd-Numbered Anchors 奇数锚点 + Even-Numbered Anchors 偶数锚点 + Minimum angle 最小角度 + Maximum angle 最大角度 + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 选择已链接 + Select Embedded 选择嵌入 + Select Missing 选择缺失 + Select Modified 选择已修改 + Select by Link Status 按链接状态选择 + Select by Link Status… 按链接状态选择… + Search images 搜索图像 + No images match. 没有匹配的图像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已选择 {n} 个已链接的图像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已选择 {n} 个嵌入的图像 +@msgplural Selected {n} missing image|Selected {n} missing images 已选择 {n} 个缺失的图像 +@msgplural Selected {n} modified image|Selected {n} modified images 已选择 {n} 个已修改的图像 +@msgplural Selected {n} image|Selected {n} images 已选择 {n} 个图像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 个已隐藏或锁定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 个位于模板图层上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 个位于隔离的编组之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 个现在无法选择 + +# Compound Shapes add-on + Compound Shapes 复合形状 + Shape Mode Buttons Make Compound Shapes 形状模式按钮创建复合形状 + +# 3D Box add-on + 3D Box 3D 盒子 + 3D Box Tool 3D 盒子工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b2bbeec797..945626915d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1933,6 +1933,7 @@ file-filter Templates 範本 @msg unknown preference `{key}` 未知的偏好設定 `{key}` @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) 「資料復原」沒有可存放拷貝的位置:請設定「偏好設定 → 檔案處理 → 資料復原 → 資料夾」 (recoveryFolder) @msg Data Recovery can't keep copies in {path}: {e} 「資料復原」無法將拷貝存放到 {path}:{e} +@msg Plug-ins can't be loaded from {path}: {e} 無法從 {path} 載入增效模組:{e} @msg `{area}` is no recovery area name `{area}` 不是復原區域名稱 @msg `{name}` is no recovery entry name `{name}` 不是復原項目名稱 @msg no clock to keep a heartbeat by 沒有可用來維持心跳的時鐘 @@ -2855,6 +2856,8 @@ file-filter Templates 範本 @msg the blend has no spine 漸變物件沒有脊線 @msg the spine has no segments 脊線沒有線段 @msg no such spine point 沒有這個脊線點 +@msg `with` must be a list of at most 10000 spine point indexes `with` 必須是最多 10000 個脊線點索引的清單 +@msg `with` moves points, not a handle `with` 移動的是點,不是控制把手 @msg no such spine segment 沒有這個脊線線段 @msg a key object sits on that point 該點上有關鍵物件 @msg a spine keeps at least two points 脊線至少要保留兩個點 @@ -4184,7 +4187,9 @@ digits Malayalam 馬來亞拉姆數字 Patterns 圖樣 Stroke Options 筆畫選項 Character: 字元: + Paragraph: 段落: Character options 字元選項 + Paragraph options 段落選項 Stroke options 筆畫選項 Transform options 變形選項 Stroke Weight 筆畫寬度 @@ -4493,6 +4498,9 @@ digits Malayalam 馬來亞拉姆數字 Update Changed Links 更新已變更的連結 @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 個連結影像已在磁碟上變更。要顯示新版本嗎? @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 連結的圖片在找到其檔案之前顯示檔案中儲存的低解析度預覽:請在「連結」面板中重新連結 +@msg linked type areas past VectorCraft's limits were left out 超出 VectorCraft 限制的串連文字區域已略過 +@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 在串連區域、繞圖文字或複合路徑中用作遮色片的文字不會剪裁 +@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 檔案中沒有預覽的連結圖片在找到其檔案之前顯示預留位置:請在「連結」面板中重新連結 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 框架高度不足以容納所顯示字體一行的區域文字已加高框架 ({_1}):否則文字不會顯示 Update Modified Links 更新已修改的連結 UPPERCASE 全部大寫 @@ -5736,6 +5744,9 @@ anchor Points: 點: Find Nearest Swatch… 尋找最接近的色票… Find Nearest Swatch 尋找最接近的色票 Apply Nearest Swatch 套用最接近的色票 +# Color Effects add-on: Apply Fill to Stroke and Apply Stroke to Fill (Object › Plug-ins › Color Effects, #5530). + Apply Fill to Stroke 將填色套用至筆畫 + Apply Stroke to Fill 將筆畫套用至填色 Select objects to find the swatches nearest their colors. 選取物件以尋找與其顏色最接近的色票。 @msg select objects or give `color` 請選取物件或提供 `color` @msg `color` is not a colour `color` 不是顏色 @@ -5973,6 +5984,10 @@ breakText Glyphs 字符 Bow 弓形 Spike 尖峰 Skip Spaces 略過空格 + Release Type on a Path… 釋放路徑文字… + Release Type on a Path 釋放路徑文字 + Text and Path 文字和路徑 + Path Only 僅路徑 @msg The art is too large to copy as a picture: other apps get no PNG of it 圖稿太大,無法作為圖片複製:其他應用程式不會取得它的 PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). @@ -5984,3 +5999,43 @@ breakText Glyphs 字符 Fully Outside 完全在外 No artboards match. 沒有符合的工作區域。 Chosen: {n} of {total} 已選:{n} / {total} + +# Contour add-on + Contour 輪廓 + Contour Tool 輪廓工具 + Sharp 尖角 + Bake 展開 + Turn the Contour into plain paths 將輪廓轉為一般路徑 + Set Corners… 設定轉角… + All Anchors 所有錨點 + Odd-Numbered Anchors 奇數錨點 + Even-Numbered Anchors 偶數錨點 + Minimum angle 最小角度 + Maximum angle 最大角度 + +# Selection Tools add-on: Select by Link Status (Object › Plug-ins › Selection Tools, the Links panel menu, #5526). + Select Linked 選取已連結 + Select Embedded 選取已內嵌 + Select Missing 選取遺失 + Select Modified 選取已修改 + Select by Link Status 依連結狀態選取 + Select by Link Status… 依連結狀態選取… + Search images 搜尋影像 + No images match. 沒有符合的影像。 +@msgplural Selected {n} linked image|Selected {n} linked images 已選取 {n} 個已連結的影像 +@msgplural Selected {n} embedded image|Selected {n} embedded images 已選取 {n} 個已內嵌的影像 +@msgplural Selected {n} missing image|Selected {n} missing images 已選取 {n} 個遺失的影像 +@msgplural Selected {n} modified image|Selected {n} modified images 已選取 {n} 個已修改的影像 +@msgplural Selected {n} image|Selected {n} images 已選取 {n} 個影像 +@msgplural {selected}; {n} more is hidden or locked|{selected}; {n} more are hidden or locked {selected};另有 {n} 個已隱藏或鎖定 +@msgplural {selected}; {n} more is on a template layer|{selected}; {n} more are on template layers {selected};另有 {n} 個位於範本圖層上 +@msgplural {selected}; {n} more is outside the isolated group|{selected}; {n} more are outside the isolated group {selected};另有 {n} 個位於隔離的群組之外 +@msgplural {selected}; {n} more can't be selected now|{selected}; {n} more can't be selected now {selected};另有 {n} 個現在無法選取 + +# Compound Shapes add-on + Compound Shapes 複合形狀 + Shape Mode Buttons Make Compound Shapes 形狀模式按鈕製作複合形狀 + +# 3D Box add-on + 3D Box 3D 盒子 + 3D Box Tool 3D 盒子工具 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 579df2187b..78eb6149d1 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -60,6 +60,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-center-show", include_bytes!("../../../assets/icons/dc-center-show.svg")), ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), + ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), ("dc-crystallize", include_bytes!("../../../assets/icons/dc-crystallize.svg")), ("dc-cube", include_bytes!("../../../assets/icons/dc-cube.svg")), ("dc-dash-align", include_bytes!("../../../assets/icons/dc-dash-align.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index a3601af18d..e352653279 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -85,6 +85,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-eyedropper" => "pipette", "tool-measure" => "dc-measure", "tool-dimension" => "dc-dimension", + "tool-contour" => "dc-contour", "tool-blend" => "dc-blend", "tool-objects-on-path" => "dc-objects-on-path", "tool-symbol" => "dc-symbol-sprayer", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bdfcaffffa..afb8cbbc4b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -126,6 +126,10 @@ pub struct VectorcraftApp { pub session: Session, pub ui: UiState, pub views: Vec, + /// The document ([`vectorcraft_engine::DocState::uid`]) each of `views` belonged to at the last + /// [`VectorcraftApp::sync_views`], which puts the views back with their documents after + /// `document.move` reorders them (#5663). + pub(crate) view_uids: Vec, pub services: Services, pub canvas: CanvasCache, pub perf: Perf, @@ -147,6 +151,13 @@ pub struct VectorcraftApp { /// moves ([`native_menu::sync`]). run_count: u64, control_rx: Option>, + /// A `ui.pointer` request taken from the channel while synthetic input sent before it was not + /// yet applied: it runs, ahead of the channel, on the first frame after that input is applied. + deferred_control: Option, + /// When synthetic input was last dropped before a UI pass took it, the sequence number of the + /// next control request ([`ControlRequest::next_seq`]): a `ui.pointer` request made before it + /// came after that input and is answered with an error. + synthetic_dropped_before: u64, /// Window captures asked for and not answered yet. pending_screenshots: Vec, /// Admitted captures whose settled frame has not come yet (issued one at a time). diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a419204162..dff97c9a55 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -58,12 +58,15 @@ mod tree; mod ui_commands; pub use bar::menu_bar; +pub(crate) use bar::menu_open; pub(crate) use bar::{home_key, home_showing}; #[cfg(test)] use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; pub use entries::{MenuEntry, Row, context_entries, entry, menu_entries, pretty_shortcut, shown_shortcut}; pub(crate) use invoke::graph_dialog; +#[cfg(test)] +pub(crate) use invoke::with_held_keys; pub use invoke::{click_target, invoke, invoke_from_system_menu}; #[cfg(test)] pub(crate) use labels::lists_plugin; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index a0e4e0d6ac..1d8d001975 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -42,6 +42,10 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { (ui.cursor().min.x, switch_on_hover(ui.ctx(), &titles)) }) .inner; + // Whether a top-level menu is open: the docking renderer lowers the floating panels' OS windows + // while one is, or the menu would open under them. + ctx.data_mut(|d| d.insert_temp(menu_open_id(), open)); + let field = ctx.data(|d| d.get_temp::(field_key)); if !open && focused_text_field(&ctx).is_none() { ctx.data_mut(|d| d.remove::(field_key)); @@ -58,6 +62,16 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { end } +/// Where the menu bar keeps whether one of its top-level menus is open. +fn menu_open_id() -> egui::Id { + egui::Id::unique("menu-bar-open") +} + +/// Whether a menu of the in-window menu bar is open (`false` when no menu bar was drawn yet). +pub(crate) fn menu_open(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::(menu_open_id())).unwrap_or(false) +} + /// Whether the pointer at `p` is really over the menu title `title`: inside it, and with no /// popup above it (a tall menu that egui moves up can cover the bar; hovering that menu must /// not switch to the title under it). diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 18e77b792e..5b0d0f3c40 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -15,10 +15,13 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups -/// that hold the selected objects (`scope: "group"`). -pub(super) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { +/// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified +/// chosen with Shift add to the selection (`add: true`). +pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + // Select Linked, Embedded, Missing and Modified with Shift add to the selection. + crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, } } @@ -68,6 +71,9 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) } "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), + crate::addons::pathtools::set_corners::COMMAND => { + (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) + } crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 2d134f76f8..47ecead548 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -494,6 +494,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.task_bar), + "window.pathfinder.compoundShapes" => flag(&mut app.ui.shape_modes_compound), "window.taskBar.pin" => { let place = &mut app.ui.task_bar_place; opt_bool(p, "pinned").map(|pinned| { @@ -577,6 +578,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), + crate::addons::select::link_status::COMMAND => crate::addons::select::link_status::run(app, p), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), crate::addons::document::EXPORT_ALL => crate::addons::document::export_all(app, p), crate::addons::document::BATCH_TRACE => crate::addons::document::batch_trace(app, p), @@ -705,6 +707,7 @@ fn run_ui_part8(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::tile_edge_color::open(app), "ui.layerOptions" => crate::dialogs::layer_options::open(app, p), + "ui.rename" => crate::panels::layers::rename(app, p), "ui.newLayer" => crate::dialogs::layer_options::open_new(app, p), "ui.newArtboard" => crate::dialogs::artboard_options::open_new(app), "ui.layersPanelOptions" => crate::dialogs::layers_panel_options::open(app), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 2dd1051b12..78553cc7bd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -79,6 +79,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { crate::toolbar::strips(&app.ui, toolbar).iter().any(|f| f.tools.iter().any(|id| id == tool)) } "window.taskBar" => app.ui.task_bar, + "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); @@ -134,7 +135,7 @@ fn swapped_out(app: &VectorcraftApp, id: &str) -> bool { /// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]) or an item /// another stands in for ([`swapped_out`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { - let en = enabled(app, id); + let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)); if (!en && hidden_when_disabled(id)) || swapped_out(app, id) { return None; } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index a3bda35231..52f8f8473a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -523,6 +523,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ), ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), ("window.taskBar", "Contextual Task Bar", "", "{}"), + ( + "window.pathfinder.compoundShapes", + "Shape Mode Buttons Make Compound Shapes", + "", + "{} toggles the Compound Shapes add-on's setting: on, the Pathfinder panel's Shape Mode buttons make a compound shape and Alt-click gives the permanent Pathfinder result; off (the default), the other way round. Members of a compound shape selected always take the mode", + ), ( "window.taskBar.pin", "Pin Bar Position", @@ -777,7 +783,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil and paintbrush, the same at any zoom; pt for smooth and blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -849,6 +855,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", ), + ( + "ui.rename", + "Rename", + "", + "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, or a row the panel's search, filter or Show Layers Only hides, is an error and nothing opens → {id, name}", + ), ( "ui.newLayer", "New Layer Options…", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index cc177a4de1..ff39d90cff 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -270,6 +270,28 @@ pub(crate) fn showing(ui: &UiState, panel: &str) -> bool { (ui.open_panel.as_deref() == Some(panel) && iconic) || (!iconic && layout.panel_state(&panel.to_string()) == craft_ui::docking::PanelState::Front) } +/// Can either panel that uses row thumbnails be seen, including in a floating window or flyout? +/// An iconic group's open flyout is named for the icon that opened it; its active tab can differ. +fn thumbnail_panel_showing(ui: &UiState, ctx: &egui::Context) -> bool { + if !ui.dock || ui.screen_mode >= 3 { + return false; + } + let layout = layout_of(ui); + let regular = ["layers", "links"] + .iter() + .any(|panel| !in_iconic_column(&layout, panel) && layout.panel_state(&(*panel).to_string()) == craft_ui::docking::PanelState::Front); + let flyout = craft_ui::docking::flyout::(ctx, area_id()); + let iconic = flyout.as_ref().and_then(|anchor| { + dock_columns(&layout) + .into_iter() + .filter(|column| column.iconic) + .flat_map(|column| &column.groups) + .find(|group| group.panels.contains(anchor)) + .and_then(|group| group.active_panel()) + }); + regular || iconic.is_some_and(|panel| matches!(panel.as_str(), "layers" | "links")) +} + /// Where a panel with no other destination goes: a panel of the first expanded dock column, /// else of any column. fn first_dock_panel(layout: &Layout, except: &str) -> Option { @@ -1113,6 +1135,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { } } let modal = modal_open(app, &ctx); + // Palette windows are OS windows of their own, held above the app's window while it is active, + // so a dialog or a menu drawn in the main window would be covered by them. + #[cfg(not(target_arch = "wasm32"))] + palette_window_levels(&ctx, &layout, modal, egui::Popup::is_any_open(&ctx) || crate::menus::menu_open(&ctx)); let mut blocked = Vec::new(); if modal || egui::Popup::is_any_open(&ctx) { blocked.push(ctx.content_rect()); @@ -1169,11 +1195,64 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.open_dropped_files(window.dropped, None, shift); } forward_keys(app, &ctx, output.forwarded_events, output.forwarded_modifiers); + if !thumbnail_panel_showing(&app.ui, &ctx) { + // No panel can ask for these rows again this pass. Keep the cache of open documents, but + // discard worker jobs queued behind the one already rendering. + crate::panels::layers::show_thumbs_of(None); + } } /// Whether a modal is open: a dialog, About, the command palette, a native file dialog, or a /// window behind the modal backdrop last frame (export progress, plug-in runs). Floating panels /// in OS windows of their own take no input meanwhile, as the main window behind it takes none. +/// The window level and visibility a palette window takes: hidden under a modal dialog (a click +/// must not bring it back over the dialog), at the normal level under a menu or another popup drawn +/// in the main window (so the menu is seen), and otherwise its palette level, which craft-ui leaves +/// a palette at when it creates one: topmost while the app is active, behind other applications' +/// windows while it is not. +#[cfg(not(target_arch = "wasm32"))] +fn palette_window_state(modal: bool, popup: bool, active: bool) -> (egui::WindowLevel, bool) { + if modal { + return (egui::WindowLevel::Normal, false); + } + if popup { + // Hidden as under a dialog: a menu is drawn in the main window, and lowering a palette + // window is not always enough for it to go behind the window (the OS may keep it above + // while the app is activated through it). + return (egui::WindowLevel::Normal, false); + } + let level = if active { + egui::WindowLevel::AlwaysOnTop + } else if cfg!(target_os = "windows") { + egui::WindowLevel::AlwaysOnBottom + } else { + egui::WindowLevel::Normal + }; + (level, true) +} + +/// Sends the palette windows of `layout` the level and visibility [`palette_window_state`] gives +/// when they change. craft-ui varies a palette's level through the viewport builder, which egui +/// applies when the window opens and not to one already on screen, so the commands go explicitly to +/// the windows there are. +#[cfg(not(target_arch = "wasm32"))] +fn palette_window_levels(ctx: &egui::Context, layout: &Layout, modal: bool, popup: bool) { + let active = ctx.input(|i| i.focused || i.raw.viewports.values().any(|v| v.focused == Some(true))); + let key = area_id().with("palette-levels-state"); + if ctx.data(|d| d.get_temp::<(bool, bool, bool)>(key)) == Some((modal, popup, active)) { + return; + } + ctx.data_mut(|d| d.insert_temp(key, (modal, popup, active))); + + let (level, visible) = palette_window_state(modal, popup, active); + for window in &layout.floating { + let viewport = craft_ui::docking::DockArea::::window_viewport(area_id(), window.id); + ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::WindowLevel(level)); + ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::Visible(visible)); + } +} + +/// Does a modal dialog block the app's other windows ([`modal_open`] for the docking renderer)? pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { app.ui.dialog.is_some() || app.ui.about diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 77e3d08bc6..a7c6614044 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -34,6 +34,9 @@ struct Host { child_transition_overlay: Option<(ViewportId, Rect, bool)>, child_empty_overlay: Option<(ViewportId, Rect)>, child_pass_through_overlay: Option<(ViewportId, Rect)>, + child_raise_overlay: Option<(ViewportId, Rect, bool)>, + child_raise_layer: Option<(ViewportId, egui::LayerId)>, + child_layer_order: HashMap>, /// The window with the keyboard. focus: ViewportId, time: f64, @@ -98,8 +101,23 @@ impl Host { host.borrow().child_transition_overlay.filter(|(viewport, _, _)| *viewport == id).map(|(_, rect, painted)| (rect, painted)); let child_empty_overlay = host.borrow().child_empty_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); let child_pass_through_overlay = host.borrow().child_pass_through_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); + let child_raise_overlay = host.borrow().child_raise_overlay.filter(|(viewport, _, _)| *viewport == id).map(|(_, rect, raise)| (rect, raise)); + let child_raise_layer = host.borrow().child_raise_layer.filter(|(viewport, _)| *viewport == id).map(|(_, layer)| layer); + let mut layer_order = Vec::new(); let mut full = ctx.run_ui(input, |ui| { + layer_order = ui.ctx().memory(|memory| memory.layer_ids().collect()); + if let Some((rect, _)) = child_raise_overlay { + egui::Area::new(egui::Id::unique("Child raised overlay")).order(egui::Order::Background).fixed_pos(rect.min).show(ui.ctx(), |ui| { + ui.allocate_space(rect.size()); + }); + } (viewport.viewport_ui_cb)(ui); + if let Some(layer) = child_raise_layer { + ui.ctx().move_to_top(layer); + } + if child_raise_overlay.is_some_and(|(_, raise)| raise) { + ui.ctx().move_to_top(egui::LayerId::new(egui::Order::Background, egui::Id::unique("Child raised overlay"))); + } if let Some(rect) = child_overlay { egui::Window::new("Child overlay").fixed_pos(rect.min).fixed_size(rect.size()).show(ui.ctx(), |ui| { ui.label("Child overlay"); @@ -151,6 +169,7 @@ impl Host { let mut shown = Vec::new(); full.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); let mut host = host.borrow_mut(); + host.child_layer_order.insert(id, layer_order); if let Some(window) = host.windows.get_mut(&id) { window.texts = shown; } @@ -174,6 +193,9 @@ impl Harness { child_transition_overlay: None, child_empty_overlay: None, child_pass_through_overlay: None, + child_raise_overlay: None, + child_raise_layer: None, + child_layer_order: HashMap::new(), focus: ViewportId::ROOT, time: 0.0, commands: Vec::new(), @@ -374,6 +396,84 @@ fn a_modal_blocks_native_windows_and_takes_the_keyboard_from_them() { assert_eq!(h.app.session.tool_id(), "pen", "the window takes keys again once the modal closes"); } +/// The level and visibility a palette window takes under a dialog or a menu, and otherwise: a +/// palette stays out of the way of anything drawn in the main window. +#[test] +fn a_palette_window_keeps_out_of_the_way_of_the_main_windows_dialog_and_menus() { + use egui::WindowLevel; + assert_eq!(palette_window_state(true, true, true), (WindowLevel::Normal, false), "hidden under a dialog, even in a menu"); + assert_eq!(palette_window_state(true, false, true), (WindowLevel::Normal, false), "hidden under a dialog"); + assert_eq!(palette_window_state(false, true, true), (WindowLevel::Normal, false), "hidden under a menu: it is drawn in the main window"); + assert_eq!(palette_window_state(false, false, true), (WindowLevel::AlwaysOnTop, true), "its palette level while the app is active"); + let inactive = palette_window_state(false, false, false); + assert!(inactive.1, "shown while the app is inactive"); + assert_ne!(inactive.0, WindowLevel::AlwaysOnTop, "and not above other applications' windows: {:?}", inactive.0); +} + +/// With a menu of the in-window menu bar open, the palettes take the normal level (still shown): +/// the menu is drawn in the main window, or it would open under them. +#[test] +fn a_menu_of_the_menu_bar_lowers_the_palette_windows() { + let mut h = Harness::new(); + let viewport = h.float("navigator"); + h.host.borrow_mut().commands.clear(); + let layout = layout_of(&h.app.ui); + h.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("menu-bar-open"), true)); + assert!(crate::menus::menu_open(&h.ctx), "the menu bar's state says a menu is open"); + palette_window_levels(&h.ctx, &layout, false, crate::menus::menu_open(&h.ctx)); + h.frames(1); + let commands: Vec<(egui::ViewportId, ViewportCommand)> = h.host.borrow().commands.clone(); + let levels: Vec = commands + .iter() + .filter_map(|(id, command)| match command { + ViewportCommand::WindowLevel(level) if *id == viewport => Some(*level), + _ => None, + }) + .collect(); + assert!(levels.contains(&egui::WindowLevel::Normal), "the palette drops its topmost level under the menu: {levels:?}"); + assert!( + commands.iter().any(|(id, command)| *id == viewport && matches!(command, ViewportCommand::Visible(false))), + "and is hidden until the menu closes" + ); +} +/// A modal dialog is drawn in the main window, so the palettes' OS windows leave their topmost +/// level while it is open and take it back after, or the dialog would be covered by them. +#[test] +fn a_modal_lowers_the_native_palette_windows() { + let mut h = Harness::new(); + let viewport = h.float("swatches"); + let levels = |h: &Harness| -> Vec { + h.host + .borrow() + .commands + .iter() + .filter_map(|(id, command)| match command { + ViewportCommand::WindowLevel(level) if *id == viewport => Some(*level), + _ => None, + }) + .collect() + }; + let hidden = |h: &Harness| -> Vec { + h.host + .borrow() + .commands + .iter() + .filter_map(|(id, command)| match command { + ViewportCommand::Visible(visible) if *id == viewport => Some(*visible), + _ => None, + }) + .collect() + }; + h.app.ui.about = true; + h.frames(4); + assert!(levels(&h).contains(&egui::WindowLevel::Normal), "the palette leaves AlwaysOnTop under the modal: {:?}", levels(&h)); + assert_eq!(hidden(&h), [false], "and is hidden, so a click cannot bring it up over the dialog: {:?}", hidden(&h)); + h.app.ui.about = false; + h.frames(4); + assert!(levels(&h).contains(&egui::WindowLevel::AlwaysOnTop), "and takes its palette level back: {:?}", levels(&h)); + assert_eq!(hidden(&h), [false, true], "shown again with the dialog gone: {:?}", hidden(&h)); +} + #[test] fn a_file_dropped_on_a_native_window_opens() { let mut h = Harness::new(); @@ -528,6 +628,7 @@ fn wheel_over_a_floating_character_font_field_changes_the_font() { }, ]); h.frame(vec![]); + h.frame(vec![]); assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), covered); h.host.borrow_mut().child_transparent_overlay = Some((viewport, field.expand(10.0))); @@ -560,6 +661,7 @@ fn wheel_over_a_floating_character_font_field_changes_the_font() { }, ]); h.frame(vec![]); + h.frame(vec![]); assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), covered); } @@ -658,6 +760,380 @@ fn wheel_stays_under_an_empty_interactive_overlay() { assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), covered); } +#[test] +fn a_raised_overlay_blocks_the_next_font_wheel_event() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + let overlay_layer = egui::LayerId::new(egui::Order::Background, egui::Id::unique("Child raised overlay")); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.frame(vec![]); + let order = h.host.borrow().child_layer_order.get(&viewport).cloned().expect("child layer order"); + let field_index = order.iter().position(|layer| *layer == field_layer).expect("font field in layer order"); + let overlay_index = order.iter().position(|layer| *layer == overlay_layer).unwrap_or_else(|| panic!("overlay absent from {order:?}")); + assert!(field_index > overlay_index, "the font field must start above the overlay: {order:?}"); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerGone, + ]); + h.frame(vec![]); + let order = h.host.borrow().child_layer_order.get(&viewport).cloned().expect("child layer order"); + let field_index = order.iter().position(|layer| *layer == field_layer).expect("font field in layer order"); + let overlay_index = order.iter().position(|layer| *layer == overlay_layer).unwrap_or_else(|| panic!("overlay absent from {order:?}")); + assert!(overlay_index > field_index, "the overlay must finish above the font field: {order:?}"); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + h.frame(vec![]); + h.frame(vec![]); + assert!( + h.ctx.input_for(viewport, |input| input.raw.events.iter().any(|event| matches!(event, Event::MouseWheel { .. }))), + "the raised overlay must receive the wheel event" + ); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + assert_eq!(h.ctx.input_for(viewport, |input| input.pointer.latest_pos()), None); +} + +#[test] +fn an_overlay_raised_with_the_wheel_event_does_not_change_the_font() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + let overlay_layer = egui::LayerId::new(egui::Order::Background, egui::Id::unique("Child raised overlay")); + let order = h.host.borrow().child_layer_order.get(&viewport).cloned().expect("child layer order"); + let field_index = order.iter().position(|layer| *layer == field_layer).expect("font field in layer order"); + let overlay_index = order.iter().position(|layer| *layer == overlay_layer).expect("overlay in layer order"); + assert!(field_index > overlay_index, "the font field must be above the overlay before the wheel event: {order:?}"); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + h.frame(vec![]); + h.frame(vec![]); + assert!( + h.ctx.input_for(viewport, |input| input.raw.events.iter().any(|event| matches!(event, Event::MouseWheel { .. }))), + "the raised overlay must receive the wheel event" + ); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_closed_overlay_does_not_replay_its_wheel_into_the_panel() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, pointer).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, field.expand(10.0), true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.host.borrow_mut().child_raise_overlay = None; + h.frame(vec![]); + h.frame(vec![]); + assert!( + !h.ctx.input_for(viewport, |input| input.raw.events.iter().any(|event| matches!(event, Event::MouseWheel { .. }))), + "a closed overlay cannot receive a later wheel event" + ); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_wheel_before_opening_a_floating_font_menu_changes_the_font() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerButton { pos: pointer, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + Event::PointerButton { pos: pointer, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ]); + h.frames(3); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_delayed_wheel_does_not_change_a_font_field_that_moved() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + crate::font_menu::offset_wheel_fields_for_test(&h.ctx, viewport, vec2(300.0, 0.0)); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn wheel_events_on_both_sides_of_an_overlay_are_checked_separately() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let covered = pos2(field.min.x + 4.0, field.center().y); + let clear = pos2(field.max.x - 4.0, field.center().y); + let overlay = Rect::from_min_max(field.min - vec2(2.0, 2.0), pos2(field.center().x, field.max.y + 2.0)); + assert!(covered.x < overlay.max.x && clear.x > overlay.max.x); + h.host.borrow_mut().child_raise_overlay = Some((viewport, overlay, false)); + h.frames(2); + let field_layer = crate::font_menu::wheel_field_layer_for_test(&h.ctx, viewport, clear).expect("the font field layer"); + h.host.borrow_mut().child_raise_layer = Some((viewport, field_layer)); + h.frame(vec![]); + h.host.borrow_mut().child_raise_layer = None; + h.frame(vec![]); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_raise_overlay = Some((viewport, overlay, true)); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(covered), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerMoved(clear), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frame(vec![]); + h.frame(vec![]); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); + assert_eq!(h.ctx.input_for(viewport, |input| input.pointer.latest_pos()), Some(clear)); +} + +#[test] +fn leaving_a_floating_font_field_resets_queued_fractional_wheel_input() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let inside = pos2(field.min.x + 4.0, field.center().y); + let outside = pos2(field.max.x + 500.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(inside), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerMoved(outside), + ]); + h.frame(vec![]); + h.frame(vec![]); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(inside), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn a_floating_wheel_turn_precedes_a_pointer_leave_in_the_menu_order() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + h.app.ui.recent_fonts = ["Source Sans 3", "Source Serif 4", "Inter"].map(str::to_string).into(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let inside = pos2(field.min.x + 4.0, field.center().y); + let outside = pos2(field.max.x + 500.0, field.center().y); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([Event::PointerMoved(inside), wheel.clone()]); + h.frame(vec![]); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap()[0]["family"], "Source Serif 4"); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([wheel, Event::PointerMoved(outside)]); + h.frame(vec![]); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap()[0]["family"], "Inter"); +} + +#[test] +fn moving_under_an_overlay_resets_queued_fractional_font_wheel_input() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let covered = pos2(field.min.x + 4.0, field.center().y); + let clear = pos2(field.max.x - 4.0, field.center().y); + let overlay = Rect::from_min_max(field.min - vec2(2.0, 2.0), pos2(field.center().x, field.max.y + 2.0)); + h.host.borrow_mut().child_raise_overlay = Some((viewport, overlay, true)); + h.frames(2); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(clear), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + Event::PointerMoved(covered), + Event::PointerMoved(clear), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -0.6), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frame(vec![]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + #[test] fn wheel_without_a_move_uses_the_floating_viewports_pointer() { let mut h = Harness::new(); @@ -684,5 +1160,6 @@ fn wheel_without_a_move_uses_the_floating_viewports_pointer() { source: egui::MouseWheelSource::Unknown, }); h.frame(vec![]); + h.frame(vec![]); assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); } diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index f8287944be..60b59a2a8e 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -161,6 +161,52 @@ fn a_tab_dragged_out_floats_and_comes_back_where_it_was_after_its_window_closes( assert!(h.tab("layers").is_some()); } +#[test] +fn thumbnail_work_is_needed_only_while_layers_or_links_can_be_seen() { + let mut h = Harness::new(); + h.app.run("window.panel", json!({"panel": "layers"})).unwrap(); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx)); + h.app.ui.dock = false; + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "Tab hides every panel"); + h.app.ui.dock = true; + h.app.ui.screen_mode = 3; + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "presentation mode hides panels"); + h.app.ui.screen_mode = 0; + h.app.run("window.panel.float", json!({"panel": "layers"})).unwrap(); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx), "a floating Layers panel still needs thumbnails"); + h.app.run("window.panel", json!({"panel": "layers", "toggle": true})).unwrap(); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx)); + h.app.run("window.panel", json!({"panel": "links"})).unwrap(); + h.frame(vec![]); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx), "the Links flyout also uses row thumbnails"); +} + +#[test] +fn a_collapsed_dock_uses_the_flyouts_active_tab_for_thumbnail_work() { + let mut h = Harness::new(); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + // A customized layout keeps the group's active tab independent of the icon that opened it. + h.app.ui.docking = Some(layout_of(&h.app.ui)); + h.app.run("window.panel", json!({"panel": "properties"})).unwrap(); + h.frame(vec![]); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "Properties does not use row thumbnails"); + // A tab press emits Activate without revealing a different flyout anchor. + gesture(&mut h.app, Action::Activate { panel: "layers".into() }).unwrap(); + h.frame(vec![]); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"), "the flyout is still named for its opening icon"); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx), "the active Layers tab keeps thumbnail jobs"); + gesture(&mut h.app, Action::Activate { panel: "properties".into() }).unwrap(); + h.frame(vec![]); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "returning to Properties drops hidden Layers jobs"); + h.app.run("window.panel", json!({"panel": "layers"})).unwrap(); + h.frame(vec![]); + assert!(thumbnail_panel_showing(&h.app.ui, &h.ctx)); + gesture(&mut h.app, Action::Activate { panel: "properties".into() }).unwrap(); + h.frame(vec![]); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("layers")); + assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "a Properties tab under the Layers icon does not need thumbnails"); +} + /// A Character field shortcut with the Character panel in front of its floating window brings /// that window forward and leaves the panel showing. #[test] diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 3c9138f8d8..afddf276f5 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -2291,6 +2291,29 @@ mod tests { assert_eq!(set_names(&app), before, "no set added"); } + /// Where the host can read part of a file, Load Actions… reads one byte past 8 MiB: a larger + /// file is refused without reading all of it, and a smaller one loads. + #[test] + fn load_actions_reads_a_file_no_further_than_one_byte_past_its_limit() { + let mut app = app_with_sets(); + let files = with_files(&mut app, "/sets/big.vcactions"); + app.run(SAVE_SET, json!({"set": 1, "path": "/sets/small.vcactions"})).unwrap(); + files.borrow_mut().insert("/sets/big.vcactions".into(), vec![b' '; files::MAX_SET_FILE + 100]); + app.services.read = Some(Box::new(|_: &str| Err("the whole file was read".to_string()))); + let asked = std::rc::Rc::new(std::cell::RefCell::new(vec![])); + let (f, a) = (files.clone(), asked.clone()); + app.services.read_head = Some(Box::new(move |path: &str, max: usize| { + a.borrow_mut().push(max); + let bytes = f.borrow().get(path).cloned().ok_or_else(|| "no such file".to_string())?; + Ok(bytes.into_iter().take(max).collect()) + })); + let before = set_names(&app); + assert_eq!(app.run(LOAD_SET, json!({"path": "/sets/big.vcactions"})).unwrap_err(), "the action set file is larger than 8 MiB"); + assert_eq!(set_names(&app), before, "no set added"); + assert_eq!(app.run(LOAD_SET, json!({"path": "/sets/small.vcactions"})).unwrap()["name"], json!("Mine 2")); + assert_eq!(*asked.borrow(), [files::MAX_SET_FILE + 1; 2], "each read stops one byte past the limit"); + } + /// Save Actions… does not write a set that Load Actions… would refuse: more than 1,000 actions. #[test] fn save_actions_does_not_write_a_set_load_actions_refuses() { diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index ef00fccceb..ead40505fa 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -181,7 +181,8 @@ pub(crate) fn can_load(app: &VectorcraftApp) -> bool { /// the file's text `data`, and adds its set after the others, with its actions. A set with the /// same name as one in the panel gets the next free number (`Print 2`). Loaded actions keep their /// function keys. The current set and the other sets stay as they are → -/// `{set: index, name, actions: n}`. +/// `{set: index, name, actions: n}`. Where the host can read part of a file (the desktop), a file +/// larger than 8 MiB is refused after its first 8 MiB and one byte are read. pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { let (text, stem) = match p.get("data") { Some(Value::String(data)) => { @@ -200,7 +201,12 @@ pub fn load_set(app: &mut VectorcraftApp, p: &Value) -> Result { crate::picks::open(app, &pick).ok_or("cancelled")? } }; - let bytes = app.services.read.as_ref().ok_or("no file reader")?(&path)?; + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(&path, MAX_SET_FILE + 1)?, + (None, Some(read)) => read(&path)?, + (None, None) => return Err("no file reader".into()), + }; if bytes.len() > MAX_SET_FILE { return Err("the action set file is larger than 8 MiB".into()); } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 7e0c7a12b0..a27dfa3ec2 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -13,7 +13,8 @@ //! (dropped on its row) or onto the object; Alt copies instead. Dropped on Duplicate Selected Item //! or Delete Selected Item, a fill/stroke row (with the other selected rows, when it is one of //! them) or an effect row is copied or removed. Cmd-click and Shift-click select several -//! fills/strokes for Duplicate and Delete. +//! fills/strokes for Duplicate and Delete. Delete on a selected Opacity row sets it back to +//! Default (100%, Normal). use std::sync::OnceLock; @@ -59,11 +60,16 @@ impl Sel { Sel::None | Sel::Effect(_) | Sel::Contents | Sel::Opacity => None, } } - /// Is a fill/stroke or effect row selected (what Duplicate and Delete act on)? An Opacity row - /// is not an item: it can't be copied or removed. + /// Is a fill/stroke or effect row selected (what Duplicate acts on)? An Opacity row is not an + /// item: it can't be copied. fn editable(self) -> bool { matches!(self, Sel::Item(_) | Sel::Effect(_) | Sel::ItemEffect(..)) } + /// Does Delete act on the selected row? A fill/stroke or effect row is removed; deleting an + /// Opacity row sets it back to Default (100%, Normal) (#5742). + fn deletable(self) -> bool { + self.editable() || matches!(self, Sel::Opacity | Sel::ItemOpacity(_)) + } } /// The selected row of `node` (the first selected object): a selected effect row while that @@ -490,7 +496,7 @@ fn delete_key(app: &mut VectorcraftApp, ui: &mut Ui) { let node = first_subject(app); let sel = current_sel(app, &ctx, node.as_ref()); if keys - && sel.editable() + && sel.deletable() && ctx.memory(|m| m.focused().is_none()) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) || i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { @@ -1088,7 +1094,8 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, opaci let link = name_link(ui, pos2(lx, r.center().y), ("ap-op-link", item), tl!("Opacity:")).clicked(); if link || resp.clicked() { select_row(app, ui.ctx(), this); - // The panel has the keyboard (Delete then removes nothing, rather than the object). + // The panel has the keyboard (Delete then sets the row back to Default, rather than + // deleting the object). super::set_row_keys(ui.ctx(), ROW_KEYS, true); } if link { @@ -1238,6 +1245,8 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let suffix = ui_keys.and_then(|u| u.unit.as_deref()).map(crate::dialogs::unit_suffix).unwrap_or_default(); let nx = if vectorcraft_effects::is_length(&e.id, key, relative) { widgets::num_field(ui, id, Some(x), unit, 70.0) + } else if let Some(range) = vectorcraft_effects::raster_px_range(&e.id, key) { + widgets::range_field_named(ui, id, None, x, range, &crate::dialogs::unit_suffix("px"), 2, 70.0) } else { widgets::plain_field(ui, id, x, &suffix, 2, 70.0) }; @@ -1413,7 +1422,8 @@ fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, node: Option<&Node>, sel: Sel) if duplicate.clicked() { duplicate_selected(app, ui, node, sel); } - let delete = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Selected Item"), false, can, 24.0); + let can_delete = can || (has && sel.deletable()); + let delete = widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Selected Item"), false, can_delete, 24.0); if delete.clicked() { delete_selected(app, ui, node, sel); } @@ -1556,8 +1566,20 @@ fn highlight_copies(app: &mut VectorcraftApp, ctx: &egui::Context, n: &Node, sel set_pstate(ctx, "ap-multi", Highlight { owner: Some(n.id), rows, order, anchor, active }); } -/// Remove the highlighted fills/strokes or effects; a removed item effect leaves its fill/stroke selected. +/// Remove the highlighted fills/strokes or effects; a removed item effect leaves its fill/stroke +/// selected. A selected Opacity row is set back to Default (100%, Normal) and stays selected. fn delete_selected(app: &mut VectorcraftApp, ui: &Ui, node: Option<&Node>, sel: Sel) { + match sel { + Sel::Opacity => { + app.run("transparency.set", json!({"item": null, "opacity": 100, "blend": "Normal"})).ok(); + return; + } + Sel::ItemOpacity(i) => { + app.run("transparency.set", aligned(app, json!({"item": i, "opacity": 100, "blend": "Normal"}))).ok(); + return; + } + _ => {} + } let ok = match selected_effects(ui.ctx(), node, sel) { Some((item, ks)) => app.run("effect.remove", aligned(app, json!({"item": item, "indices": ks}))).is_ok(), None if matches!(sel, Sel::Item(_)) => { @@ -1614,7 +1636,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Duplicate Item"), has && sel.editable(), false) { duplicate_selected(app, ui, node.as_ref(), sel); } - if menu_item(ui, tl!("Remove Item"), has && sel.editable(), false) { + if menu_item(ui, tl!("Remove Item"), has && sel.deletable(), false) { delete_selected(app, ui, node.as_ref(), sel); } if menu_item(ui, tl!("Clear Appearance"), has, false) { diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 7d9cdd3293..82042a9a38 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -85,6 +85,47 @@ fn removing_items_keeps_a_surviving_item_opacity_row_selected() { assert_eq!(app.session.appearance_item(), None); } +/// #5742: Delete Selected Item on an Opacity row sets it back to Default (100%, Normal): the +/// object's own, or a fill's, leaving the other untouched. Duplicate stays off for it. +#[test] +fn deleting_an_opacity_row_sets_it_back_to_default() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + app.run("transparency.set", json!({"item": null, "opacity": 50, "blend": "Multiply"})).unwrap(); + app.run("transparency.set", json!({"item": 0, "opacity": 40, "blend": "Screen"})).unwrap(); + let owner = Some(NodeId(id)); + let ctx = egui::Context::default(); + let delete = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let node = first_subject(app); + let sel = current_sel(app, ui.ctx(), node.as_ref()); + assert!(sel.deletable() && !sel.editable(), "{sel:?}"); + delete_selected(app, ui, node.as_ref(), sel); + }); + out.textures_delta.clear(); + }; + let node = |app: &VectorcraftApp| first_subject(app).unwrap(); + // The fill's Opacity row: only the fill goes back to Default. + app.run("appearance.setActiveItem", json!({ "index": 0 })).unwrap(); + set_pstate(&ctx, "ap-sel", (owner, Sel::ItemOpacity(0))); + delete(&mut app); + let n = node(&app); + assert_eq!((n.appearance.items[0].opacity(), n.appearance.items[0].blend()), (1.0, BlendMode::Normal)); + assert_eq!((n.opacity, n.blend), (0.5, BlendMode::Multiply)); + assert_eq!(pstate::<(Option, Sel)>(&ctx, "ap-sel").1, Sel::ItemOpacity(0)); + // The object's Opacity row. + app.run("appearance.setActiveItem", json!({ "index": null })).unwrap(); + set_pstate(&ctx, "ap-sel", (owner, Sel::Opacity)); + delete(&mut app); + let n = node(&app); + assert_eq!(opacity_text(n.opacity, n.blend), "Default"); + // One step, so Undo brings the object's opacity back. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app).opacity, 0.5); +} + #[test] fn opacity_labels() { assert_eq!(opacity_text(1.0, BlendMode::Normal), "Default"); diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 77023bacb1..deff9d8723 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -5,7 +5,8 @@ //! Artboard duplicates its artboard (as Duplicate Artboards does, with //! its art when the Artboard tool's Move/Copy Artwork with Artboard is on). The highlighted row is the active artboard, the one the status bar's navigator shows and //! Fit Artboard in Window fits: clicking a row makes it active, double-clicking its number also -//! fits it in the window. The options icon at a row's right end opens Artboard Options: a click on +//! fits it in the window. Shift-click selects a range of artboards and Ctrl/Cmd-click adds or +//! removes one, with any tool: another tool gives way to the Artboard tool first (#5698). The options icon at a row's right end opens Artboard Options: a click on //! the active artboard's icon, or a double-click on another row's icon. The lock column left of it //! shows a lock on a locked artboard, and a click there locks or unlocks the artboard //! (`artboard.setProps` with `locked`); Delete leaves locked artboards. @@ -488,6 +489,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } let m = ui.input(|inp| inp.modifiers); + // A Shift- or Ctrl/Cmd-click selects several artboards with any tool: it first + // switches to the Artboard tool, which holds the selection, so Properties and the + // Control bar then show the controls that change every selected artboard. + if resp.clicked() && (m.shift || m.command) && app.session.tool_id() != "artboard" { + app.select_tool("artboard"); + } let tool = app.session.tool_id() == "artboard"; row_clicked |= resp.clicked(); if resp.clicked() && tool && m.shift { diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index edae3a32e2..bf2b470503 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -156,10 +156,20 @@ fn shift_clicking_rows_selects_several_artboards() { frame(&mut app, 9.0, click(4, egui::Modifiers::NONE)); assert_eq!(picked(&app, 4), [3]); assert_eq!(highlighted(frame(&mut app, 10.0, vec![])), 1); - // With another tool, a Shift-click makes the row's artboard active, as a plain click does. + // With another tool, a plain click makes the row's artboard active and keeps the tool. app.select_tool("selection"); - frame(&mut app, 11.0, click(2, egui::Modifiers::SHIFT)); - assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![1], 1)); + frame(&mut app, 11.0, click(2, egui::Modifiers::NONE)); + assert_eq!((app.session.tool_id(), selected(&app, 4)), ("selection", 1)); + // A Shift-click switches to the Artboard tool and selects the range (#5698). + frame(&mut app, 12.0, click(4, egui::Modifiers::SHIFT)); + assert_eq!(app.session.tool_id(), "artboard"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![1, 2, 3], 3)); + // So does a Ctrl/Cmd-click, adding one artboard to the one active. + app.select_tool("selection"); + frame(&mut app, 13.0, click(1, egui::Modifiers::NONE)); + frame(&mut app, 14.0, click(3, egui::Modifiers::COMMAND)); + assert_eq!(app.session.tool_id(), "artboard"); + assert_eq!((picked(&app, 4), selected(&app, 4)), (vec![0, 2], 2)); } /// Double-clicking a row's number goes to its artboard and its name renames it; a click on diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 495ce2f119..7e68824c19 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -651,7 +651,7 @@ pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Opti Some(Ok(Value::Null)) } -enum TextInput { +pub(crate) enum TextInput { Key(ToolKey, Mods), Copy, Cut, @@ -659,83 +659,87 @@ enum TextInput { Face(Face), } -/// Route editing keys (with modifiers), clipboard events and Cmd+C/X/V to the Type tool (Cmd+A is -/// left to the Select All shortcut, which selects the text being edited). -pub(crate) fn route_type_input(app: &mut VectorcraftApp, ctx: &egui::Context) { +/// Takes an editing key (with modifiers), a clipboard event or Cmd+C/X/V for the Type tool into +/// `todo` (Cmd+A is left to the Select All shortcut, which selects the text being edited). Returns +/// false for an event the tool takes, which is then removed from the input. +pub(crate) fn type_input(e: &egui::Event, todo: &mut Vec) -> bool { + match e { + egui::Event::Copy => { + todo.push(TextInput::Copy); + false + } + egui::Event::Cut => { + todo.push(TextInput::Cut); + false + } + egui::Event::Paste(s) => { + todo.push(TextInput::Paste(Some(s.clone()))); + false + } + egui::Event::Key { key, pressed, modifiers: m, .. } => { + let mods = Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl && !m.command, space: false }; + let tk = match key { + Key::ArrowLeft => Some(ToolKey::Left), + Key::ArrowRight => Some(ToolKey::Right), + Key::ArrowUp => Some(ToolKey::Up), + Key::ArrowDown => Some(ToolKey::Down), + Key::Home => Some(ToolKey::Home), + Key::End => Some(ToolKey::End), + Key::Backspace => Some(ToolKey::Backspace), + Key::Delete => Some(ToolKey::Delete), + Key::Tab if !m.command => Some(ToolKey::Tab), + _ => None, + }; + if let Some(tk) = tk { + if *pressed { + todo.push(TextInput::Key(tk, mods)); + } + return false; + } + // Type › Bold and Italic, as page layout apps have them while text is edited. + if m.command && m.shift && !m.alt && matches!(key, Key::B | Key::I) { + if *pressed { + todo.push(TextInput::Face(if *key == Key::B { Face::Bold } else { Face::Italic })); + } + return false; + } + if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) { + if *pressed { + todo.push(match key { + Key::C => TextInput::Copy, + Key::X => TextInput::Cut, + _ => TextInput::Paste(None), + }); + } + return false; + } + true + } + _ => true, + } +} + +/// Keeps `ctx` for the Type tool's clipboard, which Edit › Copy and Cut also write to. +pub(crate) fn keep_ctx(ctx: &egui::Context) { CTX.get_or_init(|| ctx.clone()); - let mut todo = vec![]; - ctx.input_mut(|i| { - i.events.retain(|e| match e { - egui::Event::Copy => { - todo.push(TextInput::Copy); - false +} + +/// Applies an editing key or clipboard event taken by [`type_input`] to the Type tool. +pub(crate) fn apply_type_input(app: &mut VectorcraftApp, t: TextInput) { + match t { + TextInput::Key(k, m) => text_key(app, k, m), + TextInput::Copy => { + text_copy(app); + } + TextInput::Cut => { + if text_copy(app) { + text_key(app, ToolKey::Delete, Mods::default()); } - egui::Event::Cut => { - todo.push(TextInput::Cut); - false - } - egui::Event::Paste(s) => { - todo.push(TextInput::Paste(Some(s.clone()))); - false - } - egui::Event::Key { key, pressed, modifiers: m, .. } => { - let mods = Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl && !m.command, space: false }; - let tk = match key { - Key::ArrowLeft => Some(ToolKey::Left), - Key::ArrowRight => Some(ToolKey::Right), - Key::ArrowUp => Some(ToolKey::Up), - Key::ArrowDown => Some(ToolKey::Down), - Key::Home => Some(ToolKey::Home), - Key::End => Some(ToolKey::End), - Key::Backspace => Some(ToolKey::Backspace), - Key::Delete => Some(ToolKey::Delete), - Key::Tab if !m.command => Some(ToolKey::Tab), - _ => None, - }; - if let Some(tk) = tk { - if *pressed { - todo.push(TextInput::Key(tk, mods)); - } - return false; - } - // Type › Bold and Italic, as page layout apps have them while text is edited. - if m.command && m.shift && !m.alt && matches!(key, Key::B | Key::I) { - if *pressed { - todo.push(TextInput::Face(if *key == Key::B { Face::Bold } else { Face::Italic })); - } - return false; - } - if m.command && !m.shift && !m.alt && matches!(key, Key::C | Key::X | Key::V) { - if *pressed { - todo.push(match key { - Key::C => TextInput::Copy, - Key::X => TextInput::Cut, - _ => TextInput::Paste(None), - }); - } - return false; - } - true - } - _ => true, - }) - }); - for t in todo { - match t { - TextInput::Key(k, m) => text_key(app, k, m), - TextInput::Copy => { - text_copy(app); - } - TextInput::Cut => { - if text_copy(app) { - text_key(app, ToolKey::Delete, Mods::default()); - } - } - TextInput::Paste(s) => text_paste(app, s, false), - TextInput::Face(f) => { - if let Err(e) = toggle_face(app, f) { - app.status(e); - } + } + TextInput::Paste(s) => text_paste(app, s, false), + TextInput::Face(f) => { + if let Err(e) = toggle_face(app, f) { + app.status(e); } } } @@ -994,6 +998,9 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { /// The panel state key of the panel menu's Show Snap to Glyph Options. const SNAP_TO_GLYPH_OPTIONS: &str = "ch-snap-to-glyph-options"; +/// Set when Show Snap to Glyph Options is chosen: the next frame scrolls the panel to the options, +/// which come after every character attribute (#5273). +const SNAP_TO_GLYPH_REVEAL: &str = "ch-snap-to-glyph-reveal"; pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { show_owned(app, ui, crate::font_menu::WheelOwner::Character); @@ -1007,13 +1014,18 @@ fn show_owned(app: &mut VectorcraftApp, ui: &mut Ui, owner: crate::font_menu::Wh } } -/// The Snap to Glyph options (Show Snap to Glyph Options): which guides View › Snap to Glyph gives, -/// each a checkbox running `view.snapToGlyph.options`. Dimmed while Snap to Glyph is off. +/// The Snap to Glyph options (Show Snap to Glyph Options): View › Snap to Glyph itself, then which +/// guides it gives, each a checkbox running `view.snapToGlyph.options` (dimmed while Snap to Glyph +/// is off). Shown from the panel menu, the panel scrolls to them (#5273). fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); ui.separator(); - widgets::section_header(ui, "Snap to Glyph"); + let top = ui.cursor().min; let (o, enabled) = (app.session.prefs.glyph_snap, app.ui.view.snap_to_glyph); + // A UI command that takes no params: it can't refuse. + if widgets::check(ui, "Snap to Glyph", enabled, true) { + app.run("view.snapToGlyph", json!({})).ok(); + } egui::Grid::new("ch-snap-to-glyph").num_columns(2).show(ui, |ui| { for (i, (label, key, on)) in [ ("Baseline", "baseline", o.baseline), @@ -1035,6 +1047,10 @@ fn snap_to_glyph_options(app: &mut VectorcraftApp, ui: &mut Ui) { } } }); + if pstate::(ui.ctx(), SNAP_TO_GLYPH_REVEAL) { + set_pstate(ui.ctx(), SNAP_TO_GLYPH_REVEAL, false); + ui.scroll_to_rect(egui::Rect::from_min_max(top, ui.min_rect().max), Some(egui::Align::BOTTOM)); + } } /// The character attributes of the type selected (an empty state without any). @@ -1222,6 +1238,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let glyph = pstate::(ui.ctx(), SNAP_TO_GLYPH_OPTIONS); if menu_item(ui, if glyph { tl!("Hide Snap to Glyph Options") } else { tl!("Show Snap to Glyph Options") }, true, false) { set_pstate(ui.ctx(), SNAP_TO_GLYPH_OPTIONS, !glyph); + set_pstate(ui.ctx(), SNAP_TO_GLYPH_REVEAL, !glyph); } // Show Font Height Options shows the Set Font Height Reference dropdown under Font Size. let heights: bool = pstate(ui.ctx(), FONT_HEIGHT_OPTIONS); diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 4a4264fe70..2a35193852 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1207,6 +1207,43 @@ fn snap_to_glyph_options_show_from_the_menu_and_set_the_options() { assert!(!section(&mut app).iter().any(|(t, _)| t == "Proximity Guides")); } +/// #5273: the Snap to Glyph options come after every character attribute, so showing them from the +/// panel menu scrolls a short panel down to them; their first checkbox turns View › Snap to Glyph +/// on and off, which undims the others. +#[test] +fn snap_to_glyph_options_scroll_into_view_and_turn_snapping_on() { + use super::super::tests_appearance::{click, frame_events, text_rect}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": "Glyphs"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + const VIEW: f32 = 160.0; + // The panel as a short dock shows it: in a scroll area. + let panel = |app: &mut VectorcraftApp, ui: &mut egui::Ui| { + egui::ScrollArea::vertical().max_height(VIEW).show(ui, |ui| show(app, ui)); + }; + let texts = frame_events(&ctx, &mut app, vec![], menu); + let item = texts.iter().find(|(t, _)| t.trim() == "Show Snap to Glyph Options").unwrap().1; + click(&ctx, &mut app, item.center(), menu); + // The scroll is animated: it lands over the next second. + let mut texts = vec![]; + for i in 0..30 { + let raw = egui::RawInput { time: Some(10.0 + f64::from(i) * 0.1), ..Default::default() }; + texts = super::super::tests_appearance::frame_raw(&ctx, &mut app, raw, panel); + } + for label in ["Snap to Glyph", "Anchor Point"] { + let r = text_rect(&texts, label); + assert!(r.top() >= 0.0 && r.bottom() <= VIEW + 1.0, "{label} at {r:?} is outside the panel"); + } + assert!(!app.ui.view.snap_to_glyph); + click(&ctx, &mut app, text_rect(&texts, "Snap to Glyph").center(), panel); + assert!(app.ui.view.snap_to_glyph, "the first checkbox turns Snap to Glyph on"); + let texts = frame_events(&ctx, &mut app, vec![], panel); + click(&ctx, &mut app, text_rect(&texts, "Anchor Point").center(), panel); + assert!(!app.session.prefs.glyph_snap.anchors, "the options take clicks once it is on"); +} + /// After Select All in a frame of threaded text, the Character and Paragraph panels and Copy act on /// the text of every frame of the story. #[test] diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 2b71ea0545..631d38ab7f 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -41,6 +41,8 @@ use crate::{VectorcraftApp, icons}; /// Dragging a stop this far below the ramp removes it. const REMOVE_DISTANCE: f32 = 28.0; +/// The Delete Stop button beside the ramp, points square. +const DELETE_STOP_SIZE: f32 = 22.0; /// The Angle field's preset menu, degrees. const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0]; /// The Aspect Ratio field's preset menu, percent. @@ -280,7 +282,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if hidden { if !freeform { ui.add_space(6.0); - ramp(app, ui, &g.gradient, is_grad); + ramp_row(app, ui, &g.gradient, is_grad); } return; } @@ -358,7 +360,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); ui.add_space(6.0); - ramp(app, ui, &g.gradient, is_grad); + ramp_row(app, ui, &g.gradient, is_grad); ui.add_space(4.0); stop_fields(app, ui, &g.gradient, is_grad); // Dither applies to gradient fills only: off and dimmed behind the Stroke proxy. @@ -569,7 +571,7 @@ fn thumbnail(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: } /// The selected stop's colour (click: its popover; the eyedropper samples one from the art), -/// opacity and location (a selected diamond's midpoint instead), and Delete Stop. +/// opacity and location (a selected diamond's midpoint instead). fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { let stops = &g.stops; let sel = app.session.selected_stop().filter(|i| *i < stops.len() && is_grad); @@ -623,14 +625,29 @@ fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } } }); - let can_del = sel.is_some() && stops.len() > MIN_STOPS; - if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Stop"), false, can_del, 22.0).clicked() - && let Some(i) = sel - && let Some(v) = remove_stop(stops, i) - { - let next = i.min(v.len() - 1); - set_stops(app, &v, Some(next), Live::Released); - } + }); +} + +/// The ramp with Delete Stop at its right end, level with the ramp so it shows whenever the ramp +/// does: it deletes the selected stop, never below two. +fn ramp_row(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let w = (ui.available_width() - DELETE_STOP_SIZE).max(DELETE_STOP_SIZE * 2.0); + ramp(app, ui, g, is_grad, w); + ui.vertical(|ui| { + // Level with the ramp (the bar starts 10 points down and is 18 tall). + ui.add_space(8.0); + let sel = app.session.selected_stop().filter(|i| *i < g.stops.len() && is_grad); + let can_del = sel.is_some() && g.stops.len() > MIN_STOPS; + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Stop"), false, can_del, DELETE_STOP_SIZE).clicked() + && let Some(i) = sel + && let Some(v) = remove_stop(&g.stops, i) + { + let next = i.min(v.len().saturating_sub(1)); + set_stops(app, &v, Some(next), Live::Released); + } + }); }); } @@ -709,10 +726,9 @@ fn dropped_swatch(app: &VectorcraftApp, ui: &Ui, g: &Gradient, area_resp: &egui: Some(drop_color(g, g.stops.iter().position(|s| marker(s.offset).contains(p)), x_to_offset(p.x, bar.left(), bar.width()), c, link)) } -/// The gradient slider: ramp, stops below, midpoint diamonds above. -fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) { +/// The gradient slider, `w` points wide: ramp, stops below, midpoint diamonds above. +fn ramp(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool, w: f32) { let t = Tokens::get(ui.ctx()); - let w = ui.available_width(); let (area, area_resp) = ui.allocate_exact_size(vec2(w, 50.0), Sense::hover()); let bar = Rect::from_min_size(area.min + vec2(8.0, 10.0), vec2(w - 16.0, 18.0)); paint_ramp(ui, g, bar); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 83a290bb1d..65602079b8 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -726,3 +726,39 @@ fn the_panel_menu_saves_deletes_and_hides_presets() { p.menu_click(&mut app, text_at(&texts, "Show Presets").unwrap()); assert!(text_at(&p.frame(&mut app, vec![], Modifiers::NONE), "Presets:").is_some()); } + +/// A stop is deleted by dragging it down off the ramp or with Delete Stop, which sits at the +/// ramp's right end (so a short panel doesn't hide it below the stop fields, #5403); one undo +/// step each, and a two-stop gradient keeps both. +#[test] +fn a_stop_dragged_off_the_ramp_or_deleted_with_the_button_beside_it_goes() { + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]); + let mut app = app(json!({"gradient": {"stops": stops}})); + let mut p = Panel::new(); + p.frame(&mut app, vec![], Modifiers::NONE); + let mid = p.widget(("grad-stop", 1)).center(); + // Dragged down off the ramp, the middle stop goes. + p.drag(&mut app, mid, mid + vec2(0.0, 60.0), Modifiers::NONE); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]); + // Delete Stop, level with the ramp and right of it, removes the selected stop. + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + let bar = p.widget("grad-bar"); + let del = *p.row_after(bar.left_center(), 22.0).last().expect("Delete Stop beside the ramp"); + assert!(del.left() >= bar.right(), "right of the ramp"); + p.click(&mut app, del.center()); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]); + app.run("edit.redo", json!({})).unwrap(); + // Two stops stay two: dragged off, the stop comes back, and the button is off. + let first = p.widget(("grad-stop", 0)).center(); + p.drag(&mut app, first, first + vec2(0.0, 60.0), Modifiers::NONE); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + p.frame(&mut app, vec![], Modifiers::NONE); + p.click(&mut app, del.center()); + assert_eq!(hexes(&app), ["#ffffff", "#000000"]); +} diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 8f87786892..65f7c6bc3e 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -69,7 +69,7 @@ use model::{push_rows, rows_of_doc}; use rows::{drag_ghost, key, rename_id, resolve_click, row}; #[cfg(test)] use thumbs::THUMBS; -pub(crate) use thumbs::{ThumbSource, node_arc, real_thumb, thumb_options}; +pub(crate) use thumbs::{ThumbSource, node_arc, real_thumb, retain_open_thumbs, show_thumbs_of, thumb_options}; /// Width of the eye and the lock columns. const COLUMN: f32 = 25.0; @@ -184,6 +184,7 @@ pub(crate) const ROW_KEYS: &str = "ly-keys"; /// The Layers panel: the layer tree with its click, drag and rename rules and the bottom buttons; Delete/Backspace after a row click delete the highlighted rows. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); + show_thumbs_of(app.session.active().map(|st| st.uid)); let Some(st) = app.session.active() else { return }; // A rename belongs to the document it started in (node ids are per document): drop it when // another document shows, so it can't rename that document's node with the same id. @@ -249,7 +250,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(id) = located { open_around(app, &doc, &[id]); } - let reveal = located.or(reveal); + // A row Rename (`ui.rename`) opened the name field of comes into view first. + let renamed = ui.data_mut(|d| d.remove_temp::(key("rename-reveal"))); + let reveal = renamed.or(located).or(reveal); let Some(st) = app.session.active() else { return }; let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query, &app.ui.layers_filter); let view = View { @@ -376,6 +379,58 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { see_selection(app, ui, selected); } +/// The search typed into the Layers panel's Search All field, as the panel matches it. +fn search_query(ctx: &egui::Context) -> String { + ctx.data(|d| d.get_temp::(egui::Id::unique("layers-search"))).unwrap_or_default().trim().to_lowercase() +} + +/// `ui.rename {id?}`: open the Layers panel's name field on the row of layer, group or object +/// `id`, as double-clicking the row's name does: Enter renames it (`layer.setProps`, one undo +/// step), Escape leaves the name as it was. Without `id`, the row Rename names is the Layers +/// panel's highlighted row when a row was clicked last, else the one selected object or group, +/// else the one highlighted row, else the current layer. Several of them, or a row the panel's +/// search, filter or Show Layers Only leaves out, is an error that opens nothing. +pub fn rename(app: &mut VectorcraftApp, p: &Value) -> Result { + let ctx = app.ui_ctx.clone().ok_or("the Layers panel is not shown")?; + let st = app.session.active().ok_or("no document open")?; + let one = |ids: &[NodeId]| match ids { + [id] => Ok(*id), + _ => Err("select one layer, group or object to rename".to_string()), + }; + let id = match p.get("id") { + Some(v) => { + let id = NodeId(v.as_u64().ok_or_else(|| format!("`id` is an object id, not {v}"))?); + st.doc.node(id).map(|_| id).ok_or("no such layer or object")? + } + None => { + let rows = st.highlighted_rows(); + let selected = &st.selection.objects; + let rows_first = super::has_row_keys(&ctx, ROW_KEYS) || selected.is_empty(); + if rows_first && !rows.is_empty() { + one(&rows)? + } else if !selected.is_empty() { + one(selected)? + } else { + st.current_layer().ok_or("no layer to rename")? + } + } + }; + let doc = st.doc.clone(); + let node = doc.node(id).ok_or("no such layer or object")?; + if !listed_when_opened(&doc, &st.layers_open, &app.ui.layers_panel, &search_query(&ctx), &app.ui.layers_filter, id) { + return Err("the Layers panel's search, filter or Show Layers Only hides its row".into()); + } + let name = node.identify_label(app.session.prefs.identify_objects_by == "xmlId"); + crate::panel_docking::reveal_panel(app, "layers")?; + open_around(app, &doc, &[id]); + ctx.data_mut(|d| { + d.insert_temp(rename_id(), (id.0, name.clone())); + d.insert_temp(key("rename-reveal"), id); + }); + ctx.request_repaint(); + Ok(json!({ "id": id.0, "name": name })) +} + /// Open the layers and groups around rows `ids`. fn open_around(app: &mut VectorcraftApp, doc: &Document, ids: &[NodeId]) { let around: Vec = diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index f7abe7aa3e..000a3c07eb 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -16,6 +16,25 @@ pub(super) fn rename_id() -> egui::Id { egui::Id::unique("layers-rename") } +/// Whether a row's name is italic: a layer whose Layer Options › Print is off does not print, and +/// the panel shows that in its name, as the reference application does (a template layer's Print is +/// off too). +fn prints_italic(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { printable: false, .. }) +} + +/// Paints the row name `name` at `pos` (left, vertically centred), italic when `italic`, and +/// returns its rect. Row names are painted rather than widgets, so italics come from a layout job's +/// text format: egui slants the glyphs itself, no italic face is needed. +fn paint_name(painter: &egui::Painter, pos: egui::Pos2, name: &str, font: egui::FontId, color: Color32, italic: bool) -> egui::Rect { + let mut job = egui::text::LayoutJob::default(); + job.append(name, 0.0, egui::TextFormat { font_id: font, color, italics: italic, ..Default::default() }); + let galley = painter.layout_job(job); + let rect = egui::Align2::LEFT_CENTER.anchor_size(pos, galley.size()); + painter.galley(rect.min, galley, color); + rect +} + /// The colour of the layer holding `id`. fn layer_colour(doc: &Document, id: NodeId) -> Color32 { let [r, g, b] = doc.layer_color(id); @@ -57,7 +76,7 @@ pub(super) fn drag_ghost(ui: &Ui, view: &View, src: NodeId, pos: egui::Pos2) { } let label = n.identify_label(view.identify_xml_id); let name = if view.identify_xml_id { label } else { painted_name(n, &label, crate::i18n::current()) }; - ui.painter().text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(13.0), t.text); + paint_name(ui.painter(), egui::pos2(x, r.center().y), &name, egui::FontId::proportional(13.0), t.text, prints_italic(n)); }); } @@ -316,7 +335,7 @@ pub(super) fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) { } else { painted_name(n, &n.display_name(), crate::i18n::current()) }; - let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if item.dim { t.text_dim } else { t.text }); + let text = paint_name(&painter, egui::pos2(x, r.center().y), &shown, font, if item.dim { t.text_dim } else { t.text }, prints_italic(n)); name_end = text.right(); // A clipping path's name is underlined, a masked object's with a dashed line. if clip_path { diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 297afd6936..0bd0efdde6 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -211,6 +211,67 @@ fn two_rects() -> (VectorcraftApp, NodeId, [NodeId; 2]) { (app, layer, [NodeId(a), NodeId(b)]) } +/// The painted names one headless frame of the panel draws italic. +fn italic_names(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + fn collect(shape: &egui::Shape, names: &mut Vec) { + match shape { + egui::Shape::Text(t) => { + if t.galley.job.sections.iter().any(|s| s.format.italics) { + names.push(t.galley.text().to_string()); + } + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, names)), + _ => {} + } + } + let mut names = Vec::new(); + out.shapes.iter().for_each(|c| collect(&c.shape, &mut names)); + names +} + +/// A layer whose Layer Options › Print is off has its name italic in the panel (#5739), as the +/// reference application shows it; a printing layer's name stays upright, and unticking Print again +/// makes it upright. +#[test] +fn a_layer_that_does_not_print_has_its_name_italic() { + let (mut app, layer, _) = two_rects(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + assert!(!italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "a printing layer's name is upright"); + app.session.execute("layer.setProps", &json!({"ids": [layer.0], "printable": false})).unwrap(); + assert!(italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "Print off: its name is italic"); + app.session.execute("layer.setProps", &json!({"ids": [layer.0], "printable": true})).unwrap(); + assert!(!italic_names(&mut app, &ctx).iter().any(|n| n == "Layer 1"), "Print on again: upright again"); +} + +#[test] +fn closing_a_document_releases_only_its_layer_thumbnails() { + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let first = app.session.active().unwrap().uid; + frame(&mut app, &ctx, vec![], false); + assert!(THUMBS.with(|c| c.borrow().cached(first))); + + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let second = app.session.active().unwrap().uid; + frame(&mut app, &ctx, vec![], false); + assert!(THUMBS.with(|c| c.borrow().cached(second))); + + // Close the first document the way File › Close does (Don't Save), with no panel drawn after. + assert_eq!(app.run("file.close", json!({"index": 0})).unwrap(), json!({"pending": crate::unsaved::KIND})); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents().iter().all(|d| d.uid != first), "the first document closed"); + THUMBS.with(|c| { + let thumbs = c.borrow(); + assert!(!thumbs.cached(first), "closed document textures are released"); + assert!(thumbs.cached(second), "open document textures stay cached"); + }); +} + #[test] fn row_thumbnails_wait_for_the_end_of_a_drag() { let (mut app, _, _) = two_rects(); @@ -239,6 +300,42 @@ fn row_thumbnails_wait_for_the_end_of_a_drag() { assert_eq!(renders(), after, "once"); } +#[test] +fn the_row_thumbnails_follow_the_document_shown_and_none_once_it_closes() { + let (mut app, _, _) = two_rects(); + let ctx = egui::Context::default(); + let showing = || THUMBS.with(|c| c.borrow().showing); + frame(&mut app, &ctx, vec![], false); + let first = app.session.active().map(|st| st.uid); + assert_eq!(showing(), first); + // With no thumbnails drawn, the panel still tells which document it shows. + let p = &mut app.ui.layers_panel; + (p.thumb_layers, p.thumb_groups, p.thumb_objects) = (false, false, false); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + frame(&mut app, &ctx, vec![], false); + let second = app.session.active().map(|st| st.uid); + assert_ne!(second, first); + assert_eq!(showing(), second, "the new document's rows are drawn"); + for _ in 0..2 { + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + } + frame(&mut app, &ctx, vec![], false); + assert_eq!(showing(), None, "no document is shown once both close"); + + // The Links panel alone does the same. + let links = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::links::show(app, ui)); + out.textures_delta.clear(); + }; + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + links(&mut app); + assert_eq!(showing(), app.session.active().map(|st| st.uid)); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + links(&mut app); + assert_eq!(showing(), None, "the Links panel shows no document"); +} + #[test] fn clicking_a_target_circle_targets_the_layer() { let (mut app, layer, [a, b]) = two_rects(); @@ -372,6 +469,66 @@ fn shift_enter_renames_a_layer_and_keeps_the_field_open() { assert!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).is_none(), "and closes the field"); } +/// Rename (`ui.rename`, F2) opens the name field on the selected object's row, as a +/// double-click on the name does: Enter renames it in one undo step. +#[test] +fn rename_opens_the_name_field_of_the_selected_object() { + let (mut app, _, [a, _]) = two_rects(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let name = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(a).unwrap().display_name(); + let before = name(&app); + app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let opened = app.run("ui.rename", json!({})).unwrap(); + assert_eq!(opened, json!({"id": a.0, "name": before})); + assert_eq!(ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())), Some((a.0, before.clone())), "the field opens on its row"); + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + frame(&mut app, &ctx, vec![], false); + frame(&mut app, &ctx, vec![], false); + assert!(ctx.memory(|m| m.has_focus(rename_id().with("field"))), "with the keyboard"); + frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text("Sun".into())], false); + frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], false); + frame(&mut app, &ctx, vec![], false); + assert_eq!(name(&app), "Sun"); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(name(&app), before, "one undo step"); +} + +/// Rename (`ui.rename`) has no default key, F2 being free: it is listed in Keyboard Shortcuts, +/// where a key can be assigned to it. +#[test] +fn rename_has_no_default_key() { + use crate::shortcut_editor::{command_for_key, default_command_shortcut}; + crate::shortcut_editor::sync(&crate::state::UiState::default()); + assert_eq!(default_command_shortcut("ui.rename"), None); + assert_eq!(command_for_key("F2"), None); + let (mut app, _, _) = two_rects(); + let listed = app.run("shortcuts.list", json!({"query": "ui.rename"})).unwrap(); + let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| r["label"].clone()).collect(); + assert_eq!(rows, [json!("Rename")], "Keyboard Shortcuts lists it"); +} + +/// Without a selection Rename names the current layer; it refuses several objects and a row the +/// panel doesn't list, and opens nothing then. +#[test] +fn rename_names_the_current_layer_and_refuses_several_or_hidden_rows() { + let (mut app, layer, [a, b]) = two_rects(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let open = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(u64, String)>(rename_id())).map(|r| r.0); + assert_eq!(app.run("ui.rename", json!({})).unwrap()["id"], json!(layer.0), "nothing selected: the current layer"); + ctx.data_mut(|d| d.remove::<(u64, String)>(rename_id())); + app.session.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert!(app.run("ui.rename", json!({})).is_err(), "two objects"); + assert_eq!(open(&ctx), None); + app.ui.layers_panel.layers_only = true; + assert!(app.run("ui.rename", json!({"id": a.0})).is_err(), "Show Layers Only lists no object rows"); + assert_eq!(open(&ctx), None); + assert!(app.run("ui.rename", json!({"id": 999_999})).is_err(), "no such object"); + assert_eq!(app.run("ui.rename", json!({"id": layer.0})).unwrap()["id"], json!(layer.0)); + assert_eq!(open(&ctx), Some(layer.0)); +} + #[test] fn an_open_rename_does_not_follow_into_another_document() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/layers/thumbs.rs b/crates/ui-egui/src/panels/layers/thumbs.rs index dea908ea07..49ce4b61b9 100644 --- a/crates/ui-egui/src/panels/layers/thumbs.rs +++ b/crates/ui-egui/src/panels/layers/thumbs.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use vectorcraft_doc::{NodeKind, TextKind}; use vectorcraft_geom::PathData; @@ -51,10 +52,14 @@ type ThumbJob = ((u64, NodeId), Weak, u32); #[derive(Default)] pub(super) struct Thumbs { entries: HashMap<(u64, NodeId), ThumbEntry>, + /// Documents still open. None until the app first synchronizes its documents. + open_docs: Option>, /// What the worker is rendering, by row. pending: HashMap<(u64, NodeId), (Weak, u32)>, worker: Option>, worker_started: bool, + /// The uid of the document whose rows were last drawn: the worker holds jobs for it alone. + pub(super) showing: Option, settle: Settle, /// (pass, ms, count) rendered on the UI thread in that pass. spent: (u64, f64, u32), @@ -76,9 +81,31 @@ const LIGHT_THUMB_MS: f64 = 4.0; const LIGHT_THUMB_NODES: usize = 200; /// A node whose paths have more anchors than this in all has its first thumbnail made on the -/// worker. +/// worker. Type's glyphs, mesh points and image pixels count against it too, each as the anchors +/// that take about as long to render: [`GLYPH_ANCHORS`], [`MESH_POINT_ANCHORS`] and +/// [`IMAGE_PIXELS_PER_ANCHOR`]. const LIGHT_THUMB_ANCHORS: usize = 2_000; +/// Anchors one glyph of type counts as. +const GLYPH_ANCHORS: usize = 4; + +/// Anchors one point of a gradient mesh counts as. +const MESH_POINT_ANCHORS: usize = 1; + +/// Pixels of an image that count as one anchor. +const IMAGE_PIXELS_PER_ANCHOR: usize = 100; + +/// The most symbols and placed documents counted inside one another: a node holding them deeper +/// (a symbol whose art holds an instance of itself, for one) has its first thumbnail made on the +/// worker. +const MAX_THUMB_NESTING: usize = 8; + +/// The most steps counting a node takes: each object, subpath, text run and symbol looked at is +/// one step, and so is every 64 bytes of a symbol or placed file name looked up. A node that +/// needs more has its thumbnail made on the worker, and the painted thumbnail draws nothing for +/// it. A row drawn before counts at most this many objects too. +const THUMB_COUNT_STEPS: usize = 20_000; + /// At most this long (ms) and this many thumbnails are rendered on the UI thread in a pass; the /// rest go to the worker, or wait for the next pass where there is none. const THUMB_BUDGET_MS: f64 = 8.0; @@ -93,34 +120,130 @@ pub(crate) fn thumb_options() -> vectorcraft_render::RenderOptions { /// Has `n` at most `nodes` objects inside it, and at most `anchors` anchors in its paths and the /// paths inside it, the frames of area type and the paths of type on a path included (counting /// stops at either limit)? With `masks`, the art of the opacity masks that are not disabled, and -/// the objects and anchors inside it, count as well. -fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool) -> bool { - fn own_anchors(n: &Node) -> usize { - match &n.kind { - NodeKind::Text(t) => match &t.kind { - TextKind::Area { frame: p } | TextKind::OnPath { path: p, .. } => p.anchor_count(), - TextKind::Point => 0, - }, - _ => n.path_data().map_or(0, PathData::anchor_count), +/// the objects and anchors inside it, count as well. With `doc` (the document `n` is in), type's +/// glyphs, mesh points and image pixels count as anchors too ([`LIGHT_THUMB_ANCHORS`]), and a +/// symbol instance and a placed document count the objects and anchors of the art they show: the +/// symbol's art in `doc`, and the placed file's art when it has been read (a placed document whose +/// file has not been read, or art nested deeper than [`MAX_THUMB_NESTING`], is not small). A node +/// that takes more than [`THUMB_COUNT_STEPS`] steps to count is not small. +fn small_node(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> bool { + weigh(n, nodes, anchors, masks, doc).0 +} + +/// [`small_node`], and the steps counting took. +fn weigh(n: &Node, nodes: usize, anchors: usize, masks: bool, doc: Option<&Document>) -> (bool, usize) { + /// What may still be counted. + struct Left { + nodes: usize, + anchors: usize, + steps: usize, + masks: bool, + } + impl Left { + /// Count `anchors` more: false past the limit. + fn take(&mut self, anchors: usize) -> bool { + match self.anchors.checked_sub(anchors) { + Some(left) => { + self.anchors = left; + true + } + None => false, + } + } + /// Take `steps` more: false past the limit. + fn step(&mut self, steps: usize) -> bool { + match self.steps.checked_sub(steps) { + Some(left) => { + self.steps = left; + true + } + None => false, + } + } + /// Look up `name`: false past the step limit. + fn look_up(&mut self, name: &str) -> bool { + self.step(1 + name.len() / 64) + } + /// Count one more object: false past the limit. + fn object(&mut self) -> bool { + match self.nodes.checked_sub(1) { + Some(left) => { + self.nodes = left; + true + } + None => false, + } + } + /// Count the anchors of `p`, a step for each subpath. + fn path(&mut self, p: &PathData) -> bool { + p.subpaths.iter().all(|s| self.step(1) && self.take(s.anchors.len())) } } - fn count(n: &Node, nodes: &mut usize, anchors: &mut usize, masks: bool) -> bool { - let Some(left) = anchors.checked_sub(own_anchors(n)) else { return false }; - *anchors = left; - let mask = n.extras().mask.as_deref().filter(|m| masks && !m.disabled).map(|m| &m.art); - for c in n.children().into_iter().flatten().chain(mask) { - if *nodes == 0 { + /// Count `art`, drawn in place of an object (`doc` its document), one level deeper. + fn inside(art: &Node, doc: &Document, left: &mut Left, depth: usize) -> bool { + depth < MAX_THUMB_NESTING && left.object() && count(art, Some(doc), left, depth + 1) + } + /// Count symbol `name` of `doc` (one that doesn't exist draws nothing). + fn symbol(name: &str, doc: &Document, left: &mut Left, depth: usize) -> bool { + for s in &doc.symbols { + if !left.look_up(name) { return false; } - *nodes -= 1; - if !count(c, nodes, anchors, masks) { - return false; + if s.name == name { + return inside(&s.art, doc, left, depth); } } true } - let (mut nodes, mut anchors) = (nodes, anchors); - count(n, &mut nodes, &mut anchors, masks) + /// Count what `n` draws besides its children. + fn own(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { + let path = match &n.kind { + NodeKind::Text(t) => match &t.kind { + TextKind::Area { frame: p } | TextKind::OnPath { path: p, .. } => Some(p), + TextKind::Point => None, + }, + _ => n.path_data(), + }; + if !path.is_none_or(|p| left.path(p)) { + return false; + } + let Some(doc) = doc else { return true }; + match &n.kind { + // Glyphs are counted only up to one past what the anchors left allow. + NodeKind::Text(t) => t.runs.iter().all(|r| { + let glyphs = r.text.chars().take(left.anchors / GLYPH_ANCHORS + 1).count(); + left.step(1) + && left.take(glyphs.saturating_mul(GLYPH_ANCHORS)) + && r.inline.as_ref().is_none_or(|a| symbol(&a.symbol, doc, left, depth)) + }), + NodeKind::SymbolInstance { symbol: name, .. } => symbol(name, doc, left, depth), + NodeKind::Mesh(m) => left.take(m.points.len().saturating_mul(MESH_POINT_ANCHORS)), + NodeKind::Image(im) => left.take((im.width as usize).saturating_mul(im.height as usize) / IMAGE_PIXELS_PER_ANCHOR), + NodeKind::PlacedDocument(p) => { + left.look_up(&p.key) && vectorcraft_doc::placed_document::read_cached(p).is_some_and(|e| inside(&e.art, &e.doc, left, depth)) + } + _ => true, + } + } + fn count(n: &Node, doc: Option<&Document>, left: &mut Left, depth: usize) -> bool { + if !(left.step(1) && own(n, doc, left, depth)) { + return false; + } + let mask = n.extras().mask.as_deref().filter(|m| left.masks && !m.disabled).map(|m| &m.art); + n.children().into_iter().flatten().chain(mask).all(|c| left.object() && count(c, doc, left, depth)) + } + let mut left = Left { nodes, anchors, steps: THUMB_COUNT_STEPS, masks }; + let small = count(n, doc, &mut left, 0); + (small, THUMB_COUNT_STEPS - left.steps) +} + +/// Is row `n` (an object of `doc`) light enough to make its thumbnail on the UI thread? `quick`: +/// whether its last thumbnail was quick to render, if it has one. +fn light_row(n: &Node, quick: Option, doc: &Document) -> bool { + match quick { + Some(quick) => quick && small_node(n, THUMB_COUNT_STEPS, LIGHT_THUMB_ANCHORS, true, Some(doc)), + None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, Some(doc)), + } } /// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or the worker. @@ -129,6 +252,50 @@ fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, } impl Thumbs { + #[cfg(test)] + pub(super) fn cached(&self, uid: u64) -> bool { + self.entries.keys().any(|key| key.0 == uid) + } + + /// Release thumbnails and queued jobs for documents that have closed, keeping the cache for + /// other open documents even when the panels are hidden or another document is active. When a + /// document closes, the worker drops its jobs, the one running included, and the images it + /// finished that the panels have not collected yet. + fn retain_open(&mut self, uids: &[u64]) { + if self.open_docs.as_ref().is_some_and(|open| open.len() == uids.len() && uids.iter().all(|uid| open.contains(uid))) { + return; + } + let open: HashSet = uids.iter().copied().collect(); + let closed = self.open_docs.as_ref().is_some_and(|before| before.iter().any(|uid| !open.contains(uid))); + let stale = + self.entries.keys().chain(self.pending.keys()).any(|key| !open.contains(&key.0)) || self.showing.is_some_and(|uid| !open.contains(&uid)); + self.entries.retain(|key, _| open.contains(&key.0)); + self.pending.retain(|key, _| open.contains(&key.0)); + self.showing = self.showing.filter(|uid| open.contains(uid)); + if closed { + // Images finished before now are dropped with the rest of the queue: the open + // documents' rows are asked for again. + if let Some(w) = &self.worker { + let open = open.clone(); + w.forget(move |key| !open.contains(&key.0)); + if w.poll().is_none() { + self.worker = None; + } + } + self.pending.clear(); + } else if stale + && let Some(w) = &self.worker + && !w.discard({ + let open = open.clone(); + move |key| !open.contains(&key.0) + }) + { + self.worker = None; + self.pending.clear(); + } + self.open_docs = Some(open); + } + /// Keep `img` (None: nothing drawn) as the thumbnail of row `key` showing `node`. fn upload(&mut self, ctx: &egui::Context, key: (u64, NodeId), node: Weak, px: u32, img: Option<&vectorcraft_render::Rendered>, ms: f64) { let color = img.map(crate::canvas::color_image); @@ -157,9 +324,30 @@ impl Thumbs { } } + /// The panels draw the rows of document `uid` (None: no document). When that is another + /// document than before, the worker drops the jobs it has not started for every other + /// document, so they don't hold up this one's thumbnails, and those rows are asked for again + /// when their document shows again. The thumbnails of still-open documents stay. + pub(super) fn show(&mut self, uid: Option) { + if self.showing == uid { + return; + } + self.showing = uid; + self.pending.retain(|key, _| Some(key.0) == uid); + if let Some(w) = &self.worker + && !w.discard(move |key| Some(key.0) != uid) + { + self.worker = None; + self.pending.clear(); + } + } + /// Keep the thumbnail `d` the worker finished. fn receive(&mut self, ctx: &egui::Context, d: Done) { let (key, node, px) = d.key; + if self.open_docs.as_ref().is_some_and(|open| !open.contains(&key.0)) { + return; + } if self.pending.get(&key).is_some_and(|(p, ppx)| p.ptr_eq(&node) && *ppx == px) { self.pending.remove(&key); } @@ -187,6 +375,7 @@ impl Thumbs { for d in done { self.receive(ctx, d); } + self.show(Some(src.uid)); let key = (src.uid, n.id); let pass = ctx.cumulative_pass_nr(); let (fresh, light) = match self.entries.get_mut(&key) { @@ -209,10 +398,7 @@ impl Thumbs { let in_budget = self.spent.1 < THUMB_BUDGET_MS && self.spent.2 < THUMB_BUDGET_COUNT; // A row drawn before is light when its last thumbnail was quick to render, unless its // object now has more anchors than the limit. - let light = match light { - Some(quick) => quick && small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, true), - None => small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true), - } && in_budget; + let light = light_row(n, light, src.doc) && in_budget; if !light && let Some(w) = &self.worker { let (doc, node) = (src.doc.clone(), n.clone()); let job: ThumbJob = (key, Arc::downgrade(n), px); @@ -241,6 +427,17 @@ impl Thumbs { } } +/// The Layers or Links panel shows the rows of document `uid` in this frame (None: no document +/// is open), whether or not a thumbnail is drawn; see [`Thumbs::show`]. +pub(crate) fn show_thumbs_of(uid: Option) { + THUMBS.with(|c| c.borrow_mut().show(uid)); +} + +/// Forget thumbnails of documents no longer open, even if neither thumbnail panel is shown. +pub(crate) fn retain_open_thumbs(uids: &[u64]) { + THUMBS.with(|c| c.borrow_mut().retain_open(uids)); +} + /// A real rendered thumbnail of row `n`, cached by node identity (unchanged nodes keep their `Arc` /// allocation, so the address is a free change detector). Only rendered for visible rows; see /// [`Thumbs::texture`] for when. @@ -260,10 +457,11 @@ pub(crate) fn real_thumb(ui: &Ui, src: &ThumbSource, n: &Arc, r: egui::Rec } /// Tiny vector thumbnail painted with egui (fallback when rendering isn't possible). A node with -/// more than [`LIGHT_THUMB_ANCHORS`] anchors paints nothing, since this runs on every frame and +/// more than [`LIGHT_THUMB_ANCHORS`] anchors, or that takes more than [`THUMB_COUNT_STEPS`] steps +/// to count, paints nothing, since this runs on every frame and /// measuring its bounds takes time in proportion to its anchor count. pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { - if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false) { + if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false, None) { return; } let Some(b) = n.visual_bounds() else { return }; @@ -293,10 +491,51 @@ pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) { mod tests { use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, LayerColor, NodeKind, OpacityMask, TextKind, TextObject}; - use vectorcraft_geom::{Point, SubPath}; + use vectorcraft_geom::{Affine, Point, SubPath}; use super::*; + #[test] + fn a_finished_job_cannot_restore_a_closed_documents_thumbnail() { + let mut thumbs = Thumbs::default(); + let ctx = egui::Context::default(); + thumbs.retain_open(&[2]); + thumbs.receive(&ctx, Done { key: ((1, NodeId(1)), Weak::new(), 16), img: None, ms: 0.0 }); + assert!(thumbs.entries.is_empty(), "a closed document's late result is discarded"); + thumbs.receive(&ctx, Done { key: ((2, NodeId(2)), Weak::new(), 16), img: None, ms: 0.0 }); + assert!(thumbs.entries.contains_key(&(2, NodeId(2))), "an open document's result is kept"); + } + + #[test] + fn closing_a_document_drops_the_image_its_running_job_finishes_while_the_panels_are_hidden() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + thumbs.retain_open(&[1, 2]); + // A job of document 1 is running, so discarding the queue cannot drop it. + let (started, running) = std::sync::mpsc::channel::<()>(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let key = (1, NodeId(1)); + let job: crate::thumb_worker::JobFn = Box::new(move |_| { + started.send(()).ok(); + held.recv().ok(); + None + }); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Weak::new(), 1), job))); + running.recv().expect("the job starts"); + // Another row of document 1 waits behind it. + let queued = (1, NodeId(3)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(queued, (queued, Weak::new(), 1), Box::new(|_| None)))); + // Document 1 closes while no panel collects results, then its running job finishes. + thumbs.retain_open(&[2]); + release.send(()).ok(); + // A job of document 2 queued after them comes back first: document 1's images were dropped. + let next = (2, NodeId(2)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(next, (next, Weak::new(), 1), Box::new(|_| None)))); + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the same worker finishes document 2's job"); + assert_eq!(done.key.0, next, "no worker keeps the closed document's image"); + } + /// An open zigzag of `anchors` anchors. fn line(anchors: usize) -> PathData { let pts: Vec = (0..anchors).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64 * 50.0)).collect(); @@ -330,7 +569,12 @@ mod tests { } fn small(n: &Node) -> bool { - small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true) + small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, None) + } + + /// Is `n`, an object of `doc`, small? + fn small_in(doc: &Document, n: &Node) -> bool { + small_node(n, LIGHT_THUMB_NODES, LIGHT_THUMB_ANCHORS, true, Some(doc)) } /// `n` with an opacity mask of `art`, disabled or not. @@ -350,7 +594,7 @@ mod tests { assert!(!small(&masked(rect(1), inner, false)), "a mask holding a long path"); let child = Node::group(NodeId(1), vec![Arc::new(masked(rect(4), long(), false))]); assert!(!small(&child), "a group holding an object with a long mask"); - assert!(small_node(&masked(rect(1), long(), false), usize::MAX, LIGHT_THUMB_ANCHORS, false), "masks left out"); + assert!(small_node(&masked(rect(1), long(), false), usize::MAX, LIGHT_THUMB_ANCHORS, false, None), "masks left out"); } #[test] @@ -373,6 +617,179 @@ mod tests { assert!(!small(&both), "a path and an area frame whose anchors together pass the limit"); } + /// Point type `id` of `glyphs` glyphs. + fn glyphs(id: u64, glyphs: usize) -> Node { + let t = TextObject::point(Point::ZERO, &"a".repeat(glyphs), CharStyle::default()); + Node::new(NodeId(id), NodeKind::Text(Box::new(t))) + } + + /// A gradient mesh `id` of `rows` x `rows` patches. + fn mesh(id: u64, rows: u32) -> Node { + let m = vectorcraft_doc::GradientMesh::from_surface(rows, rows, &|u, v| Point::new(u * 100.0, v * 100.0), &|_, _| Color::BLACK); + Node::new(NodeId(id), NodeKind::Mesh(m)) + } + + /// An image `id` of `w` x `h` pixels. + fn image(id: u64, w: u32, h: u32) -> Node { + let im = vectorcraft_doc::ImageObject { + key: "im".into(), + width: w, + height: h, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + Node::new(NodeId(id), NodeKind::Image(Box::new(im))) + } + + /// An instance `id` of symbol `name`. + fn instance(id: u64, name: &str) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) + } + + /// A document whose symbol `name` is `art`. + fn with_symbol(name: &str, art: Node) -> Document { + let mut doc = Document::new(200.0, 200.0); + doc.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); + doc + } + + /// A placed document `id` showing file `key`, read already when `art` is given. + fn placed(id: u64, key: &str, art: Option) -> Node { + let p = vectorcraft_doc::PlacedDocument { + link: vectorcraft_doc::LinkInfo::new("/art/placed.vectorcraft"), + key: key.into(), + bounding: false, + page_box: Default::default(), + width: 100.0, + height: 100.0, + xf: Affine::IDENTITY, + placement: Default::default(), + }; + if let Some(art) = art { + let frame = vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0); + vectorcraft_doc::placed_document::prime(&p, Arc::new(key.as_bytes().to_vec()), (Document::new(100.0, 100.0), art, frame)); + } + Node::new(NodeId(id), NodeKind::PlacedDocument(Box::new(p))) + } + + #[test] + fn type_meshes_and_images_count_their_work_as_anchors() { + let doc = Document::new(200.0, 200.0); + let limit = LIGHT_THUMB_ANCHORS / GLYPH_ANCHORS; + assert!(small_in(&doc, &glyphs(1, limit)), "type of as many glyphs as the limit"); + assert!(!small_in(&doc, &glyphs(1, limit + 1)), "type of more glyphs"); + assert!(!small_in(&doc, &glyphs(1, 5_000)), "long type"); + let beside = Node::group(NodeId(1), vec![Arc::new(glyphs(2, limit / 2)), Arc::new(path(3, LIGHT_THUMB_ANCHORS / 2 + 1))]); + assert!(!small_in(&doc, &beside), "type and a path that together pass the limit"); + // (rows + 1)² points: 1,936 and 2,025. + assert!(small_in(&doc, &mesh(1, 43)), "a small mesh"); + assert!(!small_in(&doc, &mesh(1, 44)), "a mesh of more points"); + let px = (LIGHT_THUMB_ANCHORS * IMAGE_PIXELS_PER_ANCHOR) as u32; + assert!(small_in(&doc, &image(1, px / 100, 100)), "an image of as many pixels as the limit"); + assert!(!small_in(&doc, &image(1, px / 100, 101)), "a larger image"); + assert!(!small_in(&doc, &image(1, 4_000, 3_000)), "a photo"); + // Without the document only paths and frames count, as the painted thumbnail needs. + assert!(small(&glyphs(1, 5_000)) && small(&mesh(1, 100)) && small(&image(1, 4_000, 3_000))); + } + + #[test] + fn a_symbol_instance_and_a_placed_document_count_the_art_they_show() { + let doc = with_symbol("Long", path(10, LIGHT_THUMB_ANCHORS + 1)); + assert!(!small_in(&doc, &instance(1, "Long")), "an instance of a symbol of a long path"); + assert!(small(&instance(1, "Long")), "without the document"); + assert!(small_in(&doc, &instance(1, "Missing")), "an instance of a symbol that doesn't exist"); + let doc = with_symbol("Short", path(10, LIGHT_THUMB_ANCHORS)); + assert!(small_in(&doc, &instance(1, "Short")), "an instance of a symbol of a path at the limit"); + let two = Node::group(NodeId(1), vec![Arc::new(instance(2, "Short")), Arc::new(instance(3, "Short"))]); + assert!(!small_in(&doc, &two), "two instances whose art together passes the limit"); + let many = with_symbol("Group", Node::group(NodeId(10), (0..LIGHT_THUMB_NODES).map(|i| Arc::new(rect(i as u64 + 11))).collect())); + assert!(!small_in(&many, &instance(1, "Group")), "a symbol of more objects than the limit"); + // Inline graphics in type draw their symbol too. + let mut t = TextObject::point(Point::ZERO, "a", CharStyle::default()); + t.runs[0].inline = Some(vectorcraft_doc::InlineArt { symbol: "Long".into(), scale: 1.0, baseline_shift: 0.0, bounds: None }); + let long = with_symbol("Long", path(10, LIGHT_THUMB_ANCHORS + 1)); + assert!(!small_in(&long, &Node::new(NodeId(1), NodeKind::Text(Box::new(t)))), "type showing a long symbol inline"); + + let doc = Document::new(200.0, 200.0); + assert!(small_in(&doc, &placed(1, "thumbs-small-placed", Some(path(10, LIGHT_THUMB_ANCHORS)))), "a placed file of a short path"); + assert!(!small_in(&doc, &placed(1, "thumbs-long-placed", Some(path(10, LIGHT_THUMB_ANCHORS + 1)))), "a placed file of a long path"); + assert!(!small_in(&doc, &placed(1, "thumbs-unread-placed", None)), "a placed file not read yet"); + } + + #[test] + fn a_symbol_that_holds_itself_is_not_small_and_is_counted_to_an_end() { + let doc = with_symbol("Loop", Node::group(NodeId(10), vec![Arc::new(rect(11)), Arc::new(instance(12, "Loop"))])); + assert!(!small_in(&doc, &instance(1, "Loop"))); + assert!(!small_node(&instance(1, "Loop"), usize::MAX, usize::MAX, true, Some(&doc)), "without limits on objects and anchors"); + // Nested as deep as counted, the art is small. + let mut doc = with_symbol("S0", rect(10)); + for i in 1..MAX_THUMB_NESTING { + let art = Node::group(NodeId(10 + i as u64), vec![Arc::new(instance(100 + i as u64, &format!("S{}", i - 1)))]); + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("S{i}"), art: Arc::new(art), dynamic: false }); + } + assert!(small_in(&doc, &instance(1, &format!("S{}", MAX_THUMB_NESTING - 1))), "symbols as deep as counted"); + let art = Node::group(NodeId(9), vec![Arc::new(instance(99, &format!("S{}", MAX_THUMB_NESTING - 1)))]); + doc.symbols.push(vectorcraft_doc::Symbol { name: "Deeper".into(), art: Arc::new(art), dynamic: false }); + assert!(!small_in(&doc, &instance(1, "Deeper")), "one level deeper"); + } + + /// A document of symbols `L0` to `L{levels}`: `L0` is an empty group, and each one above it a + /// group of `fan` instances of the one below. + fn fan_out(levels: usize, fan: usize) -> Document { + let mut doc = with_symbol("L0", Node::group(NodeId(10), vec![])); + let mut id = 100; + for level in 1..=levels { + let below = format!("L{}", level - 1); + let kids = (0..fan) + .map(|_| { + id += 1; + Arc::new(instance(id, &below)) + }) + .collect(); + id += 1; + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("L{level}"), art: Arc::new(Node::group(NodeId(id), kids)), dynamic: false }); + } + doc + } + + #[test] + fn symbols_that_each_hold_many_instances_are_counted_within_the_step_limit() { + // 40 instances on each of 4 levels: 40⁴ (2,560,000) empty groups, and no anchors. + let doc = fan_out(4, 40); + let top = instance(1, "L4"); + assert!(!light_row(&top, Some(true), &doc), "a row drawn before, quick to render"); + assert!(!light_row(&top, None, &doc), "a row not drawn yet"); + let (small, steps) = weigh(&top, THUMB_COUNT_STEPS, usize::MAX, true, Some(&doc)); + assert!(!small && steps <= THUMB_COUNT_STEPS, "{steps} steps"); + let (small, steps) = weigh(&top, usize::MAX, usize::MAX, true, Some(&doc)); + assert!(!small && steps <= THUMB_COUNT_STEPS, "{steps} steps without a limit on objects"); + // 5 instances on each of 3 levels stay light once drawn quickly. + let doc = fan_out(3, 5); + assert!(light_row(&instance(1, "L3"), Some(true), &doc)); + assert!(!light_row(&instance(1, "L3"), Some(false), &doc), "drawn slowly"); + } + + #[test] + fn empty_subpaths_text_runs_and_symbol_lookups_take_steps() { + let doc = Document::new(200.0, 200.0); + let style = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let empty = Node::path(NodeId(1), PathData::new(vec![SubPath::default(); THUMB_COUNT_STEPS]), style.clone()); + assert!(!small_in(&doc, &empty), "a path of many empty subpaths"); + let fewer = Node::path(NodeId(1), PathData::new(vec![SubPath::default(); 100]), style); + assert!(small_in(&doc, &fewer), "a path of a few"); + let mut t = TextObject::point(Point::ZERO, "", CharStyle::default()); + t.runs = vec![vectorcraft_doc::TextRun::new("", CharStyle::default()); THUMB_COUNT_STEPS]; + assert!(!small_in(&doc, &Node::new(NodeId(2), NodeKind::Text(Box::new(t)))), "type of many empty runs"); + let mut doc = with_symbol("S", rect(10)); + for i in 0..THUMB_COUNT_STEPS { + doc.symbols.push(vectorcraft_doc::Symbol { name: format!("Other {i}"), art: Arc::new(rect(11)), dynamic: false }); + } + assert!(small_in(&doc, &instance(1, "S")), "the first of many symbols"); + assert!(!small_in(&doc, &instance(1, &format!("Other {}", THUMB_COUNT_STEPS - 1))), "the last of many symbols"); + } + #[test] fn the_painted_thumbnail_leaves_out_a_long_path() { let ctx = egui::Context::default(); @@ -435,6 +852,147 @@ mod tests { assert!(thumbs.pending.is_empty()); } + /// A document of `rows` paths of 5,000 anchors on its layer, and the paths as the layer holds + /// them. + fn long_paths(rows: usize) -> (Arc, Vec>) { + let mut doc = Document::new(200.0, 200.0); + let layer = doc.layers.first().map(|l| l.id); + let ids: Vec = (0..rows) + .map(|_| { + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, path(id.0, 5_000)).unwrap(); + id + }) + .collect(); + let doc = Arc::new(doc); + let nodes = ids.iter().filter_map(|id| node_arc(&doc, *id)).collect(); + (doc, nodes) + } + + /// Keep the worker of `thumbs` busy with a job of row (0, 0) until the sender returned sends, + /// so the jobs submitted meanwhile wait in its queue. + fn hold(thumbs: &Thumbs) -> std::sync::mpsc::Sender<()> { + let (started, running) = std::sync::mpsc::channel::<()>(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let key = (0, NodeId(0)); + let job: crate::thumb_worker::JobFn = Box::new(move |_| { + started.send(()).ok(); + held.recv().ok(); + None + }); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Weak::new(), 1), job))); + running.recv().expect("the job starts"); + release + } + + /// The next job `thumbs`'s worker finishes, checked against the thumbnail of the same node in + /// `rows` of `doc` made on this thread, then kept. + fn receive_checked(ctx: &egui::Context, thumbs: &mut Thumbs, uid: u64, doc: &Document, rows: &[Arc]) { + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes a job"); + assert_eq!(done.key.0.0, uid, "a job of document {uid} is done next"); + let n = rows.iter().find(|n| n.id == done.key.0.1).expect("one of its rows"); + let there = done.img.as_ref().expect("the worker draws the path"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, 24).expect("this thread draws the path"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the path"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + thumbs.receive(ctx, done); + } + + #[test] + fn the_shown_documents_thumbnails_are_made_before_the_queued_ones_of_another() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + let (a, a_rows) = long_paths(3); + let (b, b_rows) = long_paths(2); + let release = hold(&thumbs); + let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false }; + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); + } + assert_eq!(thumbs.pending.len(), 3, "document 1's rows wait on the worker"); + // Document 2 shows before the worker gets to them. + let src_b = ThumbSource { uid: 2, revision: 1, doc: &b, busy: false }; + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_none()); + } + assert_eq!(thumbs.pending.keys().map(|k| k.0).collect::>(), [2, 2], "only the shown document's rows are pending"); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); + for _ in &b_rows { + receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows); + } + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some(), "the shown document's thumbnails are shown"); + } + // Shown again, document 1's rows are asked for again and come back. + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none()); + } + assert_eq!(thumbs.pending.keys().filter(|k| k.0 == 1).count(), 3); + for _ in &a_rows { + receive_checked(&ctx, &mut thumbs, 1, &a, &a_rows); + } + for n in &a_rows { + assert!(thumbs.texture(&ctx, &src_a, n, 24).is_some()); + } + // Document 2's thumbnails were kept: showing it again asks for nothing. + for n in &b_rows { + assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some()); + } + assert!(thumbs.pending.is_empty()); + assert_eq!(thumbs.renders, 0, "none was made on this thread"); + } + + #[test] + fn the_queued_thumbnails_of_a_closed_document_are_dropped() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + let (a, a_rows) = long_paths(3); + let release = hold(&thumbs); + let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false }; + for n in &a_rows { + thumbs.texture(&ctx, &src_a, n, 24); + } + // The document closes and no other shows. + thumbs.show(None); + assert!(thumbs.pending.is_empty()); + // A job queued after it, straight on the worker, comes back next. + let (b, b_rows) = long_paths(1); + let (doc, node) = (b.clone(), b_rows[0].clone()); + let key = (2, node.id); + let job: crate::thumb_worker::JobFn = Box::new(move |r| render_thumb(r, &doc, &node, 24)); + assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Arc::downgrade(&b_rows[0]), 24), job))); + release.send(()).expect("the held job is waiting"); + let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes"); + assert_eq!(held.key.0, (0, NodeId(0))); + receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows); + } + + #[test] + fn an_instance_of_a_long_symbols_thumbnail_is_made_on_the_worker_and_matches_one_made_here() { + let ctx = egui::Context::default(); + let Some(worker) = ThumbWorker::start(&ctx, "test") else { return }; + let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() }; + let mut doc = with_symbol("Long", path(900, 50_000)); + let layer = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(layer, usize::MAX, instance(id.0, "Long")).unwrap(); + let doc = Arc::new(doc); + let n = node_arc(&doc, id).unwrap(); + let src = ThumbSource { uid: 1, revision: 1, doc: &doc, busy: false }; + assert!(thumbs.texture(&ctx, &src, &n, 24).is_none(), "nothing is shown until it is made"); + assert_eq!(thumbs.renders, 0, "not made on this thread"); + assert!(thumbs.pending.contains_key(&(1, n.id)), "sent to the worker"); + let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes it"); + let there = done.img.as_ref().expect("the worker draws the symbol"); + let here = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &n, 24).expect("this thread draws the symbol"); + assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the symbol's art"); + assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels"); + } + #[test] fn a_row_whose_object_becomes_a_long_path_is_drawn_again_on_the_worker() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 2439ba8f27..33bcbb0479 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -130,13 +130,22 @@ fn grabbed(drag: &PanelDrag, library: &str) -> Option { } /// The kind and `library.add` params of what `drag` holds, to add to library `library`: a color -/// (not one of that library's own), or a gradient or pattern swatch, by its name. +/// (not one of that library's own; a spot colour with its swatch's name), or a gradient or pattern +/// swatch, by its name. fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> { let PanelDrag::Paint { paint, params, library: from, .. } = drag else { return None }; let swatch = || params.get("swatch").and_then(Value::as_str); match paint { Paint::Solid { color, .. } if from.as_ref().is_none_or(|(l, _)| l != library) => { - Some((ItemKind::Color, json!({ "kind": "fillColor", "color": color }))) + // A spot swatch's name (and tint) come along, so the library keeps the ink. + let mut add = json!({ "kind": "fillColor", "color": color }); + if let Some(s) = swatch() { + add["swatch"] = json!(s); + if let Some(t) = params.get("tint") { + add["tint"] = t.clone(); + } + } + Some((ItemKind::Color, add)) } Paint::Gradient(_) => swatch().map(|s| (ItemKind::Gradient, json!({ "kind": "fillGradient", "swatch": s }))), Paint::Pattern { .. } => swatch().map(|s| (ItemKind::Pattern, json!({ "kind": "fillPattern", "swatch": s }))), diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 64c3543498..5f7f575c8f 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -375,6 +375,29 @@ fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { assert!(matches!(fill(&app), Paint::Pattern { ref pattern, .. } if pattern == "Checks"), "{:?}", fill(&app)); } +/// A spot swatch dropped on the list (as the Swatches panel drags it, with its name) is added as +/// a spot colour of that ink, at its tint (#5812). +#[test] +fn a_spot_swatch_dropped_on_the_list_stays_spot() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + app.run("swatch.new", json!({"name": "Kiss-cut", "color": "#ff00ff", "spot": true})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::panels::set_pstate(&ctx, LIST_VIEW, true); + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + let into = at(&texts, "Brand").center() + vec2(0.0, 80.0); + for tint in [1.0, 0.5] { + let paint = app.session.active().unwrap().doc.tint_paint("Kiss-cut", tint).unwrap(); + let drag = PanelDrag::Paint { params: crate::panels::paint_params(&paint), paint, rows: None, library: None }; + drop_at(&mut app, &ctx, drag, into); + } + let lib = app.session.libraries.get("Brand").unwrap(); + let inks: Vec<_> = lib.colors.iter().map(|c| (c.spot.as_deref(), c.tint)).collect(); + assert_eq!(inks, [(Some("Kiss-cut"), 1.0), (Some("Kiss-cut"), 0.5)]); +} + /// New Group… and Rename Group… ask for a name and act on the library and group they came /// from; the dialog shows only the name. #[test] diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 9fc91f5068..a7fe30185f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -4,7 +4,8 @@ //! from the last row clicked without Shift to it (with Ctrl/Cmd, adds them); the buttons Relink, //! Go To, Update and Edit Original act on the selected rows; Link Info shows the details of the //! first. The flyout adds Relink to Folder, Find in Folder (Find Linked Files: -//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Show filters, Sort, thumbnail size +//! `ui.findLinksInFolder`), Embed / Unembed, Placement Options, Select Linked / Embedded / Missing / +//! Modified (`addon.select.byLinkStatus`, Shift adds), Show filters, Sort, thumbnail size //! and Show in Folder. //! //! Everything runs through the `links.*` commands (`links.editOriginal` and `links.reveal` are UI @@ -316,6 +317,7 @@ fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64, pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let o = options(ui.ctx()); + super::layers::show_thumbs_of(app.session.active().map(|st| st.uid)); let Some(cache) = cached(app, ui.ctx(), &o) else { widgets::dim_label(ui, tl!("No document")); return; @@ -533,6 +535,8 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { row(ui, tl!("Status"), status.into()); } +/// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / +/// Missing / Modified for the whole document, and the Show, Sort and thumbnail options. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). @@ -596,6 +600,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, "links.reveal", json!({})); } ui.separator(); + // Select Linked, Embedded, Missing and Modified: every such image in the document, not only + // the rows shown; with Shift, added to the selection. + use crate::addons::select::link_status; + for (i, (status, label, _)) in link_status::STATUSES.iter().enumerate() { + if menu_item(ui, tl!(label), app.ui.link_statuses.has.get(i).copied().unwrap_or(false), false) { + let p = json!({ "status": status }); + let p = if ui.input(|i| i.modifiers.shift) { link_status::with_shift(p) } else { p }; + crate::menus::invoke(app, link_status::COMMAND, p); + } + } + ui.separator(); for (id, label) in SHOW { if menu_item(ui, tl!(label), true, o.show == id) { set_options(ui.ctx(), |o| o.show = id); diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 66f907f92a..8cb29ef305 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -380,14 +380,66 @@ fn selected_alignment(app: &VectorcraftApp, fallback: &ParaStyle) -> Option), and +/// its alignment buttons align text as the Paragraph panel's do +/// (). The bar keeps to the three that +/// don't justify, for its room; all seven are in the Paragraph options the link opens. +const CONTROL_BAR_ALIGNMENTS: usize = 3; + +/// The spacing between the Control bar's alignment buttons, as in the Paragraph panel's row. +const CONTROL_BAR_BUTTON_SPACING: f32 = 3.0; + +/// The width of the Paragraph panel in the Control bar's popover, as the Character panel's. +const CONTROL_BAR_POPOVER_WIDTH: f32 = 260.0; + +/// The Control bar's Paragraph link, as it is drawn and measured. +fn control_bar_link_text(ui: &Ui) -> egui::RichText { + egui::RichText::new(tl!("Paragraph:")).size(12.0).color(Tokens::get(ui.ctx()).text).underline() +} + +/// The Control bar's paragraph controls while type is selected or edited (#5372), after its +/// Character controls: the Paragraph link, which opens the Paragraph panel in a popover under it, +/// and the Align left, Align center and Align right buttons, `size` points square as the bar's others. `reserve` gives the room the controls +/// after them keep, asked only when type is selected: short of room, the buttons are left out, +/// then the link too. Returns whether the link shows. +pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, size: f32, reserve: impl FnOnce(&Ui) -> f32) -> bool { + let Some((_, para)) = text_style(app) else { return false }; + let text = control_bar_link_text(ui); + let link_width = widgets::text_width(ui, text.clone()); + let room = ui.available_width() - reserve(ui); + let link_room = link_width + ui.spacing().item_spacing.x; + if room < link_room { + return false; + } + let link = ui.link(text).on_hover_text(tl!("Paragraph options")); + widgets::popover(&link, link.clicked(), |ui| { + ui.set_width(CONTROL_BAR_POPOVER_WIDTH); + show(app, ui); + }); + if room >= link_room + (size + CONTROL_BAR_BUTTON_SPACING) * CONTROL_BAR_ALIGNMENTS as f32 { + let spacing = ui.spacing().item_spacing.x; + ui.spacing_mut().item_spacing.x = CONTROL_BAR_BUTTON_SPACING; + first_alignment_buttons(app, ui, ¶, size, CONTROL_BAR_ALIGNMENTS); + ui.spacing_mut().item_spacing.x = spacing; + } + true +} + /// Type › Bullets and Numbering › Apply Bullets (`type.applyBullets {bullet?}`): the paragraphs of /// the selected type, or those the Type tool's selection touches, become a bulleted list with /// `bullet`; without it, a list keeps its bullet and other paragraphs take the dot. diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 163427da5a..0423bc0c95 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -543,3 +543,150 @@ fn reset_panel_resets_the_hyphenation_options() { assert_eq!(serde_json::to_value(¶).unwrap().get("justification"), None, "saves no justification options"); } } + +type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + +/// An English context for headless Control bar frames, with AccessKit on to find its controls. +fn control_bar_ctx() -> egui::Context { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + ctx +} + +/// A document with the type `texts` (`text.create` params) makes, all of it selected. +fn control_bar_app(texts: &[Value]) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + let ids: Vec = texts.iter().map(|p| app.run("text.create", p.clone()).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + app +} + +/// The second of two headless frames of the whole Control bar, `width` wide (the first lays it out). +fn control_bar_nodes(ctx: &egui::Context, app: &mut VectorcraftApp, width: f32, events: Vec) -> Nodes { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 300.0)); + let mut nodes = Vec::new(); + for events in [events, vec![]] { + let mut out = + ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::control_bar(app, ui)); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + nodes +} + +/// The control named `name` (a button's or link's label, a label's text). +fn control_bar_node(nodes: &Nodes, name: &str) -> Option { + nodes.iter().find(|(_, n)| n.label() == Some(name) || n.value() == Some(name)).map(|(_, n)| n.clone()) +} + +/// Where the control named `name` ends, if it shows. +fn control_bar_end(nodes: &Nodes, name: &str) -> Option { + control_bar_node(nodes, name).and_then(|n| n.bounds()).map(|b| b.x1) +} + +/// The Control bar's Paragraph alignment buttons. +const BAR_ALIGNMENTS: [&str; 3] = ["Align left", "Align center", "Align right"]; + +/// #5372: with type selected, the Control bar shows a Paragraph section after the Character one, as +/// the public documentation's Control panel does: a Paragraph: link that opens the Paragraph panel +/// in a popover under it, and the Align left, Align center and Align right buttons. A click aligns +/// the selected type, and the button of its alignment shows selected. The buttons show on a bar of +/// common window widths. +#[test] +fn the_control_bar_shows_the_paragraph_alignment_of_the_selected_type() { + let ctx = control_bar_ctx(); + let mut app = control_bar_app(&[json!({"x": 20, "y": 50, "text": "Point"})]); + // Pinned, so that the room the buttons need can't creep up past common window widths. + for width in [1440.0, 1920.0] { + let nodes = control_bar_nodes(&ctx, &mut app, width, vec![]); + let ends = BAR_ALIGNMENTS.map(|n| control_bar_end(&nodes, n)); + assert!(ends.iter().all(|e| e.is_some_and(|x| x <= f64::from(width) - 10.0)), "pinned: the buttons show on a {width} pt window: {ends:?}"); + } + let width = 1920.0; + let nodes = control_bar_nodes(&ctx, &mut app, width, vec![]); + let center = |n: &egui::accesskit::Node| { + let b = n.bounds().unwrap_or_else(|| panic!("{n:?}")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + let click = |app: &mut VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + control_bar_nodes(&ctx, app, width, vec![egui::Event::PointerMoved(at), press(true)]); + control_bar_nodes(&ctx, app, width, vec![press(false)]); + control_bar_nodes(&ctx, app, width, vec![]) + }; + // A selected button shows pressed. + let on = |n: &egui::accesskit::Node| n.toggled() == Some(egui::accesskit::Toggled::True); + let button = control_bar_node(&nodes, "Align center").unwrap_or_else(|| panic!("the Control bar has Align center")); + assert!(!on(&button), "left-aligned type: Align center is not selected"); + assert!(control_bar_node(&nodes, "Align left").is_some_and(|n| on(&n)), "Align left shows selected"); + let undo = app.session.active().unwrap().history.undo.len(); + let nodes = click(&mut app, center(&button)); + assert_eq!(text_style(&app).unwrap().1.justify, Justify::Center, "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(control_bar_node(&nodes, "Align center").is_some_and(|n| on(&n)), "Align center shows selected"); + assert!(!control_bar_node(&nodes, "Align left").is_some_and(|n| on(&n)), "Align left no longer selected"); + // The Paragraph: link opens the Paragraph panel in a popover: its justifications show there, + // no panel docks, and a second click closes it. + let link = control_bar_node(&nodes, "Paragraph:").unwrap_or_else(|| panic!("the Paragraph: link")); + assert_eq!(link.description(), Some("Paragraph options")); + assert!(control_bar_node(&nodes, "Justify all lines").is_none(), "closed"); + let nodes = click(&mut app, center(&link)); + assert!(control_bar_node(&nodes, "Justify all lines").is_some(), "the popover shows the Paragraph panel"); + assert_eq!(app.ui.open_panel, None, "no panel docks"); + let nodes = click(&mut app, center(&link)); + assert!(control_bar_node(&nodes, "Justify all lines").is_none(), "a second click closes it"); +} + +/// #5372: at any width the Control bar trims itself from its right end, ending inside its margin. +/// With type selected the inline X/Y/W/H fields go first, then the Distribute and Align buttons, +/// area type's vertical alignment, the Paragraph buttons and last the Paragraph: link, while the +/// Transform link keeps its room; a wider bar never leaves out what a narrower one showed. For one point +/// type object, area type (its vertical alignment) and two objects (the Distribute buttons). +#[test] +fn the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right() { + let ctx = control_bar_ctx(); + let point = |x: i32| json!({"x": x, "y": 50, "text": "Point"}); + let area = json!({"x": 20, "y": 20, "text": "Area", "area": {"width": 100, "height": 120}}); + const VERTICAL: [&str; 4] = ["Align Top", "Align Center", "Align Bottom", "Justify Vertically"]; + for (case, texts) in [("point type", vec![point(20)]), ("area type", vec![area]), ("two objects", vec![point(20), point(300)])] { + let mut app = control_bar_app(&texts); + // Each group of controls in the bar's order, by its first and last control. + let mut groups: Vec<(&str, Vec<&str>)> = vec![("link", vec!["Paragraph:"]), ("buttons", BAR_ALIGNMENTS.to_vec())]; + if case == "area type" { + groups.push(("vertical alignment", VERTICAL.to_vec())); + } + groups.push(("Align", vec!["Horizontal Align Left", "Vertical Align Bottom"])); + if case == "two objects" { + groups.push(("Distribute", vec!["Vertical Distribute Top", "Horizontal Distribute Right"])); + } + groups.push(("X/Y/W/H", vec!["X:", "H:"])); + let mut seen = vec![false; groups.len()]; + for width in (600..=2400).step_by(10) { + let nodes = control_bar_nodes(&ctx, &mut app, width as f32, vec![]); + let inside = |x: f64| x <= f64::from(width) - 10.0; + let shown: Vec = groups + .iter() + .map(|(group, names)| { + let ends: Vec> = names.iter().map(|n| control_bar_end(&nodes, n)).collect(); + assert!(ends.iter().all(Option::is_some) || ends.iter().all(Option::is_none), "{case}, {width}: {group} {ends:?}"); + if let Some(Some(end)) = ends.last() { + assert!(inside(*end), "{case}, {width}: {group} ends at {end}"); + } + ends.iter().all(Option::is_some) + }) + .collect(); + // Narrower bars are already full before the section (the Character controls). + let transform = control_bar_end(&nodes, "Transform"); + assert!(!shown[0] || transform.is_some_and(inside), "{case}, {width}: Transform ends at {transform:?}"); + for (i, ((group, _), on)) in groups.iter().zip(&shown).enumerate() { + assert!(!seen[i] || *on, "{case}, {width}: {group} left out after a narrower bar showed it"); + assert!(!*on || shown[..i].iter().all(|s| *s), "{case}, {width}: {group} shows while a group before it is left out"); + seen[i] |= on; + } + } + assert!(seen.iter().all(|s| *s), "{case}: a wide bar shows every group: {seen:?}"); + } +} diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 4d08938c53..97959ed4a8 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -77,12 +77,19 @@ fn button(ui: &mut Ui, icon: &str, tip: &str, selected: bool, n: usize, min: usi } /// A Shape Mode button clicked: Alt makes a compound shape of the selection in `mode`; with -/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. +/// members of compound shapes selected they take `mode`; otherwise operation `op` runs. With the +/// Compound Shapes add-on's setting on, a click on the selection (not on members) makes the +/// compound shape and Alt gives the permanent result. fn shape_mode(app: &mut VectorcraftApp, ui: &Ui, op: &str, mode: ShapeMode, members: bool) { - if ui.input(|i| i.modifiers.alt) { + let alt = ui.input(|i| i.modifiers.alt); + if members { + if alt { + crate::menus::invoke(app, "object.compoundShape.make", json!({"mode": mode.name()})); + } else { + crate::menus::invoke(app, "object.compoundShape.setMode", json!({"mode": mode.name()})); + } + } else if alt != app.ui.shape_modes_compound { crate::menus::invoke(app, "object.compoundShape.make", json!({"mode": mode.name()})); - } else if members { - crate::menus::invoke(app, "object.compoundShape.setMode", json!({"mode": mode.name()})); } else { run(app, op); } @@ -588,4 +595,68 @@ mod tests { assert_eq!(app.last_pathfinder, None); assert!(!crate::menus::enabled(&app, "pathfinder.repeat")); } + + /// How many compound shapes the active document holds. + fn compound_shapes(app: &VectorcraftApp) -> usize { + let mut n = 0; + app.session.active().unwrap().doc.walk(|node| n += usize::from(node.is_compound_shape())); + n + } + + /// Off (the default) a Shape Mode click is the permanent Pathfinder result and Alt-click makes a + /// compound shape; with the Compound Shapes add-on's setting on it is the other way round. + #[test] + fn the_compound_shapes_setting_swaps_click_and_alt_on_the_shape_modes() { + // Off: unchanged. + let mut app = two_squares(); + assert!(!app.ui.shape_modes_compound); + click_button(&mut app, "Unite"); + assert_eq!((objects(&app).len(), compound_shapes(&app)), (1, 0), "a click is permanent"); + let mut app = two_squares(); + click_button_with_modifiers(&mut app, "Unite", egui::Modifiers::ALT); + assert_eq!(compound_shapes(&app), 1, "Alt makes a compound shape"); + + // On: a click makes the compound shape, Alt the permanent result. + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + assert!(app.ui.shape_modes_compound); + assert_eq!(crate::menus::checked(&app, "window.pathfinder.compoundShapes", &serde_json::Value::Null), Some(true)); + click_button(&mut app, "Unite"); + assert_eq!(compound_shapes(&app), 1, "a click makes a compound shape"); + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + click_button_with_modifiers(&mut app, "Unite", egui::Modifiers::ALT); + assert_eq!((objects(&app).len(), compound_shapes(&app)), (1, 0), "Alt is permanent"); + + // Toggled off again, and the check mark follows. + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + assert!(!app.ui.shape_modes_compound); + assert_eq!(crate::menus::checked(&app, "window.pathfinder.compoundShapes", &serde_json::Value::Null), Some(false)); + } + + /// Members of a compound shape that are selected take the clicked mode whatever the setting says. + #[test] + fn selected_members_take_the_mode_with_the_setting_on() { + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + click_button(&mut app, "Unite"); + let shape = app.session.active().unwrap().selection.objects[0]; + let front = app.session.active().unwrap().doc.node(shape).unwrap().children().unwrap().last().unwrap().id; + app.run("select.set", json!({"ids": [front.0]})).unwrap(); + click_button(&mut app, "Minus Front"); + assert_eq!(compound_shapes(&app), 1, "no second compound shape"); + assert_eq!(vectorcraft_engine::cmd::selected_member_modes(&app.session), [ShapeMode::Subtract]); + } + + /// The setting is kept with the preferences; preferences saved before it read as off. + #[test] + fn the_compound_shapes_setting_is_saved_and_older_preferences_read_as_off() { + let mut app = two_squares(); + app.run("window.pathfinder.compoundShapes", json!({})).unwrap(); + let mut saved = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["shape_modes_compound"], json!(true)); + assert!(serde_json::from_value::(saved.clone()).unwrap().shape_modes_compound); + saved.as_object_mut().unwrap().remove("shape_modes_compound"); + assert!(!serde_json::from_value::(saved).unwrap().shape_modes_compound); + } } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index b8a42e9285..306a9323f3 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -122,6 +122,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // any tool (, #4817). let blend_options = n_sel == 1 && matches!(first.as_ref().map(|n| &n.kind), Some(NodeKind::Blend { .. })); let merge_live_paint = n_sel > 1 && can_merge_live_paint(app); + // Repeat Options for one selected repeat (radial, grid or mirror), or one object of its source + // art in isolation mode: Object › Repeat › Options, the dialog of the repeat options pages + // (, + // #5181). + let repeat_options = n_sel == 1 && crate::menus::enabled(app, "object.repeat.options"); let mut actions: Vec<(&str, &str)> = vec![]; if n_sel > 1 { actions.push((tl!("Group"), "object.group")); @@ -133,6 +138,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if blend_options { actions.push((tl!("Blend Options"), "ui.blendOptions")); } + if repeat_options { + actions.push((tl!("Repeat Options"), "object.repeat.options")); + } if is_group { actions.push((tl!("Ungroup"), "object.ungroup")); actions.push((tl!("Isolate Group"), "object.isolate")); @@ -459,20 +467,27 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { } } -/// Edit Artboards (the Artboard tool): the active artboard's name, which can be edited to rename -/// it, and the Artboard Options icon; its position and size, its preset and -/// orientation (#671) (with Scale Artwork with Artboard on, a new size scales its art, #602; a new -/// W or H, preset or orientation goes to every selected artboard, in one undo step), its Fill (background color), Move -/// and Scale Artwork with Artboard, New Artboard and Delete Artboard, and Quick Actions: Rearrange All (#681) and -/// Exit back to the Selection tool (#530). +/// Edit Artboards (the Artboard tool), as in the reference app (#5219): a Transform section with +/// the active artboard's reference point, position and size (as in the Transform panel: X and Y +/// are the reference point's, and a new W or H keeps it in place, with the Constrain Width and +/// Height Proportions link; with Scale Artwork with Artboard on, a new size scales its art, #602; +/// a new W or H, preset or orientation goes to every selected artboard, in one undo step), its +/// preset and orientation (#671), and Move and Scale Artwork with Artboard; then an Artboards +/// section with its name, which can be edited to rename it, the Artboard Options icon, its Fill +/// (background color, also for every selected artboard), New Artboard and Delete Artboard; and +/// Quick Actions: Rearrange All (#681) and Exit back to the Selection tool (#530). fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { - let units = app.session.general_unit(); - let origin = app.ruler_origin(); let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); let i = super::artboards::selected(app, n); - let scale_art = super::artboards::scale_art(app); - let move_art = super::artboards::move_art(app); if let Some(ab) = app.session.active().and_then(|d| d.doc.artboards.get(i)).cloned() { + section_header(ui, tl!("Transform")); + let fw = super::field_width(ui); + super::transform::artboard_fields(app, ui, i, ab.rect, fw); + artboard_size_row(app, ui, i, ab.rect.width(), ab.rect.height()); + ui.add_space(2.0); + super::artboards::art_options(app, ui); + divider(ui); + section_header(ui, tl!("Artboards")); // The field shows the artboard's name as it is (names are never translated). Typing a new // name and pressing Enter or clicking elsewhere renames the artboard as the Artboards panel's // rename does; pressing Escape or leaving the field empty keeps the old name. A click on @@ -487,33 +502,7 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("tool.options", json!({"tool": "artboard"})).ok(); } }); - let fw = super::field_width(ui); - egui::Grid::new("ab-grid").num_columns(4).spacing([4.0, 6.0]).min_col_width(0.0).show(ui, |ui| { - let r = ab.rect; - for (row, [(l1, k1, v1), (l2, k2, v2)]) in - [[("X:", "x", r.x0), ("W:", "width", r.width())], [("Y:", "y", r.y0), ("H:", "height", r.height())]].into_iter().enumerate() - { - for (label, key, v) in [(l1, k1, v1), (l2, k2, v2)] { - dim_label(ui, label); - let offset = match key { - "x" => origin.x, - "y" => origin.y, - _ => 0.0, - }; - if let Some(v) = widgets::num_field_named(ui, ("ab", key, row), Some(tl!(label)), Some(v - offset), units, fw) { - // A new X or Y moves the active artboard; a new W or H goes to every selected one. - let indices = if matches!(key, "width" | "height") { super::artboards::resized_with(app, i) } else { vec![i] }; - let common = json!({"scaleArt": scale_art, "moveArt": move_art}); - super::artboards::set_props(app, &indices, common, |j, _| Some(json!({"index": j, key: v + offset}))).ok(); - } - } - ui.end_row(); - } - }); - artboard_size_row(app, ui, i, ab.rect.width(), ab.rect.height()); artboard_fill_row(app, ui, i, ab.color); - ui.add_space(2.0); - super::artboards::art_options(app, ui); } ui.add_space(4.0); let w = (ui.available_width() - 6.0) / 2.0; @@ -681,8 +670,11 @@ fn artboard_fill_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, color: Opt None => {} } }); + // A Fill chosen from the list goes to every selected artboard, in one undo step (#5698). if let Some(c) = set { - app.run("artboard.setProps", json!({"index": i, "color": c.as_ref().map(super::color_json)})).ok(); + let color = c.as_ref().map(super::color_json); + let indices = super::artboards::renamed_with(app, i); + super::artboards::set_props(app, &indices, json!({}), |j, _| Some(json!({"index": j, "color": color}))).ok(); } if pick { app.run("ui.colorPicker", json!({"artboard": i})).ok(); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 30ac3cd455..5e82d51f1a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -433,11 +433,11 @@ fn boards(app: &VectorcraftApp) -> Vec<(f64, f64, f64, f64)> { } /// #1482: with Artboards 1 and 3 selected, a W typed into Properties or the Transform panel -/// resizes both in one undo step, and Artboard 2 keeps its size. Properties keeps each top-left -/// corner; the Transform panel resizes each about its own center, its default reference point. +/// resizes both in one undo step, and Artboard 2 keeps its size. Both resize each about its own +/// center, their shared default reference point (#5219). #[test] fn artboard_width_resizes_every_selected_artboard_in_properties_and_transform() { - for (draw, centered) in [(show as fn(&mut VectorcraftApp, &mut Ui), false), (super::super::transform::show, true)] { + for (draw, centered) in [(show as fn(&mut VectorcraftApp, &mut Ui), true), (super::super::transform::show, true)] { let mut app = two_selected_artboards(); let before = boards(&app); let undo = app.session.doc().unwrap().history.undo.len(); @@ -499,6 +499,31 @@ fn properties_variable_font_button_for_variable_type() { assert!(frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Variable Font")); } +/// #5219: Edit Artboards starts with a Transform section (the reference point, X, Y, W and H, the +/// preset and orientation) above the Artboards section (the name, Artboard Options and Fill), as in +/// the reference app; X and Y are the reference point's, which the Transform panel shares. +#[test] +fn edit_artboards_shows_transform_above_the_artboard_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let texts = frame(&mut app, &ctx, vec![]); + let y = |label: &str| texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center().y).unwrap_or_else(|| panic!("{label} in {texts:?}")); + let (transform, artboards) = (y("Transform"), y("Artboards")); + assert!(transform < artboards, "{texts:?}"); + for label in ["X:", "Y:", "W:", "H:"] { + assert!((transform..artboards).contains(&y(label)), "{label} is in the Transform section: {texts:?}"); + } + for label in ["Artboard 1", "Fill:"] { + assert!(y(label) > artboards, "{label} is in the Artboards section: {texts:?}"); + } + // X and Y read the shared reference point, the center by default, as the Transform panel does. + // (100 pt is X and H, 50 pt is Y.) + assert!(texts.iter().filter(|(t, _)| t == "100 pt").count() == 2 && texts.iter().any(|(t, _)| t == "50 pt"), "{texts:?}"); +} + #[test] fn edit_artboards_adds_artboards_and_exits() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -665,6 +690,25 @@ fn edit_artboards_fill_sets_the_background_color() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields.get("artboard")), Some(Some(&json!(1))), "the chip opens it too"); } +/// #5698: with Artboards 1 and 3 selected, a Fill chosen in Edit Artboards goes to both, in one +/// command and one undo step; Artboard 2 keeps none. +#[test] +fn edit_artboards_fill_sets_every_selected_artboard() { + let mut app = two_selected_artboards(); + let colors = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards.iter().map(|a| a.color).collect::>(); + let undo = app.session.doc().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let texts = frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, &texts, "None"); + let texts = frame(&mut app, &ctx, vec![]); + let commands = app.run_count; + click(&mut app, &ctx, &texts, "Black"); + assert_eq!(app.run_count.wrapping_sub(commands), 1, "one command"); + assert_eq!(colors(&app), [Some(Color::BLACK), None, Some(Color::BLACK)]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); +} + fn artboard_deletion_app(count: usize) -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100, "artboards": count})).unwrap(); @@ -1320,6 +1364,34 @@ fn blend_options_is_a_quick_action_for_one_blend() { assert!(!shows(&tall(&mut app, &ctx, vec![]), "Blend Options"), "a rectangle"); } +/// One selected repeat, radial, grid or mirror, has Repeat Options in Quick Actions (#5181), which +/// opens the Repeat Options dialog with its values; a plain rectangle, or a repeat selected with +/// another object, does not. +#[test] +fn repeat_options_is_a_quick_action_for_one_repeat() { + let ctx = egui::Context::default(); + for (cmd, field) in [("object.repeat.radial", "instances"), ("object.repeat.grid", "rows"), ("object.repeat.mirror", "angle")] { + let mut app = new_app(); + let a = rect(&mut app, 20.0, 20.0, 40.0, 40.0); + let repeat = app.run(cmd, json!({"ids": [a]})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [repeat]})).unwrap(); + let texts = tall(&mut app, &ctx, vec![]); + assert!(shows(&texts, "Repeat Options"), "{cmd}"); + let depth = undo_depth(&app); + press(&mut app, &ctx, text_at(&texts, "Repeat Options").center()); + let d = app.ui.dialog.as_ref().expect("the Repeat Options dialog opens"); + assert_eq!(d.kind, "command", "{cmd}"); + assert!(d.fields.contains_key(field), "{cmd}: the dialog has the repeat's {field}"); + assert_eq!(undo_depth(&app), depth, "opening the dialog changes nothing"); + app.ui.dialog = None; + let c = rect(&mut app, 20.0, 200.0, 40.0, 40.0); + app.run("select.set", json!({"ids": [repeat, c]})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Repeat Options"), "{cmd}: a repeat and another object"); + app.run("select.set", json!({"ids": [c]})).unwrap(); + assert!(!shows(&tall(&mut app, &ctx, vec![]), "Repeat Options"), "a rectangle"); + } +} + /// Quick Actions offer Lock for a selected member in isolation and for a selected group outside it. #[test] fn lock_is_a_quick_action_in_and_outside_isolation_mode() { diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index fb9269fcfd..f6ece0ac55 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -137,10 +137,12 @@ pub(crate) fn weight_field(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, weig } /// The underlined Stroke link (`label`: the Control bar's "Stroke:", the Properties panel's -/// "Stroke"): a click toggles the Stroke panel in a popover under it. +/// "Stroke"): a click toggles the Stroke panel in a popover under it, and a drag scrubs the weight +/// field after it ([`crate::scrub`]). pub(crate) fn link(app: &mut VectorcraftApp, ui: &mut Ui, label: &str) { let t = Tokens::get(ui.ctx()); - let resp = ui.link(egui::RichText::new(label).size(12.0).color(t.text).underline()).on_hover_text(tl!("Stroke options")); + // A drag on it scrubs the weight field after it (#4088). + let resp = crate::scrub::link_label(ui, egui::RichText::new(label).size(12.0).color(t.text).underline()).on_hover_text(tl!("Stroke options")); widgets::popover(&resp, resp.clicked(), |ui| { ui.set_width(260.0); show(app, ui); diff --git a/crates/ui-egui/src/panels/tests_constrain.rs b/crates/ui-egui/src/panels/tests_constrain.rs index 8fa4c6e028..a90f2b55d1 100644 --- a/crates/ui-egui/src/panels/tests_constrain.rs +++ b/crates/ui-egui/src/panels/tests_constrain.rs @@ -256,6 +256,21 @@ fn a_thousands_comma_in_a_percentage_is_refused_in_a_size_field() { } } +/// Arithmetic with a decimal comma works in W (#5684), also after a value shown with a point; a +/// number with both separators is refused and leaves the size as it was. +#[test] +fn arithmetic_with_a_decimal_comma_works_in_a_size_field() { + let surfaces: [(&str, Draw); 3] = + [("Transform panel", transform::show), ("Properties", properties::transform_section), ("Control bar", crate::chrome::control_bar)]; + for (name, draw) in surfaces { + for (text, want) in [("100,5-20,5", 80.0), ("90-0,5*20", 80.0), ("10,5*2", 21.0), ("100.5 pt-20,5", 80.0), ("1.234,5", 100.0)] { + let mut app = rect_app(); + set_field(&mut app, draw, "100 pt", text, End::Enter(Modifiers::NONE)); + assert_eq!(size(&app), (want, 50.0), "{name}, {text}"); + } + } +} + /// A length field of the New Document dialog keeps the focus on Ctrl/Cmd+Enter, and the dialog /// creates no document. #[test] diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 0f1cf3db5f..042913ca02 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -178,8 +178,10 @@ pub fn set_artboard(app: &mut VectorcraftApp, index: usize, refi: usize, xywh: [ } } -/// The Artboard tool's view of the panel: the active artboard's position and size ([`set_artboard`]). -fn artboard_fields(app: &mut VectorcraftApp, ui: &mut Ui, index: usize, r: Rect) { +/// The Artboard tool's view of the panel, and the Properties panel's Transform section in Edit +/// Artboards: the reference point, artboard `index`'s position and size at `r` in fields +/// `fw` wide ([`set_artboard`]), and the Constrain Width and Height Proportions link. +pub(crate) fn artboard_fields(app: &mut VectorcraftApp, ui: &mut Ui, index: usize, r: Rect, fw: f32) { let units = app.session.general_unit(); let origin = app.ruler_origin(); let refi = reference_index(ui); @@ -191,20 +193,20 @@ fn artboard_fields(app: &mut VectorcraftApp, ui: &mut Ui, index: usize, r: Rect) ui.add_space(4.0); egui::Grid::new("xfp-ab-grid").num_columns(4).spacing([4.0, 6.0]).min_col_width(0.0).show(ui, |ui| { widgets::dim_label(ui, "X:"); - if let Some(v) = widgets::num_field_named(ui, "xfp-ab-x", Some(crate::i18n::t("X:")), Some(rp.x - origin.x), units, 80.0) { + if let Some(v) = widgets::num_field_named(ui, "xfp-ab-x", Some(crate::i18n::t("X:")), Some(rp.x - origin.x), units, fw) { set(app, Some(v + origin.x), None, None, None); } widgets::dim_label(ui, "W:"); - if let Some(v) = widgets::size_field_named(ui, "xfp-ab-w", Some(tl!("W:")), Some(r.width()), units, 80.0) { + if let Some(v) = widgets::size_field_named(ui, "xfp-ab-w", Some(tl!("W:")), Some(r.width()), units, fw) { set(app, None, None, Some(v), None); } ui.end_row(); widgets::dim_label(ui, "Y:"); - if let Some(v) = widgets::num_field_named(ui, "xfp-ab-y", Some(crate::i18n::t("Y:")), Some(rp.y - origin.y), units, 80.0) { + if let Some(v) = widgets::num_field_named(ui, "xfp-ab-y", Some(crate::i18n::t("Y:")), Some(rp.y - origin.y), units, fw) { set(app, None, Some(v + origin.y), None, None); } widgets::dim_label(ui, "H:"); - if let Some(v) = widgets::size_field_named(ui, "xfp-ab-h", Some(tl!("H:")), Some(r.height()), units, 80.0) { + if let Some(v) = widgets::size_field_named(ui, "xfp-ab-h", Some(tl!("H:")), Some(r.height()), units, fw) { set(app, None, None, None, Some(v)); } ui.end_row(); @@ -254,7 +256,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } if let Some((i, r)) = tool_artboard(app) { - artboard_fields(app, ui, i, r); + artboard_fields(app, ui, i, r, 80.0); return; } if let Some(guides) = selected_guides(app) { @@ -461,14 +463,23 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live /// The Control bar's underlined "Transform" link: a click toggles the Transform panel in a /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - let resp = ui.link(egui::RichText::new(tl!("Transform")).size(12.0).color(t.text).underline()).on_hover_text(tl!("Transform options")); + let resp = ui.link(link_text(ui)).on_hover_text(tl!("Transform options")); widgets::popover(&resp, resp.clicked(), |ui| { ui.set_width(300.0); show(app, ui); }); } +/// The Transform link's text, as [`link`] draws it and [`link_width`] measures it. +fn link_text(ui: &Ui) -> egui::RichText { + egui::RichText::new(tl!("Transform")).size(12.0).color(Tokens::get(ui.ctx()).text).underline() +} + +/// The width of the Transform [`link`] in `ui`. +pub fn link_width(ui: &Ui) -> f32 { + widgets::text_width(ui, link_text(ui)) +} + /// The width and height of [`constrain_link`]'s button. pub const CONSTRAIN_LINK_SIZE: f32 = 22.0; diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index ba00aabbf5..49f14f281b 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -40,6 +40,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); + check_typed_folders(app, &values)?; app.run("prefs.set", json!({ "values": values }))?; if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(app, app.touch_screen); @@ -386,16 +387,17 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } }); } - // File Handling › Data Recovery › Folder: typed, or picked with Choose… where the host - // has a folder picker (not on the web). - PrefKind::Text if sp.key == "recoveryFolder" => { + // File Handling › Data Recovery › Folder and Plug-ins & Scratch Disks › Additional + // Plug-ins Folder: typed, or picked with Choose… where the host has a folder picker + // (not on the web). + PrefKind::Text if folder_check(sp.key).is_some() => { labeled(ui, sp.label, |ui| { let mut s = v.as_str().unwrap_or("").to_string(); if ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(200.0)).changed() { d.fields.insert(sp.key.into(), json!(s)); } if app.services.pick_folder.is_some() && ui.button(tl!("Choose…")).clicked() { - choose_recovery_folder(app, d); + choose_folder(app, d, sp.key); } }); } @@ -411,15 +413,30 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, } } -/// Data Recovery › Choose…: the folder picked becomes the Folder field's value when a folder can be -/// made in it. Otherwise the status bar says why and the field keeps its value, as it does when -/// the picker is canceled. The answer fills the field even when the active document closed while -/// the picker was open. -fn choose_recovery_folder(app: &mut VectorcraftApp, d: &mut Dialog) { - let r = crate::picks::in_app_dialog(app, d, |app, d| { +/// A check of a folder path: `Err` says why the folder can't be the preference's value. +type FolderCheck = fn(&str) -> Result<(), String>; + +/// The check a folder preference with a Choose… button gives a folder before it becomes the +/// preference's value: Data Recovery keeps its copies in its folder, and the Additional Plug-ins +/// Folder is read for plug-ins. `None` for any other preference. +fn folder_check(key: &str) -> Option { + match key { + "recoveryFolder" => Some(writable_folder), + "pluginsFolder" => Some(plugins_folder), + _ => None, + } +} + +/// Choose… beside the folder preference `key`: the folder picked becomes the field's value when it +/// passes the preference's [`folder_check`]. Otherwise the status bar says why and the field keeps +/// its value, as it does when the picker is canceled. The answer fills the field even when the +/// active document closed while the picker was open. +fn choose_folder(app: &mut VectorcraftApp, d: &mut Dialog, key: &'static str) { + let Some(check) = folder_check(key) else { return }; + let r = crate::picks::in_app_dialog(app, d, move |app, d| { let Some(path) = crate::picks::folder(app) else { return Ok(()) }; - writable_folder(&path)?; - d.fields.insert("recoveryFolder".into(), json!(path)); + check(&path)?; + d.fields.insert(key.into(), json!(path)); Ok(()) }); if let Err(e) = r { @@ -427,10 +444,43 @@ fn choose_recovery_folder(app: &mut VectorcraftApp, d: &mut Dialog) { } } +/// OK's check of the folder preferences with a Choose… button: a folder typed into one of their +/// fields gets the same [`folder_check`] as a picked one. An empty field (the default folder) and +/// a folder the preference already holds are not checked. The web has no folders to check. +fn check_typed_folders(app: &VectorcraftApp, fields: &Map) -> Result<(), String> { + if cfg!(target_arch = "wasm32") { + return Ok(()); + } + let saved = app.session.prefs.to_json(); + for (key, v) in fields { + let (Some(check), Some(path)) = (folder_check(key), v.as_str()) else { continue }; + let path = path.trim(); + if path.is_empty() || saved[key.as_str()].as_str().is_some_and(|s| s.trim() == path) { + continue; + } + check(path)?; + } + Ok(()) +} + +/// `Ok` when `path` is a folder whose contents can be listed, as the plug-ins in it are found by +/// listing it. A folder outside the automation roots in force is refused before it is looked at. +fn plugins_folder(path: &str) -> Result<(), String> { + vectorcraft_engine::file_access::check_read(path)?; + let dir = std::path::Path::new(path); + if !dir.is_dir() { + return Err(format!("{path} is not a folder")); + } + std::fs::read_dir(dir).map(drop).map_err(|e| format!("Plug-ins can't be loaded from {path}: {e}")) +} + /// `Ok` when `path` is a folder that can be listed and that a folder can be created in, as the /// recovery store lists its folders there and makes its own: the folder is listed, and an empty -/// folder is made there and removed. A folder that can't be removed again is an error too. +/// folder is made there and removed. A folder that can't be removed again is an error too. A +/// folder outside the automation roots in force is refused before it is looked at. fn writable_folder(path: &str) -> Result<(), String> { + vectorcraft_engine::file_access::check_write(path)?; + vectorcraft_engine::file_access::check_read(path)?; let dir = std::path::Path::new(path); if !dir.is_dir() { return Err(format!("{path} is not a folder")); diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index ff5dcbca7b..75a165674f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -458,12 +458,12 @@ fn a_chosen_recovery_folder_fills_the_field_and_cancel_keeps_it() { let answer = picked.clone(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); let mut d = a.ui.dialog.clone().unwrap(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), picked); assert!(a.ui.status.is_empty(), "{}", a.ui.status); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write check leaves nothing behind"); a.services.pick_folder = Some(Box::new(|| None)); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), picked, "cancel keeps the field"); a.ui.dialog = Some(d); confirm(&mut a).unwrap(); @@ -486,7 +486,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = path.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert_eq!(a.ui.status, format!("{} is not a folder", path.to_string_lossy())); } @@ -501,7 +501,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = locked.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert!(a.ui.status.starts_with("Data Recovery can't keep copies in "), "{}", a.ui.status); } @@ -515,7 +515,7 @@ fn a_recovery_folder_that_cannot_be_written_is_refused() { let answer = unlisted.to_string_lossy().into_owned(); a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); a.ui.status.clear(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); assert_eq!(d.str("recoveryFolder"), "kept"); assert!(a.ui.status.starts_with("Data Recovery can't keep copies in "), "{}", a.ui.status); } @@ -535,7 +535,7 @@ fn a_chosen_recovery_folder_fills_the_field_after_the_active_document_closes() { a.run("file.new", json!({"width": 100, "height": 80})).unwrap(); open(&mut a, Some("File Handling")); let mut d = a.ui.dialog.take().unwrap(); - choose_recovery_folder(&mut a, &mut d); + choose_folder(&mut a, &mut d, "recoveryFolder"); a.ui.dialog = Some(d); assert!(matches!(shown.requests().as_slice(), [crate::picks::PickRequest::Folder])); a.session.execute("file.close", &json!({})).unwrap(); @@ -546,3 +546,112 @@ fn a_chosen_recovery_folder_fills_the_field_after_the_active_document_closes() { assert_eq!(a.ui.dialog.as_ref().unwrap().str("recoveryFolder"), picked, "{}", a.ui.status); let _ = std::fs::remove_dir_all(&dir); } + +/// Plug-ins & Scratch Disks › Additional Plug-ins Folder has a Choose… button where the host has a +/// folder picker, and none where it has not (the web). +#[test] +fn plugins_folder_has_a_choose_button_with_a_folder_picker() { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + a.services.pick_folder = Some(Box::new(|| None)); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Additional Plug-ins Folder") && text.contains("Choose…"), "{text}"); + a.services.pick_folder = None; + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Additional Plug-ins Folder") && !text.contains("Choose…"), "{text}"); +} + +/// Choose… beside Additional Plug-ins Folder puts the folder picked into the field, and OK saves +/// it; a canceled picker, a file and a missing folder leave the field as it was. +#[test] +fn a_chosen_plugins_folder_fills_the_field_and_others_keep_it() { + let dir = temp_folder("plugins-chosen"); + let file = dir.join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let mut d = a.ui.dialog.clone().unwrap(); + for path in [file.clone(), dir.join("missing")] { + let answer = path.to_string_lossy().into_owned(); + a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + a.ui.status.clear(); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), ""); + assert_eq!(a.ui.status, format!("{} is not a folder", path.to_string_lossy())); + } + let picked = dir.to_string_lossy().into_owned(); + let answer = picked.clone(); + a.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + a.ui.status.clear(); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), picked); + assert!(a.ui.status.is_empty(), "{}", a.ui.status); + a.services.pick_folder = Some(Box::new(|| None)); + choose_folder(&mut a, &mut d, "pluginsFolder"); + assert_eq!(d.str("pluginsFolder"), picked, "cancel keeps the field"); + a.ui.dialog = Some(d); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugins_folder, picked); + let _ = std::fs::remove_dir_all(&dir); +} + +/// OK checks a folder typed into Data Recovery › Folder or Additional Plug-ins Folder as Choose… +/// checks a picked one: one that fails keeps the dialog open and changes no preference. An empty +/// field and a folder the preference already holds are not checked. +#[test] +fn ok_refuses_a_typed_folder_that_choose_would_refuse() { + let dir = temp_folder("typed-folders"); + let file = dir.join("not-a-folder.txt"); + std::fs::write(&file, b"x").unwrap(); + let missing = dir.join("missing").to_string_lossy().into_owned(); + for key in ["recoveryFolder", "pluginsFolder"] { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + let before = a.session.prefs.to_json(); + for path in [file.to_string_lossy().into_owned(), missing.clone()] { + let d = a.ui.dialog.as_mut().unwrap(); + d.fields.insert(key.into(), json!(path)); + d.fields.insert("showToolTips".into(), json!(!a.session.prefs.show_tool_tips)); + assert_eq!(confirm(&mut a), Err(format!("{path} is not a folder")), "{key}"); + assert!(a.ui.dialog.is_some(), "{key}: the dialog stays open"); + assert_eq!(a.session.prefs.to_json(), before, "{key}: no preference changes"); + } + // A typed folder that passes is saved, with the spaces around it as typed. + let typed = format!(" {} ", dir.to_string_lossy()); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(typed)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(typed), "{key}"); + // An empty field keeps the default folder. + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!("")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(""), "{key}"); + // A folder already saved is not checked again, so OK works while it is unavailable. + a.run("prefs.set", json!({"key": key, "value": missing})).unwrap(); + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert("showToolTips".into(), json!(!a.session.prefs.show_tool_tips)); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.to_json()[key], json!(missing), "{key}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Under automation roots, OK refuses a typed folder outside them before it looks at the folder. +#[test] +fn ok_refuses_a_typed_folder_outside_the_automation_roots_before_looking_at_it() { + use vectorcraft_engine::file_access::{self, Access}; + let dir = temp_folder("typed-roots"); + let inside = dir.join("inside"); + std::fs::create_dir_all(&inside).unwrap(); + let outside = dir.join("outside-missing").to_string_lossy().into_owned(); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap().unwrap(); + for (key, access) in [("recoveryFolder", Access::Write), ("pluginsFolder", Access::Read)] { + let mut a = VectorcraftApp::new(Session::new(), Default::default()); + open(&mut a, Some("File Handling")); + a.ui.dialog.as_mut().unwrap().fields.insert(key.into(), json!(outside)); + let r = file_access::confine(Some(&roots), || confirm(&mut a)); + assert_eq!(r, Err(roots.check(&outside, access).unwrap_err()), "{key}"); + assert!(a.ui.dialog.is_some(), "{key}: the dialog stays open"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 1b28f7d1fb..3a7f5d89ad 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -1,7 +1,8 @@ //! Background rendering (native): heavy documents render off the UI thread while the canvas shows //! the previous frame reprojected to the current view. A second worker renders a low-resolution //! frame for the parts that frame does not reach (`canvas::fill_uncovered`). Light documents -//! render synchronously so edits never lag behind overlays. +//! render synchronously so edits never lag behind overlays, after a first frame that renders here +//! too: the UI thread waits for it only briefly (`canvas::FIRST_FRAME_GRACE`). use std::sync::Arc; use std::sync::mpsc::{Receiver, Sender, channel}; @@ -80,16 +81,31 @@ impl Worker { (Self { tx, rx, pending: None }, jobs, done_tx) } - pub fn submit(&mut self, job: Job) { + /// Queue `job`, unless the job pending is the same frame. Whether it was queued. + pub fn submit(&mut self, job: Job) -> bool { if self.pending.as_ref() == Some(&job.key) { - return; + return false; } self.pending = Some(job.key.clone()); - let _ = self.tx.send(job); + // A worker that has stopped renders nothing: the canvas keeps the frame it shows. + self.tx.send(job).is_ok() } + /// The newest finished frame, if any. pub fn poll(&mut self) -> Option { - let mut last = None; + self.newest(None) + } + + /// The newest finished frame, waiting up to `timeout` for one when none has finished yet. + pub fn wait(&mut self, timeout: std::time::Duration) -> Option { + let first = self.rx.try_recv().ok().or_else(|| self.rx.recv_timeout(timeout).ok())?; + self.newest(Some(first)) + } + + /// The newest of `first` and the frames finished since, the pending job cleared when it is + /// the one. + fn newest(&mut self, first: Option) -> Option { + let mut last = first; while let Ok(d) = self.rx.try_recv() { last = Some(d); } diff --git a/crates/ui-egui/src/scrub.rs b/crates/ui-egui/src/scrub.rs index 832b828708..70ceb50606 100644 --- a/crates/ui-egui/src/scrub.rs +++ b/crates/ui-egui/src/scrub.rs @@ -1,8 +1,10 @@ //! Scrubbing numeric fields (#400, beyond Illustrator; Photoshop's scrubby labels): a horizontal //! drag on a numeric field's label (`W:`, `Opacity:`, the Character panel's size icon) steps the //! field's value by one unit every [`PX_PER_STEP`] points, ten with Shift and a tenth with -//! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. The -//! text box itself never scrubs, and a field without a label doesn't. +//! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. A +//! label that is a link (the Control bar's `Stroke:` and `Opacity:`, which open their panels; +//! #4088) scrubs its field the same way, and a click on it still follows the link. The text box +//! itself never scrubs, and a field without a label doesn't. //! //! The panels apply each value the drag passes as they apply a typed one, so the art follows the //! drag live; the app holds an undo group open meanwhile ([`begin_frame`], [`end_frame`]), so the @@ -113,24 +115,44 @@ pub(crate) fn end_frame(app: &mut VectorcraftApp, ctx: &Context) { struct Label { rect: Rect, pass: u64, + /// The label is a link, this widget: a click follows it instead of focusing the field. + link: Option, } /// Note the label (text or icon) drawn at `rect`: a numeric field drawn right after it on the /// same line takes it as its label, which scrubs the field. pub(crate) fn note_label(ui: &Ui, rect: Rect) { + note(ui, rect, None); +} + +/// A link that labels the numeric field drawn after it (it opens a panel when clicked): a drag on +/// it scrubs the field, and a click stays the link's. Its text can't be selected, which a drag +/// across it would otherwise do. +pub(crate) fn link_label(ui: &mut Ui, text: egui::RichText) -> Response { + let link = ui + .scope(|ui| { + ui.style_mut().interaction.selectable_labels = false; + ui.link(text) + }) + .inner; + note(ui, link.rect, Some(link.id)); + link +} + +fn note(ui: &Ui, rect: Rect, link: Option) { let pass = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(label_id(), Label { rect, pass })); + ui.data_mut(|d| d.insert_temp(label_id(), Label { rect, pass, link })); } /// The label noted just before the field at `field`, on its line. -fn take_label(ui: &Ui, field: Rect) -> Option { +fn take_label(ui: &Ui, field: Rect) -> Option